57 Commits

Author SHA1 Message Date
roman 15dbe26220 Added option to generate test variations. 2023-06-25 21:44:21 +03:00
roman 9818067013 Fix sharable link issues. Browsersync works with ngrok now. 2023-06-25 12:19:32 +03:00
roman 996d222436 Added live-editing in browser option of dataOption (json). 2023-06-25 07:00:07 +03:00
roman e964892e65 Added option to share remote preview URL. (ngrok) 2023-06-23 18:57:31 +03:00
roman 6d1ab34b2b Merge branch 'js-rendering' into dev
# Conflicts:
#	layouts/scripts/dist/frame-index.min.js
#	layouts/scripts/dist/frame-index.min.js.map
#	layouts/scripts/dist/index.min.js
#	layouts/scripts/dist/index.min.js.map
2023-06-21 22:01:13 +03:00
roman 18d89a9a19 1.0.27 2023-06-21 21:47:35 +03:00
roman 5c7ea9df3c Added map files. 2023-06-21 21:47:27 +03:00
roman 010154797a Render Component with JavaScript. 2023-06-21 21:46:31 +03:00
roman 98d0720bc0 Render Component with JavaScript. 2023-06-21 21:45:34 +03:00
roman 378038b244 Added base_url helper to blocks. 2023-04-23 12:52:41 +03:00
roman 090978e8f8 Updated swiper version 2023-04-13 20:17:57 +03:00
roman aae474901b Change position of swiper.css in loading queue. 2023-03-18 16:56:37 +02:00
Roman Axelrod a4193d63e1 Add WordPress hook name to components. 2023-03-14 13:56:28 +02:00
roman 9f5c157e54 Update templates, white spacings and code format. 2023-02-17 14:24:43 +02:00
roman b399d2fc89 Update format of elementor template. 2023-02-17 14:08:26 +02:00
roman c899f8c229 Added validation message in build php process. 2023-02-17 13:57:36 +02:00
roman 80464a61d7 Update output code format. 2023-02-17 13:50:40 +02:00
roman 3a78aee088 - Update export dir of wordpress projects. 2023-02-17 13:33:22 +02:00
roman 0f60a0ac30 Merge pull request 'elementor-build' (#8) from elementor-build into master
Reviewed-on: #8
2023-02-17 08:19:32 +00:00
roman 7dcaa80d71 Merge pull request 'project-path-feat' (#7) from project-path-feat into master
Reviewed-on: #7
2023-02-17 08:18:41 +00:00
roman 0a8cdf1504 Merge branch 'master' into project-path-feat 2023-02-17 10:18:11 +02:00
roman 1718157b4e Add minimum required version of node to package.json. 2023-01-14 19:43:55 +02:00
roman df7866b8b5 Updated Build Template of Elementor block. 2023-01-02 14:23:11 +02:00
roman 50d743140b Updated Build Template of Elementor block. 2023-01-02 12:48:49 +02:00
roman f86afc8394 Added new Resolution - 320px. 2022-12-29 10:01:37 +02:00
roman 269fbbc401 Update logic of hubspot builder. 2022-12-14 16:07:42 +02:00
roman f236674c1e Update logic of hubspot builder. 2022-12-14 12:51:43 +02:00
roman e9827fdd88 Fix dist path of hubspot blocks. 2022-12-14 12:01:52 +02:00
roman b441ac613d Merge branch 'master' into project-path-feat 2022-12-14 03:19:25 +02:00
roman 394d5a42d9 Fix source maps of JS file. 2022-12-14 03:19:15 +02:00
roman 6885db162e Merge branch 'master' into project-path-feat 2022-12-14 00:24:08 +02:00
roman 1a19d63192 Set Height limit to frame. 2022-12-14 00:23:53 +02:00
roman 3c163b8e76 Fix zip archive typo. 2022-12-11 15:08:01 +02:00
roman c627c873f9 Merge branch 'master' into project-path-feat 2022-12-11 09:44:17 +02:00
roman ec61e01950 Add hook_prefix to Component object. 2022-12-11 09:42:40 +02:00
roman 682299445c Add hook_prefix to Component object. 2022-12-11 09:37:16 +02:00
roman ddbc713603 Add scripts/styling to the page only on frontend side. (not in admin panel). 2022-12-10 12:59:26 +02:00
roman 4abdd29709 Add FLAG::THIS in PHP builder. 2022-12-09 19:56:49 +02:00
roman a0def8467b Make sure WordPress className initialized. 2022-12-09 18:29:42 +02:00
roman bd5cafa549 - Support Zip archive with provided PROJECT_PATH.
- Added notes for future tests.
- Make sure we can overwrite MODULE_PATH and PROJECT_PATH.
- Simplify the process of env variables setup. Provide default values.
- Include env.js in package.json
Organized all env in env.js file. It allows us to overwrite these values.
2022-12-09 17:54:41 +02:00
roman dd860ec473 1.0.26 2022-12-09 12:46:54 +02:00
roman c1340f2035 - Added notes for future tests.
- Make sure we can overwrite MODULE_PATH and PROJECT_PATH.
- Simplify the process of env variables setup. Provide default values.
- Include env.js in package.json
Organized all env in env.js file. It allows us to overwrite these values.
2022-12-09 12:46:03 +02:00
roman b43a4d6b4f - Make sure we can overwrite MODULE_PATH and PROJECT_PATH.
- Simplify the process of env variables setup. Provide default values.
- Include env.js in package.json
Organized all env in env.js file. It allows us to overwrite these values.
2022-12-09 12:31:39 +02:00
roman 1a98a60fac - Make sure we can overwrite MODULE_PATH and PROJECT_PATH.
- Simplify the process of env variables setup. Provide default values.
- Include env.js in package.json
Organized all env in env.js file. It allows us to overwrite these values.
2022-12-09 12:26:54 +02:00
roman de0b6740d1 - Simplify the process of env variables setup. Provide default values.
- Include env.js in package.json
Organized all env in env.js file. It allows us to overwrite these values.
2022-12-09 07:41:39 +02:00
roman f9c0852ede - Include env.js in package.json
Organized all env in env.js file. It allows us to overwrite these values.
2022-12-09 07:13:01 +02:00
roman cdbb4d3064 Organized all env in env.js file. It allows us to overwrite these values. 2022-12-09 07:11:33 +02:00
roman 8d7ce53e46 1.0.25 2022-12-08 14:15:57 +02:00
roman e42643f182 rebuild dist bundle. 2022-12-08 14:15:44 +02:00
roman 05b5ccb2b5 Code format - build of wordpress. 2022-12-08 13:34:12 +02:00
roman 54523ed903 1.0.24 2022-12-08 13:25:43 +02:00
roman f611185a47 Wrap build options/platforms in reusable function. 2022-12-08 13:25:32 +02:00
roman 7024c2bfcb 1.0.23 2022-12-08 13:09:21 +02:00
roman b882c9a1c3 Added "WordPress + Component Manager" adapter. 2022-12-08 13:09:05 +02:00
roman 1dc8d192f7 Merge pull request 'acf-build' (#6) from acf-build into master
Reviewed-on: #6
2022-12-08 03:41:08 +00:00
roman d8c3d4c54b - Added compile note (date) in PHP bundle.
- Update spacings/code-format of PHP bundle.
2022-12-08 05:40:39 +02:00
roman 6626ecff2a Update spacings/code-format of PHP bundle. 2022-12-08 05:16:21 +02:00
37 changed files with 11565 additions and 350 deletions
+4
View File
@@ -18,6 +18,10 @@ indent_size = 2
indent_style = tab indent_style = tab
indent_size = 4 indent_size = 4
[*.php]
indent_style = tab
indent_size = 4
[*.md] [*.md]
trim_trailing_whitespace = false trim_trailing_whitespace = false
+7 -23
View File
@@ -3,20 +3,20 @@
import config from 'config'; import config from 'config';
import prompts from "prompts"; import prompts from "prompts";
import {buildHubspotEmail} from "./platforms/hubspot/hubspot-email-adapter.js"; import {buildExportFiles, getConfigs} from "./helpers.js";
import {getConfigs} from "./helpers.js";
import {buildWordPress} from "./platforms/wordpress/wordpress-adapter.js";
import {buildHubspotPage} from "./platforms/hubspot/hubspot-page-adapter.js";
const {isDev, developmentBlockName} = getConfigs(); const {isDev, developmentBlockName} = getConfigs();
const blockName = !isDev && config.has('blockName') ? config.get('blockName') : developmentBlockName; const blockName = !isDev && config.has('blockName') ? config.get('blockName') : developmentBlockName;
export const PLATFORM_OPTIONS = [{ export const PLATFORM_OPTIONS = [{
name: 'wordpress-acf-block',
title: 'WordPress AFC Block'
}, {
name: 'wordpress', name: 'wordpress',
title: 'WordPress' title: 'WordPress'
}, { }, {
name: 'wordpress-blocks', name: 'wordpress-component-manager',
title: 'WordPress Block' title: 'WordPress (Component Manager)'
}, { }, {
name: 'wordpress-elementor', name: 'wordpress-elementor',
title: 'WordPress Elementor' title: 'WordPress Elementor'
@@ -36,7 +36,7 @@ export const PLATFORM_OPTIONS = [{
const data = await getExportData(); const data = await getExportData();
const selectedPlatform = PLATFORM_OPTIONS[data['platform']]; const selectedPlatform = PLATFORM_OPTIONS[data['platform']];
await buildExportFiles(selectedPlatform); await buildExportFiles(blockName, selectedPlatform);
console.log('--------------------\nDone!'); console.log('--------------------\nDone!');
@@ -44,22 +44,6 @@ console.log('--------------------\nDone!');
// Functions // Functions
// //
export async function buildExportFiles(platform) {
if (platform.name.startsWith('wordpress')) {
if (platform.name === 'wordpress-blocks') {
await buildWordPress(blockName, true);
} else if (platform.name === 'wordpress-elementor') {
await buildWordPress(blockName, false, true);
} else {
await buildWordPress(blockName);
}
} else if (platform.name === 'hubspot-email') {
await buildHubspotEmail(blockName)
} else if (platform.name === 'hubspot') {
await buildHubspotPage(blockName)
}
}
function getExportData() { function getExportData() {
return prompts([ return prompts([
{ {
+46
View File
@@ -0,0 +1,46 @@
import path from 'path';
/**
* Since this file overwrites environment variables for `config` lib,
* it's important to "import" this file before all scripts in entry point file,
* especially before `config` module import.
*/
/**
* Export constant variables
*/
export const PRODUCTION_REGISTRY_URL = 'https://blocks-registery.axe-web.com';
export const IS_DEV = process.env.NODE_ENV === 'development';
export const BLOCK_NAME = process.env.BLOCK_NAME;
/**
* Overwrite env variables.
*/
process.env.NODE_CONFIG_DIR = path.join(getProjectPath(), 'config');
export function getModulePath() {
let modulePath = 'node_modules/block-dev-tool';
if (typeof process.env.MODULE_PATH !== 'undefined') {
modulePath = process.env.MODULE_PATH;
} else if (process.env.BLOCK_NAME) {
modulePath = 'node_modules/@axe-web/block-dev-tool';
}
return modulePath;
}
export function getProjectPath() {
let projectPath = '';
if (typeof process.env.PROJECT_PATH !== 'undefined') {
projectPath = path.join(process.env.PROJECT_PATH ?? '', process.env.BLOCK_NAME ?? '')
} else if (process.env.BLOCK_NAME) {
projectPath = path.join('blocks', process.env.BLOCK_NAME ?? '')
}
return projectPath;
}
+30 -22
View File
@@ -1,23 +1,24 @@
import path from 'path'; import path from 'path';
import {BLOCK_NAME, getModulePath, getProjectPath, IS_DEV} from "./env.js";
import config from 'config'; import config from 'config';
import {fileURLToPath} from 'url'; import {fileURLToPath} from 'url';
import memFs from 'mem-fs'; import memFs from 'mem-fs';
import editor from 'mem-fs-editor'; import editor from 'mem-fs-editor';
import fsExtra from "fs-extra"; import fsExtra from "fs-extra";
import archiver from "archiver"; import archiver from "archiver";
import {buildWordPress} from "./platforms/wordpress/wordpress-adapter.js";
import {buildHubspotEmail} from "./platforms/hubspot/hubspot-email-adapter.js";
import {buildHubspotPage} from "./platforms/hubspot/hubspot-page-adapter.js";
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename); const __dirname = path.dirname(__filename);
export function getConfigs() { export function getConfigs() {
const isDev = process.env.NODE_ENV === 'development'; // Check README file in case you get "missing files" error.
const developmentBlockName = process.env.BLOCK_NAME;
return { return {
isDev, isDev: IS_DEV,
developmentBlockName, developmentBlockName: BLOCK_NAME,
modulesPath: process.env.MODULE_PATH ?? (isDev ? '' : 'node_modules/block-dev-tool'), modulesPath: getModulePath(),
projectPath: process.env.PROJECT_PATH ?? (isDev ? path.join('blocks', developmentBlockName) : ''), projectPath: getProjectPath(),
}; };
} }
@@ -42,29 +43,26 @@ function getErrorHtml(message = '', errorMessage = '') {
</div>`; </div>`;
} }
export async function getBlockConfigs(jsonFileName = 'default', export async function getBlockData(jsonFileName = 'default', {projectPath} = {jsonFileName: 'default'}) {
{includeConfigs, projectPath, modulesPath, dataFiles} = {}) {
let data = await readJSONFile(path.join(projectPath, 'data', `${jsonFileName}.json`)); let data = await readJSONFile(path.join(projectPath, 'data', `${jsonFileName}.json`));
if (data.error) { if (data.error) {
return data; return data;
} }
if (includeConfigs) {
Object.assign(data, {
config: Object.assign(JSON.parse(JSON.stringify(config)), // The entire config object.
{
projectDir: modulesPath, activeDataFile: jsonFileName, dataFiles: dataFiles.map((name) => {
return {
name, active: jsonFileName === name,
};
}), remToPx: config.has('remToPx') ? config.get('remToPx') : 16,
})
});
}
return data; return data;
} }
export function getBlockConfigs(args = {modulesPath: '', dataFiles: []}) {
return Object.assign(JSON.parse(JSON.stringify(config)), // The entire config object.
{
projectDir: args.modulesPath, dataFiles: args.dataFiles.map((name) => {
return {
name,
};
}), remToPx: config.has('remToPx') ? config.get('remToPx') : 16,
});
}
export function getBlockName(name = '') { export function getBlockName(name = '') {
if (name.startsWith('@')) { if (name.startsWith('@')) {
name = name.substring(1); name = name.substring(1);
@@ -152,3 +150,13 @@ export async function zipProject(srcDir, outputFileName = 'dist.zip') {
// 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand // 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand
await archive.finalize(); await archive.finalize();
} }
export async function buildExportFiles(blockName, platform) {
if (platform.name.startsWith('wordpress')) {
await buildWordPress(blockName, {platform: platform.name});
} else if (platform.name === 'hubspot-email') {
await buildHubspotEmail(blockName)
} else if (platform.name === 'hubspot') {
await buildHubspotPage(blockName)
}
}
+1 -3
View File
@@ -4,9 +4,7 @@
<body class="{{#if iframeMode}}body--iframe{{/if}}"> <body class="{{#if iframeMode}}body--iframe{{/if}}">
<main> <div id="hbs-container"></div>
{{> (include_block_template) }}
</main>
{{> (include_partial "layouts/partials/scripts") }} {{> (include_partial "layouts/partials/scripts") }}
+3 -5
View File
@@ -4,11 +4,9 @@
<body class="{{#if iframeMode}}body--iframe{{/if}}"> <body class="{{#if iframeMode}}body--iframe{{/if}}">
<main> <div class="container">
<div class="container"> <div id="hbs-container"></div>
{{> (include_block_template) }} </div>
</div>
</main>
{{> (include_partial "layouts/partials/scripts") }} {{> (include_partial "layouts/partials/scripts") }}
+3
View File
@@ -14,6 +14,9 @@
<script> <script>
window.devTool = { window.devTool = {
previewFrameUrl: '{{ previewFrameUrl }}', previewFrameUrl: '{{ previewFrameUrl }}',
{{#if publicUrl}}
publicUrl: true,
{{/if}}
}; };
</script> </script>
+1 -1
View File
@@ -2,11 +2,11 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://unpkg.com/swiper@8.4.5/swiper-bundle.min.css"/>
{{#if config.cssUrl }} {{#if config.cssUrl }}
{{#each config.cssUrl }} {{#each config.cssUrl }}
<link rel="stylesheet" href="{{ this }}"> <link rel="stylesheet" href="{{ this }}">
{{/each}} {{/each}}
{{/if}}<link rel="stylesheet" href="/styles/page--view.css">{{# if config.blockName}} {{/if}}<link rel="stylesheet" href="/styles/page--view.css">{{# if config.blockName}}
<link rel="stylesheet" href="/styles/{{ config.blockName }}.min.css">{{/if}} <link rel="stylesheet" href="/styles/{{ config.blockName }}.min.css">{{/if}}
<link rel="stylesheet" href="https://unpkg.com/swiper@8/swiper-bundle.min.css"/>
</head> </head>
+3 -1
View File
@@ -1,6 +1,8 @@
<script src="/socket.io/socket.io.js"></script>
<script src="https://cdn.jsdelivr.net/npm/handlebars@latest/dist/handlebars.js"></script>
<script src="/scripts/dist/frame-index.min.js"></script> <script src="/scripts/dist/frame-index.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://unpkg.com/swiper@8/swiper-bundle.min.js"></script>{{#if config.jsUrl }} <script src="https://unpkg.com/swiper@8.4.5/swiper-bundle.min.js"></script>{{#if config.jsUrl }}
{{#each config.jsUrl }}<script src="{{ this }}"></script> {{#each config.jsUrl }}<script src="{{ this }}"></script>
{{/each}} {{/each}}
{{/if}} {{/if}}
+6 -3
View File
@@ -4,13 +4,16 @@
<div class="page_toolbar__middle"> <div class="page_toolbar__middle">
<div> <div>
Sizes: <b>1rem = {{ config.remToPx }}px</b> Version: <b>1rem = {{ config.version }}px</b>
</div> </div>
</div> </div>
<div class="page_toolbar__right"> <div class="page_toolbar__right">
{{#if config.styleGuideUrl}} {{#if shareUrl}}
<a href="{{ config.styleGuideUrl }}" target="_blank" class="palette" title="Open Style Guide"></a> <a href="{{ shareUrl }}" target="_blank" class="share" title="Share URL"></a>
{{/if}}
{{#if styleGuideUrl}}
<a href="{{ styleGuideUrl }}" target="_blank" class="palette" title="Open Style Guide"></a>
{{/if}} {{/if}}
<a href="{{ previewFrameUrl }}" target="_blank" class="open_in_new_tab" title="Open in New Window"></a> <a href="{{ previewFrameUrl }}" target="_blank" class="open_in_new_tab" title="Open in New Window"></a>
</div> </div>
+167 -1
View File
@@ -1 +1,167 @@
!function(){let e;function n(n){const t=document.querySelector("body > main").scrollHeight;if(e===t)return;e=t,window.parent.postMessage("resize:"+JSON.stringify({height:e}),"*")}n(),new ResizeObserver(n).observe(document.body)}(); window.initBlock = initBlock;
let template;
let data = {};
let reload;
// Blocks Initialization.
function initBlock(blockName = '', selector = '', cb) {
reload = function () {
document.querySelectorAll(selector).forEach((el) => cb(el));
};
reload();
}
// Scrollbars / Frame resizes notifications.
(function () {
let height;
handleHeightChange(); // Initial frame's height setup.
setupResizeListener(); // Listen to frame's height changes.
///
function setupResizeListener() {
const resizeObserver = new ResizeObserver(handleHeightChange);
resizeObserver.observe(document.body);
}
function handleHeightChange() {
const updatedHeight = getCurrentHeight();
if (height === updatedHeight) {
return;
}
const RESIZE_CODE = 'resize:';
height = updatedHeight;
window.parent.postMessage(RESIZE_CODE + JSON.stringify({height}), '*');
}
function getCurrentHeight() {
return document.querySelector('#hbs-container').scrollHeight;
}
})();
// Data Updates Listeners.
(function () {
loadDataOptions();
listenToDataOptionsUpdates();
function listenToDataOptionsUpdates() {
window.addEventListener('message', function (event) {
const message = event.data;
const prefix = 'dataUpdate:';
if (typeof message !== "string" || !message.startsWith(prefix)) {
return;
}
try {
data = JSON.parse(message.substring(prefix.length));
updateBlock({data});
} catch (e) {
console.log('Error parsing incoming data.', e);
}
});
}
function getQueryParams() {
const urlParams = new URLSearchParams(window.location.search);
const params = {};
for (const [key, value] of urlParams) {
params[key] = value;
}
return params;
}
function loadDataOptions() {
const queryParameters = new URLSearchParams({name: getQueryParams().data || 'default'});
fetch(`/data?${queryParameters}`)
.then((response) => response.json())
.then((response) => {
data = response.data; // Update state.
updateBlock({data});
});
}
})();
// Listen to Template updates.
(function () {
initSocket();
function initSocket() {
const socket = window.io.connect();
socket.on('error', function (err) {
console.log(err);
});
// socket.on('connect', function () {
// console.log('user connected', socket.id)
// });
socket.on('templateUpdate', function (args) {
updateBlock({template: args.template});
});
}
})();
function updateBlock(args = {}) {
if (args.template) {
template = args.template; // Update state.
}
if (args.data) {
data = args.data; // Update state.
}
if (!template) {
return;
}
renderBlock(template, data || {}, document.getElementById("hbs-container"));
}
function renderBlock(templateHbs, jsonData, target) {
const template = Handlebars.compile(templateHbs);
/**
* Handlebars Helpers
*/
Handlebars.registerHelper('esc_attr', function (attr) {
return attr;
});
Handlebars.registerHelper('esc_url', function (attr) {
return attr;
});
Handlebars.registerHelper('esc_html', function (attr) {
return attr;
});
Handlebars.registerHelper('base_url', function () {
return '/';
});
let html;
try {
html = template(jsonData);
} catch (e) {
html = `<div style="max-width: 1280px; margin: 1rem auto;">
<h1 style="all: unset; font-size: 1.5rem; font-weight: bold; display: block;">Syntax Error:</h1>
<pre style="all: unset; padding: 10px 15px; background-color: #ffe6e6; border: 1px solid red; border-radius: 0.25rem; overflow: auto; display: block; white-space: pre;">${e.toString()}</pre>
</div>`;
}
target.innerHTML = html;
if (reload) {
reload();
}
}
//# sourceMappingURL=frame-index.min.js.map
File diff suppressed because one or more lines are too long
+9935 -16
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+3
View File
@@ -0,0 +1,3 @@
<svg width="478" height="506" viewBox="0 0 478 506" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M379.8 315.4C352.01 315.4 327.062 327.817 310.146 347.315L186.499 278.249C188.838 270.119 190.1 261.521 190.1 252.7C190.1 243.782 188.834 235.223 186.427 227.037L309.923 158.096C326.774 177.698 351.821 190.2 379.7 190.2C430.409 190.2 471.8 148.918 471.8 98.1C471.8 47.2863 430.514 6 379.7 6C328.886 6 287.6 47.2863 287.6 98.1C287.6 106.995 288.859 115.615 291.265 123.769L167.886 192.697C151.025 173.006 125.968 160.6 98.1 160.6C47.3908 160.6 6 201.882 6 252.7C6 303.523 47.3954 344.8 98.2 344.8C126.093 344.8 151.144 332.287 168.074 312.598L291.571 381.633C289.143 389.853 287.8 398.557 287.8 407.5C287.8 458.209 329.082 499.6 379.9 499.6C430.714 499.6 472 458.314 472 407.5C472 356.677 430.605 315.4 379.8 315.4ZM379.8 45.1C409.086 45.1 432.9 68.9137 432.9 98.2C432.9 127.486 409.086 151.3 379.8 151.3C350.514 151.3 326.7 127.486 326.7 98.2C326.7 68.9203 350.607 45.1 379.8 45.1ZM98.2 305.8C68.9137 305.8 45.1 281.986 45.1 252.7C45.1 223.414 68.9137 199.6 98.2 199.6C127.486 199.6 151.3 223.414 151.3 252.7C151.3 281.98 127.393 305.8 98.2 305.8ZM379.8 460.5C350.514 460.5 326.7 436.686 326.7 407.4C326.7 378.114 350.514 354.3 379.8 354.3C409.086 354.3 432.9 378.114 432.9 407.4C432.9 436.686 409.086 460.5 379.8 460.5Z" fill="#21252D" stroke="#21252D" stroke-width="12"/>
</svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

+5 -1
View File
@@ -8,7 +8,11 @@ export function setupFrameResizeListener() {
} }
const data = JSON.parse(e.data.substring(RESIZE_CODE.length)) const data = JSON.parse(e.data.substring(RESIZE_CODE.length))
previewFrame.style.height = data.height + 'px' let height = Number.parseInt(data.height)
if (height > 20000) {
height = 20000; // Limit max height.
}
previewFrame.style.height = height + 'px'
}); });
} }
+134 -3
View File
@@ -1,8 +1,18 @@
'use strict'; 'use strict';
window.initBlock = initBlock;
let template;
let data = {};
let reload;
// Blocks Initialization. // Blocks Initialization.
function initBlock(blockName = '', selector = '', cb) { function initBlock(blockName = '', selector = '', cb) {
document.querySelectorAll(selector).forEach((el) => cb(el)); reload = function () {
document.querySelectorAll(selector).forEach((el) => cb(el));
}
reload();
} }
// Scrollbars / Frame resizes notifications. // Scrollbars / Frame resizes notifications.
@@ -20,7 +30,7 @@ function initBlock(blockName = '', selector = '', cb) {
resizeObserver.observe(document.body); resizeObserver.observe(document.body);
} }
function handleHeightChange(entries) { function handleHeightChange() {
const updatedHeight = getCurrentHeight(); const updatedHeight = getCurrentHeight();
if (debug) { if (debug) {
@@ -41,6 +51,127 @@ function initBlock(blockName = '', selector = '', cb) {
} }
function getCurrentHeight() { function getCurrentHeight() {
return document.querySelector('body > main').scrollHeight; return document.querySelector('#hbs-container').scrollHeight;
} }
})(); })();
// Data Updates Listeners.
(function () {
loadDataOptions();
listenToDataOptionsUpdates();
function listenToDataOptionsUpdates() {
window.addEventListener('message', function (event) {
const message = event.data;
const prefix = 'dataUpdate:';
if (typeof message !== "string" || !message.startsWith(prefix)) {
return;
}
try {
data = JSON.parse(message.substring(prefix.length));
updateBlock({data});
} catch (e) {
console.log('Error parsing incoming data.', e);
}
});
}
function getQueryParams() {
const urlParams = new URLSearchParams(window.location.search);
const params = {};
for (const [key, value] of urlParams) {
params[key] = value;
}
return params;
}
function loadDataOptions() {
const queryParameters = new URLSearchParams({name: getQueryParams().data || 'default'});
fetch(`/data?${queryParameters}`)
.then((response) => response.json())
.then((response) => {
data = response.data; // Update state.
updateBlock({data});
})
}
})();
// Listen to Template updates.
(function () {
initSocket();
function initSocket() {
const socket = window.io.connect();
socket.on('error', function (err) {
console.log(err);
});
// socket.on('connect', function () {
// console.log('user connected', socket.id)
// });
socket.on('templateUpdate', function (args) {
updateBlock({template: args.template});
});
}
})();
function updateBlock(args = {}) {
if (args.template) {
template = args.template; // Update state.
}
if (args.data) {
data = args.data; // Update state.
}
if (!template) {
return;
}
renderBlock(template, data || {}, document.getElementById("hbs-container"));
}
function renderBlock(templateHbs, jsonData, target) {
const template = Handlebars.compile(templateHbs);
/**
* Handlebars Helpers
*/
Handlebars.registerHelper('esc_attr', function (attr) {
return attr;
});
Handlebars.registerHelper('esc_url', function (attr) {
return attr;
});
Handlebars.registerHelper('esc_html', function (attr) {
return attr;
});
Handlebars.registerHelper('base_url', function () {
return '/';
});
let html;
try {
html = template(jsonData);
} catch (e) {
html = `<div style="max-width: 1280px; margin: 1rem auto;">
<h1 style="all: unset; font-size: 1.5rem; font-weight: bold; display: block;">Syntax Error:</h1>
<pre style="all: unset; padding: 10px 15px; background-color: #ffe6e6; border: 1px solid red; border-radius: 0.25rem; overflow: auto; display: block; white-space: pre;">${e.toString()}</pre>
</div>`;
}
target.innerHTML = html;
if (reload) {
reload();
}
}
@@ -9,10 +9,21 @@ import {
import {isClickOutside, isEscHit} from "../responsive-button/ResponsiveButton.jsx"; import {isClickOutside, isEscHit} from "../responsive-button/ResponsiveButton.jsx";
import {DesignPreview} from "./DesignPreview.jsx"; import {DesignPreview} from "./DesignPreview.jsx";
export const PRODUCTION_REGISTRY_URL = 'https://blocks-registery.axe-web.com';
function DataOptions(props = {}) { function DataOptions(props = {}) {
props.rootAttributes = props.rootAttributes ?? {}; props.rootAttributes = props.rootAttributes ?? {};
const initialState = {dataName: 'default', data: {}, dataOptions: [], designPreview: []}; const initialState = {
dataName: 'default',
data: {},
dataText: '{}',
dataOptions: [],
designPreview: [],
errorMessage: null,
loading: false,
};
const [state, setState] = useState(initialState); const [state, setState] = useState(initialState);
const [previewOption, setPreviewOption] = useState(getDesignPreviewImage(state.dataName, state.designPreview)); const [previewOption, setPreviewOption] = useState(getDesignPreviewImage(state.dataName, state.designPreview));
const updateState = (update) => setState(Object.assign({}, state, update)); const updateState = (update) => setState(Object.assign({}, state, update));
@@ -20,8 +31,7 @@ function DataOptions(props = {}) {
const [sidebarOpen, setSidebarOpen] = useState(false); const [sidebarOpen, setSidebarOpen] = useState(false);
useEffect(async () => { useEffect(async () => {
const data = await fetchDataOptions(state.dataName); await syncDataOptions(state.dataName);
updateState(data);
}, []); }, []);
const handleCloseSidebarEscEvent = useCallback((e) => { const handleCloseSidebarEscEvent = useCallback((e) => {
@@ -66,7 +76,7 @@ function DataOptions(props = {}) {
<SidebarDataOptionsStyle> <SidebarDataOptionsStyle>
<label htmlFor="data-options">Data Options</label> <label htmlFor="data-options">Data Options</label>
<select name="data" id="data-options" onChange={(e) => changeDataOption(e)} value={state.dataName}> <select name="data" id="data-options" onChange={(e) => changeDataOption(e)} value={state.dataName} disabled={state.loading}>
{state.dataOptions.map((item) => { {state.dataOptions.map((item) => {
const isSelected = state.dataName === item; const isSelected = state.dataName === item;
return <option value={item} selected={isSelected}>{item}</option> return <option value={item} selected={isSelected}>{item}</option>
@@ -76,10 +86,21 @@ function DataOptions(props = {}) {
} }
{state.data && {state.data &&
<pre>{JSON.stringify(state.data, null, 2)}</pre> <textarea value={state.dataText} onChange={dataOptionUpdate} disabled={state.loading}/>
} }
<button className='btn btn--secondary' onClick={(e) => copyToClipboard(e, state.data)}>Copy to Clipboard</button> {state.errorMessage &&
<p className={'alert alert--error'}>{state.errorMessage}</p>
}
{state.loading &&
<p className={'alert'}>Loading, please wait...</p>
}
<div className={'actions'}>
<button className='btn btn--secondary' disabled={state.loading} onClick={(e) => copyToClipboard(e, state.data)}>Copy to Clipboard</button>
<button className='btn btn--secondary' disabled={state.loading} onClick={(e) => generateVariation(e, state.data)}>Generate Test</button>
</div>
</SidebarStyle> </SidebarStyle>
</div>; </div>;
@@ -87,6 +108,51 @@ function DataOptions(props = {}) {
// Functions // Functions
// //
function generateVariation() {
const url = PRODUCTION_REGISTRY_URL + '/content-generator/';
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
const requestOptions = {
method: 'POST',
headers: myHeaders,
body: JSON.stringify({json: state.data}),
};
updateState({loading: true, errorMessage: null});
return fetch(url, requestOptions)
.then(response => response.json())
.then(result => {
if (result.statusCode !== 200) {
throw new Error(result.message);
}
const data = result.variation;
updateState({dataText: JSON.stringify(data, null, 2), data});
updateIframe(data);
})
.catch(error => {
updateState({loading: false, errorMessage: 'Something went wrong, please try again.'})
});
}
function dataOptionUpdate(e) {
let data;
try {
data = JSON.parse(e.target.value);
} catch (err) {
updateState({dataText: e.target.value, errorMessage: 'Invalid JSON, please review and try again.'});
return;
}
updateState({dataText: e.target.value, data, errorMessage: null});
updateIframe(data);
}
function openSidebar() { function openSidebar() {
setSidebarOpen(true); setSidebarOpen(true);
setTimeout(() => document.querySelector('.sidebar-active').focus()); setTimeout(() => document.querySelector('.sidebar-active').focus());
@@ -98,15 +164,7 @@ function DataOptions(props = {}) {
async function changeDataOption(e) { async function changeDataOption(e) {
const dataName = e.target.value; const dataName = e.target.value;
await syncDataOptions(dataName);
const previewFrameUrl = new URL(window.devTool.previewFrameUrl);
previewFrameUrl.searchParams.set('data', dataName);
previewFrameUrl.searchParams.set('iframe', 'true');
props.rootAttributes.previewFrame.src = previewFrameUrl.href;
const dataOption = await fetchDataOptions(dataName);
updateState(Object.assign({}, dataOption, {dataName}));
} }
async function fetchDataOptions(name = 'default') { async function fetchDataOptions(name = 'default') {
@@ -138,6 +196,23 @@ function DataOptions(props = {}) {
setPreviewOption(getDesignPreviewImage(state.dataName, state.designPreview)); setPreviewOption(getDesignPreviewImage(state.dataName, state.designPreview));
} }
async function syncDataOptions(dataName) {
const dataOptions = await fetchDataOptions(dataName);
updateIframe(dataOptions.data);
const newState = Object.assign({errorMessage: null},
dataOptions,
{dataName},
{dataText: JSON.stringify(dataOptions.data, null, 2)},
);
updateState(newState);
}
function updateIframe(data) {
const previewIframe = props.rootAttributes.previewFrame;
previewIframe.contentWindow.postMessage('dataUpdate:' + JSON.stringify(data || {}), '*');
}
} }
function copyToClipboard(e, context) { function copyToClipboard(e, context) {
@@ -24,7 +24,10 @@ export const SidebarStyle = styled.div`
visibility: visible; visibility: visible;
} }
pre { pre, textarea {
height: 100%;
//min-height: 480px;
resize: vertical;
overflow-x: auto; overflow-x: auto;
padding: 0.5rem; padding: 0.5rem;
background-color: #EDF2F7; background-color: #EDF2F7;
@@ -33,6 +36,20 @@ export const SidebarStyle = styled.div`
border: 1px solid #cbd5e0; border: 1px solid #cbd5e0;
width: 100%; width: 100%;
box-sizing: border-box; box-sizing: border-box;
margin: 0.5rem 0;
display: block;
white-space: pre;
}
.actions {
display: flex;
width: 100%;
justify-content: space-between;
}
.alert--error {
color: red;
} }
`; `;
@@ -0,0 +1,3 @@
<svg width="478" height="506" viewBox="0 0 478 506" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M379.8 315.4C352.01 315.4 327.062 327.817 310.146 347.315L186.499 278.249C188.838 270.119 190.1 261.521 190.1 252.7C190.1 243.782 188.834 235.223 186.427 227.037L309.923 158.096C326.774 177.698 351.821 190.2 379.7 190.2C430.409 190.2 471.8 148.918 471.8 98.1C471.8 47.2863 430.514 6 379.7 6C328.886 6 287.6 47.2863 287.6 98.1C287.6 106.995 288.859 115.615 291.265 123.769L167.886 192.697C151.025 173.006 125.968 160.6 98.1 160.6C47.3908 160.6 6 201.882 6 252.7C6 303.523 47.3954 344.8 98.2 344.8C126.093 344.8 151.144 332.287 168.074 312.598L291.571 381.633C289.143 389.853 287.8 398.557 287.8 407.5C287.8 458.209 329.082 499.6 379.9 499.6C430.714 499.6 472 458.314 472 407.5C472 356.677 430.605 315.4 379.8 315.4ZM379.8 45.1C409.086 45.1 432.9 68.9137 432.9 98.2C432.9 127.486 409.086 151.3 379.8 151.3C350.514 151.3 326.7 127.486 326.7 98.2C326.7 68.9203 350.607 45.1 379.8 45.1ZM98.2 305.8C68.9137 305.8 45.1 281.986 45.1 252.7C45.1 223.414 68.9137 199.6 98.2 199.6C127.486 199.6 151.3 223.414 151.3 252.7C151.3 281.98 127.393 305.8 98.2 305.8ZM379.8 460.5C350.514 460.5 326.7 436.686 326.7 407.4C326.7 378.114 350.514 354.3 379.8 354.3C409.086 354.3 432.9 378.114 432.9 407.4C432.9 436.686 409.086 460.5 379.8 460.5Z" fill="#21252D" stroke="#21252D" stroke-width="12"/>
</svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

+4
View File
@@ -5,6 +5,10 @@ function Publish(props = {}) {
const [state, setState] = useState({loading: false}); const [state, setState] = useState({loading: false});
const updateState = (update) => setState(Object.assign({}, state, update)); const updateState = (update) => setState(Object.assign({}, state, update));
if (window.devTool.publicUrl) {
return;
}
return <div> return <div>
{state.loading && {state.loading &&
<div className="overlay overlay--loading">Loading, Please wait...</div> <div className="overlay overlay--loading">Loading, Please wait...</div>
@@ -4,7 +4,7 @@ import {ButtonStyling, ResponsiveButtonStyle, ResponsiveOptionsDropdown} from ".
const responsiveOptions = { const responsiveOptions = {
desktop: [1920, 1800, 1680, 1440, 1360, 1280, 1024], desktop: [1920, 1800, 1680, 1440, 1360, 1280, 1024],
tablet: [992, 768, 600], tablet: [992, 768, 600],
mobile: [480, 414, 375, 360], mobile: [480, 414, 375, 360, 320],
} }
const defaultResponsiveOptions = { const defaultResponsiveOptions = {
+3 -3
View File
@@ -4,11 +4,11 @@
<body class="{{#if iframeMode}}body--iframe{{/if}}"> <body class="{{#if iframeMode}}body--iframe{{/if}}">
<main> <div>
<section class="fullscreen_layout"></section> <section class="fullscreen_layout"></section>
{{> (include_block_template) }} <div id="hbs-container"></div>
<section class="fullscreen_layout"></section> <section class="fullscreen_layout"></section>
</main> </div>
{{> (include_partial "layouts/partials/scripts") }} {{> (include_partial "layouts/partials/scripts") }}
+6 -1
View File
@@ -139,7 +139,7 @@ body {
max-width: var(--breakpoint); max-width: var(--breakpoint);
} }
.open_in_new_tab, .palette { .open_in_new_tab, .share, .palette {
--size: 1.5rem; --size: 1.5rem;
width: var(--size); width: var(--size);
height: var(--size); height: var(--size);
@@ -162,4 +162,9 @@ body {
background-image: url("/scripts/dist/toolbar/images/icon-palette.svg"); background-image: url("/scripts/dist/toolbar/images/icon-palette.svg");
} }
.share {
background-size: calc(var(--size) - 0.35rem);
background-image: url("/scripts/dist/toolbar/images/icon-share.svg");
}
/*# sourceMappingURL=page--main.css.map */ /*# sourceMappingURL=page--main.css.map */
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sourceRoot":"","sources":["page--main.scss","_buttons.scss","_overlay.scss","_page--preview.scss"],"names":[],"mappings":"AAAA;EACE;EACA;;;AAGF;EACE;EACA;EAEA;;;ACTF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAEA;EACE;EACA;;AAGF;EACE;EACA;;AAGF;EACE;EACA;EACA;;;AC5BJ;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;AFIF;EACE;EACA;EACA;EACA;EAEA;EACA;EACA;EAEA;EACA;EACA;EAEA;EACA;;AAEA;EACE;EACA;EACA;EACA;;AAEA;EACE;;AAEA;EAHF;IAII;;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;;AAKF;EADF;IAEI;;;AAKN;EAEE;EACA;EACA;EACA;;AAGF;EACE;;;AGlFJ;EACE;EACA;EACA;;;AAGF;EACE;EACA;EACA;EACA;EAEA;EACA;EAEA;EACA;EACA;EAEA;EACA;EAEA;;AAEA;EACE;EAEA;EACA;;;AH6DJ;EACE;EACA;EACA;EAEA;EACA;EACA;EACA;EACA;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;AAGF;EAEE","file":"page--main.css"} {"version":3,"sourceRoot":"","sources":["page--main.scss","_buttons.scss","_overlay.scss","_page--preview.scss"],"names":[],"mappings":"AAAA;EACE;EACA;;;AAGF;EACE;EACA;EAEA;;;ACTF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;AAEA;EACE;EACA;;AAGF;EACE;EACA;;AAGF;EACE;EACA;EACA;;;AC5BJ;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;AFIF;EACE;EACA;EACA;EACA;EAEA;EACA;EACA;EAEA;EACA;EACA;EAEA;EACA;;AAEA;EACE;EACA;EACA;EACA;;AAEA;EACE;;AAEA;EAHF;IAII;;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;;AAGF;EACE;EACA;EACA;EACA;EACA;EACA;EACA;;AAKF;EADF;IAEI;;;AAKN;EAEE;EACA;EACA;EACA;;AAGF;EACE;;;AGlFJ;EACE;EACA;EACA;;;AAGF;EACE;EACA;EACA;EACA;EAEA;EACA;EAEA;EACA;EACA;EAEA;EACA;EAEA;;AAEA;EACE;EAEA;EACA;;;AH6DJ;EACE;EACA;EACA;EAEA;EACA;EACA;EACA;EACA;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;AAGF;EAEE;;;AAGF;EAEE;EACA","file":"page--main.css"}
+6
View File
@@ -112,3 +112,9 @@ body {
@extend .open_in_new_tab; @extend .open_in_new_tab;
background-image: url("/scripts/dist/toolbar/images/icon-palette.svg"); background-image: url("/scripts/dist/toolbar/images/icon-palette.svg");
} }
.share {
@extend .open_in_new_tab;
background-size: calc(var(--size) - 0.35rem);
background-image: url("/scripts/dist/toolbar/images/icon-share.svg");
}
+771 -49
View File
File diff suppressed because it is too large Load Diff
+16 -10
View File
@@ -1,19 +1,20 @@
{ {
"name": "@axe-web/block-dev-tool", "name": "@axe-web/block-dev-tool",
"version": "1.0.22", "version": "1.0.27",
"author": { "author": {
"name": "AXE-WEB", "name": "AXE-WEB",
"email": "office@axe-web.com", "email": "office@axe-web.com",
"url": "https://axe-web.com/" "url": "https://axe-web.com/"
}, },
"scripts": { "scripts": {
"start": "component-dev", "info": "NODE_ENV=development BLOCK_NAME=header MODULE_PATH= node debug.js",
"info": "node debug.js", "dev": "NODE_ENV=development BLOCK_NAME=header MODULE_PATH= node server.js",
"dev": "NODE_ENV=development NODE_CONFIG_DIR=blocks/text-block/config BLOCK_NAME=text-block node server.js", "build-platform": "NODE_ENV=development BLOCK_NAME=header MODULE_PATH= node ./build.js",
"build": "rollup --config rollup.config.js", "dev-dev-tool": "NODE_ENV=development rollup --config rollup.config.js --watch",
"build-platform": "NODE_ENV=development NODE_CONFIG_DIR=blocks/text-block/config BLOCK_NAME=text-block node ./build.js", "build-dev-tool": "rollup --config rollup.config.js"
"build-platform-cli": "component-build", },
"dev-js": "NODE_ENV=development rollup --config rollup.config.js --watch" "engines": {
"node": ">=14.17.3"
}, },
"license": "ISC", "license": "ISC",
"type": "module", "type": "module",
@@ -36,12 +37,14 @@
"lodash-es": "^4.17.21", "lodash-es": "^4.17.21",
"mem-fs": "^2.2.1", "mem-fs": "^2.2.1",
"mem-fs-editor": "^9.5.0", "mem-fs-editor": "^9.5.0",
"ngrok": "^5.0.0-beta.2",
"node-fetch": "^3.2.10", "node-fetch": "^3.2.10",
"open": "^8.4.0", "open": "^8.4.0",
"plugin-error": "^2.0.0", "plugin-error": "^2.0.0",
"prompts": "^2.4.2", "prompts": "^2.4.2",
"sanitize-html": "^2.7.1", "sanitize-html": "^2.7.1",
"sass": "^1.50.1" "sass": "^1.50.1",
"ws": "^8.13.0"
}, },
"devDependencies": { "devDependencies": {
"@babel/preset-react": "^7.18.6", "@babel/preset-react": "^7.18.6",
@@ -56,13 +59,16 @@
"rollup-plugin-copy": "^3.4.0", "rollup-plugin-copy": "^3.4.0",
"rollup-plugin-jsx": "^1.0.3", "rollup-plugin-jsx": "^1.0.3",
"rollup-plugin-terser": "^7.0.2", "rollup-plugin-terser": "^7.0.2",
"socket.io": "^4.6.2",
"styled-components": "^5.3.5" "styled-components": "^5.3.5"
}, },
"bin": { "bin": {
"component-dev": "./server.js", "component-dev": "./server.js",
"component-build": "./build.js" "component-build": "./build.js",
"component-info": "./debug.js"
}, },
"files": [ "files": [
"env.js",
"helpers.js", "helpers.js",
"debug.js", "debug.js",
"layouts/**/*.hbs", "layouts/**/*.hbs",
+6 -3
View File
@@ -18,8 +18,8 @@ export async function buildHubspotEmail(blockName) {
}); });
} }
export async function createDistFolder(blockName) { export async function createDistFolder(blockName, projectPath = '') {
const distPath = path.join('exports', 'hubspot', `${blockName}.module`); const distPath = path.join(projectPath, 'exports', 'hubspot', `${blockName}.module`);
await mkdir(distPath, {recursive: true}) await mkdir(distPath, {recursive: true})
return distPath; return distPath;
@@ -248,9 +248,11 @@ export async function buildHubspotJSONFiles(distPath, metaData) {
export function handlebarsToHubl(handlebars) { export function handlebarsToHubl(handlebars) {
handlebars = handlebars.replace(/{{ else }}/g, '{% else %}');
handlebars = handlebars.replace(/{{else}}/g, '{% else %}');
handlebars = handlebars.replace(/{{#if /g, '{% if module.'); handlebars = handlebars.replace(/{{#if /g, '{% if module.');
handlebars = handlebars.replace(/{{\/if}}/g, '{% endif %}'); handlebars = handlebars.replace(/{{\/if}}/g, '{% endif %}');
handlebars = handlebars.replace(/{{#each /g, '{% for module.'); handlebars = handlebars.replace(/{{#each /g, '{% for item in module.');
handlebars = handlebars.replace(/{{\/each}}/g, '{% endfor %}'); handlebars = handlebars.replace(/{{\/each}}/g, '{% endfor %}');
handlebars = handlebars.replace(/{{base_url}}/g, ''); handlebars = handlebars.replace(/{{base_url}}/g, '');
handlebars = handlebars.replace(/{esc_attr /g, '{'); handlebars = handlebars.replace(/{esc_attr /g, '{');
@@ -262,6 +264,7 @@ export function handlebarsToHubl(handlebars) {
handlebars = handlebars.replace(/}}}/g, '}}'); handlebars = handlebars.replace(/}}}/g, '}}');
handlebars = handlebars.replace(/{{/g, '{{module.'); handlebars = handlebars.replace(/{{/g, '{{module.');
handlebars = handlebars.replace(/{{module. /g, '{{ module.'); handlebars = handlebars.replace(/{{module. /g, '{{ module.');
handlebars = handlebars.replace(/.url/g, '.src');
return handlebars; return handlebars;
} }
+1 -1
View File
@@ -5,7 +5,7 @@ import {buildHubspotJSONFiles, createDistFolder, handlebarsToHubl,} from "./hubs
export async function buildHubspotPage(blockName) { export async function buildHubspotPage(blockName) {
const {modulesPath, projectPath} = getConfigs(); const {modulesPath, projectPath} = getConfigs();
const distPath = await createDistFolder(blockName); const distPath = await createDistFolder(blockName, projectPath);
const srcPath = path.join(projectPath, 'src'); const srcPath = path.join(projectPath, 'src');
+98 -80
View File
@@ -9,125 +9,143 @@ use LightnCandy\LightnCandy;
use Brick\VarExporter\VarExporter; use Brick\VarExporter\VarExporter;
trait Custom_Handlebars { trait Custom_Handlebars {
public array $custom_handlebars = []; public array $custom_handlebars = [];
public function register_default_handlebar_helpers() { public function register_default_handlebar_helpers(): void {
$this->add_handlebar( 'esc_url', function ( $context ) { $this->add_handlebar( 'esc_url', function ( $context ) {
if ( function_exists( 'esc_url' ) ) { if ( function_exists( 'esc_url' ) ) {
return esc_url( $context ); return esc_url( $context );
} }
return $context; return $context;
} ); } );
$this->add_handlebar( 'esc_attr', function ( $context ) { $this->add_handlebar( 'esc_attr', function ( $context ) {
if ( function_exists( 'esc_attr' ) ) { if ( function_exists( 'esc_attr' ) ) {
return esc_attr( $context ); return esc_attr( $context );
} }
return $context; return $context;
} ); } );
$this->add_handlebar( 'esc_html', function ( $context ) { $this->add_handlebar( 'esc_html', function ( $context ) {
if ( function_exists( 'esc_html' ) ) { if ( function_exists( 'esc_html' ) ) {
return esc_html( $context ); return esc_html( $context );
} }
return $context; return $context;
} ); } );
$this->add_handlebar( 'safe_html', function ( $context ) { $this->add_handlebar( 'safe_html', function ( $context ) {
if ( function_exists( 'wp_kses_post' ) ) { if ( function_exists( 'wp_kses_post' ) ) {
return wp_kses_post( $context ); return wp_kses_post( $context );
} }
return $context; return $context;
} ); } );
} }
public function add_handlebar( $key, $func ) { public function add_handlebar( $key, $func ): void {
$this->custom_handlebars[ $key ] = $func; $this->custom_handlebars[ $key ] = $func;
} }
} }
class Component_Builder { class Component_Builder {
use Custom_Handlebars; use Custom_Handlebars;
public string $component_name = ''; public string $component_name = '';
public string $module_path = ''; public string $module_path = '';
public string $project_path = ''; public string $project_path = '';
private string $dist_path = '';
function __construct( $component_name, $module_path, $project_path ) { function __construct( $args = [] ) {
$this->module_path = $module_path; if ( ! isset( $args['backPath'] ) || ! isset( $args['projectPath'] ) || ! isset( $args['blockName'] ) || ! isset( $args['platform'] ) ) {
$this->project_path = $project_path; throw new \Exception( 'Error: Missing arguments. Make sure all parameter passed.' );
$this->component_name = $component_name; }
$this->register_default_handlebar_helpers();
}
function build(): void { $this->module_path = $args['backPath'];
$root_path = __DIR__ . '/' . $this->module_path . '/../../' . $this->project_path; $this->project_path = $args['projectPath'];
$this->component_name = $args['blockName'];
$this->buildTemplatePhpFile( $root_path ); $this->dist_path = __DIR__ . '/' . $this->module_path . '/../../' . $this->project_path . '/exports' . '/' . $args['platform'];
} $this->register_default_handlebar_helpers();
private function buildTemplatePhpFile( $root_path ) { $this->add_handlebar( 'base_url', function ( $context ) {
$file_name = $this->get_handlebars_template( "$root_path/src/$this->component_name.template.hbs" ); $path = join( '/', [ 'blocks', $this->block_project, $this->block_name, 'templates' ] );
return plugins_url( $path . '/', 'axeweb-blocks-library/axeweb-blocks-library.php' );
} );
}
$output_folder = $root_path . '/exports/wordpress/templates'; function build(): void {
rename( $file_name, "$output_folder/$this->component_name.template.php" ); $root_path = __DIR__ . '/' . $this->module_path . '/../../' . $this->project_path;
}
private function get_handlebars_template( $path = '' ): string { $this->buildTemplatePhpFile( $root_path );
$template = file_get_contents( $path ); }
$phpStr = LightnCandy::compile( $template,
[
'flags' => Flags::FLAG_NOESCAPE | Flags::FLAG_PARENT | Flags::FLAG_SPVARS | Flags::FLAG_ELSE | Flags::FLAG_JSLENGTH | Flags::FLAG_JSTRUE,
'helpers' => $this->custom_handlebars ?? [],
]
);
/** private function buildTemplatePhpFile( $root_path ): void {
* NOTE: $file_name = $this->get_handlebars_template( "$root_path/src/$this->component_name.template.hbs" );
* PHP 8.0.0 has problems with the LightCandy lib.
* If you're running the exact php8.0.0 version, try to downgrade to LightCandy@1.2.5.
*/
return self::create_cache_file( $path, $phpStr ); $output_folder = $this->dist_path . '/templates';
} rename( $file_name, "$output_folder/$this->component_name.template.php" );
}
private static function create_cache_file( string $file_path, string $content ): string { private function get_handlebars_template( $path = '' ): string {
$file_path_parts = explode( ".", $file_path ); $template = file_get_contents( $path );
array_pop( $file_path_parts ); // remove ".hbs" format. $phpStr = LightnCandy::compile( $template,
$file_path_parts[] = 'php'; [
$file_path = join( '.', $file_path_parts ); 'flags' => Flags::FLAG_NOESCAPE | Flags::FLAG_PARENT | Flags::FLAG_SPVARS | Flags::FLAG_ELSE | Flags::FLAG_JSLENGTH | Flags::FLAG_JSTRUE | Flags::FLAG_THIS,
'helpers' => $this->custom_handlebars ?? [],
]
);
$comment = " /**
* NOTE:
* PHP 8.0.0 has problems with the LightCandy lib.
* If you're running the exact php8.0.0 version, try to downgrade to LightCandy@1.2.5.
*/
return self::create_cache_file( $path, $phpStr );
}
private static function create_cache_file( string $file_path, string $content ): string {
$file_path_parts = explode( ".", $file_path );
array_pop( $file_path_parts ); // remove ".hbs" format.
$file_path_parts[] = 'php';
$file_path = join( '.', $file_path_parts );
$comment = "
/** /**
* FILE INFO: * FILE INFO:
* This file was generated by LightCandy::compile function. * This file was generated by LightCandy::compile function.
* The original source is the .HBS(handlebars) file that is located next to this generated PHP file. * The original source is the .HBS(handlebars) file that is located next to this generated PHP file.
*
* Compiled at " . date( 'Y-m-d h:i:s' ) . "
*/ */
"; ";
$t = file_put_contents( $file_path, '<?php ' . $comment . $content . ' ?>' ); $t = file_put_contents( $file_path, '<?php ' . $comment . $content . ' ?>' );
if ( $t === false ) { if ( $t === false ) {
die( "Error: Can't generate HBS template to PHP file. Cache folder is not accessible." ); throw new \Exception( "Error: Can't generate HBS template to PHP file. Cache folder is not accessible." );
} }
return $file_path; return $file_path;
} }
} }
function build( $args = [] ) { /**
( new Component_Builder( $args['blockName'], $args['backPath'], $args['projectPath'] ) )->build(); * Functions below will be triggered by JavaScript (index.js).
*/
function build( $args = [] ): void {
( new Component_Builder( $args ) )->build();
} }
/** /**
* @throws ExportException * @throws ExportException
*/ */
function jsonToPhp( $args = [] ): ?string { function jsonToPhp( $args = [] ): ?string {
$json = $args['json'] ?? []; $json = $args['json'] ?? [];
return VarExporter::export( $json ); return VarExporter::export( $json );
} }
@@ -2,48 +2,54 @@
namespace AXEWEB_Blocks\Blocks\<%= ownerClass %>\<%= blockClassModel %>; namespace AXEWEB_Blocks\Blocks\<%= ownerClass %>\<%= blockClassModel %>;
class <%= blockClassModel %>_Component { class <%= blockClassModel %>_Component <% if (isComponentManager || isElementor) { %>extends \Core\Component <% } %>{
const VERSION = '<%= version %>';
public $block_project = '<%= ownerFilename %>';
public $block_name = '<%= blockFilename %>';
public $hook_prefix = 'axeweb_blocks/<%= ownerFilename %>/<%= blockFilename %>';
public function __construct() { <% if (!isComponentManager && !isElementor) { %>public function __construct() {
parent::__construct();
// add_action( 'wp_enqueue_scripts', [ $this, 'register_assets' ] ); // add_action( 'wp_enqueue_scripts', [ $this, 'register_assets' ] );
add_action( 'after_setup_theme', [ $this, 'register_assets' ] ); add_action( 'after_setup_theme', [ $this, 'register_assets' ] );
} }
function register_assets(): void { <% } %>function register_assets(): void {
// $version = get_plugin_data( __DIR__ . "/../../scytale-custom-blocks.php" )['Version']; // In Plugins $base_path = plugin_dir_url( __FILE__ ); // In Plugins
$version = \Core\Global_Functions::get_current_version_number(); // In Theme // $base_path = get_template_directory_uri() . '/components/partials/<%= blockFilename %>/'; // In Theme
// $base_path = plugin_dir_url( __FILE__ ); // In Plugins $style_deps = apply_filters( 'axeweb_blocks/<%= ownerFilename %>/<%= blockFilename %>::style_deps', [ 'assets-style' ] );
$base_path = get_template_directory_uri() . '/components/partials/<%= blockFilename %>/'; wp_register_style( 'block-<%= blockFilename %>', $base_path . 'templates/styles/<%= blockFilename %>.min.css', $style_deps, self::VERSION );
wp_register_style( '<%= blockFilename %>', $script_deps = apply_filters( 'axeweb_blocks/<%= ownerFilename %>/<%= blockFilename %>::script_deps', [ 'assets-script' ] );
$base_path . 'templates/styles/<%= blockFilename %>.min.css', wp_register_script( 'block-<%= blockFilename %>', $base_path . 'templates/scripts/<%= blockFilename %>.min.js', $script_deps, self::VERSION, true );<% if (!isElementor) { %>
[ 'style-wp' ],
$version
);
wp_enqueue_style( '<%= blockFilename %>' );
wp_register_script( 'script-<%= blockFilename %>', if ( ! is_admin() ) {
$base_path . 'templates/scripts/<%= blockFilename %>.min.js', wp_enqueue_style( 'block-<%= blockFilename %>' );
[ 'jquery', 'swiper' ], wp_enqueue_script( 'block-<%= blockFilename %>' );
$version, }<% } %>
true
);
wp_enqueue_script( 'script-<%= blockFilename %>' );
} }
public function render( $args = [] ): void { public function get_content( $args = [] ): string {
$args = array_merge( [], Helpers\<%= blockClassModel %>_Defaults::default_args( $args ), $args); $default_args = apply_filters( 'axeweb_blocks/<%= ownerFilename %>/<%= blockFilename %>::default_args', [] ); // Not really practical.
$args = apply_filters( 'axeweb_blocks/<%= ownerFilename %>/<%= blockFilename %>::prepare_args', array_merge( $default_args, $args ) );
$output = ( include( __DIR__ . '/templates/<%= blockFilename %>.template.php' ) )( $args, self::class ); $output = ( include( __DIR__ . '/templates/<%= blockFilename %>.template.php' ) )( $args, self::class );
echo apply_filters( 'the_content', wpautop( $output ) ); return apply_filters( 'axeweb_blocks/<%= ownerFilename %>/<%= blockFilename %>::content', $output );
}<% if (isElementor) { %>
function register_custom_logic(): void {
add_action( 'elementor/widgets/widgets_registered', [ $this, 'register_elementor_widget' ] );
} }
<% if (isElementor) { %>function register_elementor_widget( $widgets_manager ): void { function register_elementor_widget( $widgets_manager ): void {
require_once "helpers/<%= blockClassModel %>_Elementor_Widget.php"; require_once "helpers/<%= blockClassModel %>_Elementor_Widget.php";
$widgets_manager->register_widget_type( new Helpers\<%= blockClassModel %>_Elementor_Widget() ); $widgets_manager->register_widget_type( new Helpers\<%= blockClassModel %>_Elementor_Widget() );
}<% } %> }<% } %>
} }
// ( new <%= blockClassModel %>_Component() ); // Initialization <% if (isComponentManager) { %><%= blockClassModel %>_Component::get_instance();<% } else {
%>new <%= blockClassModel %>_Component();<% } %>
@@ -3,39 +3,33 @@
namespace AXEWEB_Blocks\Blocks\<%= ownerClass %>\<%= blockClassModel %>; namespace AXEWEB_Blocks\Blocks\<%= ownerClass %>\<%= blockClassModel %>;
class <%= blockClassModel %>_Component extends \Core\Component { class <%= blockClassModel %>_Component extends \Core\Component {
const VERSION = '<%= version %>';
public $block_project = '<%= ownerFilename %>';
public $block_name = '<%= blockFilename %>';
public $hook_prefix = 'axeweb_blocks/<%= ownerFilename %>/<%= blockFilename %>';
public function get_content( $args = [] ): string { public function get_content( $args = [] ): string {
$default_args = apply_filters( 'axeweb_blocks/<%= ownerFilename %>/<%= blockFilename %>::default_args', [] ); // Not really practical. $default_args = apply_filters( 'axeweb_blocks/<%= ownerFilename %>/<%= blockFilename %>::default_args', [] ); // Not really practical.
$args = apply_filters( 'axeweb_blocks/<%= ownerFilename %>/<%= blockFilename %>::prepare_args', array_merge( $default_args, $args ) ); $args = apply_filters( 'axeweb_blocks/<%= ownerFilename %>/<%= blockFilename %>::prepare_args', array_merge( $default_args, $args ) );
$output = ( include( __DIR__ . '/templates/<%= blockFilename %>.template.php' ) )( $args, self::class ); $output = ( include( __DIR__ . '/templates/<%= blockFilename %>.template.php' ) )( $args, self::class );
return apply_filters( 'axeweb_blocks/<%= ownerFilename %>/<%= blockFilename %>::content', $output ); return apply_filters( 'axeweb_blocks/<%= ownerFilename %>/<%= blockFilename %>::content', $output );
} }
<% if (!include_acf_block && !include_native_gutenberg_block) { %>function register_assets(): void {
<% if (!include_acf_block && !include_native_gutenberg_block) { %>function register_assets(): void {
$version = get_plugin_data( __DIR__ . "/../../scytale-custom-blocks.php" )['Version']; // In Plugins $version = get_plugin_data( __DIR__ . "/../../scytale-custom-blocks.php" )['Version']; // In Plugins
// $version = \Core\Global_Functions::get_current_version_number(); // In Theme // $version = \Core\Global_Functions::get_current_version_number(); // In Theme
// $base_path = get_template_directory_uri() . '/components/partials/<%= blockFilename %>/'; // $base_path = get_template_directory_uri() . '/components/partials/<%= blockFilename %>/';
wp_enqueue_style( 'block-<%= blockFilename %>', plugins_url( 'templates/styles/<%= blockFilename %>.min.css', __FILE__ ), ['assets-style'], get_blocks_version() );<% if (include_script) { %> wp_enqueue_style( 'block-<%= blockFilename %>', plugins_url( 'templates/styles/<%= blockFilename %>.min.css', __FILE__ ), ['assets-style'], self::VERSION );<% if (include_script) { %>
wp_enqueue_script( 'block-<%= blockFilename %>', plugins_url( 'templates/scripts/<%= blockFilename %>.min.js', __FILE__ ), ['assets-script'], get_blocks_version(), true );<% } %> wp_enqueue_script( 'block-<%= blockFilename %>', plugins_url( 'templates/scripts/<%= blockFilename %>.min.js', __FILE__ ), ['assets-script'], self::VERSION, true );<% } %>
wp_enqueue_script( 'script-block-<%= blockFilename %>' ); wp_enqueue_script( 'script-block-<%= blockFilename %>' );
}<% } %> }<% } %>
<% if (include_acf_block) { %> function register_acf_block() {
<% if (include_elementor_widget) { %>function register_custom_logic(): void { $this->register_block( __DIR__ . "/<%= blockFilename %>.block.json", [
add_action( 'elementor/widgets/widgets_registered', [ $this, 'register_elementor_widget' ] ); 'style_assets' => [
}
<% } %><% if (include_elementor_widget) { %> function register_elementor_widget( $widgets_manager ) {
$widgets_manager->register_widget_type( new Helpers\<%= blockClassModel %>_Elementor_Widget() );
}
<% } %><% if (include_acf_block) { %> function register_acf_block() {
$this->register_block( __DIR__ . "/<%= blockFilename %>.block.json", [
'style_assets' => [
[ [
'name' => '<%= blockFilename %>', 'name' => '<%= blockFilename %>',
'url' => plugins_url( 'templates/styles/<%= blockFilename %>.min.css', __FILE__ ), 'url' => plugins_url( 'templates/styles/<%= blockFilename %>.min.css', __FILE__ ),
@@ -47,9 +41,8 @@ class <%= blockClassModel %>_Component extends \Core\Component {
'url' => plugins_url( 'templates/scripts/<%= blockFilename %>.min.js', __FILE__ ), 'url' => plugins_url( 'templates/scripts/<%= blockFilename %>.min.js', __FILE__ ),
] ]
] ]
] ); ] );
} }
<% } %><% if (include_native_gutenberg_block) { %> function register_native_gutenberg_block() { <% } %><% if (include_native_gutenberg_block) { %> function register_native_gutenberg_block() {
register_block_type( __DIR__ . '/templates/gutenberg-block/block.json' );<% if (include_script) { %> register_block_type( __DIR__ . '/templates/gutenberg-block/block.json' );<% if (include_script) { %>
@@ -64,7 +57,6 @@ class <%= blockClassModel %>_Component extends \Core\Component {
); );
} );<% } %> } );<% } %>
}<% } %> }<% } %>
} }
<%= blockClassModel %>_Component::get_instance(); <%= blockClassModel %>_Component::get_instance();
@@ -18,43 +18,29 @@ class <%= blockClassModel %>_Elementor_Widget extends \Elementor\Widget_Base {
} }
protected function _register_controls() { protected function _register_controls() {
$this->start_controls_section( 'section_content', [ 'label' => 'Content' ] ); $block_data = \Core\Block::get_block_data( __DIR__ . '/../<%= blockFilename %>.block.json' );
\Core\Elementor_Block::register_groups( $block_data, $this );
$repeater = new \Elementor\Repeater();
// $repeater->add_control(
// 'video_url', [
// 'label' => 'YouTube URL',
// 'type' => \Elementor\Controls_Manager::URL,
// 'label_block' => true,
// 'condition' => [
// 'type' => 'video',
// ],
// ]
// );
$this->end_controls_section();
} }
function get_style_depends() { function get_style_depends() {
return [ '<%= blockFilename %>' ]; return [ 'block-<%= blockFilename %>' ];
} }
function get_script_depends() { function get_script_depends() {
return [ 'script-<%= blockFilename %>' ]; return [ 'block-<%= blockFilename %>' ];
} }
protected function render() { protected function render() {
$settings = $this->get_settings_for_display(); $settings = $this->get_settings_for_display();
$component = new \AXEWEB_Blocks\Blocks\Scytale\<%= blockClassModel %>\<%= blockClassModel %>_Component(); $component = new \AXEWEB_Blocks\Blocks\<%= ownerClass %>\<%= blockClassModel %>\<%= blockClassModel %>_Component();
$args = self::prepare( $settings ); $args = self::prepare( $settings );
$component->render( $args ); $component->render( $args );
} }
public static function prepare( $args ): array { public static function prepare( $args ): array {
// Prepare $args for render function. // Prepare $args for render function.
return $args; return $args;
} }
} }
+13 -3
View File
@@ -9,10 +9,14 @@ import execPhp from "exec-php";
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename); const __dirname = path.dirname(__filename);
export async function buildWordPress(blockName, isBlock = false, isElementor = false) { export async function buildWordPress(blockName, args = {}) {
const isBlock = args.platform === 'wordpress-acf-block';
const isElementor = args.platform === 'wordpress-elementor';
const isComponentManager = args.platform === 'wordpress-component-manager'
const {modulesPath, projectPath} = getConfigs(); const {modulesPath, projectPath} = getConfigs();
const distPath = path.join(projectPath, 'exports', 'wordpress'); const distPath = path.join(projectPath, 'exports', args.platform);
// await mkdir(distPath, {recursive: true}) // await mkdir(distPath, {recursive: true})
await mkdir(path.join(distPath, 'templates'), {recursive: true}) await mkdir(path.join(distPath, 'templates'), {recursive: true})
@@ -38,6 +42,7 @@ export async function buildWordPress(blockName, isBlock = false, isElementor = f
include_script: true, include_script: true,
include_elementor_widget: isElementor, include_elementor_widget: isElementor,
isElementor, isElementor,
isComponentManager,
}); });
await copyFile(blockFilePath, path.join(distPath, data.blockFilename + '.block.json')); await copyFile(blockFilePath, path.join(distPath, data.blockFilename + '.block.json'));
@@ -46,7 +51,12 @@ export async function buildWordPress(blockName, isBlock = false, isElementor = f
const phpGeneratorPath = path.join(modulesPath, 'platforms', 'php'); const phpGeneratorPath = path.join(modulesPath, 'platforms', 'php');
await execCommand(`cd ${phpGeneratorPath} && composer install`); await execCommand(`cd ${phpGeneratorPath} && composer install`);
await execPHPFile(path.join(phpGeneratorPath, 'build.php'), 'build', {blockName, backPath, projectPath}); await execPHPFile(path.join(phpGeneratorPath, 'build.php'), 'build', {
blockName,
backPath,
projectPath,
platform: args.platform
});
await copyStaticFile( await copyStaticFile(
path.join(projectPath, 'src', 'styles', `${data.blockFilename}.min.css`), path.join(projectPath, 'src', 'styles', `${data.blockFilename}.min.css`),
+111 -30
View File
@@ -1,5 +1,6 @@
#!/usr/bin/env node #!/usr/bin/env node
import {PRODUCTION_REGISTRY_URL} from "./env.js";
import path from 'path'; import path from 'path';
import fetch from "node-fetch"; import fetch from "node-fetch";
import express from 'express'; import express from 'express';
@@ -18,27 +19,39 @@ import open from "open";
import {sanitizeUrl} from "@braintree/sanitize-url"; import {sanitizeUrl} from "@braintree/sanitize-url";
import sanitizeHtml from 'sanitize-html'; import sanitizeHtml from 'sanitize-html';
import {escape} from "lodash-es"; import {escape} from "lodash-es";
import {getBlockConfigs, getConfigs, readJSONFile, zipProject} from "./helpers.js"; import {getBlockData, getBlockConfigs, getConfigs, readJSONFile, zipProject} from "./helpers.js";
import PluginError from 'plugin-error'; import PluginError from 'plugin-error';
import {Server} from "socket.io";
import {createServer} from 'http';
import {authtoken, connect} from "ngrok";
/** /**
* Constants * Constants
*/ */
const PRODUCTION_REGISTRY_URL = 'https://blocks-registery.axe-web.com';
const {isDev, modulesPath, projectPath, developmentBlockName} = getConfigs(); const {isDev, modulesPath, projectPath, developmentBlockName} = getConfigs();
const blocksRegistry = isDev ? 'http://localhost:3020' : PRODUCTION_REGISTRY_URL; const blocksRegistry = isDev ? 'http://localhost:3020' : PRODUCTION_REGISTRY_URL;
const DevToolToken = 'D9lgz0TvzXCnp0xnwVBL109DaAR6Puk6F7YewDhgmP8='; // Temporary token for development purposes.
const dataFiles = prepareListOfDataFiles(await fs.readdir(path.join(projectPath, 'data')));
/**
* State
*/
let port = 3000; // This variable is used in `*.hbs` and it will be updated once BrowserSync is ready.
let previewFrameUrl = `/`; // This variable is used in `*.hbs` and it will be updated once BrowserSync is ready.
let shareUrl = '';
const sessions = [];
/** /**
* Init server * Init server
*/ */
let port = 3000; // This variable is used in `*.hbs` and it will be updated once BrowserSync is ready.
let previewFrameUrl = `http://localhost:${port}`; // This variable is used in `*.hbs` and it will be updated once BrowserSync is ready.
const dataFiles = prepareListOfDataFiles(await fs.readdir(path.join(projectPath, 'data')));
const app = express(); const app = express();
const httpServer = createServer(app);
initSessionsServer(httpServer);
const sass = gulpSass(dartSass); const sass = gulpSass(dartSass);
const hbs = create({ const hbs = create({
@@ -64,9 +77,8 @@ app.set('views', path.join(modulesPath, 'layouts'));
// Routes // Routes
// //
app.get('/', async (req, res) => { app.get('/', (req, res) => {
let jsonFileName = req.query.data ? req.query.data : 'default'; const data = getBlockConfigs({modulesPath, dataFiles});
const data = await getBlockConfigs(jsonFileName, {includeConfigs: true, projectPath, modulesPath, dataFiles});
if (data.error && data.errorMessage) { if (data.error && data.errorMessage) {
return res.send(data.errorMessage); return res.send(data.errorMessage);
} }
@@ -75,29 +87,33 @@ app.get('/', async (req, res) => {
const baseViewUrl = `view/${baseView}`; const baseViewUrl = `view/${baseView}`;
data.helpers = { data.helpers = {
port,
include_partial: (filesPath) => handlebarLayoutsPath(modulesPath, filesPath), include_partial: (filesPath) => handlebarLayoutsPath(modulesPath, filesPath),
baseView, }
previewFrameUrl: `${previewFrameUrl}/${baseViewUrl}`,
data.baseView = baseView;
data.port = `/${baseViewUrl}`;
data.previewFrameUrl = `${previewFrameUrl}/${baseViewUrl}`;
// data.previewFrameUrl = `/${baseViewUrl}`;
data.shareUrl = shareUrl;
if (req.headers.referer) {
// NGROK, public URL
data.shareUrl = undefined; // Link already shared.
data.previewFrameUrl = `/${baseViewUrl}`;
data.publicUrl = true;
} }
res.render('index', data); res.render('index', data);
}); });
app.get('/view/:baseView', async (req, res) => { app.get('/view/:baseView', (req, res) => {
let jsonFileName = req.query.data ? req.query.data : 'default'; const data = {config: getBlockConfigs({modulesPath, dataFiles})};
const data = await getBlockConfigs(jsonFileName, {includeConfigs: true, projectPath, modulesPath, dataFiles});
if (data.error && data.errorMessage) { if (data.error && data.errorMessage) {
return res.send(data.errorMessage); return res.send(data.errorMessage);
} }
const blockName = config.has('blockName') ? config.get('blockName') : developmentBlockName;
data.helpers = { data.helpers = {
include_partial: (filesPath) => handlebarLayoutsPath(modulesPath, filesPath), include_partial: (filesPath) => handlebarLayoutsPath(modulesPath, filesPath),
include_block_template: () => handlebarLayoutsPath(projectPath, 'src', `${blockName}.template`),
section_class: `${blockName}--${jsonFileName}`,
base_url: '/',
} }
if (!!req.query.iframe) { if (!!req.query.iframe) {
@@ -111,7 +127,9 @@ app.get('/view/:baseView', async (req, res) => {
app.get('/publish', async (req, res) => { app.get('/publish', async (req, res) => {
const data = await readJSONFile(path.join(projectPath, `block.json`)); const data = await readJSONFile(path.join(projectPath, `block.json`));
let responseData; let responseData = {
uploadUrl: undefined
};
try { try {
const response = await fetch(`${blocksRegistry}`, { const response = await fetch(`${blocksRegistry}`, {
@@ -132,7 +150,7 @@ app.get('/publish', async (req, res) => {
} }
if (responseData.uploadUrl) { if (responseData.uploadUrl) {
await zipProject(path.join(projectPath, 'src')); await zipProject(path.join(projectPath, 'src'), path.join(projectPath, 'dist.zip'));
const body = await fs.readFile(path.join(projectPath, 'dist.zip')); const body = await fs.readFile(path.join(projectPath, 'dist.zip'));
const response = await fetch(`${responseData.uploadUrl}`, { const response = await fetch(`${responseData.uploadUrl}`, {
method: 'PUT', method: 'PUT',
@@ -158,7 +176,7 @@ app.get('/data', async (req, res) => {
let jsonDataFileName = req.query.name ? req.query.name : 'default'; let jsonDataFileName = req.query.name ? req.query.name : 'default';
const dataFiles = prepareListOfDataFiles(await fs.readdir(path.join(projectPath, 'data'))); const dataFiles = prepareListOfDataFiles(await fs.readdir(path.join(projectPath, 'data')));
const data = await getBlockConfigs(jsonDataFileName, {projectPath, modulesPath, dataFiles}); const data = await getBlockData(jsonDataFileName, {projectPath});
const designPreviewFiles = getListOfDesignPreviewFiles(jsonDataFileName, await fs.readdir(path.join(projectPath, 'design', 'preview'))); const designPreviewFiles = getListOfDesignPreviewFiles(jsonDataFileName, await fs.readdir(path.join(projectPath, 'design', 'preview')));
return res.json({ return res.json({
@@ -176,10 +194,14 @@ app.use(express.static(path.join(projectPath, 'src')));
app.use(express.static(path.join(projectPath, 'design'))); app.use(express.static(path.join(projectPath, 'design')));
app.use(express.static(path.join(modulesPath, 'layouts'))); app.use(express.static(path.join(modulesPath, 'layouts')));
// Custom Middleware
app.use(setHeaders);
// Setup Gulp // Setup Gulp
await buildAssetFiles(); await buildAssetFiles();
// BrowserSync // BrowserSync
shareUrl = await getShareableUrl();
const bsOptions = await startBrowserSync(); const bsOptions = await startBrowserSync();
port = bsOptions.port; port = bsOptions.port;
previewFrameUrl = bsOptions.previewFrameUrl; previewFrameUrl = bsOptions.previewFrameUrl;
@@ -210,7 +232,7 @@ function getListOfDesignPreviewFiles(jsonDataFileName, previewFiles) {
function startBrowserSync() { function startBrowserSync() {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const listener = app.listen(0, async () => { const listener = httpServer.listen(0, async () => {
const PORT = listener.address().port; const PORT = listener.address().port;
console.log(`The web server has started on port ${PORT}`); console.log(`The web server has started on port ${PORT}`);
@@ -228,14 +250,22 @@ function startBrowserSync() {
return cb(); return cb();
}])); }]));
bs.watch("src/**/*.hbs", function (event, file) { bs.watch(path.join(projectPath, "src/**/*.hbs"), function () {
browserSyncReload(bs, '', 'Template File Change: ' + file) return syncTemplate(sessions);
}); });
bs.init({ const args = {
proxy: `http://localhost:${PORT}`, proxy: `http://localhost:${PORT}`,
open: false open: false
}, (err, bs) => { };
if (shareUrl) {
args.socket = {
domain: shareUrl
};
}
bs.init(args, (err, bs) => {
if (err) { if (err) {
return reject(err); return reject(err);
} }
@@ -290,8 +320,8 @@ function buildScriptFiles(done) {
}) })
.pipe(gulp.src(path.join(projectPath, 'vendor/*.js'))) .pipe(gulp.src(path.join(projectPath, 'vendor/*.js')))
// .pipe(gulp.dest('src/')) // .pipe(gulp.dest('src/'))
.pipe(uglify())
.pipe(rename({extname: '.min.js'})) .pipe(rename({extname: '.min.js'}))
.pipe(uglify())
.pipe(sourcemaps.write('.')) .pipe(sourcemaps.write('.'))
.pipe(gulp.dest(path.posix.join(projectPath, 'src'))); .pipe(gulp.dest(path.posix.join(projectPath, 'src')));
} }
@@ -317,7 +347,7 @@ function buildAssetFiles() {
// Run first build. // Run first build.
return new Promise((resolve) => { return new Promise((resolve) => {
gulp.series('build-script-files', 'build-styling-files', function (cb) { gulp.series('build-script-files', 'build-styling-files', function () {
resolve(); resolve();
})(); })();
}); });
@@ -358,3 +388,54 @@ function handlebarLayoutsPath() {
return path.join(...arguments) return path.join(...arguments)
.replace(/\\/g, '/'); // Windows path issue. Fix all "\" for Handlebars. .replace(/\\/g, '/'); // Windows path issue. Fix all "\" for Handlebars.
} }
function initSessionsServer(httpServer) {
const io = new Server(httpServer);
io.on('connection', async (socket) => {
sessions.push(socket);
await syncTemplate(sessions);
});
return httpServer;
}
function setHeaders(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
next();
}
async function syncTemplate(sessions = []) {
const blockName = config.has('blockName') ? config.get('blockName') : developmentBlockName;
const hbsTemplate = await fs.readFile(handlebarLayoutsPath(projectPath, 'src', `${blockName}.template.hbs`), 'utf8');
sessions.forEach(socket => {
socket.emit('templateUpdate', {template: hbsTemplate});
});
}
async function getShareableUrl() {
let domain = PRODUCTION_REGISTRY_URL;
let data = {}
try {
const response = await fetch(`${domain}/dev-tool/?devToolToken=${DevToolToken}`);
data = await response.json();
} catch (e) {
console.log('Error:', `Can't load data from DevTool endpoint: ${domain}`);
}
if (data.statusCode !== 200) {
console.log('Reply from DevTool endpoint:', data.message);
return null;
}
let url;
try {
await authtoken(data.ngrokApiToken);
url = await connect(port);
} catch (e) {
console.log('Error:', `Can't connect to ngrok, probably wrong token.`);
}
return url;
}
+10
View File
@@ -0,0 +1,10 @@
/**
* FUTURE TESTS.
*
* # ENV
* In `blocks-builder` service, we update MODULE_PATH and PROJECT_PATH environment variables before we run platform
* bundle build process. Actually before we call buildExportFiles().
*
* We have to make sure that this logic is working properly and stable.
*
*/