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

WIP: implement JSON story file format as indexer #22296

Closed
Closed
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
23 changes: 15 additions & 8 deletions code/addons/docs/src/preset.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import fs from 'fs-extra';
import remarkSlug from 'remark-slug';
import remarkExternalLinks from 'remark-external-links';
import remarkSlug from 'remark-slug';
import { dedent } from 'ts-dedent';

import type { CsfPluginOptions } from '@storybook/csf-plugin';
import { loadCsf, loadCsfFromJson } from '@storybook/csf-tools';
import { global } from '@storybook/global';
import type { CompileOptions, JSXOptions } from '@storybook/mdx2-csf';
import { logger } from '@storybook/node-logger';
import type {
IndexerOptions,
StoryIndexer,
DocsOptions,
IndexerOptions,
Options,
StorybookConfig,
StoryIndexer,
} from '@storybook/types';
import type { CsfPluginOptions } from '@storybook/csf-plugin';
import type { JSXOptions, CompileOptions } from '@storybook/mdx2-csf';
import { global } from '@storybook/global';
import { loadCsf } from '@storybook/csf-tools';
import { logger } from '@storybook/node-logger';
import { ensureReactPeerDeps } from './ensure-react-peer-deps';

async function webpack(
Expand Down Expand Up @@ -149,6 +149,13 @@ const storyIndexers = (indexers: StoryIndexer[] | null) => {
test: /(stories|story)\.mdx$/,
indexer: mdxIndexer,
},
{
test: /(stories|story)\.json$/,
indexer: async (fileName: string, opts: IndexerOptions) => {
const code = (await fs.readFile(fileName, 'utf-8')).toString();
return loadCsfFromJson(code, { ...opts, fileName });
},
},
...(indexers || []),
];
};
Expand Down
6 changes: 3 additions & 3 deletions code/lib/builder-vite/src/codegen-importfn-script.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { logger } from '@storybook/node-logger';
import type { Options } from '@storybook/types';
import * as path from 'path';
import { normalizePath } from 'vite';
import type { Options } from '@storybook/types';
import { logger } from '@storybook/node-logger';

import { listStories } from './list-stories';

Expand Down Expand Up @@ -29,7 +29,7 @@ async function toImportFn(stories: string[]) {
const objectEntries = stories.map((file) => {
const ext = path.extname(file);
const relativePath = normalizePath(path.relative(process.cwd(), file));
if (!['.js', '.jsx', '.ts', '.tsx', '.mdx', '.svelte', '.vue'].includes(ext)) {
if (!['.js', '.jsx', '.ts', '.tsx', '.mdx', '.svelte', '.vue', '.json'].includes(ext)) {
logger.warn(`Cannot process ${ext} file with storyStoreV7: ${relativePath}`);
}

Expand Down
58 changes: 53 additions & 5 deletions code/lib/csf-tools/src/CsfFile.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
/// <reference types="@types/jest" />;

/* eslint-disable no-underscore-dangle */
import { dedent } from 'ts-dedent';
import yaml from 'js-yaml';
import { loadCsf } from './CsfFile';
import { dedent } from 'ts-dedent';
import { loadCsf, loadCsfFromJson } from './CsfFile';

expect.addSnapshotSerializer({
print: (val: any) => yaml.dump(val).trimEnd(),
Expand Down Expand Up @@ -529,9 +529,57 @@ describe('CsfFile', () => {
}
`)
).toMatchInlineSnapshot(`
meta:
title: Chip
stories: []
meta:
title: Chip
stories: []
`);
});
});

describe('json parsing', () => {
it('json', () => {
expect(
loadCsfFromJson(
JSON.stringify({
title: 'Foo/Bar/Baz',
parameters: {
server: {
params: {
ParamA: 'ParamA',
},
},
},
args: {
ArgsA: 'ArgsA',
},
stories: [
{
name: 'StoryA',
args: {
StoryArgsA: 'StoryArgsA',
},
},
{
name: 'StoryB',
args: {
StoryArgsB: 'StoryArgsB',
},
},
],
}),
{
fileName: 'foo.json',
makeTitle: (path) => path,
}
)
).toMatchInlineSnapshot(`
meta:
title: Foo/Bar/Baz
stories:
- id: foo-bar-baz--storya
name: StoryA
- id: foo-bar-baz--storyb
name: StoryB
`);
});
});
Expand Down
41 changes: 39 additions & 2 deletions code/lib/csf-tools/src/CsfFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,14 @@ import * as t from '@babel/types';
import * as generate from '@babel/generator';

import * as traverse from '@babel/traverse';
import { toId, isExportStory, storyNameFromExport } from '@storybook/csf';
import type { Tag, StoryAnnotations, ComponentAnnotations } from '@storybook/types';
import { isExportStory, storyNameFromExport, toId } from '@storybook/csf';
import type {
ComponentAnnotations,
IndexedCSFFile,
IndexedStory,
StoryAnnotations,
Tag,
} from '@storybook/types';
import { babelParse } from './babelParse';
import { findVarInitialization } from './findVarInitialization';

Expand Down Expand Up @@ -525,6 +531,37 @@ export const loadCsf = (code: string, options: CsfOptions) => {
return new CsfFile(ast, options);
};

/**
* loadCsfFromJson reads a JSON string and returns an IndexedCSFFile
* @param jsonString the JSON string to parse
* @param options the CsfOptions to use when creating the IndexedCSFFile
* @returns an IndexedCSFFile
*/
export const loadCsfFromJson = (jsonString: string, options: CsfOptions): IndexedCSFFile => {
const json = JSON.parse(jsonString);
const meta: StaticMeta = {
title: json.title,
// TODO: meta tags?
};
// TODO: title format helpers?
const metaTitle = meta.title.replace(/\/|\\/g, '-').toLowerCase();
const stories: IndexedStory[] = json.stories.map((story: any) => {
const id = `${metaTitle}--${story.name.toLowerCase().replace(/ /g, '-')}`;
const { name } = story;
// TODO: how to extract / load parameters?
// TODO: how to extract / load tags?
return {
id,
name,
// TODO: add parameters, tags?
} as IndexedStory;
});
return {
meta,
stories,
};
};

interface FormatOptions {
sourceMaps?: boolean;
}
Expand Down