histoire 0.11.4 → 0.11.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import path from 'pathe';
2
2
  import { createRequire } from 'node:module';
3
3
  const require = createRequire(import.meta.url);
4
- export const APP_PATH = path.join(path.dirname(require.resolve('@histoire/app/package.json')), 'dist');
4
+ export const APP_PATH = path.join(path.dirname(require.resolve('@histoire/app/package.json')), process.env.HISTOIRE_DEV ? 'src' : 'dist');
5
5
  export const TEMP_PATH = path.join(process.cwd(), 'node_modules', '.histoire');
@@ -5,7 +5,7 @@ import { lookup as lookupMime } from 'mrmime';
5
5
  import pc from 'picocolors';
6
6
  import { performance } from 'node:perf_hooks';
7
7
  import { APP_PATH } from './alias.js';
8
- import { getViteConfigWithPlugins, resolveViteConfig } from './vite.js';
8
+ import { getViteConfigWithPlugins } from './vite.js';
9
9
  import { findAllStories } from './stories.js';
10
10
  import { useCollectStories } from './collect/index.js';
11
11
  import { BuildPluginApi } from './plugin.js';
@@ -28,7 +28,6 @@ export async function build(ctx) {
28
28
  const { stop } = await createMarkdownFilesWatcher(ctx);
29
29
  await stop();
30
30
  }
31
- const resolvedViteConfig = await resolveViteConfig(ctx);
32
31
  const server = await createViteServer(await getViteConfigWithPlugins(true, ctx));
33
32
  await server.pluginContainer.buildStart({});
34
33
  const moduleLoader = useModuleLoader({
@@ -128,19 +127,19 @@ export async function build(ctx) {
128
127
  const styleOutput = result.output.find(o => o.name === 'style.css' && o.type === 'asset');
129
128
  // Preload
130
129
  const preloadOutputs = result.output.filter(o => PRELOAD_MODULES.includes(o.name) && o.type === 'chunk');
131
- const preloadHtml = generateScriptLinks(preloadOutputs.map(o => o.fileName), 'preload', ctx, resolvedViteConfig);
130
+ const preloadHtml = generateScriptLinks(preloadOutputs.map(o => o.fileName), 'preload', ctx);
132
131
  // Prefetch
133
132
  const prefetchOutputs = result.output.filter(o => PREFETCHED_MODULES.includes(o.name) && o.type === 'chunk');
134
- const prefetchHtml = generateScriptLinks(prefetchOutputs.map(o => o.fileName), 'prefetch', ctx, resolvedViteConfig);
133
+ const prefetchHtml = generateScriptLinks(prefetchOutputs.map(o => o.fileName), 'prefetch', ctx);
135
134
  // Index
136
135
  const indexOutput = result.output.find(o => o.name === 'bundle-main' && o.type === 'chunk');
137
136
  const indexHtml = generateEntryHtml(indexOutput.fileName, styleOutput.fileName, {
138
137
  HEAD: `${preloadHtml}${prefetchHtml}`,
139
- }, ctx, resolvedViteConfig);
138
+ }, ctx);
140
139
  await writeFile('index.html', indexHtml, ctx);
141
140
  // Sandbox
142
141
  const sandboxOutput = result.output.find(o => o.name === 'bundle-sandbox' && o.type === 'chunk');
143
- const sandboxHtml = generateEntryHtml(sandboxOutput.fileName, styleOutput.fileName, {}, ctx, resolvedViteConfig);
142
+ const sandboxHtml = generateEntryHtml(sandboxOutput.fileName, styleOutput.fileName, {}, ctx);
144
143
  await writeFile('__sandbox.html', sandboxHtml, ctx);
145
144
  const duration = performance.now() - startTime;
146
145
  if (emptyStoryCount) {
@@ -149,7 +148,7 @@ export async function build(ctx) {
149
148
  console.log(pc.green(`✅ Built ${storyCount} stories (${variantCount} variants) in ${Math.round(duration / 1000 * 100) / 100}s`));
150
149
  // Render
151
150
  if (previewStoryCallbacks.length) {
152
- const { baseUrl, close } = await startPreview(resolvedViteConfig, null, ctx);
151
+ const { baseUrl, close } = await startPreview(null, ctx);
153
152
  for (const storyFile of ctx.storyFiles) {
154
153
  const story = storyFile.story;
155
154
  for (const variant of story.variants) {
@@ -189,15 +188,15 @@ function generateBaseHtml(head, body, ctx) {
189
188
  </body>
190
189
  </html>`;
191
190
  }
192
- function generateEntryHtml(jsEntryFile, cssEntryFile, variables, ctx, resolvedViteConfig) {
193
- return generateBaseHtml(`<link rel="stylesheet" href="${resolvedViteConfig.base}${cssEntryFile}">
191
+ function generateEntryHtml(jsEntryFile, cssEntryFile, variables, ctx) {
192
+ return generateBaseHtml(`<link rel="stylesheet" href="${ctx.resolvedViteConfig.base}${cssEntryFile}">
194
193
  ${ctx.config.theme?.favicon ? `<link rel="icon" type="${lookupMime(ctx.config.theme.favicon)}" href="${ctx.config.theme.favicon}"/>` : ''}
195
194
  ${variables.HEAD ?? ''}`, `<div id="app"></div>
196
- <script type="module" src="${resolvedViteConfig.base}${jsEntryFile}"></script>`, ctx);
195
+ <script type="module" src="${ctx.resolvedViteConfig.base}${jsEntryFile}"></script>`, ctx);
197
196
  }
198
197
  async function writeFile(fileName, content, ctx) {
199
198
  await fs.writeFile(join(ctx.config.outDir, fileName), content, 'utf8');
200
199
  }
201
- function generateScriptLinks(prefetchScripts, rel, ctx, resolvedViteConfig) {
202
- return prefetchScripts.map(s => `<link rel="${rel}" href="${resolvedViteConfig.base}${s}" as="script" crossOrigin="anonymous">`).join('');
200
+ function generateScriptLinks(prefetchScripts, rel, ctx) {
201
+ return prefetchScripts.map(s => `<link rel="${rel}" href="${ctx.resolvedViteConfig.base}${s}" as="script" crossOrigin="anonymous">`).join('');
203
202
  }
@@ -1,12 +1,10 @@
1
1
  import pc from 'picocolors';
2
2
  import { createContext } from '../context.js';
3
- import { resolveViteConfig } from '../vite.js';
4
3
  import { startPreview } from '../preview.js';
5
4
  export async function previewCommand(options) {
6
5
  const ctx = await createContext({
7
6
  mode: 'build',
8
7
  });
9
- const viteConfig = await resolveViteConfig(ctx);
10
- const { baseUrl } = await startPreview(viteConfig, options.port, ctx);
8
+ const { baseUrl } = await startPreview(options.port, ctx);
11
9
  console.log(`Preview server listening on ${pc.cyan(baseUrl)}`);
12
10
  }
@@ -82,22 +82,27 @@ export function getDefaultConfig() {
82
82
  {
83
83
  label: 'Transparent',
84
84
  color: 'transparent',
85
+ contrastColor: '#333',
85
86
  },
86
87
  {
87
88
  label: 'White',
88
89
  color: '#fff',
90
+ contrastColor: '#333',
89
91
  },
90
92
  {
91
93
  label: 'Light gray',
92
94
  color: '#aaa',
95
+ contrastColor: '#000',
93
96
  },
94
97
  {
95
98
  label: 'Dark gray',
96
99
  color: '#333',
100
+ contrastColor: '#fff',
97
101
  },
98
102
  {
99
103
  label: 'Black',
100
104
  color: '#000',
105
+ contrastColor: '#eee',
101
106
  },
102
107
  ],
103
108
  sandboxDarkClass: 'dark',
@@ -1,7 +1,9 @@
1
+ import { ResolvedConfig } from 'vite';
1
2
  import type { ServerStoryFile, FinalSupportPlugin, ServerMarkdownFile, HistoireConfig, ConfigMode } from '@histoire/shared';
2
3
  export interface Context {
3
4
  root: string;
4
5
  config: HistoireConfig;
6
+ resolvedViteConfig: ResolvedConfig;
5
7
  mode: ConfigMode;
6
8
  storyFiles: ServerStoryFile[];
7
9
  supportPlugins: FinalSupportPlugin[];
@@ -1,15 +1,20 @@
1
1
  import { resolveConfig as resolveViteConfig } from 'vite';
2
2
  import { resolveConfig } from './config.js';
3
+ import { mergeHistoireViteConfig } from './vite.js';
3
4
  export async function createContext(options) {
4
5
  const config = await resolveConfig(process.cwd(), options.mode);
5
- const viteConfig = await resolveViteConfig({}, 'build');
6
+ const command = options.mode === 'dev' ? 'serve' : 'build';
7
+ const viteConfig = await resolveViteConfig({}, command);
6
8
  const supportPlugins = config.plugins.map(p => p.supportPlugin).filter(Boolean);
7
- return {
9
+ const ctx = {
8
10
  root: viteConfig.root,
9
11
  config,
12
+ resolvedViteConfig: null,
10
13
  mode: options.mode,
11
14
  storyFiles: [],
12
15
  supportPlugins,
13
16
  markdownFiles: [],
14
17
  };
18
+ ctx.resolvedViteConfig = await mergeHistoireViteConfig(viteConfig, ctx);
19
+ return ctx;
15
20
  }
@@ -2,7 +2,7 @@ import MarkdownIt from 'markdown-it';
2
2
  import type { Plugin as VitePlugin } from 'vite';
3
3
  import type { Context } from './context.js';
4
4
  export declare function onMarkdownListChange(handler: () => unknown): void;
5
- export declare function createMarkdownRenderer(): Promise<MarkdownIt>;
5
+ export declare function createMarkdownRenderer(ctx: Context): Promise<MarkdownIt>;
6
6
  export declare function createMarkdownPlugins(ctx: Context): Promise<VitePlugin[]>;
7
7
  export declare function createMarkdownFilesWatcher(ctx: Context): Promise<{
8
8
  stop: () => Promise<void>;
@@ -8,6 +8,7 @@ import chokidar from 'chokidar';
8
8
  import fs from 'fs-extra';
9
9
  import path from 'pathe';
10
10
  import { paramCase } from 'change-case';
11
+ import pc from 'picocolors';
11
12
  import { slugify } from './util/slugify.js';
12
13
  import { addStory, notifyStoryChange, removeStory } from './stories.js';
13
14
  const onMarkdownListChangeHandlers = [];
@@ -19,7 +20,7 @@ function notifyMarkdownListChange() {
19
20
  handler();
20
21
  }
21
22
  }
22
- export async function createMarkdownRenderer() {
23
+ export async function createMarkdownRenderer(ctx) {
23
24
  const highlighter = await shiki.getHighlighter({
24
25
  theme: 'github-dark',
25
26
  });
@@ -43,16 +44,36 @@ export async function createMarkdownRenderer() {
43
44
  return self.renderToken(tokens, idx, options);
44
45
  };
45
46
  md.renderer.rules.link_open = function (tokens, idx, options, env, self) {
46
- const hrefIndex = tokens[idx].attrIndex('href');
47
- const classIndex = tokens[idx].attrIndex('class');
48
- if (hrefIndex >= 0 && !tokens[idx].attrs[hrefIndex][1].startsWith('/') && !tokens[idx].attrs[hrefIndex][1].startsWith('#') && (classIndex < 0 || !tokens[idx].attrs[classIndex][1].includes('header-anchor'))) {
49
- // If you are sure other plugins can't add `target` - drop check below
50
- const aIndex = tokens[idx].attrIndex('target');
51
- if (aIndex < 0) {
52
- tokens[idx].attrPush(['target', '_blank']); // add new attribute
47
+ const token = tokens[idx];
48
+ const hrefIndex = token.attrIndex('href');
49
+ const classIndex = token.attrIndex('class');
50
+ if (hrefIndex >= 0) {
51
+ const href = token.attrs[hrefIndex][1];
52
+ if (href.startsWith('.')) {
53
+ const queryIndex = href.indexOf('?');
54
+ const pathname = queryIndex >= 0 ? href.slice(0, queryIndex) : href;
55
+ const query = queryIndex >= 0 ? href.slice(queryIndex) : '';
56
+ // File lookup
57
+ const file = path.resolve(path.dirname(env.file), pathname);
58
+ const storyFile = ctx.storyFiles.find(f => f.path === file);
59
+ const mdFile = ctx.markdownFiles.find(f => f.absolutePath === file);
60
+ if (!storyFile && !mdFile?.storyFile) {
61
+ throw new Error(pc.red(`[md] Cannot find story file: ${pathname} from ${env.file}`));
62
+ }
63
+ // Add attributes
64
+ const newHref = `${ctx.resolvedViteConfig.base}story/${encodeURIComponent(storyFile?.id ?? mdFile.storyFile.id)}${query}`;
65
+ token.attrSet('href', newHref);
66
+ token.attrSet('data-route', 'true');
53
67
  }
54
- else {
55
- tokens[idx].attrs[aIndex][1] = '_blank'; // replace value of existing attr
68
+ else if (!href.startsWith('/') && !href.startsWith('#') && (classIndex < 0 || !token.attrs[classIndex][1].includes('header-anchor'))) {
69
+ // Add target="_blank" to external links
70
+ const aIndex = token.attrIndex('target');
71
+ if (aIndex < 0) {
72
+ token.attrPush(['target', '_blank']); // add new attribute
73
+ }
74
+ else {
75
+ token.attrs[aIndex][1] = '_blank'; // replace value of existing attr
76
+ }
56
77
  }
57
78
  }
58
79
  // pass token to default renderer.
@@ -62,7 +83,7 @@ export async function createMarkdownRenderer() {
62
83
  return md;
63
84
  }
64
85
  async function createMarkdownRendererWithPlugins(ctx) {
65
- let md = await createMarkdownRenderer();
86
+ let md = await createMarkdownRenderer(ctx);
66
87
  if (ctx.config.markdown) {
67
88
  const result = await ctx.config.markdown(md);
68
89
  if (result) {
@@ -82,7 +103,10 @@ export async function createMarkdownPlugins(ctx) {
82
103
  return;
83
104
  if (!id.includes('lang.md'))
84
105
  return;
85
- const html = md.render(code);
106
+ const file = id.substring(0, id.indexOf('?vue'));
107
+ const html = md.render(code, {
108
+ file,
109
+ });
86
110
  return `export default Comp => {
87
111
  Comp.doc = ${JSON.stringify(html)}
88
112
  }`;
@@ -102,7 +126,9 @@ export async function createMarkdownFilesWatcher(ctx) {
102
126
  const truncatedName = path.basename(absolutePath, '.md');
103
127
  const isRelatedToStory = dirFiles.some((file) => !file.endsWith('.md') && file.startsWith(truncatedName));
104
128
  const { data: frontmatter, content } = matter(await fs.readFile(absolutePath, 'utf8'));
105
- const html = md.render(content);
129
+ const html = md.render(content, {
130
+ file: absolutePath,
131
+ });
106
132
  const file = {
107
133
  id: paramCase(relativePath.toLowerCase()),
108
134
  relativePath,
@@ -1,8 +1,7 @@
1
- import type { ResolvedConfig as ViteConfig } from 'vite';
2
1
  import type { Context } from './context.js';
3
2
  interface ReturnPayload {
4
3
  baseUrl: string;
5
4
  close: () => Promise<void>;
6
5
  }
7
- export declare function startPreview(viteConfig: ViteConfig, port: number | null, ctx: Context): Promise<ReturnPayload>;
6
+ export declare function startPreview(port: number | null, ctx: Context): Promise<ReturnPayload>;
8
7
  export {};
@@ -1,9 +1,9 @@
1
1
  import http from 'node:http';
2
2
  import connect from 'connect';
3
3
  import sirv from 'sirv';
4
- export async function startPreview(viteConfig, port, ctx) {
4
+ export async function startPreview(port, ctx) {
5
5
  const app = connect();
6
- app.use(viteConfig.base, sirv(ctx.config.outDir, {
6
+ app.use(ctx.resolvedViteConfig.base, sirv(ctx.config.outDir, {
7
7
  dev: true,
8
8
  etag: true,
9
9
  single: true,
@@ -22,7 +22,7 @@ export async function startPreview(viteConfig, port, ctx) {
22
22
  httpServer.on('error', onError);
23
23
  httpServer.listen(finalPort, () => {
24
24
  httpServer.off('error', onError);
25
- const baseUrl = `http://localhost:${finalPort}${viteConfig.base}`;
25
+ const baseUrl = `http://localhost:${finalPort}${ctx.resolvedViteConfig.base}`;
26
26
  resolve({
27
27
  baseUrl,
28
28
  close: () => new Promise((resolve, reject) => {
@@ -42,6 +42,7 @@ export async function createServer(ctx, options = {}) {
42
42
  // onStoryChange debouncing
43
43
  let queued = false;
44
44
  let queuedFiles = [];
45
+ let currentFiles = [];
45
46
  let queueTimer;
46
47
  let collecting = false;
47
48
  let didAllStoriesYet = false;
@@ -86,12 +87,16 @@ export async function createServer(ctx, options = {}) {
86
87
  // Debounce
87
88
  queueTimer = setTimeout(collect, 100);
88
89
  }
90
+ else if (!changedFile && !currentFiles.length) {
91
+ // Full collect in progress
92
+ queued = false;
93
+ }
89
94
  }
90
95
  });
91
96
  async function collect() {
92
97
  collecting = true;
93
98
  clearCache();
94
- const currentFiles = queuedFiles.slice();
99
+ currentFiles = queuedFiles.slice();
95
100
  queuedFiles = [];
96
101
  queued = false;
97
102
  console.log('Collect stories start', currentFiles.length ? currentFiles.map(f => f.fileName).join(', ') : 'all');
@@ -1,4 +1,4 @@
1
- import { ResolvedConfig, InlineConfig } from 'vite';
1
+ import { InlineConfig } from 'vite';
2
2
  import { Context } from './context.js';
3
3
  export declare const STORIES_ID = "virtual:$histoire-stories";
4
4
  export declare const RESOLVED_STORIES_ID: string;
@@ -22,5 +22,5 @@ export declare const SUPPORT_PLUGINS_COLLECT = "virtual:$histoire-support-plugin
22
22
  export declare const RESOLVED_SUPPORT_PLUGINS_COLLECT: string;
23
23
  export declare const MARKDOWN_FILES = "virtual:$histoire-markdown-files";
24
24
  export declare const RESOLVED_MARKDOWN_FILES: string;
25
- export declare function resolveViteConfig(ctx: Context): Promise<ResolvedConfig>;
25
+ export declare function mergeHistoireViteConfig(viteConfig: InlineConfig, ctx: Context): Promise<InlineConfig>;
26
26
  export declare function getViteConfigWithPlugins(isServer: boolean, ctx: Context): Promise<InlineConfig>;
package/dist/node/vite.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from 'node:module';
2
2
  import { relative, resolve, join, dirname } from 'pathe';
3
- import { resolveConfig as resolveViteConfigInternal, mergeConfig as mergeViteConfig, loadConfigFromFile as loadViteConfigFromFile, } from 'vite';
3
+ import { mergeConfig as mergeViteConfig, loadConfigFromFile as loadViteConfigFromFile, } from 'vite';
4
4
  import { lookup as lookupMime } from 'mrmime';
5
5
  import fs from 'fs-extra';
6
6
  import ViteInspect from 'vite-plugin-inspect';
@@ -11,7 +11,6 @@ import { parseColor } from './colors.js';
11
11
  import { createMarkdownPlugins } from './markdown.js';
12
12
  import { getSearchDataJS, generateDocSearchData, generateTitleSearchData } from './search.js';
13
13
  import { getInjectedImport } from './util/vendors.js';
14
- import { findUp } from './util/find-up.js';
15
14
  const require = createRequire(import.meta.url);
16
15
  // @TODO wait for virtual modules HMR to work in vite to use `virtual:` and `\0` prefix
17
16
  // https://github.com/vitejs/vite/pull/10313
@@ -48,13 +47,10 @@ export const MARKDOWN_FILES = 'virtual:$histoire-markdown-files';
48
47
  export const RESOLVED_MARKDOWN_FILES = `/__resolved__${MARKDOWN_FILES}`;
49
48
  // export const RESOLVED_MARKDOWN_FILES = `\0${MARKDOWN_FILES}`
50
49
  const ID_SEPARATOR = '__-__';
51
- export async function resolveViteConfig(ctx) {
52
- const command = ctx.mode === 'dev' ? 'serve' : 'build';
53
- let viteConfig = (await resolveViteConfigInternal({}, command));
54
- viteConfig = mergeHistoireViteConfig(viteConfig, ctx);
55
- return viteConfig;
56
- }
57
- async function mergeHistoireViteConfig(viteConfig, ctx) {
50
+ const PLUGINS_HAVE_DEV = [
51
+ '@histoire/plugin-vue',
52
+ ];
53
+ export async function mergeHistoireViteConfig(viteConfig, ctx) {
58
54
  if (ctx.config.vite) {
59
55
  const command = ctx.mode === 'dev' ? 'serve' : 'build';
60
56
  const overrides = typeof ctx.config.vite === 'function'
@@ -86,18 +82,14 @@ async function mergeHistoireViteConfig(viteConfig, ctx) {
86
82
  return viteConfig;
87
83
  }
88
84
  export async function getViteConfigWithPlugins(isServer, ctx) {
89
- const resolvedViteConfig = await resolveViteConfig(ctx);
90
85
  const userViteConfigFile = await loadViteConfigFromFile({ command: ctx.mode === 'dev' ? 'serve' : 'build', mode: ctx.mode });
91
86
  const userViteConfig = mergeViteConfig(userViteConfigFile?.config ?? {}, { server: { port: 6006 } });
92
87
  const inlineConfig = await mergeHistoireViteConfig(userViteConfig, ctx);
93
88
  const plugins = [];
94
- const hasPnpm = !!(await findUp(ctx.root, ['pnpm-lock.yaml']));
95
89
  function optimizeDeps(deps) {
96
90
  const result = [];
97
91
  for (const dep of deps) {
98
- if (!hasPnpm) {
99
- result.push(dep);
100
- }
92
+ result.push(dep);
101
93
  try {
102
94
  result.push(dirname(require.resolve(`${dep}/package.json`)));
103
95
  }
@@ -117,7 +109,7 @@ export async function getViteConfigWithPlugins(isServer, ctx) {
117
109
  'vue',
118
110
  ],
119
111
  alias: {
120
- 'histoire-style': join(APP_PATH, 'style.css'),
112
+ 'histoire-style': join(APP_PATH, process.env.HISTOIRE_DEV ? 'app/style/main.pcss' : 'style.css'),
121
113
  },
122
114
  },
123
115
  optimizeDeps: {
@@ -142,8 +134,13 @@ export async function getViteConfigWithPlugins(isServer, ctx) {
142
134
  allow: [
143
135
  APP_PATH,
144
136
  TEMP_PATH,
145
- resolvedViteConfig.root,
137
+ ctx.resolvedViteConfig.root,
146
138
  process.cwd(),
139
+ ...process.env.HISTOIRE_DEV
140
+ ? [
141
+ '../../packages/histoire-vendors',
142
+ ]
143
+ : [],
147
144
  ],
148
145
  },
149
146
  watch: {
@@ -325,7 +322,7 @@ if (import.meta.hot) {
325
322
  return ctx.config.setupCode?.[index] ?? '';
326
323
  }
327
324
  if (id === RESOLVED_SUPPORT_PLUGINS_CLIENT) {
328
- const plugins = ctx.supportPlugins.map(p => `'${p.id}': () => import(${JSON.stringify(require.resolve(`${p.moduleName}/client`, {
325
+ const plugins = ctx.supportPlugins.map(p => `'${p.id}': () => import(${JSON.stringify(require.resolve(`${p.moduleName}/client${process.env.HISTOIRE_DEV && PLUGINS_HAVE_DEV.includes(p.moduleName) ? '-dev' : ''}`, {
329
326
  paths: [ctx.root, import.meta.url],
330
327
  }))})`);
331
328
  return `export const clientSupportPlugins = {
@@ -333,7 +330,7 @@ if (import.meta.hot) {
333
330
  }`;
334
331
  }
335
332
  if (id === RESOLVED_SUPPORT_PLUGINS_COLLECT) {
336
- const plugins = ctx.supportPlugins.map(p => `'${p.id}': () => import(${JSON.stringify(require.resolve(`${p.moduleName}/collect`, {
333
+ const plugins = ctx.supportPlugins.map(p => `'${p.id}': () => import(${JSON.stringify(require.resolve(`${p.moduleName}/collect${process.env.HISTOIRE_DEV && PLUGINS_HAVE_DEV.includes(p.moduleName) ? '-dev' : ''}`, {
337
334
  paths: [ctx.root, import.meta.url],
338
335
  }))})`);
339
336
  return `export const collectSupportPlugins = {
@@ -342,7 +339,7 @@ if (import.meta.hot) {
342
339
  }
343
340
  if (id === RESOLVED_MARKDOWN_FILES) {
344
341
  const filesJs = ctx.markdownFiles.map(f => `${JSON.stringify(f.relativePath)}: () => import(${JSON.stringify(`virtual:md:${f.id}`)})`).join(',');
345
- return `import { reactive } from ${getInjectedImport('@histoire/vendors/vue')}
342
+ return `import { reactive } from ${process.env.HISTOIRE_DEV ? `'vue'` : getInjectedImport('@histoire/vendors/vue')}
346
343
  export const markdownFiles = reactive({${filesJs}})
347
344
  if (import.meta.hot) {
348
345
  if (!window.__hst_md_hmr) {
@@ -434,7 +431,7 @@ if (import.meta.hot) {
434
431
  }
435
432
  }
436
433
  </script>
437
- <script type="module" src="/@fs/${APP_PATH}/bundle-sandbox.js"></script>
434
+ <script type="module" src="/@fs/${APP_PATH}/bundle-sandbox${process.env.HISTOIRE_DEV ? '-dev' : ''}.js"></script>
438
435
  </body>
439
436
  </html>`;
440
437
  // Apply Vite HTML transforms. This injects the Vite HMR client, and
@@ -464,7 +461,7 @@ if (import.meta.hot) {
464
461
  </head>
465
462
  <body>
466
463
  <div id="app"></div>
467
- <script type="module" src="/@fs/${APP_PATH}/bundle-main.js"></script>
464
+ <script type="module" src="/@fs/${APP_PATH}/bundle-main${process.env.HISTOIRE_DEV ? '-dev' : ''}.js"></script>
468
465
  </body>
469
466
  </html>`;
470
467
  // Apply Vite HTML transforms. This injects the Vite HMR client, and
@@ -492,7 +489,7 @@ if (import.meta.hot) {
492
489
  if (exclude.some(r => r.test(id)))
493
490
  return;
494
491
  if (include.some(r => r.test(id))) {
495
- const file = relative(resolvedViteConfig.root, id);
492
+ const file = relative(ctx.resolvedViteConfig.root, id);
496
493
  const index = code.indexOf('export default');
497
494
  const result = `${code.substring(0, index)}_sfc_main.__file = '${file}'\n${code.substring(index)}`;
498
495
  return result;
@@ -500,6 +497,41 @@ if (import.meta.hot) {
500
497
  },
501
498
  });
502
499
  }
500
+ if (process.env.HISTOIRE_DEV && !isServer) {
501
+ plugins.push({
502
+ name: 'histoire-dev-plugin',
503
+ config() {
504
+ // Examples context
505
+ return {
506
+ resolve: {
507
+ alias: [
508
+ ...[
509
+ ['floating-vue/dist/style.css', 'node_modules/floating-vue/dist/style.css'],
510
+ ['floating-vue', 'floating-vue'],
511
+ ['@iconify/vue', 'iconify'],
512
+ ['pinia', 'pinia'],
513
+ ['scroll-into-view-if-needed', 'scroll'],
514
+ ['vue-router', 'vue-router'],
515
+ ['@vueuse/core', 'vue-use'],
516
+ ['vue', 'vue'],
517
+ ].reduce((acc, [name, entry]) => {
518
+ acc.push({
519
+ find: new RegExp(`^${name.replace(/\//g, '\\/')}$`),
520
+ replacement: `@histoire/vendors/${entry}`,
521
+ });
522
+ acc.push({
523
+ find: new RegExp(`^${name.replace(/\//g, '\\/')}\\/`),
524
+ replacement: `@histoire/vendors/${entry}/`,
525
+ });
526
+ return acc;
527
+ }, []),
528
+ { find: /@histoire\/controls$/, replacement: '@histoire/controls/src/index.ts' },
529
+ ],
530
+ },
531
+ };
532
+ },
533
+ });
534
+ }
503
535
  return mergeViteConfig(inlineConfig, {
504
536
  configFile: false,
505
537
  plugins,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "histoire",
3
- "version": "0.11.4",
3
+ "version": "0.11.6",
4
4
  "description": "A fast story book powered by Vite",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -33,10 +33,10 @@
33
33
  "histoire": "./bin.mjs"
34
34
  },
35
35
  "dependencies": {
36
- "@histoire/app": "^0.11.4",
37
- "@histoire/controls": "^0.11.4",
38
- "@histoire/shared": "^0.11.4",
39
- "@histoire/vendors": "^0.11.4",
36
+ "@histoire/app": "^0.11.6",
37
+ "@histoire/controls": "^0.11.6",
38
+ "@histoire/shared": "^0.11.6",
39
+ "@histoire/vendors": "^0.11.6",
40
40
  "@types/flexsearch": "^0.7.3",
41
41
  "@types/markdown-it": "^12.2.3",
42
42
  "birpc": "^0.1.1",
package/src/node/alias.ts CHANGED
@@ -3,6 +3,6 @@ import { createRequire } from 'node:module'
3
3
 
4
4
  const require = createRequire(import.meta.url)
5
5
 
6
- export const APP_PATH = path.join(path.dirname(require.resolve('@histoire/app/package.json')), 'dist')
6
+ export const APP_PATH = path.join(path.dirname(require.resolve('@histoire/app/package.json')), process.env.HISTOIRE_DEV ? 'src' : 'dist')
7
7
 
8
8
  export const TEMP_PATH = path.join(process.cwd(), 'node_modules', '.histoire')
package/src/node/build.ts CHANGED
@@ -3,7 +3,6 @@ import {
3
3
  build as viteBuild,
4
4
  createServer as createViteServer,
5
5
  InlineConfig as ViteInlineConfig,
6
- ResolvedConfig as ViteConfig,
7
6
  mergeConfig as mergeViteConfig,
8
7
  Plugin as VitePlugin,
9
8
  } from 'vite'
@@ -17,7 +16,7 @@ import type {
17
16
  } from '@histoire/shared'
18
17
  import { APP_PATH } from './alias.js'
19
18
  import { Context } from './context.js'
20
- import { getViteConfigWithPlugins, resolveViteConfig } from './vite.js'
19
+ import { getViteConfigWithPlugins } from './vite.js'
21
20
  import { findAllStories } from './stories.js'
22
21
  import type { RollupOutput } from 'rollup'
23
22
  import { useCollectStories } from './collect/index.js'
@@ -46,8 +45,6 @@ export async function build (ctx: Context) {
46
45
  await stop()
47
46
  }
48
47
 
49
- const resolvedViteConfig = await resolveViteConfig(ctx)
50
-
51
48
  const server = await createViteServer(await getViteConfigWithPlugins(true, ctx))
52
49
  await server.pluginContainer.buildStart({})
53
50
 
@@ -156,22 +153,22 @@ export async function build (ctx: Context) {
156
153
 
157
154
  // Preload
158
155
  const preloadOutputs = result.output.filter(o => PRELOAD_MODULES.includes(o.name) && o.type === 'chunk')
159
- const preloadHtml = generateScriptLinks(preloadOutputs.map(o => o.fileName), 'preload', ctx, resolvedViteConfig)
156
+ const preloadHtml = generateScriptLinks(preloadOutputs.map(o => o.fileName), 'preload', ctx)
160
157
 
161
158
  // Prefetch
162
159
  const prefetchOutputs = result.output.filter(o => PREFETCHED_MODULES.includes(o.name) && o.type === 'chunk')
163
- const prefetchHtml = generateScriptLinks(prefetchOutputs.map(o => o.fileName), 'prefetch', ctx, resolvedViteConfig)
160
+ const prefetchHtml = generateScriptLinks(prefetchOutputs.map(o => o.fileName), 'prefetch', ctx)
164
161
 
165
162
  // Index
166
163
  const indexOutput = result.output.find(o => o.name === 'bundle-main' && o.type === 'chunk')
167
164
  const indexHtml = generateEntryHtml(indexOutput.fileName, styleOutput.fileName, {
168
165
  HEAD: `${preloadHtml}${prefetchHtml}`,
169
- }, ctx, resolvedViteConfig)
166
+ }, ctx)
170
167
  await writeFile('index.html', indexHtml, ctx)
171
168
 
172
169
  // Sandbox
173
170
  const sandboxOutput = result.output.find(o => o.name === 'bundle-sandbox' && o.type === 'chunk')
174
- const sandboxHtml = generateEntryHtml(sandboxOutput.fileName, styleOutput.fileName, {}, ctx, resolvedViteConfig)
171
+ const sandboxHtml = generateEntryHtml(sandboxOutput.fileName, styleOutput.fileName, {}, ctx)
175
172
  await writeFile('__sandbox.html', sandboxHtml, ctx)
176
173
 
177
174
  const duration = performance.now() - startTime
@@ -182,7 +179,7 @@ export async function build (ctx: Context) {
182
179
 
183
180
  // Render
184
181
  if (previewStoryCallbacks.length) {
185
- const { baseUrl, close } = await startPreview(resolvedViteConfig, null, ctx)
182
+ const { baseUrl, close } = await startPreview(null, ctx)
186
183
  for (const storyFile of ctx.storyFiles) {
187
184
  const story = storyFile.story
188
185
  for (const variant of story.variants) {
@@ -226,13 +223,13 @@ function generateBaseHtml (head: string, body: string, ctx: Context) {
226
223
  </html>`
227
224
  }
228
225
 
229
- function generateEntryHtml (jsEntryFile: string, cssEntryFile: string, variables: { HEAD?: string }, ctx: Context, resolvedViteConfig: ViteConfig) {
226
+ function generateEntryHtml (jsEntryFile: string, cssEntryFile: string, variables: { HEAD?: string }, ctx: Context) {
230
227
  return generateBaseHtml(
231
- `<link rel="stylesheet" href="${resolvedViteConfig.base}${cssEntryFile}">
228
+ `<link rel="stylesheet" href="${ctx.resolvedViteConfig.base}${cssEntryFile}">
232
229
  ${ctx.config.theme?.favicon ? `<link rel="icon" type="${lookupMime(ctx.config.theme.favicon)}" href="${ctx.config.theme.favicon}"/>` : ''}
233
230
  ${variables.HEAD ?? ''}`,
234
231
  `<div id="app"></div>
235
- <script type="module" src="${resolvedViteConfig.base}${jsEntryFile}"></script>`,
232
+ <script type="module" src="${ctx.resolvedViteConfig.base}${jsEntryFile}"></script>`,
236
233
  ctx,
237
234
  )
238
235
  }
@@ -241,6 +238,6 @@ async function writeFile (fileName: string, content: string, ctx: Context) {
241
238
  await fs.writeFile(join(ctx.config.outDir, fileName), content, 'utf8')
242
239
  }
243
240
 
244
- function generateScriptLinks (prefetchScripts: string[], rel: string, ctx: Context, resolvedViteConfig: ViteConfig) {
245
- return prefetchScripts.map(s => `<link rel="${rel}" href="${resolvedViteConfig.base}${s}" as="script" crossOrigin="anonymous">`).join('')
241
+ function generateScriptLinks (prefetchScripts: string[], rel: string, ctx: Context) {
242
+ return prefetchScripts.map(s => `<link rel="${rel}" href="${ctx.resolvedViteConfig.base}${s}" as="script" crossOrigin="anonymous">`).join('')
246
243
  }
@@ -1,6 +1,5 @@
1
1
  import pc from 'picocolors'
2
2
  import { createContext } from '../context.js'
3
- import { resolveViteConfig } from '../vite.js'
4
3
  import { startPreview } from '../preview.js'
5
4
 
6
5
  export interface PreviewOptions {
@@ -11,8 +10,7 @@ export async function previewCommand (options: PreviewOptions) {
11
10
  const ctx = await createContext({
12
11
  mode: 'build',
13
12
  })
14
- const viteConfig = await resolveViteConfig(ctx)
15
13
 
16
- const { baseUrl } = await startPreview(viteConfig, options.port, ctx)
14
+ const { baseUrl } = await startPreview(options.port, ctx)
17
15
  console.log(`Preview server listening on ${pc.cyan(baseUrl)}`)
18
16
  }
@@ -93,22 +93,27 @@ export function getDefaultConfig (): HistoireConfig {
93
93
  {
94
94
  label: 'Transparent',
95
95
  color: 'transparent',
96
+ contrastColor: '#333',
96
97
  },
97
98
  {
98
99
  label: 'White',
99
100
  color: '#fff',
101
+ contrastColor: '#333',
100
102
  },
101
103
  {
102
104
  label: 'Light gray',
103
105
  color: '#aaa',
106
+ contrastColor: '#000',
104
107
  },
105
108
  {
106
109
  label: 'Dark gray',
107
110
  color: '#333',
111
+ contrastColor: '#fff',
108
112
  },
109
113
  {
110
114
  label: 'Black',
111
115
  color: '#000',
116
+ contrastColor: '#eee',
112
117
  },
113
118
  ],
114
119
  sandboxDarkClass: 'dark',
@@ -1,4 +1,4 @@
1
- import { resolveConfig as resolveViteConfig } from 'vite'
1
+ import { resolveConfig as resolveViteConfig, ResolvedConfig } from 'vite'
2
2
  import type {
3
3
  ServerStoryFile,
4
4
  FinalSupportPlugin,
@@ -7,10 +7,12 @@ import type {
7
7
  ConfigMode,
8
8
  } from '@histoire/shared'
9
9
  import { resolveConfig } from './config.js'
10
+ import { mergeHistoireViteConfig } from './vite.js'
10
11
 
11
12
  export interface Context {
12
13
  root: string
13
14
  config: HistoireConfig
15
+ resolvedViteConfig: ResolvedConfig
14
16
  mode: ConfigMode
15
17
  storyFiles: ServerStoryFile[]
16
18
  supportPlugins: FinalSupportPlugin[]
@@ -23,16 +25,22 @@ export interface CreateContextOptions {
23
25
 
24
26
  export async function createContext (options: CreateContextOptions): Promise<Context> {
25
27
  const config = await resolveConfig(process.cwd(), options.mode)
26
- const viteConfig = await resolveViteConfig({}, 'build')
28
+ const command = options.mode === 'dev' ? 'serve' : 'build'
29
+ const viteConfig = await resolveViteConfig({}, command)
27
30
 
28
31
  const supportPlugins = config.plugins.map(p => p.supportPlugin).filter(Boolean)
29
32
 
30
- return {
33
+ const ctx = {
31
34
  root: viteConfig.root,
32
35
  config,
36
+ resolvedViteConfig: null,
33
37
  mode: options.mode,
34
38
  storyFiles: [],
35
39
  supportPlugins,
36
40
  markdownFiles: [],
37
41
  }
42
+
43
+ ctx.resolvedViteConfig = await mergeHistoireViteConfig(viteConfig as unknown, ctx)
44
+
45
+ return ctx
38
46
  }
@@ -9,6 +9,7 @@ import chokidar from 'chokidar'
9
9
  import fs from 'fs-extra'
10
10
  import path from 'pathe'
11
11
  import { paramCase } from 'change-case'
12
+ import pc from 'picocolors'
12
13
  import type { ServerMarkdownFile } from '@histoire/shared'
13
14
  import { slugify } from './util/slugify.js'
14
15
  import type { Context } from './context.js'
@@ -26,7 +27,7 @@ function notifyMarkdownListChange () {
26
27
  }
27
28
  }
28
29
 
29
- export async function createMarkdownRenderer () {
30
+ export async function createMarkdownRenderer (ctx: Context) {
30
31
  const highlighter = await shiki.getHighlighter({
31
32
  theme: 'github-dark',
32
33
  })
@@ -54,17 +55,38 @@ export async function createMarkdownRenderer () {
54
55
  }
55
56
 
56
57
  md.renderer.rules.link_open = function (tokens, idx, options, env, self) {
57
- const hrefIndex = tokens[idx].attrIndex('href')
58
- const classIndex = tokens[idx].attrIndex('class')
59
-
60
- if (hrefIndex >= 0 && !tokens[idx].attrs[hrefIndex][1].startsWith('/') && !tokens[idx].attrs[hrefIndex][1].startsWith('#') && (classIndex < 0 || !tokens[idx].attrs[classIndex][1].includes('header-anchor'))) {
61
- // If you are sure other plugins can't add `target` - drop check below
62
- const aIndex = tokens[idx].attrIndex('target')
63
-
64
- if (aIndex < 0) {
65
- tokens[idx].attrPush(['target', '_blank']) // add new attribute
66
- } else {
67
- tokens[idx].attrs[aIndex][1] = '_blank' // replace value of existing attr
58
+ const token = tokens[idx]
59
+ const hrefIndex = token.attrIndex('href')
60
+ const classIndex = token.attrIndex('class')
61
+
62
+ if (hrefIndex >= 0) {
63
+ const href = token.attrs[hrefIndex][1]
64
+ if (href.startsWith('.')) {
65
+ const queryIndex = href.indexOf('?')
66
+ const pathname = queryIndex >= 0 ? href.slice(0, queryIndex) : href
67
+ const query = queryIndex >= 0 ? href.slice(queryIndex) : ''
68
+
69
+ // File lookup
70
+ const file = path.resolve(path.dirname(env.file), pathname)
71
+ const storyFile = ctx.storyFiles.find(f => f.path === file)
72
+ const mdFile = ctx.markdownFiles.find(f => f.absolutePath === file)
73
+ if (!storyFile && !mdFile?.storyFile) {
74
+ throw new Error(pc.red(`[md] Cannot find story file: ${pathname} from ${env.file}`))
75
+ }
76
+
77
+ // Add attributes
78
+ const newHref = `${ctx.resolvedViteConfig.base}story/${encodeURIComponent(storyFile?.id ?? mdFile.storyFile.id)}${query}`
79
+ token.attrSet('href', newHref)
80
+ token.attrSet('data-route', 'true')
81
+ } else if (!href.startsWith('/') && !href.startsWith('#') && (classIndex < 0 || !token.attrs[classIndex][1].includes('header-anchor'))) {
82
+ // Add target="_blank" to external links
83
+ const aIndex = token.attrIndex('target')
84
+
85
+ if (aIndex < 0) {
86
+ token.attrPush(['target', '_blank']) // add new attribute
87
+ } else {
88
+ token.attrs[aIndex][1] = '_blank' // replace value of existing attr
89
+ }
68
90
  }
69
91
  }
70
92
 
@@ -77,7 +99,7 @@ export async function createMarkdownRenderer () {
77
99
  }
78
100
 
79
101
  async function createMarkdownRendererWithPlugins (ctx: Context) {
80
- let md = await createMarkdownRenderer()
102
+ let md = await createMarkdownRenderer(ctx)
81
103
  if (ctx.config.markdown) {
82
104
  const result = await ctx.config.markdown(md)
83
105
  if (result) {
@@ -97,7 +119,10 @@ export async function createMarkdownPlugins (ctx: Context) {
97
119
  transform (code, id) {
98
120
  if (!id.includes('?vue&type=docs')) return
99
121
  if (!id.includes('lang.md')) return
100
- const html = md.render(code)
122
+ const file = id.substring(0, id.indexOf('?vue'))
123
+ const html = md.render(code, {
124
+ file,
125
+ })
101
126
  return `export default Comp => {
102
127
  Comp.doc = ${JSON.stringify(html)}
103
128
  }`
@@ -122,7 +147,9 @@ export async function createMarkdownFilesWatcher (ctx: Context) {
122
147
  const isRelatedToStory = dirFiles.some((file) => !file.endsWith('.md') && file.startsWith(truncatedName))
123
148
 
124
149
  const { data: frontmatter, content } = matter(await fs.readFile(absolutePath, 'utf8'))
125
- const html = md.render(content)
150
+ const html = md.render(content, {
151
+ file: absolutePath,
152
+ })
126
153
 
127
154
  const file: ServerMarkdownFile = {
128
155
  id: paramCase(relativePath.toLowerCase()),
@@ -1,7 +1,6 @@
1
1
  import http from 'node:http'
2
2
  import connect from 'connect'
3
3
  import sirv from 'sirv'
4
- import type { ResolvedConfig as ViteConfig } from 'vite'
5
4
  import type { Context } from './context.js'
6
5
 
7
6
  interface ReturnPayload {
@@ -9,11 +8,11 @@ interface ReturnPayload {
9
8
  close: () => Promise<void>
10
9
  }
11
10
 
12
- export async function startPreview (viteConfig: ViteConfig, port: number | null, ctx: Context): Promise<ReturnPayload> {
11
+ export async function startPreview (port: number | null, ctx: Context): Promise<ReturnPayload> {
13
12
  const app = connect()
14
13
 
15
14
  app.use(
16
- viteConfig.base,
15
+ ctx.resolvedViteConfig.base,
17
16
  sirv(ctx.config.outDir, {
18
17
  dev: true,
19
18
  etag: true,
@@ -38,7 +37,7 @@ export async function startPreview (viteConfig: ViteConfig, port: number | null,
38
37
 
39
38
  httpServer.listen(finalPort, () => {
40
39
  httpServer.off('error', onError)
41
- const baseUrl = `http://localhost:${finalPort}${viteConfig.base}`
40
+ const baseUrl = `http://localhost:${finalPort}${ctx.resolvedViteConfig.base}`
42
41
  resolve({
43
42
  baseUrl,
44
43
  close: () => new Promise((resolve, reject) => {
@@ -65,6 +65,7 @@ export async function createServer (ctx: Context, options: CreateServerOptions =
65
65
  // onStoryChange debouncing
66
66
  let queued = false
67
67
  let queuedFiles: ServerStoryFile[] = []
68
+ let currentFiles: ServerStoryFile[] = []
68
69
  let queueTimer
69
70
  let collecting = false
70
71
  let didAllStoriesYet = false
@@ -112,6 +113,9 @@ export async function createServer (ctx: Context, options: CreateServerOptions =
112
113
  clearTimeout(queueTimer)
113
114
  // Debounce
114
115
  queueTimer = setTimeout(collect, 100)
116
+ } else if (!changedFile && !currentFiles.length) {
117
+ // Full collect in progress
118
+ queued = false
115
119
  }
116
120
  }
117
121
  })
@@ -121,7 +125,7 @@ export async function createServer (ctx: Context, options: CreateServerOptions =
121
125
 
122
126
  clearCache()
123
127
 
124
- const currentFiles = queuedFiles.slice()
128
+ currentFiles = queuedFiles.slice()
125
129
  queuedFiles = []
126
130
  queued = false
127
131
 
package/src/node/vite.ts CHANGED
@@ -1,10 +1,8 @@
1
1
  import { createRequire } from 'node:module'
2
2
  import { relative, resolve, join, dirname } from 'pathe'
3
3
  import {
4
- resolveConfig as resolveViteConfigInternal,
5
4
  Plugin as VitePlugin,
6
5
  UserConfig as ViteConfig,
7
- ResolvedConfig,
8
6
  InlineConfig,
9
7
  mergeConfig as mergeViteConfig,
10
8
  loadConfigFromFile as loadViteConfigFromFile,
@@ -20,7 +18,6 @@ import { parseColor } from './colors.js'
20
18
  import { createMarkdownPlugins } from './markdown.js'
21
19
  import { getSearchDataJS, generateDocSearchData, generateTitleSearchData } from './search.js'
22
20
  import { getInjectedImport } from './util/vendors.js'
23
- import { findUp } from './util/find-up.js'
24
21
 
25
22
  const require = createRequire(import.meta.url)
26
23
 
@@ -61,14 +58,11 @@ export const RESOLVED_MARKDOWN_FILES = `/__resolved__${MARKDOWN_FILES}`
61
58
 
62
59
  const ID_SEPARATOR = '__-__'
63
60
 
64
- export async function resolveViteConfig (ctx: Context): Promise<ResolvedConfig> {
65
- const command = ctx.mode === 'dev' ? 'serve' : 'build'
66
- let viteConfig = (await resolveViteConfigInternal({}, command)) as unknown
67
- viteConfig = mergeHistoireViteConfig(viteConfig, ctx)
68
- return viteConfig as ResolvedConfig
69
- }
61
+ const PLUGINS_HAVE_DEV = [
62
+ '@histoire/plugin-vue',
63
+ ]
70
64
 
71
- async function mergeHistoireViteConfig (viteConfig: InlineConfig, ctx: Context) {
65
+ export async function mergeHistoireViteConfig (viteConfig: InlineConfig, ctx: Context) {
72
66
  if (ctx.config.vite) {
73
67
  const command = ctx.mode === 'dev' ? 'serve' : 'build'
74
68
  const overrides = typeof ctx.config.vite === 'function'
@@ -104,22 +98,16 @@ async function mergeHistoireViteConfig (viteConfig: InlineConfig, ctx: Context)
104
98
  }
105
99
 
106
100
  export async function getViteConfigWithPlugins (isServer: boolean, ctx: Context): Promise<InlineConfig> {
107
- const resolvedViteConfig = await resolveViteConfig(ctx)
108
-
109
101
  const userViteConfigFile = await loadViteConfigFromFile({ command: ctx.mode === 'dev' ? 'serve' : 'build', mode: ctx.mode })
110
102
  const userViteConfig = mergeViteConfig(userViteConfigFile?.config ?? {}, { server: { port: 6006 } })
111
103
 
112
104
  const inlineConfig = await mergeHistoireViteConfig(userViteConfig, ctx)
113
105
  const plugins: VitePlugin[] = []
114
106
 
115
- const hasPnpm = !!(await findUp(ctx.root, ['pnpm-lock.yaml']))
116
-
117
107
  function optimizeDeps (deps: string[]): string[] {
118
108
  const result = []
119
109
  for (const dep of deps) {
120
- if (!hasPnpm) {
121
- result.push(dep)
122
- }
110
+ result.push(dep)
123
111
  try {
124
112
  result.push(dirname(require.resolve(`${dep}/package.json`)))
125
113
  } catch (e) {
@@ -141,7 +129,7 @@ export async function getViteConfigWithPlugins (isServer: boolean, ctx: Context)
141
129
  'vue',
142
130
  ],
143
131
  alias: {
144
- 'histoire-style': join(APP_PATH, 'style.css'),
132
+ 'histoire-style': join(APP_PATH, process.env.HISTOIRE_DEV ? 'app/style/main.pcss' : 'style.css'),
145
133
  },
146
134
  },
147
135
  optimizeDeps: {
@@ -166,8 +154,13 @@ export async function getViteConfigWithPlugins (isServer: boolean, ctx: Context)
166
154
  allow: [
167
155
  APP_PATH,
168
156
  TEMP_PATH,
169
- resolvedViteConfig.root,
157
+ ctx.resolvedViteConfig.root,
170
158
  process.cwd(),
159
+ ...process.env.HISTOIRE_DEV
160
+ ? [
161
+ '../../packages/histoire-vendors',
162
+ ]
163
+ : [],
171
164
  ],
172
165
  },
173
166
  watch: {
@@ -357,7 +350,7 @@ if (import.meta.hot) {
357
350
  }
358
351
 
359
352
  if (id === RESOLVED_SUPPORT_PLUGINS_CLIENT) {
360
- const plugins = ctx.supportPlugins.map(p => `'${p.id}': () => import(${JSON.stringify(require.resolve(`${p.moduleName}/client`, {
353
+ const plugins = ctx.supportPlugins.map(p => `'${p.id}': () => import(${JSON.stringify(require.resolve(`${p.moduleName}/client${process.env.HISTOIRE_DEV && PLUGINS_HAVE_DEV.includes(p.moduleName) ? '-dev' : ''}`, {
361
354
  paths: [ctx.root, import.meta.url],
362
355
  }))})`)
363
356
  return `export const clientSupportPlugins = {
@@ -366,7 +359,7 @@ if (import.meta.hot) {
366
359
  }
367
360
 
368
361
  if (id === RESOLVED_SUPPORT_PLUGINS_COLLECT) {
369
- const plugins = ctx.supportPlugins.map(p => `'${p.id}': () => import(${JSON.stringify(require.resolve(`${p.moduleName}/collect`, {
362
+ const plugins = ctx.supportPlugins.map(p => `'${p.id}': () => import(${JSON.stringify(require.resolve(`${p.moduleName}/collect${process.env.HISTOIRE_DEV && PLUGINS_HAVE_DEV.includes(p.moduleName) ? '-dev' : ''}`, {
370
363
  paths: [ctx.root, import.meta.url],
371
364
  }))})`)
372
365
  return `export const collectSupportPlugins = {
@@ -376,7 +369,7 @@ if (import.meta.hot) {
376
369
 
377
370
  if (id === RESOLVED_MARKDOWN_FILES) {
378
371
  const filesJs = ctx.markdownFiles.map(f => `${JSON.stringify(f.relativePath)}: () => import(${JSON.stringify(`virtual:md:${f.id}`)})`).join(',')
379
- return `import { reactive } from ${getInjectedImport('@histoire/vendors/vue')}
372
+ return `import { reactive } from ${process.env.HISTOIRE_DEV ? `'vue'` : getInjectedImport('@histoire/vendors/vue')}
380
373
  export const markdownFiles = reactive({${filesJs}})
381
374
  if (import.meta.hot) {
382
375
  if (!window.__hst_md_hmr) {
@@ -473,7 +466,7 @@ if (import.meta.hot) {
473
466
  }
474
467
  }
475
468
  </script>
476
- <script type="module" src="/@fs/${APP_PATH}/bundle-sandbox.js"></script>
469
+ <script type="module" src="/@fs/${APP_PATH}/bundle-sandbox${process.env.HISTOIRE_DEV ? '-dev' : ''}.js"></script>
477
470
  </body>
478
471
  </html>`
479
472
  // Apply Vite HTML transforms. This injects the Vite HMR client, and
@@ -505,7 +498,7 @@ if (import.meta.hot) {
505
498
  </head>
506
499
  <body>
507
500
  <div id="app"></div>
508
- <script type="module" src="/@fs/${APP_PATH}/bundle-main.js"></script>
501
+ <script type="module" src="/@fs/${APP_PATH}/bundle-main${process.env.HISTOIRE_DEV ? '-dev' : ''}.js"></script>
509
502
  </body>
510
503
  </html>`
511
504
  // Apply Vite HTML transforms. This injects the Vite HMR client, and
@@ -535,7 +528,7 @@ if (import.meta.hot) {
535
528
  transform (code, id) {
536
529
  if (exclude.some(r => r.test(id))) return
537
530
  if (include.some(r => r.test(id))) {
538
- const file = relative(resolvedViteConfig.root, id)
531
+ const file = relative(ctx.resolvedViteConfig.root, id)
539
532
  const index = code.indexOf('export default')
540
533
  const result = `${code.substring(0, index)}_sfc_main.__file = '${file}'\n${code.substring(index)}`
541
534
  return result
@@ -544,6 +537,43 @@ if (import.meta.hot) {
544
537
  })
545
538
  }
546
539
 
540
+ if (process.env.HISTOIRE_DEV && !isServer) {
541
+ plugins.push({
542
+ name: 'histoire-dev-plugin',
543
+ config () {
544
+ // Examples context
545
+ return {
546
+ resolve: {
547
+ alias: [
548
+ ...[
549
+ ['floating-vue/dist/style.css', 'node_modules/floating-vue/dist/style.css'],
550
+ ['floating-vue', 'floating-vue'],
551
+ ['@iconify/vue', 'iconify'],
552
+ ['pinia', 'pinia'],
553
+ ['scroll-into-view-if-needed', 'scroll'],
554
+ ['vue-router', 'vue-router'],
555
+ ['@vueuse/core', 'vue-use'],
556
+ ['vue', 'vue'],
557
+ ].reduce((acc, [name, entry]) => {
558
+ acc.push({
559
+ find: new RegExp(`^${name.replace(/\//g, '\\/')}$`),
560
+ replacement: `@histoire/vendors/${entry}`,
561
+ })
562
+ acc.push({
563
+ find: new RegExp(`^${name.replace(/\//g, '\\/')}\\/`),
564
+ replacement: `@histoire/vendors/${entry}/`,
565
+ })
566
+ return acc
567
+ }, [] as any[]),
568
+
569
+ { find: /@histoire\/controls$/, replacement: '@histoire/controls/src/index.ts' },
570
+ ],
571
+ },
572
+ }
573
+ },
574
+ })
575
+ }
576
+
547
577
  return mergeViteConfig(inlineConfig, {
548
578
  configFile: false,
549
579
  plugins,