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

Vite: Support custom importPath in indexers #30612

Draft
wants to merge 8 commits into
base: next
Choose a base branch
from

Conversation

JReinhold
Copy link
Contributor

@JReinhold JReinhold commented Feb 21, 2025

Supersedes #26010

Todo

  • Go through all usages/references of importPath in StoryIndexGenerator and ensure their behavior still work. importPath is expected to be a file path, but can now be a virtual module, and I'm not sure yet if it's supported in all cases there.
  • Unit tests
  • Experiment with moving initializedStoryIndexGenerator to a preset instead if possible
  • Test on Windows
  • Update docs

What I did

Checklist for Contributors

Testing

The changes in this PR are covered in the following automated tests:

  • stories
  • unit tests
  • integration tests
  • end-to-end tests

Manual testing

In a react-vite sandbox, modify .storybook/main.ts stories and addons to:

  "stories": [
    "../src/**/*.mdx",
    "../src/**/*.stories.@(js|jsx|mjs|ts|tsx)", 
    "../src/**/*.stories-emoji.@(js|jsx|mjs|ts|tsx)", 
    "../src/**/*.stories.json", 
],

  "addons": [
    "@storybook/addon-essentials",
    "@storybook/addon-onboarding",
    "@chromatic-com/storybook",
    "@storybook/experimental-addon-test",
    "@storybook/addon-a11y",
    "./custom-indexers.ts"
  ],

Add the following .storybook/custom-indexers.ts file:

import { readFile } from 'node:fs/promises';
import type { Indexer, PresetProperty, StoryIndexInput } from 'storybook/internal/types';
import type { ViteFinal } from '../../../code/builders/builder-vite/src';
import type { Plugin } from 'vite';
import { readCsf } from 'storybook/internal/csf-tools';

const jsonIndexer: Indexer = {
  test: /stories\.json$/,
  createIndex: async (filename) => {
    const content = JSON.parse(await readFile(filename, 'utf-8')) as { stories: {title: string, name: string}[] };
    const stories: StoryIndexInput[] = content.stories.map((story) => ({
      type: 'story',
      title: story.title,
      name: story.name,
      importPath: `virtual:json-indexer@${filename}.js?title=${story.title}`,
      exportName: story.name
    }));
    return stories;
  },
}

const jsonVitePlugin: Plugin = {
  name: 'json-stories',
  resolveId(id) {
    if (id.startsWith('virtual:json-indexer@')) {
      return `\0${id}`;
    }
  },
  async load(id) {
    if (!id.startsWith('\0virtual:json-indexer@')) {
      return;
    }
    const url = new URL(id.replace('\\0', ''));
    const filePath = url.pathname.replace('json-indexer@', '').replace(/\.js$/, '');
    const title = url.searchParams.get('title');

    const content = JSON.parse(await readFile(filePath, 'utf-8')) as { stories: {title: string, name: string}[] };

    const stories = content.stories.filter((story) => story.title === title);
    const result = `
export default {
title: '${title}',
};

${stories.map((story) => `export const ${story.name} = { render: () => '${story.name}' };`).join('\n')}
`;
    return result;
  },
}

const emojiTransformIndexer: Indexer = {
  test: /stories-emoji\.(m?js|ts)x?$/,
  createIndex: async (fileName, options) => {
    const indexInputs = (await readCsf(fileName, options)).parse().indexInputs;
    return indexInputs.map((input) => ({
      ...input,
      title: `🎉 ${input.title}`,
      name: `😎 ${input.name}`,
      __id: undefined,
      importPath: `${input.importPath}?emoji=true`,
    }));
  },
}

const emojiVitePlugin: Plugin = {
  name: 'emoji-stories',
  async transform(code, id) {
    if (!id.endsWith('emoji=true')) {
      return;
    }
    const transformed = code
      .replaceAll(/(title:\s*')/g, '$1🎉 ')
      .replaceAll(/(name:\s*')/g, '$1😎 ');

    return transformed;
  }
}

export const experimental_indexers: PresetProperty<'experimental_indexers'> = (existingIndexers) => {
  return [jsonIndexer, emojiTransformIndexer].concat(existingIndexers || []);
};

export const viteFinal: ViteFinal = (config) => {
  return {
    ...config,
    plugins: [
      ...(config.plugins ?? []),
      jsonVitePlugin,
      emojiVitePlugin,
    ]
  };
};

Add the following file to src/stories/my.stories.json:

{
  "stories": [
    {
      "title": "Bit",
      "name": "First"
    },
    {
      "title": "Bit",
      "name": "Second"
    },
    {
      "title": "Bit",
      "name": "Third"
    },
    {
      "title": "Bot",
      "name": "First"
    },
    {
      "title": "Bot",
      "name": "Second"
    },
    {
      "title": "Bot",
      "name": "Third"
    }
  ]
}

And this file too: src/stories.Flimflom.stories-emoji.ts:

import { fn } from '@storybook/test';

import { Button } from './Button';

const meta = {
  component: Button,
  title: 'Flimflom',
  tags: ['autodocs'],
  args: { onClick: fn() },
};

export default meta;

export const Primary = {
  name: 'Primary',
  args: {
    primary: true,
    label: 'Button',
  },
};

export const Secondary = {
  name: 'Secondary',
  args: {
    label: 'Button',
  },
};

Documentation

  • Add or update documentation reflecting your changes
  • If you are deprecating/removing a feature, make sure to update
    MIGRATION.MD

Checklist for Maintainers

  • When this PR is ready for testing, make sure to add ci:normal, ci:merged or ci:daily GH label to it to run a specific set of sandboxes. The particular set of sandboxes can be found in code/lib/cli-storybook/src/sandbox-templates.ts

  • Make sure this PR contains one of the labels below:

    Available labels
    • bug: Internal changes that fixes incorrect behavior.
    • maintenance: User-facing maintenance tasks.
    • dependencies: Upgrading (sometimes downgrading) dependencies.
    • build: Internal-facing build tooling & test updates. Will not show up in release changelog.
    • cleanup: Minor cleanup style change. Will not show up in release changelog.
    • documentation: Documentation only changes. Will not show up in release changelog.
    • feature request: Introducing a new feature.
    • BREAKING CHANGE: Changes that break compatibility in some way with current major version.
    • other: Changes that don't fit in the above categories.

🦋 Canary release

This PR does not have a canary release associated. You can request a canary release of this pull request by mentioning the @storybookjs/core team here.

core team members can create a canary release here or locally with gh workflow run --repo storybookjs/storybook canary-release-pr.yml --field pr=<PR_NUMBER>

Copy link
Contributor

github-actions bot commented Feb 21, 2025

Fails
🚫

PR is not labeled with one of: ["ci:normal","ci:merged","ci:daily","ci:docs"]

Generated by 🚫 dangerJS against 23996ff

Copy link

nx-cloud bot commented Feb 21, 2025

View your CI Pipeline Execution ↗ for commit 23996ff.

Command Status Duration Result
nx run-many -t build --parallel=3 ✅ Succeeded 2m View ↗

☁️ Nx Cloud last updated this comment at 2025-02-21 10:25:15 UTC

@JReinhold JReinhold changed the title Vite: Support custom importPath in inexers Vite: Support custom importPath in indexers Feb 24, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant