Skip to content

Commit

Permalink
chore: temp dynamicRequire with ts
Browse files Browse the repository at this point in the history
  • Loading branch information
atanasster committed May 7, 2021
1 parent dadbb2b commit 9d2cf8a
Show file tree
Hide file tree
Showing 13 changed files with 164 additions and 75 deletions.
2 changes: 1 addition & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@
"name": "jest cc-cli",
"program": "${workspaceFolder}/node_modules/.bin/jest",
"cwd": "${workspaceFolder}/plugins/cc-cli",
"args": ["-u", "VariantButton_rtr_doc"],
"args": ["-u", "cli-document-data"],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"disableOptimisticBPs": true,
Expand Down
1 change: 1 addition & 0 deletions core/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"@storybook/csf": "^0.0.1",
"deepmerge": "^4.2.2",
"escape-html": "^1.0.3",
"esm": "^3.2.25",
"faker": "^4.1.0",
"path": "^0.12.7",
"typescript": "^4.0.5"
Expand Down
22 changes: 22 additions & 0 deletions core/core/src/document.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/ban-types */
import { PropsWithChildren, ReactElement } from 'react';
import { CodeLocation, PackageInfo, StoryRenderFn } from './utility';
Expand Down Expand Up @@ -389,3 +390,24 @@ class DefaultStore {
}

export const getDefaultStore = (): Store => new DefaultStore();

export const assignProps = (
obj: Document | Story,
//@ts-expect-error remove story shorthand
{ storyName, story, ...props }: Document | Story,
): Document | Story => {
//preserve component and subcomponents as strings
const componentName = obj.component;
const subcomponentsName = obj.subcomponents;
Object.assign(obj, props);
if (componentName !== undefined) {
obj.component = componentName;
}
if (subcomponentsName !== undefined) {
obj.subcomponents = subcomponentsName;
}
if (storyName) {
obj.name = storyName;
}
return obj;
};
19 changes: 19 additions & 0 deletions core/core/src/find-up.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import fs from 'fs';
import path from 'path';

export const findUpFile = (
filePath: string,
fileName: string | string[],
levels = 10,
): string | null => {
const files = fs.readdirSync(filePath);
if (levels === 0) {
return null;
}
const arFiles: string[] = Array.isArray(fileName) ? fileName : [fileName];
const pckg = files.find(file => arFiles.includes(file));
if (pckg) {
return path.resolve(filePath, pckg);
}
return findUpFile(path.resolve(filePath, '..'), fileName, levels - 1);
};
35 changes: 35 additions & 0 deletions core/core/src/modules.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import path from 'path';
import * as ts from 'typescript';

export const dynamicRequire = (filePath: string): any => {
const fileParts = filePath.split('.');
const ext = fileParts.pop()?.toLowerCase() || 'js';
if (['ts', 'tsx'].indexOf(ext) !== -1) {
const configPath = ts.findConfigFile(
path.dirname(filePath),
ts.sys.fileExists,
);
const config = configPath
? ts.readConfigFile(configPath, ts.sys.readFile)
: {
config: {
compilerOptions: {
allowJs: true,
jsx: ts.JsxEmit.ReactJSX,
module: ts.ModuleKind.CommonJS,
},
},
};

const program = ts.createProgram([filePath], config.config);
program.emit();
const jsFilePath = `${fileParts.join('.')}.js`;
try {
return require('esm')(module)(jsFilePath);
} finally {
//fs.unlinkSync(tmpFilePath);
}
}

return require('esm')(module)(filePath);
};
19 changes: 2 additions & 17 deletions core/core/src/node-utils.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,8 @@
import fs from 'fs';
import path from 'path';
import { BuildProps, defBundleName, defCssFileName } from './build';
export * from './webpack-interfaces';
export const findUpFile = (
filePath: string,
fileName: string | string[],
levels = 10,
): string | null => {
const files = fs.readdirSync(filePath);
if (levels === 0) {
return null;
}
const arFiles: string[] = Array.isArray(fileName) ? fileName : [fileName];
const pckg = files.find(file => arFiles.includes(file));
if (pckg) {
return path.resolve(filePath, pckg);
}
return findUpFile(path.resolve(filePath, '..'), fileName, levels - 1);
};
export * from './modules';
export * from './find-up';

export const defaultDistFolder = 'public';

Expand Down
18 changes: 2 additions & 16 deletions core/loader/src/replaceSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,21 +64,7 @@ ${contexts
`;
const storeConst = `const store = ${hashKey};\n`;
const loadStories = `
const assignProps = (obj, { storyName, story, ...props}) => {
//preserve component and subcomponents as strings
const componentName = obj.component;
const subcomponentsName = obj.subcomponents;
Object.assign(obj, props);
if (componentName !== undefined) {
obj.component = componentName;
}
if (subcomponentsName !== undefined) {
obj.subcomponents = subcomponentsName;
}
if (storyName) {
obj.name = storyName;
}
}
for (let i = 0; i < store.stores.length; i+= 1) {
const s = store.stores[i];
const doc = s.doc;
Expand Down Expand Up @@ -127,7 +113,7 @@ ${contexts
const newContent = `
const path = require('path-browserify');
const { loadPageTab } = require('@component-controls/core')
const { loadPageTab, assignProps } = require('@component-controls/core')
${imports}
${storeConst}
store.search = search.default || search;
Expand Down
6 changes: 0 additions & 6 deletions plugins/cc-cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@
"@component-controls/webpack-compile": "^3.9.1",
"@component-controls/webpack-configs": "^3.9.0",
"dot": "^1.1.3",
"esm": "^3.2.25",
"path": "^0.12.7"
},
"devDependencies": {
Expand Down Expand Up @@ -87,11 +86,6 @@
"^.+\\.(ts|tsx)?$": "ts-jest",
"^.+\\.(js|jsx)$": "babel-jest"
},
"globals": {
"ts-jest": {
"isolatedModules": true
}
},
"roots": [
"./test"
]
Expand Down
5 changes: 4 additions & 1 deletion plugins/cc-cli/src/data-templates/data-template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@ export const createDataTemplate = async (
if (controls) {
const values: Record<string, any> = existing?.[storyId] || {};
for (let i = Object.keys(values).length; i < numValues; i += 1) {
values[i.toString()] = randomizeData(controls);
const rnd = randomizeData(controls);
if (Object.keys(rnd).length) {
values[i.toString()] = rnd;
}
}
if (Object.keys(values).length) {
data[storyId] = values;
Expand Down
66 changes: 52 additions & 14 deletions plugins/cc-cli/src/store.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,26 @@
import { Components, Document, Stories } from '@component-controls/core';
import {
Components,
Document,
Stories,
assignProps,
} from '@component-controls/core';
import { dynamicRequire } from '@component-controls/core/node-utils';
import { parseStories } from '@component-controls/instrument';
import { loadStore } from '@component-controls/store';

interface StoreResults {
doc: Document;
stories: Stories;
components: Components;
storeName: string;
}
const cache: {
storyPath: Record<string, StoreResults>;
bundle: Record<string, StoreResults>;
} = {
storyPath: {},
bundle: {},
};
export const getStore = async ({
storyPath,
bundle,
Expand All @@ -10,22 +29,17 @@ export const getStore = async ({
storyPath: string;
bundle?: string;
name?: string;
}): Promise<
| {
doc: Document;
stories: Stories;
components: Components;
storeName: string;
}
| undefined
> => {
}): Promise<StoreResults | undefined> => {
if (bundle) {
if (!name) {
throw new Error(
'When using a bundle, you must specify the document title/name as name (-n) parameter',
);
}
const loadedStore = require(bundle);
if (cache.bundle[bundle]) {
return cache.bundle[bundle];
}
const loadedStore = require('esm')(module)(bundle);
const store = loadStore(loadedStore);
const doc = store.docs[name];
if (!doc) {
Expand All @@ -39,23 +53,47 @@ export const getStore = async ({
if (doc.isMDXComponent || !doc.stories.length) {
return undefined;
}

return {
cache.bundle[bundle] = {
doc,
stories: doc.stories.reduce((acc, id) => {
return { ...acc, [id]: store.stories[id] };
}, {}),
components: store.components,
storeName: 'bundle',
};
return cache.bundle[bundle];
} else {
if (cache.storyPath[storyPath]) {
return cache.storyPath[storyPath];
}

const { doc, stories, components = {} } = await parseStories(storyPath);

if (!doc || !stories) {
throw new Error(`Invalid story path ${storyPath}`);
}
if (doc.isMDXComponent || !Object.keys(stories).length) {
return undefined;
}
return { doc, stories, components, storeName: 'imports' };
try {
const loaded = dynamicRequire(storyPath);
if (loaded.default) {
assignProps(doc, loaded.default);
}
Object.keys(stories).forEach(storyId => {
if (loaded[storyId]) {
assignProps(stories[storyId], loaded[storyId]);
}
});
} catch (e) {
console.error(e);
}
cache.storyPath[storyPath] = {
doc,
stories,
components,
storeName: 'imports',
};
return cache.storyPath[storyPath];
}
};
13 changes: 13 additions & 0 deletions plugins/cc-cli/test/cli-document-data.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,19 @@ import { runTests } from './run-cli-tests';

describe('cli-document-data', () => {
randomizeSeed(11223344);
runTests('create cjs document', [
'-g',
'doc',
'-f',
'cjs',
'-d',
'5',
'-c',
'../../ui/components/.config',
'-i',
'Popover',
]);
return;
runTests('create cjs document', ['-g', 'doc', '-f', 'cjs', '-d', '10']);
runTests('create esm document', ['-g', 'doc', '-f', 'esm', '-d', '2']);
runTests('create typescript document', ['-g', 'doc', '-f', 'ts', '-d', '2']);
Expand Down
5 changes: 3 additions & 2 deletions plugins/cc-cli/test/run-cli-tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ export const runTests = (testName: string, args: string[]): void => {
await mockArgv(
[
...args,
'-c',
`${path.resolve(__dirname, './.config')}`,
...(args.indexOf('-c') === -1
? ['-c', `${path.resolve(__dirname, './.config')}`]
: []),
'-o',
outPath,
],
Expand Down
28 changes: 10 additions & 18 deletions ui/components/src/ActionBar/ActionBar.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,36 +8,28 @@ import { render, act } from '@testing-library/react';
import { renderErr } from '@component-controls/test-renderers';

import * as examples from './ActionBar.stories';
import data from './ActionBar.data';

describe('ActionBar', () => {
const configPath = path.resolve(__dirname, '../../.config');
const config = loadConfigurations(configPath);
let renderedExamples: ReturnType<typeof renderDocument> = [];
act(() => {
renderedExamples = renderDocument(examples, config, data);
renderedExamples = renderDocument(examples, config);
});
if (!renderedExamples) {
renderErr();
return;
}
renderedExamples.forEach(({ name, rendered, dataId, values }) => {
renderedExamples.forEach(({ name, rendered }) => {
describe(name, () => {
const runTests = () => {
it('snapshot', () => {
const { asFragment } = render(rendered);
expect(asFragment()).toMatchSnapshot();
});
it('accessibility', async () => {
const axeResults = await reactRunDOM<AxeResults>(rendered, run);
expect(axeResults).toHaveNoAxeViolations();
});
};
if (values) {
describe(dataId, runTests);
} else {
runTests();
}
it('snapshot', () => {
const { asFragment } = render(rendered);
expect(asFragment()).toMatchSnapshot();
});
it('accessibility', async () => {
const axeResults = await reactRunDOM<AxeResults>(rendered, run);
expect(axeResults).toHaveNoAxeViolations();
});
});
});
});

0 comments on commit 9d2cf8a

Please sign in to comment.