1 |
|
2 | const assert = require('assert');
|
3 | const chalk = require('chalk');
|
4 | const fs = require('fs');
|
5 | const fsExtra = require('fs-extra');
|
6 | const kebabToPascal = require('@creuna/utils/kebab-to-pascal').default;
|
7 | const path = require('path');
|
8 | const prettier = require('prettier');
|
9 | const t = require('@babel/types');
|
10 |
|
11 | const ensureEmptyFolder = require('./utils/ensure-empty-folder');
|
12 | const getConfigs = require('./utils/get-configs');
|
13 | const writeFile = require('./utils/write-file');
|
14 | const generateComponent = require('./templates/static-site-page');
|
15 |
|
16 | const dataFileTemplates = {
|
17 | json: '{}',
|
18 | js: 'export default {};'
|
19 | };
|
20 |
|
21 | module.exports = function({
|
22 | componentName,
|
23 | dataFileExtension = 'json',
|
24 | dataFileContent,
|
25 | eslintConfig,
|
26 | folderPath,
|
27 | groupName,
|
28 | humanReadableName,
|
29 | template, // Expecting an array
|
30 | url
|
31 | }) {
|
32 | return new Promise(async (resolve, reject) => {
|
33 | const { prettierConfig } = getConfigs(eslintConfig);
|
34 |
|
35 | try {
|
36 | assert(folderPath, 'No path provided.');
|
37 | assert(componentName, 'No page name provided.');
|
38 | assert(fs.existsSync(folderPath), `Path '${folderPath}' does not exist.`);
|
39 |
|
40 | const componentPath = path.join(folderPath, componentName);
|
41 | const dataFilePath = path.join(
|
42 | componentPath,
|
43 | `${componentName}.${dataFileExtension}`
|
44 | );
|
45 | const jsxFilePath = path.join(componentPath, `${componentName}.jsx`);
|
46 |
|
47 | const replacements = {
|
48 | componentName: t.identifier(kebabToPascal(componentName)),
|
49 | dataFilePath: t.stringLiteral(`./${componentName}.${dataFileExtension}`)
|
50 | };
|
51 | const componentSource = generateComponent(
|
52 | replacements,
|
53 | Array.isArray(template) ? template.join('\n') : template
|
54 | );
|
55 |
|
56 | const frontmatter =
|
57 | `/*\n` +
|
58 | (groupName ? `group: ${groupName}\n` : '') +
|
59 | (humanReadableName ? `name: ${humanReadableName}\n` : '') +
|
60 | (url ? `path: ${url}\n` : '') +
|
61 | `*/\n\n`;
|
62 |
|
63 | const jsxFileContent = prettier.format(
|
64 | frontmatter + componentSource,
|
65 | prettierConfig
|
66 | );
|
67 |
|
68 | const staticDataFileContent =
|
69 | dataFileContent || dataFileTemplates[dataFileExtension] || '';
|
70 |
|
71 | ensureEmptyFolder(componentPath);
|
72 | await fsExtra.ensureDir(componentPath);
|
73 |
|
74 | const messages = [
|
75 | writeFile(jsxFilePath, jsxFileContent),
|
76 | writeFile(dataFilePath, staticDataFileContent)
|
77 | ];
|
78 |
|
79 | resolve({
|
80 | messages: messages.concat({
|
81 | emoji: '🎉',
|
82 | text: `Created page ${chalk.greenBright(componentName)}`
|
83 | })
|
84 | });
|
85 | } catch (error) {
|
86 | reject(error.message);
|
87 | }
|
88 | });
|
89 | };
|