Skip to content

Commit

Permalink
fix(generator): restore files to pre-formatted state
Browse files Browse the repository at this point in the history
  • Loading branch information
pfulton committed Jun 15, 2023
1 parent 5537c1b commit 189ced1
Show file tree
Hide file tree
Showing 12 changed files with 270 additions and 235 deletions.
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ components/expressvars/css/**/*.css
components/vars/css/**/*.css
components/tokens/custom-*/*.css
tools/preview/storybook-static/**
tools/generator
dist
template.hbs

Expand Down
174 changes: 70 additions & 104 deletions tools/generator/plopfile.js
Original file line number Diff line number Diff line change
@@ -1,46 +1,40 @@
import { spawn } from "child_process";
import { existsSync, readdirSync, readFileSync } from "fs";
import { readFile } from "fs/promises";
import { resolve } from "path";
import { spawn } from 'child_process';
import { existsSync, readdirSync, readFileSync } from 'fs';
import { readFile } from 'fs/promises';
import { resolve } from 'path';

import yaml from "js-yaml";
import cheerio from "cheerio";
import yaml from 'js-yaml';
import cheerio from 'cheerio';

import autocompletePrompt from "inquirer-autocomplete-prompt";
import fuzzy from "fuzzy";
import autocompletePrompt from 'inquirer-autocomplete-prompt';
import fuzzy from 'fuzzy';

const fetchPackage = async (path) =>
readFile(resolve(path, "package.json"), {
encoding: "utf8",
}).then(JSON.parse);
readFile(resolve(path, 'package.json'), {
encoding: 'utf8'
})
.then(JSON.parse);

export default async (plop) => {
/* Allow customization from the environment variables */
const rootFolder = process.env.ROOT_DIR ?? resolve(process.cwd(), "../../");
const srcPath =
process.env.COMPONENT_DIR ?? resolve(rootFolder, "components");
const projectName = process.env.PROJECT_NAME ?? "Spectrum CSS";
const rootFolder = process.env.ROOT_DIR ?? resolve(process.cwd(), '../../');
const srcPath = process.env.COMPONENT_DIR ?? resolve(rootFolder, 'components');
const projectName = process.env.PROJECT_NAME ?? 'Spectrum CSS';
const pkg = await fetchPackage(rootFolder);

const tokens = await fetchPackage(resolve(srcPath, "tokens"));
const builder = await fetchPackage(
resolve(process.cwd(), "../component-builder-simple")
);
const tokens = await fetchPackage(resolve(srcPath, 'tokens'));
const builder = await fetchPackage(resolve(process.cwd(), '../component-builder-simple'));

/* Fetch the project name */
plop.setWelcomeMessage(
`Welcome to the ${projectName} component generator!\n To get started, answer a few short questions about your component.`
);
plop.setWelcomeMessage(`Welcome to the ${projectName} component generator!\n To get started, answer a few short questions about your component.`);

/* Fetch the list of existing components to avoid conflicts */
const existingComponents = readdirSync(srcPath, {
withFileTypes: true,
}).reduce((pkgs, dirent) => {
const existingComponents = readdirSync(srcPath, { withFileTypes: true }).reduce((pkgs, dirent) => {
if (dirent.isDirectory()) pkgs.push(dirent.name);
return pkgs;
}, []);

plop.setHelper("parse", (str, sep = "/", start = 0, end = undefined) => {
plop.setHelper('parse', (str, sep = '/', start = 0, end = undefined) => {
if (!str) return;
const array = str.split(sep);
return array.slice(start, end).join(sep);
Expand All @@ -49,9 +43,7 @@ export default async (plop) => {
function getExistingMarkupExample(metadataPath, name, plop) {
if (existsSync(`${metadataPath}/${name}.yml`) === false) return;

const r = readFileSync(`${metadataPath}/${name}.yml`, {
encoding: "utf8",
});
const r = readFileSync(`${metadataPath}/${name}.yml`, { encoding: 'utf8' });
const result = yaml.load(r);
if (!result) return;

Expand All @@ -60,139 +52,113 @@ export default async (plop) => {

const $ = cheerio.load(examples[0].markup);

const className = plop.renderString("spectrum-{{ pascalCase name }}", {
name,
});
const className = plop.renderString('spectrum-{{ pascalCase name }}', { name });
const $example = $(`.${className}`);

if (!$example) return;

return $example.first().toString();
}

plop.setActionType(
"install",
(_, config) =>
new Promise((resolve, reject) => {
const install = spawn("yarn", ["install"], {
cwd: config.root,
shell: true,
stdio: "inherit",
});
install.on("close", (code) => {
if (`${code}` === "0") {
resolve(`Successfully installed dependencies.`);
} else {
reject(`Failed to install dependencies; exit code ${code}.`);
}
});
})
);
plop.setActionType('install', (_, config) => new Promise((resolve, reject) => {
const install = spawn('yarn', ['install'], {
cwd: config.root,
shell: true,
stdio: 'inherit',
});
install.on('close', (code) => {
if (`${code}` === '0') {
resolve(`Successfully installed dependencies.`);
} else {
reject(`Failed to install dependencies; exit code ${code}.`);
}
});
}));

plop.setGenerator("component", {
description: "Component generator",
plop.setGenerator('component', {
description: 'Component generator',
prompts: [
{
type: "input",
name: "name",
message: "Component name (i.e. Help text)",
type: 'input',
name: 'name',
message: 'Component name (i.e. Help text)',
validate: (answer) => {
if (!answer || answer.length < 1) {
return "Naming is hard; but it must have a name. You can always change it later.";
}

const name = plop.renderString("{{ lowerCase (camelCase name) }}", {
name: answer,
});
const name = plop.renderString('{{ lowerCase (camelCase name) }}', { name: answer });
if (name && existingComponents && existingComponents.includes(name)) {
return "A component with that name already exists. You can always change it later.";
}

return true;
},
transformer: (answer) =>
plop.renderString("{{ sentenceCase name }}", {
name: answer,
}),
transformer: (answer) => plop.renderString('{{ sentenceCase name }}', { name: answer }),
},
],
actions: (data) => {
data.description = `The ${data.name} component is...`;
data.folderName = plop.renderString(
"{{ lowerCase (camelCase name) }}",
data
);
data.folderName = plop.renderString('{{ lowerCase (camelCase name) }}', data);
data.pkg = pkg;
data.tokens = { name: tokens.name, version: tokens.version };
data.builder = { name: builder.name, version: builder.version };

return [
{
type: "addMany",
type: 'addMany',
destination: `${srcPath}/{{ folderName }}`,
base: "templates",
templateFiles: "templates/**/*.hbs",
base: 'templates',
templateFiles: 'templates/**/*.hbs',
skipIfExists: true,
},
{
type: "install",
type: 'install',
root: rootFolder,
},
(data, config, plop) =>
plop.renderString(
`Successfully created component {{ folderName }}. To preview your component, run \`yarn dev\` and navigate to the {{ folderName }} story.`
),
(data, config, plop) => plop.renderString(`Successfully created component {{ folderName }}. To preview your component, run \`yarn dev\` and navigate to the {{ folderName }} story.`),
];
},
});

plop.setPrompt("autocomplete", autocompletePrompt);
plop.setGenerator("story", {
description: "Storybook generator for existing components",
plop.setPrompt('autocomplete', autocompletePrompt);
plop.setGenerator('story', {
description: 'Storybook generator for existing components',
prompts: [
{
type: "autocomplete",
name: "folderName",
message: "Select the component you wish to update",
source: (_, input = "") =>
new Promise((resolve, reject) => {
if (existingComponents.length === 0) reject("No components found.");
setTimeout(() => {
const results = fuzzy.filter(input, existingComponents);
if (results && results.length > 0)
resolve(results.map((r) => r.string));
}, Math.random() * 470 + 30);
}),
emptyText: "No components match the search.",
type: 'autocomplete',
name: 'folderName',
message: 'Select the component you wish to update',
source: (_, input = '') => new Promise((resolve, reject) => {
if (existingComponents.length === 0) reject('No components found.');
setTimeout(() => {
const results = fuzzy.filter(input, existingComponents);
if (results && results.length > 0) resolve(results.map((r) => r.string));
}, Math.random() * 470 + 30);
}),
emptyText: 'No components match the search.',
},
],
actions: (data) => {
data.name = plop.renderString("{{ sentenceCase folderName }}", data);
data.name = plop.renderString('{{ sentenceCase folderName }}', data);
data.description = `The ${data.name} component is...`;

const metadataPath = plop.renderString(
`${srcPath}/{{ folderName }}/metadata`,
data
);
const metadataPath = plop.renderString(`${srcPath}/{{ folderName }}/metadata`, data);
data.example = getExistingMarkupExample(metadataPath, data.name, plop);

return [
{
type: "addMany",
type: 'addMany',
destination: `${srcPath}/{{ folderName }}/stories`,
base: "templates/stories",
templateFiles: "templates/stories/*.hbs",
base: 'templates/stories',
templateFiles: 'templates/stories/*.hbs',
skipIfExists: true,
},
{
type: "install",
type: 'install',
root: rootFolder,
},
(data, config, plop) =>
plop.renderString(
`Successfully updated {{ folderName }}. To preview your component, run \`yarn dev\` and navigate to the {{ folderName }} story.`,
data
),
(data, config, plop) => plop.renderString(`Successfully updated {{ folderName }}. To preview your component, run \`yarn dev\` and navigate to the {{ folderName }} story.`, data),
];
},
});
Expand Down
2 changes: 1 addition & 1 deletion tools/generator/templates/.npmignore.hbs
Original file line number Diff line number Diff line change
@@ -1 +1 @@
/dist/docs/
/dist/docs/
12 changes: 6 additions & 6 deletions tools/generator/templates/README.md.hbs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# @spectrum-css/{{folderName}}
# @spectrum-css/{{ folderName }}

> The Spectrum CSS
{{name}}
component This package is part of the [Spectrum CSS
project](https://github.com/adobe/spectrum-css). See the [Spectrum CSS
documentation](https://opensource.adobe.com/spectrum-css/{{folderName}}).
> The Spectrum CSS {{ name }} component

This package is part of the [Spectrum CSS project](https://github.com/adobe/spectrum-css).

See the [Spectrum CSS documentation](https://opensource.adobe.com/spectrum-css/{{ folderName }}).
2 changes: 1 addition & 1 deletion tools/generator/templates/gulpfile.js.hbs
Original file line number Diff line number Diff line change
@@ -1 +1 @@
module.exports = require('@spectrum-css/component-builder-simple');
module.exports = require('@spectrum-css/component-builder-simple');
59 changes: 40 additions & 19 deletions tools/generator/templates/index.css.hbs
Original file line number Diff line number Diff line change
@@ -1,19 +1,40 @@
/*! Copyright 2023 Adobe. All rights reserved. This file is licensed to you
under the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or
agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, either
express or implied. See the License for the specific language governing
permissions and limitations under the License. */ .spectrum-{{pascalCase name}}
{ /* Variables defined here */ /* --spectrum-{{folderName}}-... */ &:lang(ja),
&:lang(zh), &:lang(ko) { --spectrum-{{folderName}}-line-height-cjk:
var(--spectrum-cjk-line-height-100); } } .spectrum-{{pascalCase name}}--sizeS {}
.spectrum-{{pascalCase name}}--sizeM {} .spectrum-{{pascalCase name}}--sizeL {}
.spectrum-{{pascalCase name}}--sizeXL {} @media (forced-colors: active) {
.spectrum-{{pascalCase name}}
{ --highcontrast-{{folderName}}-content-color-default: CanvasText;
forced-color-adjust: none; } } .spectrum-{{pascalCase name}}
{ /* Properties defined here */ color: var(--highcontrast-{{folderName}}-content-color-default,
var(--mod-{{folderName}}-content-color-default, var(--spectrum-{{folderName}}-content-color-default)));
}
/*!
Copyright 2023 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/

.spectrum-{{ pascalCase name }} {
/* Variables defined here */
/* --spectrum-{{ folderName }}-... */

&:lang(ja),
&:lang(zh),
&:lang(ko) {
--spectrum-{{ folderName }}-line-height-cjk: var(--spectrum-cjk-line-height-100);
}
}

.spectrum-{{ pascalCase name }}--sizeS {}
.spectrum-{{ pascalCase name }}--sizeM {}
.spectrum-{{ pascalCase name }}--sizeL {}
.spectrum-{{ pascalCase name }}--sizeXL {}

@media (forced-colors: active) {
.spectrum-{{ pascalCase name }} {
--highcontrast-{{ folderName }}-content-color-default: CanvasText;

forced-color-adjust: none;
}
}

.spectrum-{{ pascalCase name }} {
/* Properties defined here */
color: var(--highcontrast-{{ folderName }}-content-color-default, var(--mod-{{ folderName }}-content-color-default, var(--spectrum-{{ folderName }}-content-color-default)));
}
Loading

0 comments on commit 189ced1

Please sign in to comment.