Skip to content

Commit

Permalink
feat: initial work on hmr
Browse files Browse the repository at this point in the history
  • Loading branch information
atanasster committed Feb 18, 2020
1 parent bc5b391 commit 25e5591
Show file tree
Hide file tree
Showing 12 changed files with 79 additions and 151 deletions.
17 changes: 16 additions & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,22 @@
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{{
{
"type": "node",
"request": "launch",
"name": "storybook",
"runtimeExecutable": "npm",
"cwd": "${workspaceFolder}",
"runtimeArgs": [
"run-script",
"debug"
],
"port": 9229,
"skipFiles": [
"<node_internals>/**"
]
},
{
"type": "node",
"request": "launch",
"name": "jest - current file",
Expand Down
1 change: 1 addition & 0 deletions core/loader/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"devDependencies": {
"@types/jest": "^25.1.2",
"@types/loader-utils": "^1.1.3",
"@types/webpack-env": "^1.15.1",
"cross-env": "^5.2.1",
"docz-rollup": "^2.1.0",
"eslint": "^6.5.1",
Expand Down
4 changes: 2 additions & 2 deletions core/loader/src/loader.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { getOptions } from 'loader-utils';
import { parseCSF, parseMDX } from '@component-controls/instrument';
import { LoaderOptions } from './types';
import storyFiles from './store';
import { addStoriesKind } from './store';

module.exports.default = async function(source: string) {
const options: LoaderOptions = getOptions(this) || {};
Expand All @@ -16,7 +16,7 @@ module.exports.default = async function(source: string) {
break;
}
if (stories) {
storyFiles.push(stories);
addStoriesKind(stories);
}
return source;
};
19 changes: 2 additions & 17 deletions core/loader/src/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
import { ReplaceSource } from 'webpack-sources';
import { toId, storyNameFromExport } from '@storybook/csf';
import { Story, StoriesGroup } from '@component-controls/instrument';
import jsStringEscape from 'js-string-escape';
import * as path from 'path';
import * as webpack from 'webpack';
import { createHash } from 'crypto';
import { StoryStore } from './types';
import store from './store';

class StoriesInjectPlugin {
public static pluginName = 'stories-inject-plugin';
private readonly compilationHash: string;

constructor() {
const hash = createHash('md5')
.update(new Date().getTime().toString())
Expand Down Expand Up @@ -63,19 +59,8 @@ class StoriesInjectPlugin {
const source = compilation.assets[file];
const placeholderPos = source.source().indexOf(placeholder);
if (placeholderPos > -1) {
const stories: StoryStore = {};
store.forEach((kind: StoriesGroup) => {
Object.keys(kind.stories).forEach(key => {
const story: Story = kind.stories[key];
if (kind.title && story.name) {
stories[toId(kind.title, storyNameFromExport(story.name))] = {
...story,
kind: kind.title,
};
}
});
});
const newContent = jsStringEscape(JSON.stringify(stories));
const newContent = jsStringEscape(JSON.stringify(store));
const source = compilation.assets[file];
const newSource = new ReplaceSource(source, file);
newSource.replace(
placeholderPos,
Expand Down
18 changes: 16 additions & 2 deletions core/loader/src/store.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
import { StoriesGroup } from '@component-controls/instrument';
import { toId, storyNameFromExport } from '@storybook/csf';
import { StoriesGroup, Story } from '@component-controls/instrument';
import { StoryStore } from './types';

const storyFiles: StoriesGroup[] = [];
const storyFiles: StoryStore = {};

export const addStoriesKind = (kind: StoriesGroup) => {
Object.keys(kind.stories).forEach(key => {
const story: Story = kind.stories[key];
if (kind.title && story.name) {
const id = toId(kind.title, storyNameFromExport(story.name));
storyFiles[id] = {
...story,
kind: kind.title,
};
}
});
};
export default storyFiles;
9 changes: 2 additions & 7 deletions core/loader/src/story-store-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,12 @@ const injectedStories = '__STORIES_HASH__INJECTED_STORIES__';

type StringifyFunction = () => StoryStore | undefined;

let store: StoryStore;

const storyStore: StringifyFunction = () => {
if (store) {
return store;
}
if (injectedStories) {
store = JSON.parse(injectedStories);
const store = JSON.parse(injectedStories);
return store;
}
return undefined;
};

export default storyStore();
export default storyStore;
2 changes: 1 addition & 1 deletion core/loader/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"outDir": "dist",
"rootDir": "src",
"declaration": true,
"types": ["node", "jest"],
"types": ["node", "jest", "webpack-env"],
"typeRoots": ["../../node_modules/@types", "node_modules/@types"]
},
"include": ["src/**/*", "src/typings.d.ts", "test"],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ onlyColors.story = {
},
};

export const noColors = props => <Button label="Choose colors" {...props} />;
export const noColors = () => <Button label="Choose colors" />;

noColors.story = {
parameters: {
Expand Down
75 changes: 35 additions & 40 deletions integrations/storybook/src/config-legacy.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { addDecorator, useEffect } from '@storybook/client-api';
import { CHANNEL_CREATED } from '@storybook/core-events';
import { ComponentControls } from '@component-controls/specification';
import { getControlValues } from '@component-controls/core';
import { __STORYBOOK_STORY_STORE__ as storyStore } from 'global';
import injectedStoryStore from '@component-controls/loader/dist/story-store-data';
import myStoryStore from '@component-controls/loader/dist/story-store-data';
import addons, { makeDecorator } from '@storybook/addons';
import { FORCE_RE_RENDER } from '@storybook/core-events';
import { docgenToControls } from './shared/smartControls';
Expand All @@ -18,8 +17,12 @@ addDecorator(
name: 'legacyControls',
parameterName: 'controls',
wrapper: (storyFn, context) => {
const channel = addons.getChannel();
useEffect(() => {
if (storyStore.__initilized) {
return;
}
storyStore.__initilized = true;
const channel = addons.getChannel();
const onNewData = ({
storyId,
controls,
Expand All @@ -35,46 +38,39 @@ addDecorator(
};
channel.on(SET_DATA_MSG, onNewData);

const onChannelCreated = () => {
if (storyStore._smartcontrols === undefined) {
storyStore._smartcontrols = true;
Object.keys(storyStore._data).forEach((id: string) => {
const story = storyStore._data[id];
const parameters = story.parameters || {};
const { addonControls = {}, controls } = parameters;
const { smart } = addonControls;
if (injectedStoryStore && smart) {
const ccStory = injectedStoryStore[id];
if (ccStory) {
if (ccStory.arguments && ccStory.arguments.length) {
const smartControls = docgenToControls(story.parameters);
if (smartControls && Object.keys(smartControls).length) {
story.parameters.controls = {
...smartControls,
...controls,
};
story.parameters.addonControls = {
...story.parameters.addonControls,
smartLoaded: true,
};
}
}
} else {
console.error('Invalid story id:', id);
}
}
});
channel.emit(FORCE_RE_RENDER);
}
};

channel.on(CHANNEL_CREATED, onChannelCreated);

const onGetAllStories = () => {
const smartStories: {
storyId: string;
controls: ComponentControls;
}[] = [];
const injectedStoryStore = myStoryStore();
Object.keys(storyStore._data).forEach((id: string) => {
const story = storyStore._data[id];
const parameters = story.parameters || {};
const { addonControls = {}, controls } = parameters;
const { smart } = addonControls;
if (injectedStoryStore && smart) {
const ccStory = injectedStoryStore[id];
if (ccStory) {
if (ccStory.arguments && ccStory.arguments.length) {
const smartControls = docgenToControls(story.parameters);
if (smartControls && Object.keys(smartControls).length) {
story.parameters.controls = {
...smartControls,
...controls,
};
story.parameters.addonControls = {
...story.parameters.addonControls,
smartLoaded: true,
};
}
}
} else {
console.error('Invalid story id:', id);
}
}
});
channel.emit(FORCE_RE_RENDER);
Object.keys(storyStore._data).forEach((id: string) => {
const parameters = storyStore._data[id].parameters || {};
const { controls, addonControls } = parameters;
Expand All @@ -94,10 +90,9 @@ addDecorator(
}
};
channel.on(GET_ALL_STORIES, onGetAllStories);

return () => {
storyStore.__initilized = false;
channel.removeListener(SET_DATA_MSG, onNewData);
channel.removeListener(CHANNEL_CREATED, onChannelCreated);
channel.removeListener(GET_ALL_STORIES, onGetAllStories);
};
}, []);
Expand Down
80 changes: 1 addition & 79 deletions integrations/storybook/src/shared/smartControls.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
import { ComponentControls } from '@component-controls/specification';
import { controlsFromProps } from '@component-controls/core';
/*
import { controlFromProps, controlsFromProps } from '@component-controls/core';
import {
inferPropsExtractor,
getInputRows,
} from '@storybook/addon-docs/blocks';
*/

export interface PropDef {
name: string;
required: boolean;
Expand All @@ -33,78 +27,6 @@ export interface SmartControlsConfig {
}
export type SmartControls = boolean | SmartControlsConfig;

/* const extractSmartControls = (
storyId: string,
parameters: Parameters,
): ComponentControls | null => {
const params = parameters || {};
const { component, framework = null, addonControls = {} } = params;
const { smart: smartControls } = addonControls;
if (!smartControls) {
return null;
}
if (!component) {
return null;
}
// check if mdx has parameters from mdx-compiler
const mdxStoryHasParameters =
params && params.mdxParams && params.mdxParams.length > 0;
// check if story has parameters from source-loader
const storyHasParameters =
params &&
params.storySource &&
params.storySource.locationsMap &&
params.storySource.locationsMap[storyId] &&
params.storySource.locationsMap[storyId].params &&
params.storySource.locationsMap[storyId].params.length > 0;
if (!mdxStoryHasParameters && !storyHasParameters) {
return null;
}
const {
extractProps = inferPropsExtractor(framework),
}: { extractProps: any } = params.docs || {};
if (!extractProps) {
return null;
}
const { include, exclude } = smartControls;
const props = extractProps(component);
const rows = getInputRows(props);
const smartProps = rows
? rows.reduce((acc: ComponentControls, row: PropDef) => {
if (typeof smartControls === 'object') {
if (Array.isArray(include) && !include.includes(row.name)) {
return acc;
}
if (Array.isArray(exclude) && exclude.includes(row.name)) {
return acc;
}
}
const field = controlFromProps(row.name, {
defaultValue: {
value:
typeof row.defaultValue === 'object'
? row.defaultValue.summary
: row.defaultValue,
computed: false,
},
required: row.required,
description: '',
type: {
name:
typeof row.type === 'object'
? row.type.type || row.type?.summary
: row.type,
},
});
if (field) {
return { ...acc, [row.name]: field };
}
return acc;
}, {})
: null;
return smartProps;
};
*/
export const docgenToControls = (
parameters: Parameters,
): ComponentControls | null => {
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"commit": "git-cz",
"contributors:add": "all-contributors add",
"contributors:generate": "all-contributors generate",
"debug": "NODE_OPTIONS=--inspect-brk start-storybook -p 9015 -c .storybook",
"storybook": "start-storybook -p 9015 -c .storybook",
"watch": "lerna run --parallel watch",
"build-storybook": "build-storybook -c .storybook -o docs"
Expand Down
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3530,7 +3530,7 @@
resolved "https://registry.yarnpkg.com/@types/unist/-/unist-2.0.3.tgz#9c088679876f374eb5983f150d4787aa6fb32d7e"
integrity sha512-FvUupuM3rlRsRtCN+fDudtmytGO6iHJuuRKS1Ss0pG5z8oX0diNEw94UEL7hgDbpN94rgaK5R7sWm6RrSkZuAQ==

"@types/webpack-env@^1.15.0":
"@types/webpack-env@^1.15.0", "@types/webpack-env@^1.15.1":
version "1.15.1"
resolved "https://registry.yarnpkg.com/@types/webpack-env/-/webpack-env-1.15.1.tgz#c8e84705e08eed430b5e15b39c65b0944e4d1422"
integrity sha512-eWN5ElDTeBc5lRDh95SqA8x18D0ll2pWudU3uWiyfsRmIZcmUXpEsxPU+7+BsdCrO2vfLRC629u/MmjbmF+2tA==
Expand Down

0 comments on commit 25e5591

Please sign in to comment.