Browse Source

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
test-gpt-generated
Roman Axelrod 3 years ago
parent
commit
6d1ab34b2b
  1. 19
      helpers.js
  2. 4
      layouts/alignfull.hbs
  3. 4
      layouts/container.hbs
  4. 2
      layouts/partials/head.hbs
  5. 4
      layouts/partials/scripts.hbs
  6. 123
      layouts/scripts/dist/frame-index.min.js
  7. 2
      layouts/scripts/dist/frame-index.min.js.map
  8. 24
      layouts/scripts/dist/index.min.js
  9. 2
      layouts/scripts/dist/index.min.js.map
  10. 123
      layouts/scripts/frame/frame.js
  11. 26
      layouts/scripts/toolbar/data-options/DataOptions.jsx
  12. 6
      layouts/scroll.hbs
  13. 194
      package-lock.json
  14. 10
      package.json
  15. 11
      platforms/php/build.php
  16. 7
      platforms/wordpress/templates/Template_Basic_Component.php
  17. 13
      platforms/wordpress/templates/Template_Component.php
  18. 73
      server.js

19
helpers.js

@ -43,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) { return data;
Object.assign(data, { }
config: Object.assign(JSON.parse(JSON.stringify(config)), // The entire config object.
export function getBlockConfigs(args = {modulesPath: '', dataFiles: []}) {
return Object.assign(JSON.parse(JSON.stringify(config)), // The entire config object.
{ {
projectDir: modulesPath, activeDataFile: jsonFileName, dataFiles: dataFiles.map((name) => { projectDir: args.modulesPath, dataFiles: args.dataFiles.map((name) => {
return { return {
name, active: jsonFileName === name, name,
}; };
}), remToPx: config.has('remToPx') ? config.get('remToPx') : 16, }), remToPx: config.has('remToPx') ? config.get('remToPx') : 16,
})
}); });
} }
return data;
}
export function getBlockName(name = '') { export function getBlockName(name = '') {
if (name.startsWith('@')) { if (name.startsWith('@')) {
name = name.substring(1); name = name.substring(1);

4
layouts/alignfull.hbs

@ -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") }}

4
layouts/container.hbs

@ -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">
{{> (include_block_template) }} <div id="hbs-container"></div>
</div> </div>
</main>
{{> (include_partial "layouts/partials/scripts") }} {{> (include_partial "layouts/partials/scripts") }}

2
layouts/partials/head.hbs

@ -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>

4
layouts/partials/scripts.hbs

@ -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}}

123
layouts/scripts/dist/frame-index.min.js

@ -1,8 +1,16 @@
window.initBlock = initBlock; window.initBlock = initBlock;
let template;
let data = {};
let reload;
// Blocks Initialization. // Blocks Initialization.
function initBlock(blockName = '', selector = '', cb) { function initBlock(blockName = '', selector = '', cb) {
reload = function () {
document.querySelectorAll(selector).forEach((el) => cb(el)); document.querySelectorAll(selector).forEach((el) => cb(el));
};
reload();
} }
// Scrollbars / Frame resizes notifications. // Scrollbars / Frame resizes notifications.
@ -19,7 +27,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 (height === updatedHeight) { if (height === updatedHeight) {
@ -32,7 +40,118 @@ 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 '/';
});
target.innerHTML = template(jsonData);
if (reload) {
reload();
}
}
//# sourceMappingURL=frame-index.min.js.map //# sourceMappingURL=frame-index.min.js.map

2
layouts/scripts/dist/frame-index.min.js.map

File diff suppressed because one or more lines are too long

24
layouts/scripts/dist/index.min.js

@ -9893,8 +9893,7 @@ function DataOptions(props = {}) {
const updateState = update => setState(Object.assign({}, state, update)); const updateState = update => setState(Object.assign({}, state, update));
const [sidebarOpen, setSidebarOpen] = react.exports.useState(false); const [sidebarOpen, setSidebarOpen] = react.exports.useState(false);
react.exports.useEffect(async () => { react.exports.useEffect(async () => {
const data = await fetchDataOptions(state.dataName); await syncDataOptions(state.dataName);
updateState(data);
}, []); }, []);
const handleCloseSidebarEscEvent = react.exports.useCallback(e => { const handleCloseSidebarEscEvent = react.exports.useCallback(e => {
if (isEscHit(e)) { if (isEscHit(e)) {
@ -9967,14 +9966,7 @@ function DataOptions(props = {}) {
} }
async function changeDataOption(e) { async function changeDataOption(e) {
const dataName = e.target.value; const dataName = e.target.value;
const previewFrameUrl = new URL(window.devTool.previewFrameUrl); await syncDataOptions(dataName);
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') {
const queryParameters = new URLSearchParams({ const queryParameters = new URLSearchParams({
@ -10002,6 +9994,18 @@ 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);
const newState = Object.assign({}, dataOptions, {
dataName
});
updateState(newState);
}
function updateIframe(dataOptions) {
const previewIframe = props.rootAttributes.previewFrame;
previewIframe.contentWindow.postMessage('dataUpdate:' + JSON.stringify(dataOptions.data || {}), '*');
}
} }
function copyToClipboard(e, context) { function copyToClipboard(e, context) {
e.stopPropagation(); e.stopPropagation();

2
layouts/scripts/dist/index.min.js.map

File diff suppressed because one or more lines are too long

123
layouts/scripts/frame/frame.js

@ -2,11 +2,19 @@
window.initBlock = initBlock; window.initBlock = initBlock;
let template;
let data = {};
let reload;
// Blocks Initialization. // Blocks Initialization.
function initBlock(blockName = '', selector = '', cb) { function initBlock(blockName = '', selector = '', cb) {
reload = function () {
document.querySelectorAll(selector).forEach((el) => cb(el)); document.querySelectorAll(selector).forEach((el) => cb(el));
} }
reload();
}
// Scrollbars / Frame resizes notifications. // Scrollbars / Frame resizes notifications.
(function () { (function () {
let height; let height;
@ -22,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) {
@ -43,6 +51,117 @@ 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 '/';
});
target.innerHTML = template(jsonData);
if (reload) {
reload();
}
}

26
layouts/scripts/toolbar/data-options/DataOptions.jsx

@ -20,8 +20,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) => {
@ -98,15 +97,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 +129,19 @@ 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);
const newState = Object.assign({}, dataOptions, {dataName});
updateState(newState);
}
function updateIframe(dataOptions) {
const previewIframe = props.rootAttributes.previewFrame;
previewIframe.contentWindow.postMessage('dataUpdate:' + JSON.stringify(dataOptions.data || {}), '*');
}
} }
function copyToClipboard(e, context) { function copyToClipboard(e, context) {

6
layouts/scroll.hbs

@ -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") }}

194
package-lock.json

@ -32,11 +32,13 @@
"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"
}, },
"bin": { "bin": {
"component-build": "build.js", "component-build": "build.js",
"component-dev": "server.js" "component-dev": "server.js",
"component-info": "debug.js"
}, },
"devDependencies": { "devDependencies": {
"@babel/preset-react": "^7.18.6", "@babel/preset-react": "^7.18.6",
@ -51,7 +53,11 @@
"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"
},
"engines": {
"node": ">=14.17.3"
} }
}, },
"node_modules/@ampproject/remapping": { "node_modules/@ampproject/remapping": {
@ -935,9 +941,12 @@
"integrity": "sha512-XW/Aa8APYr6jSVVA1y/DEIZX0/GMKLEVekNG727R8cs56ahETkRAy/3DR7+fJyh7oUgGwNQaRfXCun0+KbWY7Q==" "integrity": "sha512-XW/Aa8APYr6jSVVA1y/DEIZX0/GMKLEVekNG727R8cs56ahETkRAy/3DR7+fJyh7oUgGwNQaRfXCun0+KbWY7Q=="
}, },
"node_modules/@types/cors": { "node_modules/@types/cors": {
"version": "2.8.12", "version": "2.8.13",
"resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.12.tgz", "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.13.tgz",
"integrity": "sha512-vt+kDhq/M2ayberEtJcIN/hxXy1Pk+59g2FV/ZQceeaTyCtCucjL2Q7FXlFjtWn4n15KCr1NE2lNNFhp0lEThw==" "integrity": "sha512-RG8AStHlUiV5ysZQKq97copd2UmVYw3/pRMLefISZ3S1hK104Cwm7iLQ3fTKx+lsUH2CE8FlLaYeEA2LSeqYUA==",
"dependencies": {
"@types/node": "*"
}
}, },
"node_modules/@types/estree": { "node_modules/@types/estree": {
"version": "1.0.0", "version": "1.0.0",
@ -2901,9 +2910,9 @@
} }
}, },
"node_modules/engine.io": { "node_modules/engine.io": {
"version": "6.2.1", "version": "6.4.2",
"resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.2.1.tgz", "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.4.2.tgz",
"integrity": "sha512-ECceEFcAaNRybd3lsGQKas3ZlMVjN3cyWwMP25D2i0zWfyiytVbTpRPa34qrr+FHddtpBVOmq4H/DCv1O0lZRA==", "integrity": "sha512-FKn/3oMiJjrOEOeUub2WCox6JhxBXq/Zn3fZOMCBxKnNYtsdKjxhl7yR3fZhM9PV+rdE75SU5SYMc+2PGzo+Tg==",
"dependencies": { "dependencies": {
"@types/cookie": "^0.4.1", "@types/cookie": "^0.4.1",
"@types/cors": "^2.8.12", "@types/cors": "^2.8.12",
@ -2914,7 +2923,7 @@
"cors": "~2.8.5", "cors": "~2.8.5",
"debug": "~4.3.1", "debug": "~4.3.1",
"engine.io-parser": "~5.0.3", "engine.io-parser": "~5.0.3",
"ws": "~8.2.3" "ws": "~8.11.0"
}, },
"engines": { "engines": {
"node": ">=10.0.0" "node": ">=10.0.0"
@ -2932,6 +2941,26 @@
"xmlhttprequest-ssl": "~2.0.0" "xmlhttprequest-ssl": "~2.0.0"
} }
}, },
"node_modules/engine.io-client/node_modules/ws": {
"version": "8.2.3",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.2.3.tgz",
"integrity": "sha512-wBuoj1BDpC6ZQ1B7DWQBYVLphPWkm8i9Y0/3YdHjHKHiohOJ1ws+3OccDWtH+PoC9DZD5WOTrJvNbWvjS6JWaA==",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": "^5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/engine.io-parser": { "node_modules/engine.io-parser": {
"version": "5.0.4", "version": "5.0.4",
"resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.0.4.tgz", "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.0.4.tgz",
@ -2948,6 +2977,26 @@
"node": ">= 0.6" "node": ">= 0.6"
} }
}, },
"node_modules/engine.io/node_modules/ws": {
"version": "8.11.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz",
"integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": "^5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/entities": { "node_modules/entities": {
"version": "2.2.0", "version": "2.2.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz", "resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz",
@ -8781,25 +8830,48 @@
} }
}, },
"node_modules/socket.io": { "node_modules/socket.io": {
"version": "4.5.4", "version": "4.6.2",
"resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.5.4.tgz", "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.6.2.tgz",
"integrity": "sha512-m3GC94iK9MfIEeIBfbhJs5BqFibMtkRk8ZpKwG2QwxV0m/eEhPIV4ara6XCF1LWNAus7z58RodiZlAH71U3EhQ==", "integrity": "sha512-Vp+lSks5k0dewYTfwgPT9UeGGd+ht7sCpB7p0e83VgO4X/AHYWhXITMrNk/pg8syY2bpx23ptClCQuHhqi2BgQ==",
"dependencies": { "dependencies": {
"accepts": "~1.3.4", "accepts": "~1.3.4",
"base64id": "~2.0.0", "base64id": "~2.0.0",
"debug": "~4.3.2", "debug": "~4.3.2",
"engine.io": "~6.2.1", "engine.io": "~6.4.2",
"socket.io-adapter": "~2.4.0", "socket.io-adapter": "~2.5.2",
"socket.io-parser": "~4.2.1" "socket.io-parser": "~4.2.4"
}, },
"engines": { "engines": {
"node": ">=10.0.0" "node": ">=10.0.0"
} }
}, },
"node_modules/socket.io-adapter": { "node_modules/socket.io-adapter": {
"version": "2.4.0", "version": "2.5.2",
"resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.4.0.tgz", "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.2.tgz",
"integrity": "sha512-W4N+o69rkMEGVuk2D/cvca3uYsvGlMwsySWV447y99gUPghxq42BxqLNMndb+a1mm/5/7NeXVQS7RLa2XyXvYg==" "integrity": "sha512-87C3LO/NOMc+eMcpcxUBebGjkpMDkNBS9tf7KJqcDsmL936EChtVva71Dw2q4tQcuVC+hAUy4an2NO/sYXmwRA==",
"dependencies": {
"ws": "~8.11.0"
}
},
"node_modules/socket.io-adapter/node_modules/ws": {
"version": "8.11.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz",
"integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": "^5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}, },
"node_modules/socket.io-client": { "node_modules/socket.io-client": {
"version": "4.5.4", "version": "4.5.4",
@ -8816,9 +8888,9 @@
} }
}, },
"node_modules/socket.io-parser": { "node_modules/socket.io-parser": {
"version": "4.2.1", "version": "4.2.4",
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.1.tgz", "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz",
"integrity": "sha512-V4GrkLy+HeF1F/en3SpUaM+7XxYXpuMUWLGde1kSSh5nQMN4hLrbPIkD+otwh6q9R6NOQBN4AMaOZ2zVjui82g==", "integrity": "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==",
"dependencies": { "dependencies": {
"@socket.io/component-emitter": "~3.1.0", "@socket.io/component-emitter": "~3.1.0",
"debug": "~4.3.1" "debug": "~4.3.1"
@ -10001,15 +10073,15 @@
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="
}, },
"node_modules/ws": { "node_modules/ws": {
"version": "8.2.3", "version": "8.13.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.2.3.tgz", "resolved": "https://registry.npmjs.org/ws/-/ws-8.13.0.tgz",
"integrity": "sha512-wBuoj1BDpC6ZQ1B7DWQBYVLphPWkm8i9Y0/3YdHjHKHiohOJ1ws+3OccDWtH+PoC9DZD5WOTrJvNbWvjS6JWaA==", "integrity": "sha512-x9vcZYTrFPC7aSIbj7sRCYo7L/Xb8Iy+pW0ng0wt2vCJv7M9HOMy0UoN3rr+IFC7hb7vXoqS+P9ktyLLLhO+LA==",
"engines": { "engines": {
"node": ">=10.0.0" "node": ">=10.0.0"
}, },
"peerDependencies": { "peerDependencies": {
"bufferutil": "^4.0.1", "bufferutil": "^4.0.1",
"utf-8-validate": "^5.0.2" "utf-8-validate": ">=5.0.2"
}, },
"peerDependenciesMeta": { "peerDependenciesMeta": {
"bufferutil": { "bufferutil": {
@ -10806,9 +10878,12 @@
"integrity": "sha512-XW/Aa8APYr6jSVVA1y/DEIZX0/GMKLEVekNG727R8cs56ahETkRAy/3DR7+fJyh7oUgGwNQaRfXCun0+KbWY7Q==" "integrity": "sha512-XW/Aa8APYr6jSVVA1y/DEIZX0/GMKLEVekNG727R8cs56ahETkRAy/3DR7+fJyh7oUgGwNQaRfXCun0+KbWY7Q=="
}, },
"@types/cors": { "@types/cors": {
"version": "2.8.12", "version": "2.8.13",
"resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.12.tgz", "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.13.tgz",
"integrity": "sha512-vt+kDhq/M2ayberEtJcIN/hxXy1Pk+59g2FV/ZQceeaTyCtCucjL2Q7FXlFjtWn4n15KCr1NE2lNNFhp0lEThw==" "integrity": "sha512-RG8AStHlUiV5ysZQKq97copd2UmVYw3/pRMLefISZ3S1hK104Cwm7iLQ3fTKx+lsUH2CE8FlLaYeEA2LSeqYUA==",
"requires": {
"@types/node": "*"
}
}, },
"@types/estree": { "@types/estree": {
"version": "1.0.0", "version": "1.0.0",
@ -12328,9 +12403,9 @@
} }
}, },
"engine.io": { "engine.io": {
"version": "6.2.1", "version": "6.4.2",
"resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.2.1.tgz", "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.4.2.tgz",
"integrity": "sha512-ECceEFcAaNRybd3lsGQKas3ZlMVjN3cyWwMP25D2i0zWfyiytVbTpRPa34qrr+FHddtpBVOmq4H/DCv1O0lZRA==", "integrity": "sha512-FKn/3oMiJjrOEOeUub2WCox6JhxBXq/Zn3fZOMCBxKnNYtsdKjxhl7yR3fZhM9PV+rdE75SU5SYMc+2PGzo+Tg==",
"requires": { "requires": {
"@types/cookie": "^0.4.1", "@types/cookie": "^0.4.1",
"@types/cors": "^2.8.12", "@types/cors": "^2.8.12",
@ -12341,13 +12416,19 @@
"cors": "~2.8.5", "cors": "~2.8.5",
"debug": "~4.3.1", "debug": "~4.3.1",
"engine.io-parser": "~5.0.3", "engine.io-parser": "~5.0.3",
"ws": "~8.2.3" "ws": "~8.11.0"
}, },
"dependencies": { "dependencies": {
"cookie": { "cookie": {
"version": "0.4.2", "version": "0.4.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.2.tgz", "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.2.tgz",
"integrity": "sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==" "integrity": "sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA=="
},
"ws": {
"version": "8.11.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz",
"integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==",
"requires": {}
} }
} }
}, },
@ -12361,6 +12442,14 @@
"engine.io-parser": "~5.0.3", "engine.io-parser": "~5.0.3",
"ws": "~8.2.3", "ws": "~8.2.3",
"xmlhttprequest-ssl": "~2.0.0" "xmlhttprequest-ssl": "~2.0.0"
},
"dependencies": {
"ws": {
"version": "8.2.3",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.2.3.tgz",
"integrity": "sha512-wBuoj1BDpC6ZQ1B7DWQBYVLphPWkm8i9Y0/3YdHjHKHiohOJ1ws+3OccDWtH+PoC9DZD5WOTrJvNbWvjS6JWaA==",
"requires": {}
}
} }
}, },
"engine.io-parser": { "engine.io-parser": {
@ -16913,22 +17002,33 @@
} }
}, },
"socket.io": { "socket.io": {
"version": "4.5.4", "version": "4.6.2",
"resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.5.4.tgz", "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.6.2.tgz",
"integrity": "sha512-m3GC94iK9MfIEeIBfbhJs5BqFibMtkRk8ZpKwG2QwxV0m/eEhPIV4ara6XCF1LWNAus7z58RodiZlAH71U3EhQ==", "integrity": "sha512-Vp+lSks5k0dewYTfwgPT9UeGGd+ht7sCpB7p0e83VgO4X/AHYWhXITMrNk/pg8syY2bpx23ptClCQuHhqi2BgQ==",
"requires": { "requires": {
"accepts": "~1.3.4", "accepts": "~1.3.4",
"base64id": "~2.0.0", "base64id": "~2.0.0",
"debug": "~4.3.2", "debug": "~4.3.2",
"engine.io": "~6.2.1", "engine.io": "~6.4.2",
"socket.io-adapter": "~2.4.0", "socket.io-adapter": "~2.5.2",
"socket.io-parser": "~4.2.1" "socket.io-parser": "~4.2.4"
} }
}, },
"socket.io-adapter": { "socket.io-adapter": {
"version": "2.4.0", "version": "2.5.2",
"resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.4.0.tgz", "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.2.tgz",
"integrity": "sha512-W4N+o69rkMEGVuk2D/cvca3uYsvGlMwsySWV447y99gUPghxq42BxqLNMndb+a1mm/5/7NeXVQS7RLa2XyXvYg==" "integrity": "sha512-87C3LO/NOMc+eMcpcxUBebGjkpMDkNBS9tf7KJqcDsmL936EChtVva71Dw2q4tQcuVC+hAUy4an2NO/sYXmwRA==",
"requires": {
"ws": "~8.11.0"
},
"dependencies": {
"ws": {
"version": "8.11.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz",
"integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==",
"requires": {}
}
}
}, },
"socket.io-client": { "socket.io-client": {
"version": "4.5.4", "version": "4.5.4",
@ -16942,9 +17042,9 @@
} }
}, },
"socket.io-parser": { "socket.io-parser": {
"version": "4.2.1", "version": "4.2.4",
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.1.tgz", "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz",
"integrity": "sha512-V4GrkLy+HeF1F/en3SpUaM+7XxYXpuMUWLGde1kSSh5nQMN4hLrbPIkD+otwh6q9R6NOQBN4AMaOZ2zVjui82g==", "integrity": "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==",
"requires": { "requires": {
"@socket.io/component-emitter": "~3.1.0", "@socket.io/component-emitter": "~3.1.0",
"debug": "~4.3.1" "debug": "~4.3.1"
@ -17847,9 +17947,9 @@
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="
}, },
"ws": { "ws": {
"version": "8.2.3", "version": "8.13.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.2.3.tgz", "resolved": "https://registry.npmjs.org/ws/-/ws-8.13.0.tgz",
"integrity": "sha512-wBuoj1BDpC6ZQ1B7DWQBYVLphPWkm8i9Y0/3YdHjHKHiohOJ1ws+3OccDWtH+PoC9DZD5WOTrJvNbWvjS6JWaA==", "integrity": "sha512-x9vcZYTrFPC7aSIbj7sRCYo7L/Xb8Iy+pW0ng0wt2vCJv7M9HOMy0UoN3rr+IFC7hb7vXoqS+P9ktyLLLhO+LA==",
"requires": {} "requires": {}
}, },
"xmlhttprequest-ssl": { "xmlhttprequest-ssl": {

10
package.json

@ -7,9 +7,9 @@
"url": "https://axe-web.com/" "url": "https://axe-web.com/"
}, },
"scripts": { "scripts": {
"info": "NODE_ENV=development BLOCK_NAME=drinks-slider MODULE_PATH= node debug.js", "info": "NODE_ENV=development BLOCK_NAME=header MODULE_PATH= node debug.js",
"dev": "NODE_ENV=development BLOCK_NAME=drinks-slider MODULE_PATH= node server.js", "dev": "NODE_ENV=development BLOCK_NAME=header MODULE_PATH= node server.js",
"build-platform": "NODE_ENV=development BLOCK_NAME=drinks-slider MODULE_PATH= node ./build.js", "build-platform": "NODE_ENV=development BLOCK_NAME=header MODULE_PATH= node ./build.js",
"dev-dev-tool": "NODE_ENV=development rollup --config rollup.config.js --watch", "dev-dev-tool": "NODE_ENV=development rollup --config rollup.config.js --watch",
"build-dev-tool": "rollup --config rollup.config.js" "build-dev-tool": "rollup --config rollup.config.js"
}, },
@ -42,7 +42,8 @@
"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",
@ -57,6 +58,7 @@
"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": {

11
platforms/php/build.php

@ -59,12 +59,21 @@ class Component_Builder {
private string $dist_path = ''; private string $dist_path = '';
function __construct( $args = [] ) { function __construct( $args = [] ) {
if ( ! isset( $args['backPath'] ) || ! isset( $args['projectPath'] ) || ! isset( $args['blockName'] ) || ! isset( $args['platform'] ) ) {
throw new \Exception( 'Error: Missing arguments. Make sure all parameter passed.' );
}
$this->module_path = $args['backPath']; $this->module_path = $args['backPath'];
$this->project_path = $args['projectPath']; $this->project_path = $args['projectPath'];
$this->component_name = $args['blockName']; $this->component_name = $args['blockName'];
$this->dist_path = __DIR__ . '/' . $this->module_path . '/../../' . $this->project_path . '/exports' . '/' . $args['platform']; $this->dist_path = __DIR__ . '/' . $this->module_path . '/../../' . $this->project_path . '/exports' . '/' . $args['platform'];
$this->register_default_handlebar_helpers(); $this->register_default_handlebar_helpers();
$this->add_handlebar( 'base_url', function ( $context ) {
$path = join( '/', [ 'blocks', $this->block_project, $this->block_name, 'templates' ] );
return plugins_url( $path . '/', 'axeweb-blocks-library/axeweb-blocks-library.php' );
} );
} }
function build(): void { function build(): void {
@ -117,7 +126,7 @@ class Component_Builder {
$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;

7
platforms/wordpress/templates/Template_Basic_Component.php

@ -4,6 +4,9 @@ namespace AXEWEB_Blocks\Blocks\<%= ownerClass %>\<%= blockClassModel %>;
class <%= blockClassModel %>_Component <% if (isComponentManager || isElementor) { %>extends \Core\Component <% } %>{ class <%= blockClassModel %>_Component <% if (isComponentManager || isElementor) { %>extends \Core\Component <% } %>{
const VERSION = '<%= version %>'; const VERSION = '<%= version %>';
public $block_project = '<%= ownerFilename %>';
public $block_name = '<%= blockFilename %>';
public $hook_prefix = 'axeweb_blocks/<%= ownerFilename %>/<%= blockFilename %>';
<% if (!isComponentManager && !isElementor) { %>public function __construct() { <% if (!isComponentManager && !isElementor) { %>public function __construct() {
parent::__construct(); parent::__construct();
@ -44,8 +47,8 @@ class <%= blockClassModel %>_Component <% if (isComponentManager || 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() );
} }<% } %>
<% } %>
} }
<% if (isComponentManager) { %><%= blockClassModel %>_Component::get_instance();<% } else { <% if (isComponentManager) { %><%= blockClassModel %>_Component::get_instance();<% } else {

13
platforms/wordpress/templates/Template_Component.php

@ -4,6 +4,9 @@ namespace AXEWEB_Blocks\Blocks\<%= ownerClass %>\<%= blockClassModel %>;
class <%= blockClassModel %>_Component extends \Core\Component { class <%= blockClassModel %>_Component extends \Core\Component {
const VERSION = '<%= version %>'; 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.
@ -24,15 +27,7 @@ class <%= blockClassModel %>_Component extends \Core\Component {
wp_enqueue_script( 'script-block-<%= blockFilename %>' ); wp_enqueue_script( 'script-block-<%= blockFilename %>' );
}<% } %> }<% } %>
<% if (include_elementor_widget) { %>function register_custom_logic(): void { <% if (include_acf_block) { %> function register_acf_block() {
add_action( 'elementor/widgets/widgets_registered', [ $this, 'register_elementor_widget' ] );
}
<% } %><% 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", [ $this->register_block( __DIR__ . "/<%= blockFilename %>.block.json", [
'style_assets' => [ 'style_assets' => [
[ [

73
server.js

@ -19,8 +19,10 @@ 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';
/** /**
* Constants * Constants
@ -29,15 +31,24 @@ import PluginError from 'plugin-error';
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 dataFiles = prepareListOfDataFiles(await fs.readdir(path.join(projectPath, 'data')));
/** /**
* Init server * State
*/ */
let port = 3000; // This variable is used in `*.hbs` and it will be updated once BrowserSync is ready. 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. 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 sessions = [];
/**
* Init server
*/
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({
@ -63,9 +74,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);
} }
@ -83,20 +93,14 @@ app.get('/', async (req, res) => {
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) {
@ -110,7 +114,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}`, {
@ -157,7 +163,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({
@ -175,6 +181,9 @@ 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();
@ -209,7 +218,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}`);
@ -227,8 +236,8 @@ function startBrowserSync() {
return cb(); return cb();
}])); }]));
bs.watch(path.join(projectPath, "src/**/*.hbs"), function (event, file) { bs.watch(path.join(projectPath, "src/**/*.hbs"), function () {
browserSyncReload(bs, '', 'Template File Change: ' + file) return syncTemplate(sessions);
}); });
bs.init({ bs.init({
@ -316,7 +325,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();
})(); })();
}); });
@ -357,3 +366,27 @@ 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});
});
}

Loading…
Cancel
Save