From cdb507992d600137678fd16924489246ddfb6b70 Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Mon, 4 Dec 2023 09:04:41 +0100 Subject: [PATCH] Fix CSF Plugin for Angular --- code/lib/csf-plugin/src/index.ts | 12 +- code/lib/csf-tools/src/enrichCsf.test.ts | 392 +++++++++++++++++------ code/lib/csf-tools/src/enrichCsf.ts | 22 +- 3 files changed, 318 insertions(+), 108 deletions(-) diff --git a/code/lib/csf-plugin/src/index.ts b/code/lib/csf-plugin/src/index.ts index aed7a531ee32..962a192bd746 100644 --- a/code/lib/csf-plugin/src/index.ts +++ b/code/lib/csf-plugin/src/index.ts @@ -12,15 +12,17 @@ const logger = console; export const unplugin = createUnplugin((options) => { return { name: 'unplugin-csf', - enforce: 'pre', - loadInclude(id) { + transformInclude(id) { return STORIES_REGEX.test(id); }, - async load(fname) { - const code = await fs.readFile(fname, 'utf-8'); + async transform(code, id) { + const sourceCode = await fs.readFile(id, 'utf-8'); try { const csf = loadCsf(code, { makeTitle: (userTitle) => userTitle || 'default' }).parse(); - enrichCsf(csf, options); + const csfSource = loadCsf(sourceCode, { + makeTitle: (userTitle) => userTitle || 'default', + }).parse(); + enrichCsf(csf, csfSource, options); return formatCsf(csf, { sourceMaps: true }); } catch (err: any) { // This can be called on legacy storiesOf files, so just ignore diff --git a/code/lib/csf-tools/src/enrichCsf.test.ts b/code/lib/csf-tools/src/enrichCsf.test.ts index a8f5f3aaa09c..d793f730cecc 100644 --- a/code/lib/csf-tools/src/enrichCsf.test.ts +++ b/code/lib/csf-tools/src/enrichCsf.test.ts @@ -11,11 +11,16 @@ expect.addSnapshotSerializer({ test: (val) => true, }); -const enrich = (code: string, options?: EnrichCsfOptions) => { +const enrich = (code: string, originalCode: string, options?: EnrichCsfOptions) => { // we don't actually care about the title - const csf = loadCsf(code, { makeTitle: (userTitle) => userTitle || 'default' }).parse(); - enrichCsf(csf, options); + const csf = loadCsf(code, { + makeTitle: (userTitle) => userTitle || 'default', + }).parse(); + const csfSource = loadCsf(originalCode, { + makeTitle: (userTitle) => userTitle || 'default', + }).parse(); + enrichCsf(csf, csfSource, options); return formatCsf(csf); }; @@ -23,17 +28,28 @@ describe('enrichCsf', () => { describe('source', () => { it('csf1', () => { expect( - enrich(dedent` + enrich( + dedent` + // compiled code export default { title: 'Button', } - export const Basic = () =>