UNPKG

2.64 kBJavaScriptView Raw
1/* eslint-env node */
2const assert = require('assert');
3const chalk = require('chalk');
4const fs = require('fs');
5const fsExtra = require('fs-extra');
6const kebabToPascal = require('@creuna/utils/kebab-to-pascal').default;
7const path = require('path');
8const prettier = require('prettier');
9const t = require('@babel/types');
10
11const ensureEmptyFolder = require('./utils/ensure-empty-folder');
12const getConfigs = require('./utils/get-configs');
13const writeFile = require('./utils/write-file');
14const generateComponent = require('./templates/static-site-page');
15
16const dataFileTemplates = {
17 json: '{}',
18 js: 'export default {};'
19};
20
21module.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};