142 Commits

Author SHA1 Message Date
roman a22a179eff Added nested blocks support (inner_blocks). ACF Only. 2025-05-12 17:28:39 -06:00
roman 95e0cae3ed Merge with latest. 2025-05-11 17:29:57 -06:00
roman 92e4f1ea2d version upgrade 2025-03-29 20:27:56 -06:00
roman 0062bb4506 1.0.33 2025-03-29 20:21:32 -06:00
roman 5dd326be0f Pass $args parameter to content hook. 2025-03-29 20:20:51 -06:00
roman 00efc1677d 1.0.33 2024-12-08 18:44:15 -07:00
roman 38c49a64ad Make sure all images are updated on Global Blocks. 2024-12-08 18:43:39 -07:00
roman 044f721d34 Updated logic of mobile/tablet sizes & scrollbars. 2024-06-23 20:24:57 -06:00
roman 74f4b11ad6 Updated logic of mobile/tablet sizes & scrollbars. 2024-06-23 20:21:44 -06:00
roman 1b2cf2697f Updated logic of mobile/tablet sizes & scrollbars. 2024-06-23 20:18:16 -06:00
roman bcad45d1e8 Temporary disabled ngrok (share live URL option) 2024-06-23 01:26:14 -06:00
roman 3daa725309 Updated logic of Elementor's build. Support Elementor_Widget Trait. 2024-05-24 15:34:12 -06:00
roman 438619c4d9 Added axeweb-block classNames to blocks in Elementor 2024-05-21 12:50:58 -06:00
roman 1b2795fa40 Merge pull request 'Update path to static files of ACF block.' (#13) from wordpress-build into master
Reviewed-on: AXE-WEB/block-dev-tool#13
2024-05-21 09:44:13 +00:00
roman 31786581bd Update path to static files of ACF block. 2024-05-21 03:38:18 -06:00
roman e25f1aa4f1 Merge pull request '1.0.32' (#12) from wordpress-build into master
Reviewed-on: AXE-WEB/block-dev-tool#12
2024-05-21 09:05:32 +00:00
roman f3cd0e5876 1.0.32 2024-05-21 03:03:24 -06:00
roman d6b0ff866b Merge pull request 'Updated the bundle of WordPress block.' (#11) from wordpress-build into master
Reviewed-on: AXE-WEB/block-dev-tool#11
2024-05-21 09:02:22 +00:00
roman 4a7ddf7d29 Updated the bundle of WordPress block. 2024-05-21 03:01:46 -06:00
roman 03a8833f46 Merge pull request 'fix windows archive issue' (#10) from dev into master
Reviewed-on: AXE-WEB/block-dev-tool#10
2024-04-15 12:20:32 +00:00
roman bf8f0e857d fix windows archive issue 2024-04-15 00:07:18 +03:00
roman b76f83d4fa Merge pull request 'dev' (#9) from dev into master
Reviewed-on: AXE-WEB/block-dev-tool#9
2024-01-06 16:16:40 +00:00
roman 977ec0003c Merge branch 'master' into dev
# Conflicts:
#	package-lock.json
#	package.json
2024-01-06 18:15:57 +02:00
roman 0e91c42e89 Update $base_url parameter since the block location changed. 2023-12-15 12:33:26 +02:00
roman 0a4fd3608f Updated path of assets files. 2023-11-13 01:01:35 +02:00
roman 11152dda87 1.0.28 2023-11-06 15:51:40 +02:00
roman 246c9ddd35 Fix capitalization function 2023-11-06 15:51:26 +02:00
roman 164ef7433a 1.0.30 2023-08-27 17:29:05 +03:00
roman a6decb9cfb Remove Block Name from Sync action. 2023-08-27 17:28:54 +03:00
roman 9c85a89a8f Fix issue of blocks folder 2023-08-23 16:55:53 +03:00
roman 58ed3de9dc Make sure we sync versions after each Publish action.
Update versions in JSON files.
2023-08-19 22:38:19 +03:00
roman 3de4a4abb6 1.0.29 2023-08-19 18:09:39 +03:00
roman 256450226b Ask if user wants to download latest version of block on lunch of the devTool. 2023-08-19 18:08:39 +03:00
roman 51db3da072 Fix scrolling issues & swiperjs conflicts. 2023-08-18 23:28:13 +03:00
roman 05c5697bc2 Fit the devTool to nodejs v16. 2023-08-14 16:11:21 +03:00
roman 01e4160040 1.0.28 2023-08-14 15:50:21 +03:00
roman 81f5166043 Print error message to have better understanding of dataObjects errors. 2023-08-14 15:50:12 +03:00
roman a1929fe33c Support missing images folder. 2023-08-13 23:50:52 +03:00
roman 840c002834 Added default layout view. 2023-08-13 23:26:38 +03:00
roman f4474fb7e4 Support work without DevConfigs. 2023-08-13 22:52:45 +03:00
roman 8ca6cb0365 Added "Content-Type" to files that are sent to S3. 2023-08-13 14:27:25 +03:00
roman e2553358be Added support of Project Global Assets. 2023-08-12 21:01:45 +03:00
roman 34dbff5701 Hide "Version" label 2023-06-26 20:05:11 +03:00
roman c408f2f5b3 Added option to generate test variations - updated error messages. 2023-06-25 22:18:44 +03:00
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: AXE-WEB/block-dev-tool#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: AXE-WEB/block-dev-tool#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: AXE-WEB/block-dev-tool#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
roman 25862c4b1c 1.0.22 2022-12-08 05:00:43 +02:00
roman a61510f136 Updated build process of ACF Block.
Added initBlock function.
2022-12-08 04:56:45 +02:00
roman 0d3ae8f03e Added "scroll" layout for scrolling tests.
Added swiperjs rules that fix the height/vertical-scrolling issues of sliders.
2022-12-07 06:38:54 +02:00
roman b58ef27f1e Fix scrolling issues of iFrame. 2022-12-06 11:32:14 +02:00
roman 161e34e8ee 1.0.21 2022-12-05 14:26:08 +02:00
roman 8eb7bea2e8 Fix resizing issue. 2022-12-05 14:26:01 +02:00
roman d9543bb22c Provide option to rewrite project/module paths. 2022-12-03 21:58:34 +02:00
roman 02abf4652e Update enqueue asset names. 2022-12-01 09:49:19 +02:00
roman 1ed038ff02 Update build of ACF blocks. 2022-11-30 21:01:02 +02:00
roman 0bb705ccdc Update build of ACF blocks. 2022-11-30 17:44:46 +02:00
roman 9d25bdcb88 Update path to assets. 2022-11-25 19:48:14 +02:00
roman 4d1d2337bf Added Basic Elementor widget logic. 2022-11-25 19:42:28 +02:00
roman 00866a8115 Update WordPress Basic Template 2022-11-25 19:25:33 +02:00
roman 1d733fb952 Fix right side icons/buttons. 2022-11-25 15:40:29 +02:00
roman 295c6f82af Added Elementor option in build process.
Elementor build still not ready.
2022-11-25 11:48:41 +02:00
roman f0af682a43 Include jpg,png,svg of toolbar in prod package. 2022-11-24 07:50:53 +02:00
roman ad35540111 1.0.20 2022-11-24 07:39:40 +02:00
roman 5cb6343184 Include layouts/partials in prod package. 2022-11-24 07:36:05 +02:00
roman 502326fd8d Add "info" command to get information about the local env. 2022-11-24 07:31:29 +02:00
roman 38a2d60f2c Merge pull request 'hubspot-pages' (#5) from hubspot-pages into master
Reviewed-on: AXE-WEB/block-dev-tool#5
2022-11-24 05:25:58 +00:00
roman 15c5286905 Merge pull request 'windows-watch' (#4) from windows-watch into master
Reviewed-on: AXE-WEB/block-dev-tool#4
2022-11-24 05:25:33 +00:00
roman f3e5b92318 Fix vertical scrolling issues. 2022-11-24 07:24:56 +02:00
roman c42c9fecba remove unnecessary code. 2022-11-23 23:59:13 +02:00
roman 6ebd37190a Pass {base} argument to gulp bundler. 2022-11-23 23:36:02 +02:00
roman 37ecce6290 Fix windows paths in Gulp scripts. 2022-11-23 22:15:27 +02:00
roman e0ae4d3d69 Print log. 2022-11-17 11:21:43 +02:00
roman 70d4630971 Add basic Handlebars to Hubl converter. 2022-11-17 00:32:11 +02:00
roman a2f8c7ebc1 Make sure options field exists on select field. 2022-11-16 22:33:29 +02:00
roman 1ae643b306 Remove duplicated code. 2022-11-16 22:28:17 +02:00
roman 52109f5010 Support Hubspot pages. 2022-11-16 22:12:02 +02:00
roman e0fb681d3b Merge pull request 'Fix handlebars path issue on Windows OS.' (#3) from window-path into master
Reviewed-on: AXE-WEB/block-dev-tool#3
2022-11-15 14:43:10 +00:00
roman 840f73d739 Fix handlebars path issue on Windows OS. 2022-11-15 16:33:22 +02:00
roman 702cd6e226 Added StyleGuideUrl to top panel. 2022-11-15 07:59:05 +02:00
roman eabe411b7a Update Production registry URL. 2022-11-14 17:37:49 +02:00
roman 7bf571e0fb Merge pull request 'excluding_yeo' (#2) from excluding_yeo into master
Reviewed-on: AXE-WEB/block-dev-tool#2
2022-11-13 09:23:58 +00:00
roman 73a10d9d55 Added namespace to "Basic Template" WordPress file. 2022-11-12 23:39:02 +02:00
roman 527416c63d Added exec-php to prod dependencies. 2022-11-12 23:36:30 +02:00
roman ac70e7eb9a Generate Template_Defaults file. 2022-11-12 23:32:01 +02:00
roman 05660eb4e4 Exclude YeoMan from the project.
Make the npm-install process faster.
2022-11-12 20:13:52 +02:00
roman 499c5b8163 Move sync command to create-block package. 2022-11-05 12:58:22 +02:00
roman 16f65254da Added sync command to project. 2022-11-05 12:52:30 +02:00
55 changed files with 2973 additions and 23396 deletions
+4
View File
@@ -18,6 +18,10 @@ indent_size = 2
indent_style = tab
indent_size = 4
[*.php]
indent_style = tab
indent_size = 4
[*.md]
trim_trailing_whitespace = false
+38 -64
View File
@@ -1,74 +1,48 @@
#!/usr/bin/env node
// For development purposes - run `npm run build-platform`.
import {exec} from 'child_process';
import config from 'config';
import Generator from "yeoman-generator";
import yeoman from 'yeoman-environment';
import {buildHubspot} from "./platforms/hubspot/hubspot-adapter.js";
import {getConfigs} from "./helpers.js";
import {buildWordPress} from "./platforms/wordpress/wordpress-adapter.js";
import path from "path";
import prompts from "prompts";
import {buildExportFiles, getConfigs} from "./helpers.js";
const {modulesPath, projectPath} = getConfigs();
const {isDev, developmentBlockName} = getConfigs();
const blockName = !isDev && config.has('blockName') ? config.get('blockName') : developmentBlockName;
const blockName = config.has('blockName') ? config.get('blockName') : 'development';
export const PLATFORM_OPTIONS = [{
name: 'wordpress',
title: 'WordPress'
}, {
name: 'hubspot',
title: 'Hubspot'
}, {
name: 'hubspot-email',
title: 'Hubspot Email'
}, {
name: 'javascript',
title: 'JavaScript'
}, {
name: 'php',
title: 'PHP'
}];
class buildGenerator extends Generator {
async prompting() {
this.data = await this.prompt([
{
type: "list",
name: "platform",
message: "Choose Platform",
choices: ['WordPress', 'WordPress Block', 'Hubspot', 'Hubspot Email', 'JavaScript', 'PHP'],
default: 'WordPress'
}
])
}
const data = await getExportData();
const selectedPlatform = PLATFORM_OPTIONS[data['platform']];
await buildExportFiles(blockName, selectedPlatform);
writing() {
new Promise((resolve => {
if (['WordPress', 'PHP'].includes(this.data.platform)) {
const backPath = modulesPath ? modulesPath.split('/').map(() => '..').join('/') : '';
console.log('--------------------\nDone!');
return new Promise((resolve, reject) => {
const phpGeneratorPath = path.join(modulesPath, 'platforms', 'php');
exec(`cd ${phpGeneratorPath} && composer install && php build.php '${blockName}' '${backPath}' '${projectPath}'`, function (error, stdout) {
if (error) {
console.log('Error:', error)
reject(error);
}
//
// Functions
//
console.log(stdout);
resolve();
});
}).then(() => {
if (this.data.platform === 'WordPress') {
return buildWordPress();
}
if (this.data.platform === 'WordPress Block') {
return buildWordPress(true);
}
});
} else if (this.data.platform === 'Hubspot Email') {
buildHubspot(blockName)
.then(() => {
resolve();
});
} else if (this.data.platform === 'Hubspot') {
console.log('"Hubspot" Coming soon...');
resolve();
} else {
resolve();
}
}))
.then(() => {
console.log('--------------------\nDone!');
});
}
function getExportData() {
return prompts([
{
type: "select",
name: "platform",
message: "Choose Platform",
choices: PLATFORM_OPTIONS.map(item => item.title),
default: 'WordPress'
}
]);
}
const build = new buildGenerator([], {env: yeoman.createEnv()}, {});
build.run().then(() => null);
Executable
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env node
import {getConfigs} from "./helpers.js";
const {isDev, modulesPath, projectPath, developmentBlockName} = getConfigs();
console.log('----------------------------------\n')
console.log('Local Details', process.versions, '\n');
console.log('Configs', {
isDev,
modulesPath,
projectPath,
developmentBlockName
});
console.log('\n----------------------------------\n')
+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;
}
+239 -27
View File
@@ -1,30 +1,37 @@
import path from 'path';
import {BLOCK_NAME, getModulePath, getProjectPath, IS_DEV} from "./env.js";
import config from 'config';
import {fileURLToPath} from 'url';
import memFs from 'mem-fs';
import editor from 'mem-fs-editor';
import fsExtra from "fs-extra";
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";
import fs from "fs/promises";
import {constants} from "fs";
import fetch from "node-fetch";
import mime from "mime-types";
import {exec} from "child_process";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
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 {
isDev,
developmentBlockName,
modulesPath: isDev ? '' : 'node_modules/block-dev-tool',
projectPath: isDev ? path.join('blocks', developmentBlockName) : '',
isDev: IS_DEV,
developmentBlockName: BLOCK_NAME,
modulesPath: getModulePath(),
projectPath: getProjectPath(),
};
}
import fsExtra from "fs-extra";
export async function readJSONFile(jsonFile) {
let data = {};
try {
await fs.access(jsonFile, constants.F_OK | constants.R_OK);
data = await fsExtra.readJson(jsonFile);
} catch (e) {
return {
@@ -42,29 +49,37 @@ function getErrorHtml(message = '', errorMessage = '') {
</div>`;
}
export async function getBlockConfigs(jsonFileName = 'default',
{includeConfigs, projectPath, modulesPath, dataFiles} = {}) {
let data = await readJSONFile(path.join(projectPath, 'data', `${jsonFileName}.json`));
if (data.error) {
return data;
}
export async function getBlockData(jsonFileName = 'default', {projectPath} = {jsonFileName: 'default'}) {
const filePath = path.join(projectPath, 'data', `${jsonFileName}.json`);
const data = await readJSONFile(filePath);
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,
})
});
if (data.error) {
console.log(filePath, data.errorMessage.replace(/<[^>]*>?/gm, ''));
return {};
}
return data;
}
export function getBlockConfigs(args = {modulesPath: '', dataFiles: []}) {
const updatedConfig = 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,
});
// Avoid cache conflict on Global Project css/js files.
if (updatedConfig.project) {
updatedConfig.project.css = updatedConfig.project.css ? updatedConfig.project.css + '?cache=' + Date.now() : undefined;
updatedConfig.project.js = updatedConfig.project.js ? updatedConfig.project.js + '?cache=' + Date.now() : undefined;
}
return updatedConfig;
}
export function getBlockName(name = '') {
if (name.startsWith('@')) {
name = name.substring(1);
@@ -100,10 +115,207 @@ export function capitalize(str) {
return str
.toLowerCase()
.split(/[ -_]/g)
.split(/[-_ ]/g)
.filter((word) => !!word)
.map((word) => {
return word.charAt(0).toUpperCase() + word.slice(1);
})
.join(' ');
}
export async function zipProject(srcDir, outputFileName = 'dist.zip') {
// create a file to stream archive data to.
const output = await fsExtra.createWriteStream(outputFileName);
return new Promise((resolve, reject) => {
// Create a file to write the archive data
const archive = archiver('zip', {
zlib: {level: 9} // Compression level
});
// Listen for errors on the archiver
archive.on('error', function (err) {
reject(err);
});
// Handle closure of the output file stream
output.on('close', function () {
console.log(`Archive created successfully and it is ${archive.pointer()} total bytes`);
resolve();
});
// Pipe archive data to the file
archive.pipe(output);
// Add files to the archive
archive.directory(srcDir, false);
// Finalize the archive - this is very important to ensure the file stream is finished
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)
}
}
export function removeCommentsFromCss(content) {
return content.replace(/\/\*[\s\S]*?\*\/|([^:]|^)\/\/.*$/gm, '');
}
export function removeCommentsFromJs(content) {
return content.replace(/\/\*[\s\S]*?\*\/|([^:]|^)\/\/.*$/gm, '');
}
export async function uploadFile(filePath, uploadUrl, validator) {
const options = {};
const contentType = mime.lookup(filePath);
if (['text/css', 'application/javascript'].includes(contentType)) {
options.encoding = 'utf8';
}
let body = await fs.readFile(filePath, options);
if (validator) {
body = validator(body);
}
try {
const response = await fetch(uploadUrl, {
method: 'PUT',
body: body,
headers: {'Content-Type': contentType}
});
return response.status !== 200;
} catch (err) {
console.log(err)
const fileName = filePath.split('/').pop();
throw new Error(`Can't upload "${fileName}" file. Server permission error.`);
}
}
export async function getImagesList(rootFolder, subFolder = '') {
const imagesPath = path.join(rootFolder, subFolder);
try {
await fs.access(imagesPath);
} catch (err) {
// Folder doesn't exist.
return [];
}
const images = await fs.readdir(imagesPath);
const imagesList = [];
for (const image of images) {
const stats = await fs.stat(path.join(imagesPath, image));
if (stats.isDirectory()) {
const subImages = await getImagesList(rootFolder, image);
imagesList.push(...subImages);
} else {
imagesList.push(path.join(subFolder, image));
}
}
return imagesList;
}
export async function isFileEmpty(filePath, ignoreComments = false) {
const fileContent = await fs.readFile(filePath, 'utf8');
const lines = fileContent.split('\n');
for (const line of lines) {
if (ignoreComments && line.trim().startsWith('//')) {
continue;
}
if (line.trim().length > 0) {
return false;
}
}
return true;
}
export function replaceNames(content, images, uploadedImages) {
images.forEach((image, index) => {
content = content.replaceAll(image, uploadedImages[index].fileName);
});
return content;
}
export async function getBlockFromCloud(blockName, blocksRegistry) {
const queryString = new URLSearchParams();
queryString.append('blockName', blockName);
queryString.append('includeDevConfig', 'true');
const response = await fetch(`${blocksRegistry}?${queryString.toString()}`);
const responseData = await response.json();
if (!responseData || !responseData.name) {
const message = "⚠️ Block not found, please contact administrator."
throw new Error(message);
}
if (responseData.statusCode && responseData.statusCode !== 200) {
const message = ["⚠️ [ERROR]", responseData.message || "Server side error."].join(' ');
throw new Error(message);
}
return responseData;
}
export async function verifyVersion(projectPath, blocksRegistry) {
const blockJson = await readJSONFile(path.join(projectPath, `block.json`));
const blockName = getBlockName(blockJson.name);
if (typeof blockJson.version === 'undefined' || !blockName.name) {
return true;
}
/*
* This block is managed on cloud.
* Let's detect the latest version.
*/
const block = await getBlockFromCloud('@' + blockJson.name, blocksRegistry);
return block.version === blockJson.version;
}
export async function syncFilesWithCloud(jsonBlockPath, bs, sourceFiles = false) {
const blockJson = await readJSONFile(jsonBlockPath);
const blockName = blockJson.name.startsWith('@') ? blockJson.name : `@${blockJson.name}`;
bs.pause();
// Looks like it takes time to pause the browser-sync server, so delay(setTimeout) is necessary.
await new Promise((resolve) => setTimeout(() => resolve(), 1000));
await new Promise((resolve) => {
const args = sourceFiles ? '--source' : '';
const createBlockModulePath = `./node_modules/@axe-web/create-block`;
// exec(`BLOCK_NAME=${blockName} node ${createBlockModulePath}/create-block.js sync ${args}`, (err, stdout, stderr) => {
exec(`node ${createBlockModulePath}/create-block.js sync ${args}`, (err, stdout, stderr) => {
if (err || stderr) {
const message = err || stderr;
console.error('Error:', message);
throw new Error(message);
}
console.log(stdout);
resolve();
});
});
bs.resume();
}
+2 -4
View File
@@ -2,11 +2,9 @@
{{> (include_partial "layouts/partials/head") }}
<body>
<body class="{{#if iframeMode}}body--iframe{{/if}}">
<main>
{{> (include_block_template) }}
</main>
<div id="hbs-container"></div>
{{> (include_partial "layouts/partials/scripts") }}
+4 -6
View File
@@ -2,13 +2,11 @@
{{> (include_partial "layouts/partials/head") }}
<body>
<body class="{{#if iframeMode}}body--iframe{{/if}}">
<main>
<div class="container">
{{> (include_block_template) }}
</div>
</main>
<div class="container">
<div id="hbs-container"></div>
</div>
{{> (include_partial "layouts/partials/scripts") }}
+4 -1
View File
@@ -14,11 +14,14 @@
<script>
window.devTool = {
previewFrameUrl: '{{ previewFrameUrl }}',
{{#if publicUrl}}
publicUrl: true,
{{/if}}
};
</script>
<div class="preview">
<iframe id="preview_frame" src="{{ previewFrameUrl }}" class="breakpoint"></iframe>
<iframe id="preview_frame" src="{{ previewFrameUrl }}?iframe=true" class="breakpoint"></iframe>
</div>
<script src="/scripts/dist/index.min.js"></script>
+3 -1
View File
@@ -2,11 +2,13 @@
<meta charset="UTF-8">
<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.project.css }} <link rel="stylesheet" href="{{ config.project.css }}">
{{/if}}
{{#if config.cssUrl }}
{{#each config.cssUrl }}
<link rel="stylesheet" href="{{ this }}">
{{/each}}
{{/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="https://unpkg.com/swiper@8/swiper-bundle.min.css"/>
</head>
+7 -2
View File
@@ -1,6 +1,11 @@
<script src="/scripts/frame-index.js"></script>
<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="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.project.js }}<script src="{{ config.project.js }}"></script>
{{/if}}
{{#if config.jsUrl }}
{{#each config.jsUrl }}<script src="{{ this }}"></script>
{{/each}}
{{/if}}
+9 -3
View File
@@ -3,12 +3,18 @@
<div class="page_toolbar__left"></div>
<div class="page_toolbar__middle">
<div>
Sizes: <b>1rem = {{ config.remToPx }}px</b>
<div style="display: none">
Version: {{ config.version }}
</div>
</div>
<div class="page_toolbar__right">
<a href="{{ previewFrameUrl }}" target="_blank" class="open_in_new_tab"></a>
{{#if shareUrl}}
<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}}
<a href="{{ previewFrameUrl }}" target="_blank" class="open_in_new_tab" title="Open in New Window"></a>
</div>
</header>
+1
View File
@@ -0,0 +1 @@
let e;window.initBlock=function(e="",n="",r){t=function(){document.querySelectorAll(n).forEach((e=>r(e)))},t()};let t,n={};function r(r={}){r.template&&(e=r.template),r.data&&(n=r.data),e&&function(e,n,r){const a=Handlebars.compile(e);let o;Handlebars.registerHelper("esc_attr",(function(e){return e})),Handlebars.registerHelper("esc_url",(function(e){return e})),Handlebars.registerHelper("esc_html",(function(e){return e})),Handlebars.registerHelper("base_url",(function(){return"/"})),Handlebars.registerHelper("inner_blocks",(function(e){const t=e.data.root.inner_blocks;return t?new Handlebars.SafeString(t):""}));try{o=a(n)}catch(e){o=`<div style="max-width: 1280px; margin: 1rem auto;">\n <h1 style="all: unset; font-size: 1.5rem; font-weight: bold; display: block;">Syntax Error:</h1>\n <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>\n </div>`}r.innerHTML=o,t&&t()}(e,n||{},document.getElementById("hbs-container"))}!function(){function e(){const e=new URLSearchParams(window.location.search),t={};for(const[n,r]of e)t[n]=r;return t}!function(){const t=new URLSearchParams({name:e().data||"default"});fetch(`/data?${t}`).then((e=>e.json())).then((e=>{n=e.data,r({data:n})}))}(),window.addEventListener("message",(function(e){const t=e.data,a="dataUpdate:";if("string"==typeof t&&t.startsWith(a))try{n=JSON.parse(t.substring(a.length)),r({data:n})}catch(e){console.log("Error parsing incoming data.",e)}}))}(),function(){const e=window.io.connect();e.on("error",(function(e){console.log(e)})),e.on("templateUpdate",(function(e){r({template:e.template})}))}();
File diff suppressed because one or more lines are too long
+33 -9822
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" height="48" width="48" fill="#21252d">
<path
d="M24 45.25q-4.35 0-8.225-1.675T9 39q-2.9-2.9-4.575-6.775Q2.75 28.35 2.75 24q0-4.5 1.675-8.375t4.625-6.75Q12 6 15.95 4.35q3.95-1.65 8.4-1.65 4.2 0 8 1.425t6.675 3.95Q41.9 10.6 43.6 14.05q1.7 3.45 1.7 7.5 0 5.7-3.2 9.35-3.2 3.65-8.9 3.65h-2.9q-.8 0-1.4.65-.6.65-.6 1.45 0 1.25.5 1.75t.5 1.55q0 2.2-1.5 3.75-1.5 1.55-3.8 1.55ZM24 24Zm-11.2 1.3q1 0 1.75-.75t.75-1.75q0-1-.75-1.75t-1.75-.75q-1 0-1.75.75t-.75 1.75q0 1 .75 1.75t1.75.75Zm6.1-8.15q1 0 1.75-.75t.75-1.75q0-1.05-.75-1.775-.75-.725-1.75-.725-1.05 0-1.775.725-.725.725-.725 1.725 0 1.05.725 1.8t1.775.75Zm10.25 0q1 0 1.75-.75t.75-1.75q0-1.05-.75-1.775-.75-.725-1.75-.725-1.05 0-1.775.725-.725.725-.725 1.725 0 1.05.725 1.8t1.775.75Zm6.2 8.15q1 0 1.75-.75t.75-1.75q0-1-.75-1.75t-1.75-.75q-1.05 0-1.775.75-.725.75-.725 1.75t.725 1.75q.725.75 1.775.75ZM23.8 40.55q.4 0 .6-.175.2-.175.2-.625 0-.7-.75-1.175-.75-.475-.75-2.375 0-2.45 1.65-4.4 1.65-1.95 4.1-1.95h4.35q3.7 0 5.525-2.2 1.825-2.2 1.825-5.8 0-6.6-4.925-10.5Q30.7 7.45 24.4 7.45q-7.1 0-12.025 4.825Q7.45 17.1 7.45 24q0 6.9 4.8 11.725 4.8 4.825 11.55 4.825Z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

+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

-27
View File
@@ -1,27 +0,0 @@
'use strict';
const heightLimit = window.outerHeight * 2;
let height = getCurrentHeight();
setupResizeListener();
///
function setupResizeListener() {
const resizeObserver = new ResizeObserver(handleHeightChange);
resizeObserver.observe(document.body);
}
function handleHeightChange(entries) {
const updatedHeight = getCurrentHeight();
if (height === updatedHeight || updatedHeight > heightLimit) {
return;
}
const RESIZE_CODE = 'resize:';
window.parent.postMessage(RESIZE_CODE + JSON.stringify({height}), '*');
height = updatedHeight;
}
function getCurrentHeight() {
return document.querySelector('body > main').scrollHeight;
}
+146
View File
@@ -0,0 +1,146 @@
'use strict';
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();
}
// 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 '/';
});
Handlebars.registerHelper('inner_blocks', function (options) {
const content = options.data.root['inner_blocks'];
if (!content) {
return '';
}
return new Handlebars.SafeString(content);
});
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();
}
}
+7 -13
View File
@@ -4,21 +4,15 @@ import {setupResponsiveness} from './toolbar/responsive.jsx';
import {setupPublish} from "./toolbar/publish.jsx";
import {setupDataOptions} from "./toolbar/data-options/DataOptions.jsx";
const previewFrame = document.getElementById('preview_frame');
const rootAttributes = {
previewFrame,
}
previewFrame: getPreviewFrame(),
};
// setupFrameResizeListener();
setupResponsiveness(rootAttributes);
setupDataOptions(rootAttributes);
setupPublish(rootAttributes)
setupPublish(rootAttributes);
window.addEventListener('message', function (e) {
const RESIZE_CODE = 'resize:';
if (typeof e.data !== 'string' || !e.data.startsWith(RESIZE_CODE)) {
return;
}
const data = JSON.parse(e.data.substring(RESIZE_CODE.length))
previewFrame.style.height = data.height + 'px';
});
function getPreviewFrame() {
return document.getElementById('preview_frame');
}
+100
View File
@@ -0,0 +1,100 @@
'use strict';
import React, {useState} from "react";
import * as ReactDOM from "react-dom/client";
function init() {
const wrapper = document.querySelector('#screen');
const root = ReactDOM.createRoot(wrapper);
const html = (<SyncScreen/>);
root.render(html);
}
function SyncScreen() {
const [loading, setLoading] = useState(null);
const [error, setError] = useState(null);
return <>
<section className="container py-5">
<h1 style={{marginBottom: '2rem'}}>Oops... Block not in sync.</h1>
{error && <p className="alert alert-danger">{error}</p>}
{loading ?
<>
{loading === 'syncing' &&
<p>Version upgrade in progress...</p>
}
<p>Please wait...</p>
</>
:
<>
<p>Your version of the block is not in sync with the cloud (not latest version).<br/>
Would you like to update it?</p>
<div className="options">
<button className="btn btn-primary" style={{marginRight: '0.5rem'}} onClick={runSyncLogic}>Yes, Update to
Latest
</button>
<button className="btn btn-secondary" onClick={ignoreVersionSync}>Ignore</button>
</div>
</>
}
</section>
</>
async function ignoreVersionSync() {
setLoading(true);
let data = {};
try {
const response = await fetch('/sync', {
method: 'POST',
body: JSON.stringify({ignore: true}),
headers: {
'Content-Type': 'application/json'
}
});
data = await response.json();
} catch (err) {
setError('Error: ' + err.message);
setLoading(false);
return;
}
if (data.status !== 200) {
setError(data.message);
setLoading(false);
return;
}
setTimeout(() => window.location.reload(), 1000);
}
async function runSyncLogic() {
setLoading('syncing');
let data = {};
try {
const response = await fetch('/sync', {method: 'POST'});
data = await response.json();
} catch (err) {
setError('Error: ' + err.message);
setLoading(false);
return;
}
if (data.status !== 200) {
setError(data.message);
setLoading(false);
return;
}
setTimeout(() => window.location.reload(), 1000);
}
}
init();
@@ -9,10 +9,21 @@ import {
import {isClickOutside, isEscHit} from "../responsive-button/ResponsiveButton.jsx";
import {DesignPreview} from "./DesignPreview.jsx";
export const PRODUCTION_REGISTRY_URL = 'https://blocks-registery.axe-web.com';
function DataOptions(props = {}) {
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 [previewOption, setPreviewOption] = useState(getDesignPreviewImage(state.dataName, state.designPreview));
const updateState = (update) => setState(Object.assign({}, state, update));
@@ -20,8 +31,7 @@ function DataOptions(props = {}) {
const [sidebarOpen, setSidebarOpen] = useState(false);
useEffect(async () => {
const data = await fetchDataOptions(state.dataName);
updateState(data);
await syncDataOptions(state.dataName);
}, []);
const handleCloseSidebarEscEvent = useCallback((e) => {
@@ -66,7 +76,7 @@ function DataOptions(props = {}) {
<SidebarDataOptionsStyle>
<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) => {
const isSelected = state.dataName === item;
return <option value={item} selected={isSelected}>{item}</option>
@@ -76,10 +86,21 @@ function DataOptions(props = {}) {
}
{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>
</div>;
@@ -87,6 +108,52 @@ function DataOptions(props = {}) {
// 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 => {
console.log(result)
if (result.statusCode !== 200) {
throw new Error(result.message);
}
const data = result.variation;
updateState({dataText: JSON.stringify(data, null, 2), data, errorMessage: null, loading: false});
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() {
setSidebarOpen(true);
setTimeout(() => document.querySelector('.sidebar-active').focus());
@@ -98,10 +165,7 @@ function DataOptions(props = {}) {
async function changeDataOption(e) {
const dataName = e.target.value;
props.rootAttributes.previewFrame.src = window.devTool.previewFrameUrl + '?data=' + dataName;
const dataOption = await fetchDataOptions(dataName);
updateState(Object.assign({}, dataOption, {dataName}));
await syncDataOptions(dataName);
}
async function fetchDataOptions(name = 'default') {
@@ -133,6 +197,23 @@ function DataOptions(props = {}) {
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) {
@@ -130,7 +130,8 @@ export function DesignPreview({previewOption = {widthDimension: 0}}) {
return 0;
}
const scrollbarOffset = 7;
// const scrollbarOffset = 7; // Looks like browser scrollbar is not included in the width calculation anymore.
const scrollbarOffset = 0;
return window.innerWidth / 2 - previewOption.widthDimension / 2 - scrollbarOffset;
}
@@ -24,7 +24,10 @@ export const SidebarStyle = styled.div`
visibility: visible;
}
pre {
pre, textarea {
height: 100%;
//min-height: 480px;
resize: vertical;
overflow-x: auto;
padding: 0.5rem;
background-color: #EDF2F7;
@@ -33,6 +36,20 @@ export const SidebarStyle = styled.div`
border: 1px solid #cbd5e0;
width: 100%;
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,4 @@
<svg xmlns="http://www.w3.org/2000/svg" height="48" width="48" fill="#21252d">
<path
d="M24 45.25q-4.35 0-8.225-1.675T9 39q-2.9-2.9-4.575-6.775Q2.75 28.35 2.75 24q0-4.5 1.675-8.375t4.625-6.75Q12 6 15.95 4.35q3.95-1.65 8.4-1.65 4.2 0 8 1.425t6.675 3.95Q41.9 10.6 43.6 14.05q1.7 3.45 1.7 7.5 0 5.7-3.2 9.35-3.2 3.65-8.9 3.65h-2.9q-.8 0-1.4.65-.6.65-.6 1.45 0 1.25.5 1.75t.5 1.55q0 2.2-1.5 3.75-1.5 1.55-3.8 1.55ZM24 24Zm-11.2 1.3q1 0 1.75-.75t.75-1.75q0-1-.75-1.75t-1.75-.75q-1 0-1.75.75t-.75 1.75q0 1 .75 1.75t1.75.75Zm6.1-8.15q1 0 1.75-.75t.75-1.75q0-1.05-.75-1.775-.75-.725-1.75-.725-1.05 0-1.775.725-.725.725-.725 1.725 0 1.05.725 1.8t1.775.75Zm10.25 0q1 0 1.75-.75t.75-1.75q0-1.05-.75-1.775-.75-.725-1.75-.725-1.05 0-1.775.725-.725.725-.725 1.725 0 1.05.725 1.8t1.775.75Zm6.2 8.15q1 0 1.75-.75t.75-1.75q0-1-.75-1.75t-1.75-.75q-1.05 0-1.775.75-.725.75-.725 1.75t.725 1.75q.725.75 1.775.75ZM23.8 40.55q.4 0 .6-.175.2-.175.2-.625 0-.7-.75-1.175-.75-.475-.75-2.375 0-2.45 1.65-4.4 1.65-1.95 4.1-1.95h4.35q3.7 0 5.525-2.2 1.825-2.2 1.825-5.8 0-6.6-4.925-10.5Q30.7 7.45 24.4 7.45q-7.1 0-12.025 4.825Q7.45 17.1 7.45 24q0 6.9 4.8 11.725 4.8 4.825 11.55 4.825Z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

@@ -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
@@ -1,10 +1,14 @@
import React, {useEffect, useState} from 'react';
import React, {useState} from 'react';
import * as ReactDOM from 'react-dom/client';
function Publish(props = {}) {
const [state, setState] = useState({loading: false});
const updateState = (update) => setState(Object.assign({}, state, update));
if (window.devTool.publicUrl) {
return;
}
return <div>
{state.loading &&
<div className="overlay overlay--loading">Loading, Please wait...</div>
@@ -4,7 +4,7 @@ import {ButtonStyling, ResponsiveButtonStyle, ResponsiveOptionsDropdown} from ".
const responsiveOptions = {
desktop: [1920, 1800, 1680, 1440, 1360, 1280, 1024],
tablet: [992, 768, 600],
mobile: [480, 414, 375, 360],
mobile: [480, 414, 375, 360, 320],
}
const defaultResponsiveOptions = {
+3 -1
View File
@@ -65,7 +65,9 @@ function Responsive(props = {}) {
function updateController() {
let frameBreakpoint = breakpoint;
if (typeof frameBreakpoint !== 'string') {
frameBreakpoint = frameBreakpoint + 'px';
// const scrollbarWidth = 15; // Looks like browser's logic was changed and now scrollbar is not included in the width.
const scrollbarWidth = 0;
frameBreakpoint = (scrollbarWidth + frameBreakpoint) + 'px';
}
previewFrame.style.setProperty('--breakpoint', frameBreakpoint);
+16
View File
@@ -0,0 +1,16 @@
<html lang="en">
{{> (include_partial "layouts/partials/head") }}
<body class="{{#if iframeMode}}body--iframe{{/if}}">
<div>
<section class="fullscreen_layout"></section>
<div id="hbs-container"></div>
<section class="fullscreen_layout"></section>
</div>
{{> (include_partial "layouts/partials/scripts") }}
</body>
</html>
+1 -5
View File
@@ -1,5 +1,4 @@
.preview {
overflow-y: scroll;
height: calc(100% - var(--top_panel_height));
position: relative;
}
@@ -9,17 +8,14 @@
margin-right: auto;
margin-left: auto;
min-height: 100%;
//height: 100%;
--top_spacing: 0px;
--breakpoint_top_spacing: 30px;
margin-top: var(--top_spacing);
height: 100%;
background-color: white;
border: 0;
outline: 1px solid #E2E8F0;
transition: max-width .3s ease-in-out, width .3s ease-in-out, margin-top .3s ease-in-out;
&.has-breakpoint {
+11 -5
View File
@@ -114,7 +114,6 @@ body {
}
.preview {
overflow-y: scroll;
height: calc(100% - var(--top_panel_height));
position: relative;
}
@@ -127,10 +126,8 @@ body {
--top_spacing: 0px;
--breakpoint_top_spacing: 30px;
margin-top: var(--top_spacing);
height: 100%;
background-color: white;
border: 0;
outline: 1px solid #E2E8F0;
transition: max-width 0.3s ease-in-out, width 0.3s ease-in-out, margin-top 0.3s ease-in-out;
}
#preview_frame.has-breakpoint {
@@ -139,11 +136,11 @@ body {
max-width: var(--breakpoint);
}
.open_in_new_tab {
.open_in_new_tab, .share, .palette {
--size: 1.5rem;
width: var(--size);
height: var(--size);
background-image: url("/scripts/toolbar/images/icon-open-new-tab.svg");
background-image: url("/scripts/dist/toolbar/images/icon-open-new-tab.svg");
background-repeat: no-repeat;
background-size: calc(var(--size) - 0.15rem);
background-position: center center;
@@ -158,4 +155,13 @@ body {
outline: none;
}
.palette {
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 */
+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","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;;;AAGF;EACE;EACA;EACA;EACA;EAGA;EACA;EAEA;EACA;EACA;EACA;;AAEA;EACE;EAEA;EACA;;;AHiEJ;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"}
+12 -1
View File
@@ -92,7 +92,7 @@ body {
width: var(--size);
height: var(--size);
background-image: url("/scripts/toolbar/images/icon-open-new-tab.svg");
background-image: url("/scripts/dist/toolbar/images/icon-open-new-tab.svg");
background-repeat: no-repeat;
background-size: calc(var(--size) - 0.15rem);
background-position: center center;
@@ -107,3 +107,14 @@ body {
border-radius: 0.25rem;
outline: none;
}
.palette {
@extend .open_in_new_tab;
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");
}
+9 -4
View File
@@ -1,11 +1,16 @@
body {
margin: 0;
overflow-y: hidden;
}
main {
margin-left: auto;
margin-right: auto;
.body--iframe {
overflow-y: scroll;
}
.fullscreen_layout {
background-color: #9cc3ff;
min-height: 100%;
background-image: url("https://i.ibb.co/pjwL8D1/shapelined-JBKdviwe-XI-unsplash.jpg");
background-size: cover;
}
/*# sourceMappingURL=page--view.css.map */
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sourceRoot":"","sources":["page--view.scss"],"names":[],"mappings":"AAAA;EACE;EACA;;;AAGF;EACE;EACA","file":"page--view.css"}
{"version":3,"sourceRoot":"","sources":["page--view.scss"],"names":[],"mappings":"AAAA;EACE;;;AAIF;EACE;;;AAGF;EACE;EACA;EACA;EACA","file":"page--view.css"}
+9 -12
View File
@@ -1,18 +1,15 @@
body {
margin: 0;
overflow-y: hidden;
}
main {
margin-left: auto;
margin-right: auto;
// iFrame mode
.body--iframe {
overflow-y: scroll;
}
// Container rules must be provided by the projectStyles (theme).
//.container {
// max-width: 1200px;
// margin-left: auto;
// margin-right: auto;
// padding-left: 15px;
// padding-right: 15px;
//}
.fullscreen_layout {
background-color: #9cc3ff;
min-height: 100%;
background-image: url('https://i.ibb.co/pjwL8D1/shapelined-JBKdviwe-XI-unsplash.jpg');
background-size: cover;
}
+18
View File
@@ -0,0 +1,18 @@
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Block Development Tool</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous">
</head>
<body>
<div id="screen">Loading...</div>
<script src="/socket.io/socket.io.js"></script>
<script src="/scripts/dist/sync.min.js"></script>
</body>
</html>
+1158 -12959
View File
File diff suppressed because it is too large Load Diff
+28 -11
View File
@@ -1,27 +1,32 @@
{
"name": "@axe-web/block-dev-tool",
"version": "1.0.19",
"version": "1.0.36",
"author": {
"name": "AXE-WEB",
"email": "office@axe-web.com",
"url": "https://axe-web.com/"
},
"scripts": {
"start": "component-dev",
"dev": "NODE_ENV=development NODE_CONFIG_DIR=blocks/team/config BLOCK_NAME=team node server.js",
"build": "rollup --config rollup.config.js",
"build-platform": "NODE_ENV=development NODE_CONFIG_DIR=blocks/team/config BLOCK_NAME=team node ./build.js",
"build-platform-cli": "component-build",
"dev-js": "rollup --config rollup.config.js --watch"
"info": "BLOCK_NAME=ebooks-resources MODULE_PATH= node debug.js",
"dev": "BLOCK_NAME=ebooks-resources MODULE_PATH= node server.js",
"build-platform": "BLOCK_NAME=ebooks-resources MODULE_PATH= node ./build.js",
"dev-dev-tool": "rollup --config rollup.config.js --watch",
"build-dev-tool": "rollup --config rollup.config.js"
},
"engines": {
"node": ">=14.17.3"
},
"license": "ISC",
"type": "module",
"dependencies": {
"@axe-web/create-block": "^1.1.30",
"@braintree/sanitize-url": "^6.0.0",
"archiver": "^5.3.1",
"body-parser": "^1.20.2",
"browser-sync": "^2.27.9",
"config": "^3.3.7",
"escape-html": "^1.0.3",
"exec-php": "^0.0.6",
"express": "^4.17.3",
"express-handlebars": "^6.0.4",
"fs-extra": "^10.0.1",
@@ -34,13 +39,15 @@
"lodash-es": "^4.17.21",
"mem-fs": "^2.2.1",
"mem-fs-editor": "^9.5.0",
"mime-types": "^2.1.35",
"ngrok": "^5.0.0-beta.2",
"node-fetch": "^3.2.10",
"open": "^8.4.0",
"plugin-error": "^2.0.0",
"prompts": "^2.4.2",
"sanitize-html": "^2.7.1",
"sass": "^1.50.1",
"yeoman-environment": "^3.10.0",
"yeoman-generator": "^5.6.1"
"ws": "^8.13.0"
},
"devDependencies": {
"@babel/preset-react": "^7.18.6",
@@ -54,15 +61,25 @@
"rollup": "^2.77.2",
"rollup-plugin-copy": "^3.4.0",
"rollup-plugin-jsx": "^1.0.3",
"rollup-plugin-terser": "^7.0.2",
"socket.io": "^4.6.2",
"styled-components": "^5.3.5"
},
"bin": {
"component-dev": "./server.js",
"component-build": "./build.js"
"component-build": "./build.js",
"component-info": "./debug.js"
},
"files": [
"env.js",
"helpers.js",
"layouts/**/*",
"debug.js",
"layouts/**/*.hbs",
"layouts/styles/*.css*",
"layouts/scripts/dist/*.js*",
"layouts/scripts/dist/**/*.jpg",
"layouts/scripts/dist/**/*.png",
"layouts/scripts/dist/**/*.svg",
"platforms/**/*"
]
}
@@ -1,47 +1,35 @@
import path from "path";
import {readFile, writeFile, mkdir, copyFile} from "fs/promises";
import {capitalize, getConfigs} from "../../helpers.js";
export async function buildHubspot(blockName) {
const distPath = `./exports/hubspot/${blockName}.module`;
await mkdir(distPath, {recursive: true})
await copyFile(`./src/${blockName}.template.hbs`, `${distPath}/module.html`)
export async function buildHubspotEmail(blockName) {
const distPath = await createDistFolder(blockName);
const metaData = {
// Template
let handlebars = await readFile(path.join(srcPath, `${blockName}.template.hbs`), "utf8");
await writeFile(path.join(distPath, 'module.html'), handlebarsToHubl(handlebars));
// JSON
await buildHubspotJSONFiles(distPath, {
global: false,
host_template_types: ["EMAIL"],
label: capitalize(blockName),
is_available_for_new_content: true
}
await writeFile(`${distPath}/meta.json`, JSON.stringify(metaData, null, 4));
const blockJSON = await readFile(`./block.json`, "utf8");
const block = JSON.parse(blockJSON);
const fields = getBlockFields(block, 'content');
// Styling TAB.
const stylingFields = getBlockFields(block, 'styling');
if (stylingFields.length) {
const stylingFieldsByName = {};
stylingFields.forEach(field => stylingFieldsByName[field.name] = field);
const stylingGroup = convertToHubspotField({
type: 'group',
name: 'style',
label: "Style",
sub_fields: stylingFieldsByName,
});
stylingGroup.tab = "STYLE";
fields.push(stylingGroup);
}
// Export JSON file.
await writeFile(`${distPath}/fields.json`, JSON.stringify(fields, null, 4));
});
}
function getBlockFields(block = {}, type = 'content') {
export async function createDistFolder(blockName, projectPath = '') {
const distPath = path.join(projectPath, 'exports', 'hubspot', `${blockName}.module`);
await mkdir(distPath, {recursive: true})
return distPath;
}
export function getBlockFields(block = {}, type = 'content') {
if (!block['field_groups']) {
return [];
}
const fields_group = block['field_groups'].find((group) => group.name === type);
const fields = [];
@@ -61,7 +49,7 @@ function getBlockFields(block = {}, type = 'content') {
});
}
function convertToHubspotField(field = {}) {
export function convertToHubspotField(field = {}) {
const data = {
id: field.name,
name: field.name,
@@ -70,9 +58,12 @@ function convertToHubspotField(field = {}) {
validation_regex: "",
required: false,
locked: false,
default: field.default
};
if (field.default) {
data.default = field.default;
}
let sub_fields = [];
switch (field.type) {
@@ -111,12 +102,14 @@ function convertToHubspotField(field = {}) {
display: "checkbox",
});
case 'select':
const choices = [];
Object.keys(data.choices).forEach(value => choices.push([value, data.choices[value]]));
const options = [];
if (field.options) {
Object.keys(field.options).forEach(value => options.push([value, field.options[value]]));
}
return Object.assign({}, data, {
type: "select",
choices: [choices]
type: "choice",
choices: options
});
case 'link':
return Object.assign({}, data, {
@@ -225,17 +218,57 @@ function convertToHubspotField(field = {}) {
}
}
export function capitalize(str) {
if (typeof str !== 'string') {
return '';
export async function buildHubspotJSONFiles(distPath, metaData) {
const {modulesPath, projectPath} = getConfigs();
await writeFile(path.join(distPath, 'meta.json'), JSON.stringify(metaData, null, 4));
const blockJSON = await readFile(path.join(projectPath, 'block.json'), "utf8");
const block = JSON.parse(blockJSON);
const fields = getBlockFields(block, 'content');
// Styling TAB.
const stylingFields = getBlockFields(block, 'styling');
if (stylingFields.length) {
const stylingFieldsByName = {};
stylingFields.forEach(field => stylingFieldsByName[field.name] = field);
const stylingGroup = convertToHubspotField({
type: 'group',
name: 'style',
label: "Style",
});
stylingGroup.children = Object.values(stylingFieldsByName);
stylingGroup.tab = "STYLE";
fields.push(stylingGroup);
}
return str
.toLowerCase()
.split(/[ -_]/g)
.filter((word) => !!word)
.map((word) => {
return word.charAt(0).toUpperCase() + word.slice(1);
})
.join(' ');
// Export JSON file.
await writeFile(path.join(distPath, 'fields.json'), JSON.stringify(fields, null, 4));
}
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, '{% endif %}');
handlebars = handlebars.replace(/{{#each /g, '{% for item in module.');
handlebars = handlebars.replace(/{{\/each}}/g, '{% endfor %}');
handlebars = handlebars.replace(/{{base_url}}/g, '');
handlebars = handlebars.replace(/{esc_attr /g, '{');
handlebars = handlebars.replace(/{esc_url /g, '{');
handlebars = handlebars.replace(/{esc_html /g, '{');
handlebars = handlebars.replace(/{{{ /g, '{{');
handlebars = handlebars.replace(/ }}}/g, '}}');
handlebars = handlebars.replace(/{{{/g, '{{');
handlebars = handlebars.replace(/}}}/g, '}}');
handlebars = handlebars.replace(/{{/g, '{{module.');
handlebars = handlebars.replace(/{{module. /g, '{{ module.');
handlebars = handlebars.replace(/.url/g, '.src');
return handlebars;
}
+28
View File
@@ -0,0 +1,28 @@
import path from "path";
import {copyFile, readFile, writeFile} from "fs/promises";
import {capitalize, getConfigs} from "../../helpers.js";
import {buildHubspotJSONFiles, createDistFolder, handlebarsToHubl,} from "./hubspot-email-adapter.js";
export async function buildHubspotPage(blockName) {
const {modulesPath, projectPath} = getConfigs();
const distPath = await createDistFolder(blockName, projectPath);
const srcPath = path.join(projectPath, 'src');
// Template
let handlebars = await readFile(path.join(srcPath, `${blockName}.template.hbs`), "utf8");
await writeFile(path.join(distPath, 'module.html'), handlebarsToHubl(handlebars));
// Assets
await copyFile(path.join(srcPath, 'styles', `${blockName}.min.css`), path.join(distPath, 'module.css'));
await copyFile(path.join(srcPath, 'scripts', `${blockName}.min.js`), path.join(distPath, 'module.js'));
// await copy(path.join(projectPath, 'src', 'images'), path.join(distPath, 'images'));
// JSON
await buildHubspotJSONFiles(distPath, {
global: false,
host_template_types: ["PAGE"],
label: capitalize(blockName),
is_available_for_new_content: true
});
}
+104 -85
View File
@@ -3,124 +3,143 @@
// Composer - Autoloader
require_once __DIR__ . '/vendor/autoload.php';
use Brick\VarExporter\ExportException;
use LightnCandy\Flags;
use LightnCandy\LightnCandy;
use Brick\VarExporter\VarExporter;
trait Custom_Handlebars {
public array $custom_handlebars = [];
public array $custom_handlebars = [];
public function register_default_handlebar_helpers() {
$this->add_handlebar( 'esc_url', function ( $context ) {
if ( function_exists( 'esc_url' ) ) {
return esc_url( $context );
}
public function register_default_handlebar_helpers(): void {
$this->add_handlebar( 'esc_url', function ( $context ) {
if ( function_exists( 'esc_url' ) ) {
return esc_url( $context );
}
return $context;
} );
return $context;
} );
$this->add_handlebar( 'esc_attr', function ( $context ) {
if ( function_exists( 'esc_attr' ) ) {
return esc_attr( $context );
}
$this->add_handlebar( 'esc_attr', function ( $context ) {
if ( function_exists( 'esc_attr' ) ) {
return esc_attr( $context );
}
return $context;
} );
return $context;
} );
$this->add_handlebar( 'esc_html', function ( $context ) {
if ( function_exists( 'esc_html' ) ) {
return esc_html( $context );
}
$this->add_handlebar( 'esc_html', function ( $context ) {
if ( function_exists( 'esc_html' ) ) {
return esc_html( $context );
}
return $context;
} );
return $context;
} );
}
$this->add_handlebar( 'safe_html', function ( $context ) {
if ( function_exists( 'wp_kses_post' ) ) {
return wp_kses_post( $context );
}
return $context;
} );
}
public function add_handlebar( $key, $func ) {
$this->custom_handlebars[ $key ] = $func;
}
public function add_handlebar( $key, $func ): void {
$this->custom_handlebars[ $key ] = $func;
}
}
class Component_Builder {
use Custom_Handlebars;
use Custom_Handlebars;
public string $component_name = '';
private string $module_path = '';
public string $component_name = '';
public string $module_path = '';
public string $project_path = '';
private string $dist_path = '';
function __construct( $component_name, $module_path, $project_path ) {
$this->module_path = $module_path;
$this->project_path = $project_path;
$this->component_name = $component_name;
$this->register_default_handlebar_helpers();
}
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.' );
}
function build(): void {
$root_path = __DIR__ . '/' . $this->module_path . '/../../' . $this->project_path;
$file_name = $this->get_handlebars_template( "$root_path/src/$this->component_name.template.hbs" );
$this->module_path = $args['backPath'];
$this->project_path = $args['projectPath'];
$this->component_name = $args['blockName'];
$output_folder = $root_path . '/exports/wordpress/templates';
foreach ( [ 'styles', 'scripts', 'images' ] as $dir ) {
$output_dir = "$output_folder/$dir";
if ( is_dir( $output_dir ) === false ) {
mkdir( $output_dir, 0777, true );
}
}
$this->dist_path = __DIR__ . '/' . $this->module_path . '/../../' . $this->project_path . '/exports' . '/' . $args['platform'];
$this->register_default_handlebar_helpers();
rename( $file_name, "$output_folder/$this->component_name.template.php" );
copy( "$root_path/src/styles/$this->component_name.min.css", "$output_folder/styles/$this->component_name.min.css" );
copy( "$root_path/src/scripts/$this->component_name.min.js", "$output_folder/scripts/$this->component_name.min.js" );
shell_exec( "cp -r $root_path/src/images $output_folder" );
$this->add_handlebar( 'base_url', function ( $context ) {
$path = join( '/', [ $this->block_project, $this->block_name, 'templates' ] );
return join( '/', [ get_site_url(),'wp-content', 'axe-web-blocks', $path, '' ] );
} );
}
echo "Generated '$file_name'.";
}
function build(): void {
$root_path = __DIR__ . '/' . $this->module_path . '/../../' . $this->project_path;
private function get_handlebars_template( $path = '' ): string {
$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 ?? [],
]
);
$this->buildTemplatePhpFile( $root_path );
}
/**
* 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.
*/
private function buildTemplatePhpFile( $root_path ): void {
$file_name = $this->get_handlebars_template( "$root_path/src/$this->component_name.template.hbs" );
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 {
$file_path_parts = explode( ".", $file_path );
array_pop( $file_path_parts ); // remove ".hbs" format.
$file_path_parts[] = 'php';
$file_path = join( '.', $file_path_parts );
private function get_handlebars_template( $path = '' ): string {
$template = file_get_contents( $path );
$template = preg_replace( '/{{inner_blocks}}/', '<InnerBlocks/>', $template );
$comment = "
$phpStr = LightnCandy::compile( $template,
[
'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 ?? [],
]
);
/**
* 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:
* 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.
*
* Compiled at " . date( 'Y-m-d h:i:s' ) . "
*/
";
$t = file_put_contents( $file_path, '<?php ' . $comment . $content . ' ?>' );
if ( $t === false ) {
die( "Error: Can't generate HBS template to PHP file. Cache folder is not accessible." );
}
$t = file_put_contents( $file_path, '<?php ' . $comment . $content . ' ?>' );
if ( $t === false ) {
throw new \Exception( "Error: Can't generate HBS template to PHP file. Cache folder is not accessible." );
}
return $file_path;
}
return $file_path;
}
}
( new Component_Builder( $argv[1], $argv[2], $argv[3] ) )->build();
/**
* Functions below will be triggered by JavaScript (index.js).
*/
function build( $args = [] ): void {
( new Component_Builder( $args ) )->build();
}
/**
* @throws ExportException
*/
function jsonToPhp( $args = [] ): ?string {
$json = $args['json'] ?? [];
return VarExporter::export( $json );
}
+2 -1
View File
@@ -6,6 +6,7 @@
},
"require": {
"php": ">=8.0",
"zordius/lightncandy": "^1.2.6"
"zordius/lightncandy": "^1.2.6",
"brick/varexporter": "^0.3.7"
}
}
+106 -1
View File
@@ -4,8 +4,113 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "1d9b4e7a02be366b48383c185193727f",
"content-hash": "6731e0a19d488ee457b6682e62ef9018",
"packages": [
{
"name": "brick/varexporter",
"version": "0.3.7",
"source": {
"type": "git",
"url": "https://github.com/brick/varexporter.git",
"reference": "3e263cd718d242594c52963760fee2059fd5833c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/brick/varexporter/zipball/3e263cd718d242594c52963760fee2059fd5833c",
"reference": "3e263cd718d242594c52963760fee2059fd5833c",
"shasum": ""
},
"require": {
"nikic/php-parser": "^4.0",
"php": "^7.2 || ^8.0"
},
"require-dev": {
"php-coveralls/php-coveralls": "^2.2",
"phpunit/phpunit": "^8.5 || ^9.0",
"vimeo/psalm": "4.23.0"
},
"type": "library",
"autoload": {
"psr-4": {
"Brick\\VarExporter\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"description": "A powerful alternative to var_export(), which can export closures and objects without __set_state()",
"keywords": [
"var_export"
],
"support": {
"issues": "https://github.com/brick/varexporter/issues",
"source": "https://github.com/brick/varexporter/tree/0.3.7"
},
"funding": [
{
"url": "https://github.com/BenMorel",
"type": "github"
}
],
"time": "2022-06-29T23:37:57+00:00"
},
{
"name": "nikic/php-parser",
"version": "v4.15.2",
"source": {
"type": "git",
"url": "https://github.com/nikic/PHP-Parser.git",
"reference": "f59bbe44bf7d96f24f3e2b4ddc21cd52c1d2adbc"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/f59bbe44bf7d96f24f3e2b4ddc21cd52c1d2adbc",
"reference": "f59bbe44bf7d96f24f3e2b4ddc21cd52c1d2adbc",
"shasum": ""
},
"require": {
"ext-tokenizer": "*",
"php": ">=7.0"
},
"require-dev": {
"ircmaxell/php-yacc": "^0.0.7",
"phpunit/phpunit": "^6.5 || ^7.0 || ^8.0 || ^9.0"
},
"bin": [
"bin/php-parse"
],
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "4.9-dev"
}
},
"autoload": {
"psr-4": {
"PhpParser\\": "lib/PhpParser"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Nikita Popov"
}
],
"description": "A PHP parser written in PHP",
"keywords": [
"parser",
"php"
],
"support": {
"issues": "https://github.com/nikic/PHP-Parser/issues",
"source": "https://github.com/nikic/PHP-Parser/tree/v4.15.2"
},
"time": "2022-11-12T15:38:23+00:00"
},
{
"name": "zordius/lightncandy",
"version": "v1.2.6",
@@ -1,31 +1,67 @@
<?php
use Core\Global_Functions;
namespace AXEWEB_Blocks\Blocks\<%= ownerClass %>\<%= blockClassModel %>;
class <%= blockClassModel %>_Component {
public function __construct() {
add_action( 'wp_enqueue_scripts', [ $this, 'register_assets' ] );
}
class <%= blockClassModel %>_Component extends \Core\Component {
const VERSION = '<%= version %>';
public $block_project = '<%= ownerFilename %>';
public $block_name = '<%= blockFilename %>';
public $hook_prefix = 'axeweb_blocks/<%= ownerFilename %>/<%= blockFilename %>';
function register_assets(): void {
wp_enqueue_style( '<%= blockFilename %>',
get_template_directory_uri() . '/components/partials/<%= blockFilename %>/templates/styles/<%= blockFilename %>.min.css',
[ 'style-wp' ],
Global_Functions::get_current_version_number()
);
$base_path = plugin_dir_url( __FILE__ ); // In Plugins
// $base_path = get_template_directory_uri() . '/components/partials/<%= blockFilename %>/'; // In Theme
wp_enqueue_script( '<%= blockFilename %>',
get_template_directory_uri() . '/components/partials/<%= blockFilename %>/templates/scripts/<%= blockFilename %>.min.js',
[ 'jquery', 'swiper' ],
Global_Functions::get_current_version_number(),
true
);
$style_deps = apply_filters( 'axeweb_blocks/<%= ownerFilename %>/<%= blockFilename %>::style_deps', [ 'assets-style' ] );
wp_register_style( 'block-<%= blockFilename %>', $base_path . 'templates/styles/<%= blockFilename %>.min.css', $style_deps, self::VERSION );
$script_deps = apply_filters( 'axeweb_blocks/<%= ownerFilename %>/<%= blockFilename %>::script_deps', [ 'assets-script' ] );
wp_register_script( 'block-<%= blockFilename %>', $base_path . 'templates/scripts/<%= blockFilename %>.min.js', $script_deps, self::VERSION, true );
}
public function render( $args = [] ): void {
$output = ( include( __DIR__ . '/templates/<%= blockFilename %>.template.php' ) )( array_merge( [], $args ), self::class );
echo apply_filters( 'the_content', wpautop( $output ) );
public function prepare_for_print() {
if ( ! is_admin() ) {
wp_enqueue_style( 'block-<%= blockFilename %>' );
wp_enqueue_script( 'block-<%= blockFilename %>' );
}
}
public function get_content( $args = [] ): string {
$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 );
return apply_filters( 'axeweb_blocks/<%= ownerFilename %>/<%= blockFilename %>::content', $output, $args );
}
function register_custom_logic(): void {
add_action( 'elementor/widgets/widgets_registered', [ $this, 'register_elementor_widget' ] );
}
function register_elementor_widget( $widgets_manager ): void {
require_once "helpers/<%= blockClassModel %>_Elementor_Widget.php";
$widgets_manager->register_widget_type( new Helpers\<%= blockClassModel %>_Elementor_Widget() );
}
function register_acf_block() {
$this->register_block( __DIR__ . "/<%= blockFilename %>.block.json", [
'style_assets' => [
[
'name' => 'block-<%= blockFilename %>',
'url' => $this->get_assets_path_url( 'templates/styles/<%= blockFilename %>.min.css' ),
]
],
'script_assets' => [
[
'name' => 'block-<%= blockFilename %>',
'url' => $this->get_assets_path_url( 'templates/scripts/<%= blockFilename %>.min.js' ),
]
]
] );
}
}
<%= blockClassModel %>_Component::get_instance();
// new <%= blockClassModel %>_Component();
@@ -1,68 +0,0 @@
<?php
namespace AXEWEB_Blocks\Blocks\<%= ownerClass %>\<%= blockClassModel %>;
class <%= blockClassModel %>_Component extends \Core\Component {
public function get_content( $args = [] ): string {
$args = array_merge( Helpers\<%= blockClassModel %>_Defaults::default_args(), $args );
$args = Helpers\<%= blockClassModel %>_API::prepare_args( $args );
<% if (templateFormat === 'hbs') { %>return $this->get_component_template( __DIR__ . '/templates/<%= blockFilename %>.template.hbs', $args );<% } %>
<% if (templateFormat === 'php') { %>
$output = ( include( __DIR__ . '/templates/<%= blockFilename %>.template.php' ) )( array_merge( [], $args ), self::class );
echo apply_filters( 'the_content', wpautop( $output ) );
<% } %>
}
<% if (!include_acf_block && !include_native_gutenberg_block) { %>
public function register_assets() {
$this->add_style( __DIR__ . '/templates/styles/<%= blockFilename %>.min.css' );
<% if (include_script) { %>$this->add_script( __DIR__ . '/templates/scripts/<%= blockFilename %>.js' );<% } %>
}
<% } %><% if (include_elementor_widget) { %> function register_custom_logic(): void {
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", [
'enqueue_assets' => function () {
wp_enqueue_style( '<%= blockFilename %>', \Core\Global_Functions::get_file_url( __DIR__ . '/templates/styles/<%= blockFilename %>.min.css', true ), [], get_blocks_version() );<% if (include_script) { %>
wp_enqueue_script( '<%= blockFilename %>', \Core\Global_Functions::get_file_url( __DIR__ . '/templates/scripts/<%= blockFilename %>.js', true ), ['assets-script'], get_blocks_version() );<% } %>
},
'default' => Helpers\<%= blockClassModel %>_Defaults::default_args(),
'supports' => [
//'jsx' => true,
'color' => [
'background' => true,
'text' => true,
],
'spacing' => [
'margin' => [ 'top', 'bottom' ],
'padding' => [ 'top', 'bottom' ]
],
]
] );
}
<% } %><% if (include_native_gutenberg_block) { %> function register_native_gutenberg_block() {
register_block_type( __DIR__ . '/templates/gutenberg-block/block.json' );<% if (include_script) { %>
add_action( 'wp_enqueue_scripts', function () {
$asset_file_front = include( plugin_dir_path( __FILE__ ) . '/templates/gutenberg-block/build/front.asset.php' );
wp_enqueue_script(
'gutenberg-<%= blockFilename %>-scripts-front',
plugins_url( 'templates/gutenberg-block/build/front.js', __FILE__ ),
$asset_file_front['dependencies'],
$asset_file_front['version'],
true
);
} );<% } %>
}<% } %>
}
@@ -1,14 +0,0 @@
<?php
namespace AXEWEB_Blocks\Blocks\<%= ownerClass %>\<%= blockClassModel %>\Helpers;
class <%= blockClassModel %>_API {
static function prepare_args( $args = [] ) {
// $args = array_merge( [], $args );
return $args;
}
}
@@ -1,15 +0,0 @@
<?php
namespace AXEWEB_Blocks\Blocks\<%= ownerClass %>\<%= blockClassModel %>\Helpers;
/**
* Component's default args.
*/
class <%= blockClassModel %>_Defaults {
public static function default_args(): array {
return [
'title' => '<%= title %>',
];
}
}
@@ -0,0 +1,44 @@
<?php
namespace AXEWEB_Blocks\Blocks\<%= ownerClass %>\<%= blockClassModel %>\Helpers;
class <%= blockClassModel %>_Elementor_Widget extends \Elementor\Widget_Base {
use \Core\Traits\Elementor_Widget;
const PLUGIN_NAME = '<%= blockFilename %>';
public function get_name() {
return self::PLUGIN_NAME;
}
public function get_title() {
return '<%= blockClassModel %>';
}
public function get_icon() {
return 'eicon-plus-square-o';
}
protected function _register_controls() {
$block_data = \Core\Block::get_block_data( __DIR__ . '/../<%= blockFilename %>.block.json' );
\Core\Elementor_Block::register_groups( $block_data, $this );
}
function get_style_depends() {
return [ 'block-<%= blockFilename %>' ];
}
function get_script_depends() {
return [ 'block-<%= blockFilename %>' ];
}
protected function render() {
$settings = $this->get_settings_for_display();
$component = new \AXEWEB_Blocks\Blocks\<%= ownerClass %>\<%= blockClassModel %>\<%= blockClassModel %>_Component();
$args = $this->prepare( $settings );
$component->render( $args );
}
}
+103 -42
View File
@@ -1,24 +1,26 @@
import path from "path";
import {mkdir, copyFile} from "fs/promises";
import fs, {mkdir, copyFile} from "fs/promises";
import {capitalize, createFiles, getBlockName, getConfigs, readJSONFile} from "../../helpers.js";
import {fileURLToPath} from 'url';
import {copy} from "fs-extra";
import {exec} from 'child_process';
import execPhp from "exec-php";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const {projectPath} = getConfigs();
export async function buildWordPress(blockName, args = {}) {
const {modulesPath, projectPath} = getConfigs();
export async function buildWordPress(isBlock = false) {
const distPath = path.join(projectPath, 'exports', 'wordpress');
await mkdir(distPath, {recursive: true})
const distPath = path.join(projectPath, 'exports', args.platform);
// await mkdir(distPath, {recursive: true})
await mkdir(path.join(distPath, 'templates'), {recursive: true})
const jsonFilePath = path.join(projectPath, 'block.json');
await copyFile(jsonFilePath, `${distPath}/block.json`)
const blockFilePath = path.join(projectPath, 'block.json');
let data = await readJSONFile(jsonFilePath);
let data = await readJSONFile(blockFilePath);
Object.assign(data, getBlockName(data.name));
// let data = await readJSONFile(path.join(projectPath, `block.json`));
const title = capitalize(data.name);
const owner = capitalize(data.project);
@@ -31,43 +33,102 @@ export async function buildWordPress(isBlock = false) {
ownerClass: owner.replace(/ /ig, '_'),
ownerFilename: owner.toLowerCase().replace(/ /ig, '-'),
templateFormat: 'php',
include_acf_block: false,
include_native_gutenberg_block: false,
include_script: true,
include_elementor_widget: false,
});
if (isBlock) {
await createFiles(data, [{
from: `templates/Template_Component.php`,
to: `${data.blockClassModel}_Component.php`,
}], {
pathDist: distPath,
generatorsPath: path.join(__dirname)
});
await copyFile(blockFilePath, path.join(distPath, data.blockFilename + '.block.json'));
await createFiles(data, [{
from: `templates/helpers/Template_API.php`,
to: `helpers/${data.blockClassModel}_API.php`,
}], {
pathDist: distPath,
generatorsPath: path.join(__dirname)
});
const backPath = modulesPath ? modulesPath.split('/').map(() => '..').join('/') : '';
await createFiles(data, [{
from: `templates/helpers/Template_Defaults.php`,
to: `helpers/${data.blockClassModel}_Defaults.php`,
}], {
pathDist: distPath,
generatorsPath: path.join(__dirname)
});
} else {
await createFiles(data, [{
from: `templates/Template_Basic_Component.php`,
to: `${data.blockClassModel}_Component.php`,
}], {
pathDist: distPath,
generatorsPath: path.join(__dirname)
});
const phpGeneratorPath = path.join(modulesPath, 'platforms', 'php');
await execCommand(`cd ${phpGeneratorPath} && composer install`);
await execPHPFile(path.join(phpGeneratorPath, 'build.php'), 'build', {
blockName,
backPath,
projectPath,
platform: args.platform
});
await copyStaticFile(
path.join(projectPath, 'src', 'styles', `${data.blockFilename}.min.css`),
path.join(distPath, 'templates', 'styles', `${data.blockFilename}.min.css`),
);
await copyStaticFile(
path.join(projectPath, 'src', 'scripts', `${data.blockFilename}.min.js`),
path.join(distPath, 'templates', 'scripts', `${data.blockFilename}.min.js`),
);
try {
const imagesPath = path.join(projectPath, 'src', 'images');
await fs.access(imagesPath);
await copy(
path.join(imagesPath),
path.join(distPath, 'templates', 'images'),
);
} catch (err) {
// Folder doesn't exist.
}
const phpDataObject = await execPHPFile(path.join(phpGeneratorPath, 'build.php'), 'jsonToPhp', {
json: await readJSONFile(path.join(projectPath, 'data', 'default.json'), "utf8"),
});
await createFiles(data, [{
from: `templates/helpers/Template_Elementor_Widget.php`,
to: `helpers/${data.blockClassModel}_Elementor_Widget.php`,
}], {
pathDist: distPath,
generatorsPath: path.join(__dirname)
});
await createFiles(data, [{
from: `templates/Template_Basic_Component.php`,
to: `${data.blockClassModel}_Component.php`,
}], {
pathDist: distPath,
generatorsPath: path.join(__dirname)
});
}
export function execCommand(cmd = '') {
return new Promise((resolve, reject) => {
exec(cmd, function (error) {
if (error) {
console.log('Error:', error)
reject(error);
}
// console.log(stdout);
resolve();
});
});
}
function execPHPFile(file = '', functionName = '', args = {}) {
return new Promise((resolve, reject) => {
execPhp(file, 'php', (err, php, out) => {
if (err) {
console.error(out);
return reject(err);
}
php[functionName.toLowerCase()](args, (err, res, out) => {
if (err) {
console.error(out);
return reject(err);
}
return resolve(res);
})
})
});
}
async function copyStaticFile(from = '', to = '') {
await mkdir(path.dirname(to), {recursive: true})
await copyFile(from, to);
}
+42 -5
View File
@@ -3,13 +3,17 @@ import {nodeResolve} from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import replace from '@rollup/plugin-replace';
import css from "@modular-css/rollup";
import copy from 'rollup-plugin-copy'
import copy from 'rollup-plugin-copy';
import {terser} from "rollup-plugin-terser";
export default {
const devMode = (process.env.NODE_ENV === 'development');
console.log('Build Mode', devMode ? 'Development' : 'Production');
export default [{
input: 'layouts/scripts/index.js',
output: {
file: 'layouts/scripts/dist/index.min.js',
sourcemap: true
sourcemap: devMode,
},
plugins: [
nodeResolve({
@@ -26,10 +30,43 @@ export default {
presets: ["@babel/preset-react"],
}),
commonjs(),
!devMode && terser(),
copy({
targets: [
{ src: 'layouts/scripts/toolbar/images/**/*', dest: 'layouts/scripts/dist/toolbar/images' }
{src: 'layouts/scripts/toolbar/images/**/*', dest: 'layouts/scripts/dist/toolbar/images'}
]
})
],
}
}, {
input: 'layouts/scripts/frame/frame.js',
output: {
file: 'layouts/scripts/dist/frame-index.min.js',
sourcemap: devMode
},
plugins: [
commonjs(),
!devMode && terser()
]
}, {
input: 'layouts/scripts/sync.jsx',
output: {
file: 'layouts/scripts/dist/sync.min.js',
sourcemap: devMode
},
plugins: [
nodeResolve({
extensions: [".js"],
}),
replace({
'process.env.NODE_ENV': JSON.stringify('production'),
preventAssignment: true,
}),
babel({
compact: false,
babelHelpers: 'bundled',
presets: ["@babel/preset-react"],
}),
commonjs(),
!devMode && terser()
]
}];
+314 -108
View File
@@ -1,10 +1,10 @@
#!/usr/bin/env node
import {PRODUCTION_REGISTRY_URL} from "./env.js";
import path from 'path';
import fetch from "node-fetch";
import express from 'express';
import {create} from 'express-handlebars';
import fsExtra from 'fs-extra';
import browserSync from 'browser-sync';
import config from 'config';
import gulp from 'gulp';
@@ -19,25 +19,65 @@ import open from "open";
import {sanitizeUrl} from "@braintree/sanitize-url";
import sanitizeHtml from 'sanitize-html';
import {escape} from "lodash-es";
import archiver from 'archiver';
import {getBlockConfigs, getConfigs, readJSONFile} from "./helpers.js";
import {
getBlockConfigs,
getBlockData,
getBlockName,
getConfigs,
getImagesList,
isFileEmpty,
readJSONFile,
removeCommentsFromCss,
removeCommentsFromJs,
replaceNames,
syncFilesWithCloud,
uploadFile,
verifyVersion,
zipProject
} from "./helpers.js";
import PluginError from 'plugin-error';
import {Server} from "socket.io";
import {createServer} from 'http';
// import {authtoken, connect} from "ngrok";
import bodyParser from "body-parser";
/**
* Constants
*/
const {isDev, modulesPath, projectPath, developmentBlockName} = getConfigs();
const blocksRegistry = isDev ? 'http://localhost:3020' : 'https://axe-web-blocks-registry.captain.devdevdev.life';
const blocksRegistry = isDev ? 'http://localhost:3020' : PRODUCTION_REGISTRY_URL;
const DevToolToken = 'D9lgz0TvzXCnp0xnwVBL109DaAR6Puk6F7YewDhgmP8='; // Temporary token for development purposes.
const dataFiles = await getDataFiles(projectPath);
const DEFAULT_VIEW_LAYOUT = 'alignfull';
/**
* 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 = [];
let ignoreVersionSync = false;
let bs;
/**
* 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();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}))
// parse application/json
app.use(bodyParser.json())
const httpServer = createServer(app);
initSessionsServer(httpServer);
const sass = gulpSass(dartSass);
const hbs = create({
@@ -49,8 +89,6 @@ const hbs = create({
}, esc_html(html) {
// TODO: Check if we can remove this helper.
return html;
}, safe_html(html) {
return sanitizeHtml(html);
}
}
});
@@ -63,50 +101,85 @@ app.set('views', path.join(modulesPath, 'layouts'));
// Routes
//
app.get('/', async (req, res) => {
let jsonFileName = req.query.data ? req.query.data : 'default';
const data = await getBlockConfigs(jsonFileName, {includeConfigs: true, projectPath, modulesPath, dataFiles});
app.get('/', async (req, res, next) => {
const data = getBlockConfigs({modulesPath, dataFiles});
if (data.error && data.errorMessage) {
return res.send(data.errorMessage);
}
const baseView = config.has('baseView') ? config.get('baseView') : 'container';
const baseView = config.has('baseView') ? config.get('baseView') : DEFAULT_VIEW_LAYOUT;
const baseViewUrl = `view/${baseView}`;
data.helpers = {
port,
include_partial: (filesPath) => path.join(modulesPath, filesPath),
baseView,
previewFrameUrl: `${previewFrameUrl}/${baseViewUrl}`,
include_partial: (filesPath) => handlebarLayoutsPath(modulesPath, filesPath),
}
try {
const verifiedVersion = await verifyVersion(projectPath, blocksRegistry);
if (!verifiedVersion && !ignoreVersionSync) {
return res.render('sync', data);
}
} catch (err) {
const errorMessage = "Can't verify block version.";
console.log(errorMessage, err);
return next(new Error(errorMessage));
}
data.baseView = baseView;
data.port = `/${baseViewUrl}`;
data.previewFrameUrl = `${previewFrameUrl}/${baseViewUrl}`;
data.shareUrl = shareUrl;
// TODO: Need to review this logic, conflicts with the browsersync work after "/sync" action.
// if (req.headers.referer) {
// // NGROK, public URL
// data.shareUrl = undefined; // Link already shared.
// data.previewFrameUrl = `/${baseViewUrl}`;
// data.publicUrl = true;
// }
res.render('index', data);
});
app.get('/view/:baseView', async (req, res) => {
let jsonFileName = req.query.data ? req.query.data : 'default';
const data = await getBlockConfigs(jsonFileName, {includeConfigs: true, projectPath, modulesPath, dataFiles});
app.get('/view/:baseView', (req, res) => {
const data = getDataOfFrame(!!req.query.iframe);
if (data.error && data.errorMessage) {
return res.send(data.errorMessage);
}
const blockName = config.has('blockName') ? config.get('blockName') : developmentBlockName;
data.helpers = {
include_partial: (filesPath) => path.join(modulesPath, filesPath),
include_block_template: () => path.join(projectPath, 'src', `${blockName}.template`),
section_class: `${blockName}--${jsonFileName}`,
base_url: '/'
}
const baseView = req.params.baseView ?? 'container';
const baseView = req.params.baseView ?? DEFAULT_VIEW_LAYOUT;
res.render(baseView, data)
});
app.get('/publish', async (req, res) => {
const data = await readJSONFile(path.join(projectPath, `block.json`));
let responseData;
// Trigger build on the registry server only if the type of the unit is `foundation` or `component`.
const uploadStaticFiles = ['foundation', 'component'].includes(data.type);
// Prepare list of static files for the registry server.
if (uploadStaticFiles) {
data.static_files = {
css: getBlockName(data.name).name + '.min.css',
js: getBlockName(data.name).name + '.min.js',
images: await getImagesList(path.join(projectPath, 'src', 'images')),
}
if (await isFileEmpty(path.join(projectPath, `src/scripts`, data.static_files.js), true)) {
delete data.static_files.js;
}
if (!data.static_files.images.length) {
delete data.static_files.images;
}
}
let responseData = {
uploadBundleUrl: undefined,
staticFilesUrls: {}
};
try {
const response = await fetch(`${blocksRegistry}`, {
@@ -126,35 +199,87 @@ app.get('/publish', async (req, res) => {
return;
}
if (responseData.uploadUrl) {
await zipProject();
const body = await fs.readFile(path.join(projectPath, 'dist.zip'));
const response = await fetch(`${responseData.uploadUrl}`, {
method: 'PUT',
body,
headers: {'Content-Type': 'application/zip'}
});
// Start files uploading process.
try {
if (responseData.uploadBundleUrl) {
await zipProject(path.join(projectPath, 'src'), path.join(projectPath, 'dist.zip'));
await uploadFile(path.join(projectPath, 'dist.zip'), responseData.uploadBundleUrl); // Bundle
}
if (response.status !== 200) {
res.json({success: false, message: "Can't upload the archive, permissions error."});
// TODO: Need to update the registry server.
await fs.unlink(path.join(projectPath, 'dist.zip'));
if (uploadStaticFiles) {
if (responseData.staticFilesUrls.css) {
await uploadFile(
path.join(projectPath, 'src/styles', data.static_files.css),
responseData.staticFilesUrls.css.uploadUrl,
(content) => {
if (responseData.staticFilesUrls.images) {
content = replaceNames(content, data.static_files.images, responseData.staticFilesUrls.images);
}
removeCommentsFromCss(content)
return content;
}); // CSS
}
if (responseData.staticFilesUrls.js) {
await uploadFile(
path.join(projectPath, 'src/scripts', data.static_files.js),
responseData.staticFilesUrls.js.uploadUrl,
(data) => removeCommentsFromJs(data)
); // JS
}
if (responseData.staticFilesUrls.images) {
for (let i = 0; i < data.static_files.images.length; i++) {
await uploadFile(
path.join(projectPath, 'src/images', data.static_files.images[i]),
responseData.staticFilesUrls.images[i].uploadUrl,
); // Images
}
}
}
} catch (err) {
// TODO: Need to update the registry server.
await fs.unlink(path.join(projectPath, 'dist.zip')); // Remove local bundle
res.json({success: false, message: err.message});
return;
}
await fs.unlink(path.join(projectPath, 'dist.zip')); // Remove local bundle
// Trigger project's global files build on the registry server.
if (uploadStaticFiles) {
try {
await triggerGlobalProjectFilesBuild(getBlockName(data.name).project);
} catch (err) {
res.json({success: false, message: 'Something wrong with Project Builder.'});
return;
}
}
try {
await syncFilesWithCloud(path.join(projectPath, 'block.json'), bs);
} catch (err) {
res.json({success: false, message: err});
return;
}
res.json({success: true});
await fs.unlink(path.join(projectPath, 'dist.zip'));
});
app.get('/data', async (req, res) => {
let jsonDataFileName = req.query.name ? req.query.name : 'default';
const dataFiles = prepareListOfDataFiles(await fs.readdir(path.join(projectPath, 'data')));
const data = await getBlockConfigs(jsonDataFileName, {projectPath, modulesPath, dataFiles});
const designPreviewFiles = getListOfDesignPreviewFiles(jsonDataFileName, await fs.readdir(path.join(projectPath, 'design', 'preview')));
const dataFiles = await getDataFiles(projectPath);
const data = await getBlockData(jsonDataFileName, {projectPath});
let designPreviewFiles = [];
try {
designPreviewFiles = getListOfDesignPreviewFiles(jsonDataFileName, await fs.readdir(path.join(projectPath, 'design', 'preview')));
} catch (err) {
console.log('Preview Design doesn\'t exist');
}
return res.json({
dataOptions: dataFiles,
@@ -163,6 +288,22 @@ app.get('/data', async (req, res) => {
});
});
app.post('/sync', async (req, res) => {
if (req.body['ignore']) {
ignoreVersionSync = true;
res.json({status: 200, message: 'Version upgrade is ignored.'});
return;
}
try {
await syncFilesWithCloud(path.join(projectPath, `block.json`), bs, true);
} catch (err) {
res.status(500).json({status: 500, message: err});
}
res.json({status: 200, message: 'Successfully synced!'});
});
// Errors handler
app.use(handleSyntaxErrors);
@@ -171,10 +312,14 @@ app.use(express.static(path.join(projectPath, 'src')));
app.use(express.static(path.join(projectPath, 'design')));
app.use(express.static(path.join(modulesPath, 'layouts')));
// Custom Middleware
app.use(setHeaders);
// Setup Gulp
await buildAssetFiles();
// BrowserSync
shareUrl = await getShareableUrl();
const bsOptions = await startBrowserSync();
port = bsOptions.port;
previewFrameUrl = bsOptions.previewFrameUrl;
@@ -203,14 +348,32 @@ function getListOfDesignPreviewFiles(jsonDataFileName, previewFiles) {
});
}
function getDataOfFrame(isIframe = false) {
const data = {config: getBlockConfigs({modulesPath, dataFiles})};
if (data.error && data.errorMessage) {
return data;
}
data.helpers = {
include_partial: (filesPath) => handlebarLayoutsPath(modulesPath, filesPath),
}
if (isIframe) {
data.iframeMode = true;
}
return data;
}
function startBrowserSync() {
return new Promise((resolve, reject) => {
const listener = app.listen(0, async () => {
const listener = httpServer.listen(0, async () => {
const PORT = listener.address().port;
console.log(`The web server has started on port ${PORT}`);
const bs = browserSync.create();
// BS is global variable.
bs = browserSync.create();
const files = getJSBundleFiles();
gulp.watch(files, {delay: 400}, gulp.series(['build-script-files', function (cb) {
@@ -218,19 +381,27 @@ function startBrowserSync() {
return cb();
}]));
gulp.watch(path.join(projectPath, 'src/**/*.scss'), {delay: 400}, gulp.series(['build-styling-files', function (cb) {
gulp.watch(path.posix.join(projectPath, "src/**/*.scss"), {delay: 400}, gulp.series(['build-styling-files', function (cb) {
browserSyncReload(bs, 'css', 'Style Files Change');
return cb();
}]));
bs.watch("src/**/*.hbs", function (event, file) {
browserSyncReload(bs, '', 'Template File Change: ' + file)
bs.watch(path.join(projectPath, "src/**/*.hbs"), function () {
return syncTemplate(sessions);
});
bs.init({
const args = {
proxy: `http://localhost:${PORT}`,
open: false
}, (err, bs) => {
};
if (shareUrl) {
args.socket = {
domain: shareUrl
};
}
bs.init(args, (err, bs) => {
if (err) {
return reject(err);
}
@@ -272,12 +443,12 @@ function browserSyncReload(bs, extension = '', message = '') {
}
function getJSBundleFiles() {
return [path.join(projectPath, 'src/**/*.js'), path.join(projectPath, 'src/**/*.mjs'), '!' + path.join(projectPath, 'src/**/*.min.js')];
return [path.posix.join(projectPath, "src/**/*.js"), path.posix.join(projectPath, "src/**/*.mjs"), "!" + path.posix.join(projectPath, "src/**/*.min.js")];
}
function buildScriptFiles(done) {
const files = getJSBundleFiles();
return gulp.src(files)
return gulp.src(files, {base: path.posix.join(projectPath, 'src')})
.pipe(sourcemaps.init({}))
.pipe(babel()).on('error', function (error) {
showError(new PluginError('JavaScript', error).toString());
@@ -285,14 +456,14 @@ function buildScriptFiles(done) {
})
.pipe(gulp.src(path.join(projectPath, 'vendor/*.js')))
// .pipe(gulp.dest('src/'))
.pipe(uglify())
.pipe(rename({extname: '.min.js'}))
.pipe(uglify())
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(path.join(projectPath, 'src/')));
.pipe(gulp.dest(path.posix.join(projectPath, 'src')));
}
function buildStyleFiles(done) {
return gulp.src(path.join(projectPath, 'src/**/*.scss'))
return gulp.src(path.join(projectPath, 'src/**/*.scss'), {base: path.posix.join(projectPath, 'src')})
.pipe(sourcemaps.init({}))
.pipe(sass.sync({outputStyle: 'compressed'}).on('error', function (error) {
showError(new PluginError('SCSS', error.messageFormatted).toString());
@@ -302,7 +473,7 @@ function buildStyleFiles(done) {
// .pipe(gulp.dest('src/'))
.pipe(rename({extname: '.min.css'}))
.pipe(sourcemaps.write('.', {}))
.pipe(gulp.dest(path.join(projectPath, 'src')))
.pipe(gulp.dest(path.posix.join(projectPath, 'src')))
}
function buildAssetFiles() {
@@ -312,7 +483,7 @@ function buildAssetFiles() {
// Run first build.
return new Promise((resolve) => {
gulp.series('build-script-files', 'build-styling-files', function (cb) {
gulp.series('build-script-files', 'build-styling-files', function () {
resolve();
})();
});
@@ -336,52 +507,6 @@ function prepareListOfDataFiles(dataFiles) {
.sort();
}
async function zipProject() {
// create a file to stream archive data to.
const output = await fsExtra.createWriteStream('dist.zip');
const archive = archiver('zip', {});
// listen for all archive data to be written
// 'close' event is fired only when a file descriptor is involved
output.on('close', function () {
console.log(archive.pointer() + ' total bytes');
console.log('archiver has been finalized and the output file descriptor has closed.');
});
// This event is fired when the data source is drained no matter what was the data source.
// It is not part of this library but rather from the NodeJS Stream API.
// @see: https://nodejs.org/api/stream.html#stream_event_end
output.on('end', function () {
console.log('Data has been drained');
});
// good practice to catch warnings (ie stat failures and other non-blocking errors)
archive.on('warning', function (err) {
if (err.code === 'ENOENT') {
// log warning
} else {
// throw error
throw err;
}
});
// good practice to catch this error explicitly
archive.on('error', function (err) {
throw err;
});
// pipe archive data to the file
archive.pipe(output);
// append files from a subdirectory, putting its contents at the root of archive
archive.directory(path.join(projectPath, 'src', '/'), false);
// finalize the archive (ie we are done appending files but streams have to finish yet)
// 'close', 'end' or 'finish' may be fired right after calling this method so register to them beforehand
await archive.finalize();
}
function handleSyntaxErrors(err, req, res, next) {
if (err) {
return res.render('error', {
@@ -394,3 +519,84 @@ function handleSyntaxErrors(err, req, res, next) {
next();
}
function handlebarLayoutsPath() {
return path.join(...arguments)
.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;
}
async function triggerGlobalProjectFilesBuild(project) {
const response = await fetch(`${blocksRegistry}/project-files`, {
method: 'POST',
body: JSON.stringify({project}),
headers: {'Content-Type': 'application/json'}
});
return response.json();
}
async function getDataFiles(projectPath) {
const dataFiles = [];
try {
await fs.access(path.join(projectPath, 'data'));
const files = prepareListOfDataFiles(await fs.readdir(path.join(projectPath, 'data')));
dataFiles.push(...files);
} catch (e) {
console.log('Warning: data folder not found.');
}
return dataFiles;
}
+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.
*
*/