Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: reorganize slider components & improved js generation script #148

Merged
merged 6 commits into from
Nov 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 73 additions & 51 deletions scripts/generate-js.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,15 @@ const fs = require("fs");
const path = require("path");
const chalk = require("chalk");
const globFs = require("glob-fs")();
const transpileTs = require("./transpile-ts");
const outdent = require("outdent");
const { camelCase } = require("lodash");

function recurse(file) {
// `file.pattern` is an object with a `glob` (string) property
file.recurse = file.pattern.glob.indexOf("**") !== -1;
return file;
}
const { camelCase, startCase } = require("lodash");
const transpileTs = require("./transpile-ts");

// Create a new folder at the specified path
function createDirectory(path) {
try {
if (!fs.existsSync(path)) {
fs.mkdirSync(path);
fs.mkdirSync(path, { recursive: true });
}
} catch (err) {
console.error(`[createDirectory]: Failed to create director at ${path}`);
Expand All @@ -32,30 +26,21 @@ function createFile(filePath, fileContent = "") {
});
}

const generateJsFiles = filePath => {
const code = fs.readFileSync(path.join(process.cwd(), filePath), {
encoding: "utf8",
});
function walkSync(dir, filelist = []) {
const files = fs.readdirSync(dir);

const transpiledCode = transpileTs(code);
const templateFilePath = filePath
.replace("stories", "stories/__js")
.replace(".tsx", ".jsx");
files.forEach(function (file) {
const fullPath = path.join(dir, file);

const templateDir = path.join(
process.cwd(),
templateFilePath.substring(0, templateFilePath.lastIndexOf(path.sep)),
);

createDirectory(templateDir);

const templatePath = path.join(process.cwd(), templateFilePath);

const componentName = templatePath.split(`__js${path.sep}`)[1];
console.log(chalk.green.bold(`CREATED: ${componentName}`), `${filePath}`);
if (isDirectory(fullPath)) {
filelist = walkSync(fullPath, filelist);
} else {
filelist.push(fullPath);
}
});

createFile(templatePath, transpiledCode);
};
return filelist;
}

// -> get all the component folders [accordion, breadcrumb...]
// -> find all the .components inside the folders
Expand All @@ -75,41 +60,47 @@ function getComponentFolderPairs() {
).filter(path => !path.match(/(__mocks__|utils)/));

const components = componentFolders.reduce((prev, curr) => {
const folderName = path.parse(curr);
const allfiles = fs
.readdirSync(`${curr}/stories`)
.filter(fn => fn.match(/(\.component\.tsx|\.css)$/));
const folderName = path.basename(curr);
const allfiles = walkSync(`${curr}${path.sep}stories`).filter(fn =>
fn.match(/(\.component\.tsx|\.css)$/),
);

return { ...prev, [folderName.base]: allfiles };
return { ...prev, [folderName]: allfiles };
}, {});

console.log(
chalk.blueBright.bold(`\nComponent Folder Pairs Successfully Created..`),
);

return components;
}

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(
component.replace(".component.tsx", "").replace(".css", ""),
componentName.replace(".component.tsx", "").replace(".css", ""),
);

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

const jsComponent = component.replace("tsx", "jsx");
let importString = outdent`
${warningMsg}
// @ts-ignore
export { default as ${templateVarName}Template } from "!!raw-loader!./${component}";\n
export { default as ${templateVarName}Template } from "!!raw-loader!.${componentPath}";\n
// @ts-ignore
export { default as ${templateVarName}TemplateJs } from "!!raw-loader!./__js/${jsComponent}";\n
export { default as ${templateVarName}TemplateJs } from "!!raw-loader!./__js${jsComponentName}";\n
`;

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

Expand All @@ -118,10 +109,9 @@ function generateImportString(component, index) {

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

Object.keys(components).forEach(componentName => {
const componentPairs = components[componentName];

const templateFilePath = path.join(
__dirname,
"../src",
Expand All @@ -132,23 +122,55 @@ function generateTemplateFile() {

createFile(templateFilePath, "");

const componentPairs = components[componentName];
componentPairs.forEach((component, index) => {
const importString = generateImportString(component, index);

console.log(
chalk.red.yellow(
`Writing template.ts (${chalk.cyanBright(component)})`,
),
);

fs.appendFileSync(templateFilePath, importString, "UTF-8", {
flags: "a+",
});
});

console.log(
chalk.green.bold(
`CREATED: ${startCase(componentName)} templates at ${chalk.cyanBright(
path.relative("./", templateFilePath),
)}`,
),
);
});
}

generateTemplateFile();
const generateJsFiles = filePath => {
const code = fs.readFileSync(path.join(process.cwd(), filePath), {
encoding: "utf8",
});

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);

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

createFile(templatePath, transpiledCode);
};

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(recurse).readdirSync("**/*.component.tsx", {});
const files = globFs.use(globRecurse).readdirSync("**/*.component.tsx", {});

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

generateTemplateFile();
2 changes: 1 addition & 1 deletion src/slider/stories/MultiSlider.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
multiSliderTemplateJs,
sliderCssTemplate,
} from "./templates";
import { App as MultiSlider } from "./MultiSlider.component";
import { App as MultiSlider } from "./components/MultiSlider.component";
import { createPreviewTabs } from "../../../scripts/create-preview-tabs";

export default {
Expand Down
2 changes: 1 addition & 1 deletion src/slider/stories/RangeSlider.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
sliderCssTemplate,
} from "./templates";
import "./Slider.css";
import { App as RangeSlider } from "./RangeSlider.component";
import { App as RangeSlider } from "./components/RangeSlider.component";
import { createPreviewTabs } from "../../../scripts/create-preview-tabs";

export default {
Expand Down
2 changes: 1 addition & 1 deletion src/slider/stories/SingleOriginSlider.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
sliderCssTemplate,
} from "./templates";
import { createPreviewTabs } from "../../../scripts/create-preview-tabs";
import { App as SingleOriginSlider } from "./SingleOriginSlider.component";
import { App as SingleOriginSlider } from "./components/SingleOriginSlider.component";

export default {
component: SingleOriginSlider,
Expand Down
2 changes: 1 addition & 1 deletion src/slider/stories/SingleReversedSlider.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
sliderCssTemplate,
} from "./templates";
import { createPreviewTabs } from "../../../scripts/create-preview-tabs";
import { App as SingleReversedSlider } from "./SingleReversedSlider.component";
import { App as SingleReversedSlider } from "./components/SingleReversedSlider.component";

export default {
component: SingleReversedSlider,
Expand Down
2 changes: 1 addition & 1 deletion src/slider/stories/SingleSlider.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
singleSliderTemplateJs,
sliderCssTemplate,
} from "./templates";
import { App as SingleSlider } from "./SingleSlider.component";
import { App as SingleSlider } from "./components/SingleSlider.component";
import { createPreviewTabs } from "../../../scripts/create-preview-tabs";

export default {
Expand Down
2 changes: 1 addition & 1 deletion src/slider/stories/SingleVerticalSlider.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
sliderCssTemplate,
} from "./templates";
import { createPreviewTabs } from "../../../scripts/create-preview-tabs";
import { App as SingleVerticalSlider } from "./SingleVerticalSlider.component";
import { App as SingleVerticalSlider } from "./components/SingleVerticalSlider.component";

export default {
component: SingleVerticalSlider,
Expand Down
2 changes: 1 addition & 1 deletion src/slider/stories/Slider.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as React from "react";
import { Meta, Story } from "@storybook/react";

import "./Slider.css";
import { App as Slider } from "./Slider.component";
import { App as Slider } from "./components/Slider.component";
import {
sliderTemplate,
sliderTemplateJs,
Expand Down