Skip to content

Commit

Permalink
docs(generatejs): 📝 update sb preview templates generation
Browse files Browse the repository at this point in the history
  • Loading branch information
navin-moorthy committed Sep 2, 2021
1 parent e0b3140 commit 2b7c51d
Show file tree
Hide file tree
Showing 10 changed files with 93 additions and 159 deletions.
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ yarn.lock
storybook-static

__js
templates
templates.ts
docs
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,6 @@ yarn-error.log*
size-plugin.json
stats-react.json
stats.html

#Project
templates
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ yarn.lock
storybook-static

__js
templates
templates.ts
docs
CHANGELOG.md
16 changes: 8 additions & 8 deletions .storybook/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export function createPreviewTabs(props: Props) {

if (js) {
tabs.push({
tab: "ReactJS",
tab: "JSX",
template: js,
language: "jsx",
copy: true,
Expand All @@ -57,7 +57,7 @@ export function createPreviewTabs(props: Props) {

if (jsUtils) {
tabs.push({
tab: "UtilsJS",
tab: "UtilsJSX",
template: jsUtils,
language: "jsx",
copy: true,
Expand All @@ -67,7 +67,7 @@ export function createPreviewTabs(props: Props) {

if (ts) {
tabs.push({
tab: "React",
tab: "TSX",
template: ts,
language: "tsx",
copy: true,
Expand All @@ -77,7 +77,7 @@ export function createPreviewTabs(props: Props) {

if (tsUtils) {
tabs.push({
tab: "Utils",
tab: "UtilsTSX",
template: tsUtils,
language: "tsx",
copy: true,
Expand Down Expand Up @@ -107,9 +107,9 @@ var previews = arguments[0];
return {
framework: "reactjs",
files: {
"src/App.js": previews["ReactJS"][0],
"src/App.js": previews["JSX"][0],
"src/styles.css": previews["CSS"] ? previews["CSS"][0] : "",
...(previews["UtilsJS"] ? {"src/Utils.component.js": previews["UtilsJS"][0]} : {}),
...(previews["UtilsJS"] ? {"src/Utils.component.js": previews["UtilsJSX"][0]} : {}),
},
userDependencies: ${joinStrs(dependencies)},
};`) as CodeSandboxTemplate;
Expand All @@ -120,9 +120,9 @@ var previews = arguments[0];
return {
framework: "react",
files: {
"src/App.tsx": previews["React"][0],
"src/App.tsx": previews["TSX"][0],
"src/styles.css": previews["CSS"] ? previews["CSS"][0] : "",
...(previews["Utils"] ? {"src/Utils.component.tsx": previews["Utils"][0]} : {}),
...(previews["Utils"] ? {"src/Utils.component.tsx": previews["UtilsTSX"][0]} : {}),
},
userDependencies: ${joinStrs(dependencies)},
};`) as CodeSandboxTemplate;
174 changes: 60 additions & 114 deletions scripts/generate-js.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,137 +3,83 @@ const path = require("path");
const chalk = require("chalk");
const globFs = require("glob-fs")();
const outdent = require("outdent");
const { camelCase, startCase } = require("lodash");

const {
walkSync,
createFile,
getDirectories,
createDirectory,
} = require("./utils/fs-utils");

const transpileTs = require("./transpile-ts");
const { createFile, createDirectory } = require("./utils/fs-utils");

// -> get all the component folders [accordion, breadcrumb...]
// -> find all the .components inside the folders
// -> create object with component pairs
// { accordion: [Accordion.component.tsx, AccordionStyled.component.tsx] }
// -> loop through them and create template.ts file
function getComponentFolderPairs() {
const componentFolders = getDirectories(
path.resolve(__dirname, "../src"),
).filter(path => !path.match(/(__mocks__|utils)/));

const components = componentFolders.reduce((prev, curr) => {
const folderName = path.basename(curr);
const allfiles = walkSync(`${curr}${path.sep}stories`).filter(fn =>
fn.match(/(\.component\.tsx|\.css)$/),
);
function globRecurse(file) {
// `file.pattern` is an object with a `glob` (string) property
file.recurse = file.pattern.glob.indexOf("**") !== -1;
return file;
}

const componentArg = process.argv[2];
const folderToRead = componentArg
? `src/${componentArg}/**/*.component.*`
: "src/**/*.component.*";
//

return { ...prev, [folderName]: allfiles };
}, {});
/**
* Get all the files from the folder.
*/
const files = globFs.use(globRecurse).readdirSync(folderToRead, {});

console.log(
chalk.blueBright.bold(`\nComponent Folder Pairs Successfully Created..`),
);
const addPackageName = string =>
string
.replace("../../index", "@renderlesskit/react")
.replace("../../../index", "@renderlesskit/react");

return components;
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}

function generateImportString(component, index) {
const componentPath = component.split("stories")[1].replace(/\\/g, "/");
const jsComponentName = componentPath.replace("tsx", "jsx");
const componentName = path.basename(componentPath);
const templateVarName = camelCase(
componentName.replace(".component.tsx", "").replace(".css", ""),
);

const warningMsg =
index === 0
? "// Auto Generated File, Do not modify directly!! execute `yarn generatejs` to regenerate\n"
: "";

let importString = outdent`
${warningMsg}
// @ts-ignore
export { default as ${templateVarName}Template } from "!!raw-loader!.${componentPath}";\n
// @ts-ignore
export { default as ${templateVarName}TemplateJs } from "!!raw-loader!./__js${jsComponentName}";\n
const createTemplateFile = (code, name, type, dir) => {
const componentName = `${name}${capitalizeFirstLetter(type)}`;
const finalCode = addPackageName(code);
const template = outdent`
export const ${componentName} = \`
${finalCode}
\`
export default ${componentName};
`;
const templatePath = path.join(dir, `${componentName}.ts`);

if (componentPath.endsWith(".css")) {
importString = outdent`
${warningMsg}
// @ts-ignore
export { default as ${templateVarName}CssTemplate } from "!!raw-loader!.${componentPath}";\n
`;
}
createFile(templatePath, template);

return importString;
}
console.log(chalk.green.bold(`CREATED: ${componentName}`));
};

function generateTemplateFile() {
const components = getComponentFolderPairs();
console.log(chalk.blueBright.bold(`Generating template.ts files..`));

Object.keys(components).forEach(componentName => {
const templateFilePath = path.join(
__dirname,
"../src",
componentName,
"stories",
"templates.ts",
);
const generatePreviewTemplateFiles = filePath => {
const storiesDirectory = path.dirname(filePath);
const templatesFolderPath = `${storiesDirectory}${path.sep}templates`;
const componentName = path.basename(filePath).replace(".component.tsx", "");
const componentType = path.extname(filePath).replace(".", "");

createFile(templateFilePath, "");

const componentPairs = components[componentName];
componentPairs.forEach((component, index) => {
const importString = generateImportString(component, index);
console.log(
chalk.green.bold(
`CREATED: ${startCase(componentName)} templates at ${chalk.cyanBright(
path.relative("./", templateFilePath),
)}`,
),
);

fs.appendFileSync(templateFilePath, importString, "UTF-8", {
flags: "a+",
});
});
});
}
const templateDir = path.join(process.cwd(), templatesFolderPath);
createDirectory(templateDir);

const generateJsFiles = filePath => {
const code = fs.readFileSync(path.join(process.cwd(), filePath), {
let code = fs.readFileSync(path.join(process.cwd(), filePath), {
encoding: "utf8",
});
createTemplateFile(code, componentName, componentType, templateDir);

const transpiledCode = transpileTs(code);
const templateFilePath = filePath
.replace("stories", `stories${path.sep}__js`)
.replace(".tsx", ".jsx");
const templateDir = path.join(process.cwd(), path.dirname(templateFilePath));

createDirectory(templateDir);

const componentName = path.basename(templateFilePath);
const templatePath = path.join(templateDir, componentName);
const jsCode = transpileTs(code);
createTemplateFile(jsCode, componentName, "jsx", templateDir);

console.log(chalk.green.bold(`CREATED: ${componentName}`));

createFile(templatePath, transpiledCode);
try {
const cssFilePath = path.join(
process.cwd(),
`${storiesDirectory}${path.sep}${componentName}.css`,
);
if (fs.existsSync(cssFilePath)) {
const cssCode = fs.readFileSync(cssFilePath, { encoding: "utf8" });
createTemplateFile(cssCode, componentName, "css", templateDir);
}
} catch (err) {
console.error(err);
}
};

function globRecurse(file) {
// `file.pattern` is an object with a `glob` (string) property
file.recurse = file.pattern.glob.indexOf("**") !== -1;
return file;
}

const files = globFs.use(globRecurse).readdirSync("**/*.component.tsx", {});

console.log(chalk.blueBright.bold(`Generating JS Files..`));
files.forEach(filePath => generateJsFiles(filePath));
files.forEach(filePath => generatePreviewTemplateFiles(filePath));

generateTemplateFile();
console.log(chalk.blueBright.bold(`\nTemplates created successfully..`));
10 changes: 4 additions & 6 deletions src/accordion/stories/AccordionBasic.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import * as React from "react";
import { Meta } from "@storybook/react";
import { CompositeState } from "reakit/ts";
import { CompositeState } from "reakit";

import js from "./templates/AccordionBasicJsx";
import ts from "./templates/AccordionBasicTsx";
import { AccordionInitialState } from "../AccordionState";
import { App as Accordion } from "./AccordionBasic.component";
import { createPreviewTabs } from "../../../.storybook/utils";
import { accordionBasicTemplate, accordionBasicTemplateJs } from "./templates";

export const Default: React.FC<
Omit<AccordionInitialState, keyof CompositeState>
Expand All @@ -16,10 +17,7 @@ export default {
title: "Accordion/Basic",
parameters: {
layout: "centered",
preview: createPreviewTabs({
js: accordionBasicTemplateJs,
ts: accordionBasicTemplate,
}),
preview: createPreviewTabs({ js, ts }),
},
} as Meta;

Expand Down
10 changes: 4 additions & 6 deletions src/accordion/stories/AccordionMulti.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import * as React from "react";
import { Meta } from "@storybook/react";
import { CompositeState } from "reakit/ts";
import { CompositeState } from "reakit";

import js from "./templates/AccordionMultiJsx";
import ts from "./templates/AccordionMultiTsx";
import { AccordionInitialState } from "../AccordionState";
import { App as Accordion } from "./AccordionMulti.component";
import { createPreviewTabs } from "../../../.storybook/utils";
import { accordionMultiTemplate, accordionMultiTemplateJs } from "./templates";

export const Default: React.FC<
Omit<AccordionInitialState, keyof CompositeState>
Expand All @@ -16,10 +17,7 @@ export default {
title: "Accordion/Multi",
parameters: {
layout: "centered",
preview: createPreviewTabs({
js: accordionMultiTemplateJs,
ts: accordionMultiTemplate,
}),
preview: createPreviewTabs({ js, ts }),
},
} as Meta;

Expand Down
14 changes: 4 additions & 10 deletions src/accordion/stories/AccordionStyled.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ import * as React from "react";
import { Meta } from "@storybook/react";
import { CompositeState } from "reakit";

import {
accordionStyledTemplate,
accordionStyledTemplateJs,
accordionStyledCssTemplate,
} from "./templates";
import "./AccordionStyled.css";
import js from "./templates/AccordionStyledJsx";
import ts from "./templates/AccordionStyledTsx";
import css from "./templates/AccordionStyledCss";
import { AccordionInitialState } from "../AccordionState";
import { App as Accordion } from "./AccordionStyled.component";
import { createPreviewTabs } from "../../../.storybook/utils";
Expand All @@ -21,11 +19,7 @@ export default {
title: "Accordion/Styled",
parameters: {
layout: "centered",
preview: createPreviewTabs({
js: accordionStyledTemplateJs,
ts: accordionStyledTemplate,
css: accordionStyledCssTemplate,
}),
preview: createPreviewTabs({ js, ts, css }),
},
} as Meta;

Expand Down
13 changes: 4 additions & 9 deletions src/accordion/stories/AccordionZAuto.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import * as React from "react";
import { Meta } from "@storybook/react";
import { CompositeState } from "reakit/ts";
import { CompositeState } from "reakit";

import js from "./templates/AccordionZAutoJsx";
import ts from "./templates/AccordionZAutoTsx";
import { AccordionInitialState } from "../AccordionState";
import { App as Accordion } from "./AccordionZAuto.component";
import { createPreviewTabs } from "../../../.storybook/utils";
import { accordionZAutoTemplate, accordionZAutoTemplateJs } from "./templates";

export const Default: React.FC<
Omit<AccordionInitialState, keyof CompositeState>
Expand All @@ -16,12 +17,6 @@ export default {
title: "Accordion/zAuto",
parameters: {
layout: "centered",
preview: createPreviewTabs({
js: accordionZAutoTemplateJs,
ts: accordionZAutoTemplate,
}),
preview: createPreviewTabs({ js, ts }),
},
} as Meta;

export const Base = Default.bind({});
Base.args = {};
Loading

0 comments on commit 2b7c51d

Please sign in to comment.