histoire 0.11.5 → 0.11.7

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,8 +28,8 @@ 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
- const server = await createViteServer(await getViteConfigWithPlugins(true, ctx));
31
+ const { viteConfig } = await getViteConfigWithPlugins(true, ctx);
32
+ const server = await createViteServer(viteConfig);
33
33
  await server.pluginContainer.buildStart({});
34
34
  const moduleLoader = useModuleLoader({
35
35
  server,
@@ -55,7 +55,8 @@ export async function build(ctx) {
55
55
  const storyCount = ctx.storyFiles.reduce((sum, file) => sum + (file.story?.variants.length ? 1 : 0), 0);
56
56
  const variantCount = ctx.storyFiles.reduce((sum, file) => sum + (file.story?.variants.length ?? 0), 0);
57
57
  const emptyStoryCount = ctx.storyFiles.length - storyCount;
58
- const buildViteConfig = mergeViteConfig(await getViteConfigWithPlugins(false, ctx), {
58
+ const { viteConfig: buildViteConfigRaw } = await getViteConfigWithPlugins(false, ctx);
59
+ const buildViteConfig = mergeViteConfig(buildViteConfigRaw, {
59
60
  mode: 'development',
60
61
  build: {
61
62
  lib: false,
@@ -128,19 +129,19 @@ export async function build(ctx) {
128
129
  const styleOutput = result.output.find(o => o.name === 'style.css' && o.type === 'asset');
129
130
  // Preload
130
131
  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);
132
+ const preloadHtml = generateScriptLinks(preloadOutputs.map(o => o.fileName), 'preload', ctx);
132
133
  // Prefetch
133
134
  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);
135
+ const prefetchHtml = generateScriptLinks(prefetchOutputs.map(o => o.fileName), 'prefetch', ctx);
135
136
  // Index
136
137
  const indexOutput = result.output.find(o => o.name === 'bundle-main' && o.type === 'chunk');
137
138
  const indexHtml = generateEntryHtml(indexOutput.fileName, styleOutput.fileName, {
138
139
  HEAD: `${preloadHtml}${prefetchHtml}`,
139
- }, ctx, resolvedViteConfig);
140
+ }, ctx);
140
141
  await writeFile('index.html', indexHtml, ctx);
141
142
  // Sandbox
142
143
  const sandboxOutput = result.output.find(o => o.name === 'bundle-sandbox' && o.type === 'chunk');
143
- const sandboxHtml = generateEntryHtml(sandboxOutput.fileName, styleOutput.fileName, {}, ctx, resolvedViteConfig);
144
+ const sandboxHtml = generateEntryHtml(sandboxOutput.fileName, styleOutput.fileName, {}, ctx);
144
145
  await writeFile('__sandbox.html', sandboxHtml, ctx);
145
146
  const duration = performance.now() - startTime;
146
147
  if (emptyStoryCount) {
@@ -149,7 +150,7 @@ export async function build(ctx) {
149
150
  console.log(pc.green(`✅ Built ${storyCount} stories (${variantCount} variants) in ${Math.round(duration / 1000 * 100) / 100}s`));
150
151
  // Render
151
152
  if (previewStoryCallbacks.length) {
152
- const { baseUrl, close } = await startPreview(resolvedViteConfig, null, ctx);
153
+ const { baseUrl, close } = await startPreview(null, ctx);
153
154
  for (const storyFile of ctx.storyFiles) {
154
155
  const story = storyFile.story;
155
156
  for (const variant of story.variants) {
@@ -189,15 +190,15 @@ function generateBaseHtml(head, body, ctx) {
189
190
  </body>
190
191
  </html>`;
191
192
  }
192
- function generateEntryHtml(jsEntryFile, cssEntryFile, variables, ctx, resolvedViteConfig) {
193
- return generateBaseHtml(`<link rel="stylesheet" href="${resolvedViteConfig.base}${cssEntryFile}">
193
+ function generateEntryHtml(jsEntryFile, cssEntryFile, variables, ctx) {
194
+ return generateBaseHtml(`<link rel="stylesheet" href="${ctx.resolvedViteConfig.base}${cssEntryFile}">
194
195
  ${ctx.config.theme?.favicon ? `<link rel="icon" type="${lookupMime(ctx.config.theme.favicon)}" href="${ctx.config.theme.favicon}"/>` : ''}
195
196
  ${variables.HEAD ?? ''}`, `<div id="app"></div>
196
- <script type="module" src="${resolvedViteConfig.base}${jsEntryFile}"></script>`, ctx);
197
+ <script type="module" src="${ctx.resolvedViteConfig.base}${jsEntryFile}"></script>`, ctx);
197
198
  }
198
199
  async function writeFile(fileName, content, ctx) {
199
200
  await fs.writeFile(join(ctx.config.outDir, fileName), content, 'utf8');
200
201
  }
201
- function generateScriptLinks(prefetchScripts, rel, ctx, resolvedViteConfig) {
202
- return prefetchScripts.map(s => `<link rel="${rel}" href="${resolvedViteConfig.base}${s}" as="script" crossOrigin="anonymous">`).join('');
202
+ function generateScriptLinks(prefetchScripts, rel, ctx) {
203
+ return prefetchScripts.map(s => `<link rel="${rel}" href="${ctx.resolvedViteConfig.base}${s}" as="script" crossOrigin="anonymous">`).join('');
203
204
  }
@@ -125,7 +125,6 @@ export default _defineComponent({
125
125
  render() {
126
126
  return _h('div', {
127
127
  ref: 'sandbox',
128
- class: '__histoire-sandbox htw-overflow-auto',
129
128
  });
130
129
  },
131
130
  });
@@ -9,12 +9,12 @@ export async function devCommand(options) {
9
9
  const ctx = await createContext({
10
10
  mode: 'dev',
11
11
  });
12
- const { server, close } = await createServer(ctx, { port: options.port });
12
+ const { server, viteConfigFile, close } = await createServer(ctx, { port: options.port });
13
13
  server.printUrls();
14
14
  // Histoire config watcher
15
15
  let watcher;
16
- if (server.config.configFile) {
17
- watcher = chokidar.watch(server.config.configFile, {
16
+ if (viteConfigFile) {
17
+ watcher = chokidar.watch(viteConfigFile, {
18
18
  ignoreInitial: true,
19
19
  });
20
20
  watcher.on('change', () => {
@@ -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',
@@ -134,6 +139,7 @@ export async function loadConfigFile(configFile) {
134
139
  try {
135
140
  const result = jiti(__filename, {
136
141
  esmResolve: true,
142
+ requireCache: false,
137
143
  })(configFile);
138
144
  if (!result.default) {
139
145
  throw new Error(`Expected default export in ${configFile}`);
@@ -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) => {
@@ -4,5 +4,6 @@ export interface CreateServerOptions {
4
4
  }
5
5
  export declare function createServer(ctx: Context, options?: CreateServerOptions): Promise<{
6
6
  server: import("vite").ViteDevServer;
7
+ viteConfigFile: string;
7
8
  close: () => Promise<void>;
8
9
  }>;
@@ -10,11 +10,15 @@ import { wrapLogError } from './util/log.js';
10
10
  import { createMarkdownFilesWatcher, onMarkdownListChange } from './markdown.js';
11
11
  export async function createServer(ctx, options = {}) {
12
12
  const getViteServer = async (collecting) => {
13
- const server = await createViteServer(await getViteConfigWithPlugins(collecting, ctx));
13
+ const { viteConfig, viteConfigFile } = await getViteConfigWithPlugins(collecting, ctx);
14
+ const server = await createViteServer(viteConfig);
14
15
  await server.pluginContainer.buildStart({});
15
- return server;
16
+ return {
17
+ server,
18
+ viteConfigFile,
19
+ };
16
20
  };
17
- const [server, nodeServer, , { stop: stopMdFileWatcher },] = await Promise.all([
21
+ const [{ server, viteConfigFile }, { server: nodeServer }, , { stop: stopMdFileWatcher },] = await Promise.all([
18
22
  getViteServer(false),
19
23
  getViteServer(true),
20
24
  watchStories(ctx),
@@ -42,6 +46,7 @@ export async function createServer(ctx, options = {}) {
42
46
  // onStoryChange debouncing
43
47
  let queued = false;
44
48
  let queuedFiles = [];
49
+ let currentFiles = [];
45
50
  let queueTimer;
46
51
  let collecting = false;
47
52
  let didAllStoriesYet = false;
@@ -86,12 +91,16 @@ export async function createServer(ctx, options = {}) {
86
91
  // Debounce
87
92
  queueTimer = setTimeout(collect, 100);
88
93
  }
94
+ else if (!changedFile && !currentFiles.length) {
95
+ // Full collect in progress
96
+ queued = false;
97
+ }
89
98
  }
90
99
  });
91
100
  async function collect() {
92
101
  collecting = true;
93
102
  clearCache();
94
- const currentFiles = queuedFiles.slice();
103
+ currentFiles = queuedFiles.slice();
95
104
  queuedFiles = [];
96
105
  queued = false;
97
106
  console.log('Collect stories start', currentFiles.length ? currentFiles.map(f => f.fileName).join(', ') : 'all');
@@ -152,6 +161,7 @@ export async function createServer(ctx, options = {}) {
152
161
  collect();
153
162
  return {
154
163
  server,
164
+ viteConfigFile,
155
165
  close,
156
166
  };
157
167
  }
@@ -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,9 @@ 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>;
26
- export declare function getViteConfigWithPlugins(isServer: boolean, ctx: Context): Promise<InlineConfig>;
25
+ export declare function mergeHistoireViteConfig(viteConfig: InlineConfig, ctx: Context): Promise<InlineConfig>;
26
+ export interface ViteConfigWithPlugins {
27
+ viteConfig: InlineConfig;
28
+ viteConfigFile: string | null;
29
+ }
30
+ export declare function getViteConfigWithPlugins(isServer: boolean, ctx: Context): Promise<ViteConfigWithPlugins>;
package/dist/node/vite.js CHANGED
@@ -1,9 +1,8 @@
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
- import ViteInspect from 'vite-plugin-inspect';
7
6
  import { APP_PATH, TEMP_PATH } from './alias.js';
8
7
  import { notifyStoryChange } from './stories.js';
9
8
  import { makeTree } from './tree.js';
@@ -47,13 +46,10 @@ export const MARKDOWN_FILES = 'virtual:$histoire-markdown-files';
47
46
  export const RESOLVED_MARKDOWN_FILES = `/__resolved__${MARKDOWN_FILES}`;
48
47
  // export const RESOLVED_MARKDOWN_FILES = `\0${MARKDOWN_FILES}`
49
48
  const ID_SEPARATOR = '__-__';
50
- export async function resolveViteConfig(ctx) {
51
- const command = ctx.mode === 'dev' ? 'serve' : 'build';
52
- let viteConfig = (await resolveViteConfigInternal({}, command));
53
- viteConfig = mergeHistoireViteConfig(viteConfig, ctx);
54
- return viteConfig;
55
- }
56
- async function mergeHistoireViteConfig(viteConfig, ctx) {
49
+ const PLUGINS_HAVE_DEV = [
50
+ '@histoire/plugin-vue',
51
+ ];
52
+ export async function mergeHistoireViteConfig(viteConfig, ctx) {
57
53
  if (ctx.config.vite) {
58
54
  const command = ctx.mode === 'dev' ? 'serve' : 'build';
59
55
  const overrides = typeof ctx.config.vite === 'function'
@@ -85,7 +81,6 @@ async function mergeHistoireViteConfig(viteConfig, ctx) {
85
81
  return viteConfig;
86
82
  }
87
83
  export async function getViteConfigWithPlugins(isServer, ctx) {
88
- const resolvedViteConfig = await resolveViteConfig(ctx);
89
84
  const userViteConfigFile = await loadViteConfigFromFile({ command: ctx.mode === 'dev' ? 'serve' : 'build', mode: ctx.mode });
90
85
  const userViteConfig = mergeViteConfig(userViteConfigFile?.config ?? {}, { server: { port: 6006 } });
91
86
  const inlineConfig = await mergeHistoireViteConfig(userViteConfig, ctx);
@@ -103,7 +98,6 @@ export async function getViteConfigWithPlugins(isServer, ctx) {
103
98
  }
104
99
  return result;
105
100
  }
106
- plugins.push(ViteInspect());
107
101
  plugins.push({
108
102
  name: 'histoire-vite-plugin',
109
103
  config() {
@@ -113,7 +107,7 @@ export async function getViteConfigWithPlugins(isServer, ctx) {
113
107
  'vue',
114
108
  ],
115
109
  alias: {
116
- 'histoire-style': join(APP_PATH, 'style.css'),
110
+ 'histoire-style': join(APP_PATH, process.env.HISTOIRE_DEV ? 'app/style/main.pcss' : 'style.css'),
117
111
  },
118
112
  },
119
113
  optimizeDeps: {
@@ -138,8 +132,13 @@ export async function getViteConfigWithPlugins(isServer, ctx) {
138
132
  allow: [
139
133
  APP_PATH,
140
134
  TEMP_PATH,
141
- resolvedViteConfig.root,
135
+ ctx.resolvedViteConfig.root,
142
136
  process.cwd(),
137
+ ...process.env.HISTOIRE_DEV
138
+ ? [
139
+ '../../packages/histoire-vendors',
140
+ ]
141
+ : [],
143
142
  ],
144
143
  },
145
144
  watch: {
@@ -171,7 +170,7 @@ export async function getViteConfigWithPlugins(isServer, ctx) {
171
170
  else if (isServer && 'server' in setupFileConfig) {
172
171
  file = setupFileConfig.server;
173
172
  }
174
- else if ('browser' in setupFileConfig) {
173
+ else if (!isServer && 'browser' in setupFileConfig) {
175
174
  file = setupFileConfig.browser;
176
175
  }
177
176
  if (file) {
@@ -321,7 +320,7 @@ if (import.meta.hot) {
321
320
  return ctx.config.setupCode?.[index] ?? '';
322
321
  }
323
322
  if (id === RESOLVED_SUPPORT_PLUGINS_CLIENT) {
324
- const plugins = ctx.supportPlugins.map(p => `'${p.id}': () => import(${JSON.stringify(require.resolve(`${p.moduleName}/client`, {
323
+ 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' : ''}`, {
325
324
  paths: [ctx.root, import.meta.url],
326
325
  }))})`);
327
326
  return `export const clientSupportPlugins = {
@@ -329,7 +328,7 @@ if (import.meta.hot) {
329
328
  }`;
330
329
  }
331
330
  if (id === RESOLVED_SUPPORT_PLUGINS_COLLECT) {
332
- const plugins = ctx.supportPlugins.map(p => `'${p.id}': () => import(${JSON.stringify(require.resolve(`${p.moduleName}/collect`, {
331
+ 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' : ''}`, {
333
332
  paths: [ctx.root, import.meta.url],
334
333
  }))})`);
335
334
  return `export const collectSupportPlugins = {
@@ -338,7 +337,7 @@ if (import.meta.hot) {
338
337
  }
339
338
  if (id === RESOLVED_MARKDOWN_FILES) {
340
339
  const filesJs = ctx.markdownFiles.map(f => `${JSON.stringify(f.relativePath)}: () => import(${JSON.stringify(`virtual:md:${f.id}`)})`).join(',');
341
- return `import { reactive } from ${getInjectedImport('@histoire/vendors/vue')}
340
+ return `import { reactive } from ${process.env.HISTOIRE_DEV ? `'vue'` : getInjectedImport('@histoire/vendors/vue')}
342
341
  export const markdownFiles = reactive({${filesJs}})
343
342
  if (import.meta.hot) {
344
343
  if (!window.__hst_md_hmr) {
@@ -430,7 +429,7 @@ if (import.meta.hot) {
430
429
  }
431
430
  }
432
431
  </script>
433
- <script type="module" src="/@fs/${APP_PATH}/bundle-sandbox.js"></script>
432
+ <script type="module" src="/@fs/${APP_PATH}/bundle-sandbox${process.env.HISTOIRE_DEV ? '-dev' : ''}.js"></script>
434
433
  </body>
435
434
  </html>`;
436
435
  // Apply Vite HTML transforms. This injects the Vite HMR client, and
@@ -460,7 +459,7 @@ if (import.meta.hot) {
460
459
  </head>
461
460
  <body>
462
461
  <div id="app"></div>
463
- <script type="module" src="/@fs/${APP_PATH}/bundle-main.js"></script>
462
+ <script type="module" src="/@fs/${APP_PATH}/bundle-main${process.env.HISTOIRE_DEV ? '-dev' : ''}.js"></script>
464
463
  </body>
465
464
  </html>`;
466
465
  // Apply Vite HTML transforms. This injects the Vite HMR client, and
@@ -488,7 +487,7 @@ if (import.meta.hot) {
488
487
  if (exclude.some(r => r.test(id)))
489
488
  return;
490
489
  if (include.some(r => r.test(id))) {
491
- const file = relative(resolvedViteConfig.root, id);
490
+ const file = relative(ctx.resolvedViteConfig.root, id);
492
491
  const index = code.indexOf('export default');
493
492
  const result = `${code.substring(0, index)}_sfc_main.__file = '${file}'\n${code.substring(index)}`;
494
493
  return result;
@@ -496,8 +495,47 @@ if (import.meta.hot) {
496
495
  },
497
496
  });
498
497
  }
499
- return mergeViteConfig(inlineConfig, {
498
+ if (process.env.HISTOIRE_DEV && !isServer) {
499
+ plugins.push({
500
+ name: 'histoire-dev-plugin',
501
+ config() {
502
+ // Examples context
503
+ return {
504
+ resolve: {
505
+ alias: [
506
+ ...[
507
+ ['floating-vue/dist/style.css', 'node_modules/floating-vue/dist/style.css'],
508
+ ['floating-vue', 'floating-vue'],
509
+ ['@iconify/vue', 'iconify'],
510
+ ['pinia', 'pinia'],
511
+ ['scroll-into-view-if-needed', 'scroll'],
512
+ ['vue-router', 'vue-router'],
513
+ ['@vueuse/core', 'vue-use'],
514
+ ['vue', 'vue'],
515
+ ].reduce((acc, [name, entry]) => {
516
+ acc.push({
517
+ find: new RegExp(`^${name.replace(/\//g, '\\/')}$`),
518
+ replacement: `@histoire/vendors/${entry}`,
519
+ });
520
+ acc.push({
521
+ find: new RegExp(`^${name.replace(/\//g, '\\/')}\\/`),
522
+ replacement: `@histoire/vendors/${entry}/`,
523
+ });
524
+ return acc;
525
+ }, []),
526
+ { find: /@histoire\/controls$/, replacement: '@histoire/controls/src/index.ts' },
527
+ ],
528
+ },
529
+ };
530
+ },
531
+ });
532
+ }
533
+ const viteConfig = mergeViteConfig(inlineConfig, {
500
534
  configFile: false,
501
535
  plugins,
502
536
  });
537
+ return {
538
+ viteConfig,
539
+ viteConfigFile: userViteConfigFile?.path ?? null,
540
+ };
503
541
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "histoire",
3
- "version": "0.11.5",
3
+ "version": "0.11.7",
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.5",
37
- "@histoire/controls": "^0.11.5",
38
- "@histoire/shared": "^0.11.5",
39
- "@histoire/vendors": "^0.11.5",
36
+ "@histoire/app": "^0.11.7",
37
+ "@histoire/controls": "^0.11.7",
38
+ "@histoire/shared": "^0.11.7",
39
+ "@histoire/vendors": "^0.11.7",
40
40
  "@types/flexsearch": "^0.7.3",
41
41
  "@types/markdown-it": "^12.2.3",
42
42
  "birpc": "^0.1.1",
@@ -63,7 +63,6 @@
63
63
  "shiki": "0.10.1",
64
64
  "sirv": "^2.0.2",
65
65
  "tinypool": "^0.1.2",
66
- "vite-plugin-inspect": "^0.7.5",
67
66
  "vite-node": "0.23.4"
68
67
  },
69
68
  "peerDependencies": {
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,9 +45,8 @@ export async function build (ctx: Context) {
46
45
  await stop()
47
46
  }
48
47
 
49
- const resolvedViteConfig = await resolveViteConfig(ctx)
50
-
51
- const server = await createViteServer(await getViteConfigWithPlugins(true, ctx))
48
+ const { viteConfig } = await getViteConfigWithPlugins(true, ctx)
49
+ const server = await createViteServer(viteConfig)
52
50
  await server.pluginContainer.buildStart({})
53
51
 
54
52
  const moduleLoader = useModuleLoader({
@@ -78,7 +76,8 @@ export async function build (ctx: Context) {
78
76
  const variantCount = ctx.storyFiles.reduce((sum, file) => sum + (file.story?.variants.length ?? 0), 0)
79
77
  const emptyStoryCount = ctx.storyFiles.length - storyCount
80
78
 
81
- const buildViteConfig: ViteInlineConfig = mergeViteConfig(await getViteConfigWithPlugins(false, ctx), {
79
+ const { viteConfig: buildViteConfigRaw } = await getViteConfigWithPlugins(false, ctx)
80
+ const buildViteConfig: ViteInlineConfig = mergeViteConfig(buildViteConfigRaw, {
82
81
  mode: 'development',
83
82
  build: {
84
83
  lib: false,
@@ -156,22 +155,22 @@ export async function build (ctx: Context) {
156
155
 
157
156
  // Preload
158
157
  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)
158
+ const preloadHtml = generateScriptLinks(preloadOutputs.map(o => o.fileName), 'preload', ctx)
160
159
 
161
160
  // Prefetch
162
161
  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)
162
+ const prefetchHtml = generateScriptLinks(prefetchOutputs.map(o => o.fileName), 'prefetch', ctx)
164
163
 
165
164
  // Index
166
165
  const indexOutput = result.output.find(o => o.name === 'bundle-main' && o.type === 'chunk')
167
166
  const indexHtml = generateEntryHtml(indexOutput.fileName, styleOutput.fileName, {
168
167
  HEAD: `${preloadHtml}${prefetchHtml}`,
169
- }, ctx, resolvedViteConfig)
168
+ }, ctx)
170
169
  await writeFile('index.html', indexHtml, ctx)
171
170
 
172
171
  // Sandbox
173
172
  const sandboxOutput = result.output.find(o => o.name === 'bundle-sandbox' && o.type === 'chunk')
174
- const sandboxHtml = generateEntryHtml(sandboxOutput.fileName, styleOutput.fileName, {}, ctx, resolvedViteConfig)
173
+ const sandboxHtml = generateEntryHtml(sandboxOutput.fileName, styleOutput.fileName, {}, ctx)
175
174
  await writeFile('__sandbox.html', sandboxHtml, ctx)
176
175
 
177
176
  const duration = performance.now() - startTime
@@ -182,7 +181,7 @@ export async function build (ctx: Context) {
182
181
 
183
182
  // Render
184
183
  if (previewStoryCallbacks.length) {
185
- const { baseUrl, close } = await startPreview(resolvedViteConfig, null, ctx)
184
+ const { baseUrl, close } = await startPreview(null, ctx)
186
185
  for (const storyFile of ctx.storyFiles) {
187
186
  const story = storyFile.story
188
187
  for (const variant of story.variants) {
@@ -226,13 +225,13 @@ function generateBaseHtml (head: string, body: string, ctx: Context) {
226
225
  </html>`
227
226
  }
228
227
 
229
- function generateEntryHtml (jsEntryFile: string, cssEntryFile: string, variables: { HEAD?: string }, ctx: Context, resolvedViteConfig: ViteConfig) {
228
+ function generateEntryHtml (jsEntryFile: string, cssEntryFile: string, variables: { HEAD?: string }, ctx: Context) {
230
229
  return generateBaseHtml(
231
- `<link rel="stylesheet" href="${resolvedViteConfig.base}${cssEntryFile}">
230
+ `<link rel="stylesheet" href="${ctx.resolvedViteConfig.base}${cssEntryFile}">
232
231
  ${ctx.config.theme?.favicon ? `<link rel="icon" type="${lookupMime(ctx.config.theme.favicon)}" href="${ctx.config.theme.favicon}"/>` : ''}
233
232
  ${variables.HEAD ?? ''}`,
234
233
  `<div id="app"></div>
235
- <script type="module" src="${resolvedViteConfig.base}${jsEntryFile}"></script>`,
234
+ <script type="module" src="${ctx.resolvedViteConfig.base}${jsEntryFile}"></script>`,
236
235
  ctx,
237
236
  )
238
237
  }
@@ -241,6 +240,6 @@ async function writeFile (fileName: string, content: string, ctx: Context) {
241
240
  await fs.writeFile(join(ctx.config.outDir, fileName), content, 'utf8')
242
241
  }
243
242
 
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('')
243
+ function generateScriptLinks (prefetchScripts: string[], rel: string, ctx: Context) {
244
+ return prefetchScripts.map(s => `<link rel="${rel}" href="${ctx.resolvedViteConfig.base}${s}" as="script" crossOrigin="anonymous">`).join('')
246
245
  }
@@ -160,7 +160,6 @@ export default _defineComponent({
160
160
  render () {
161
161
  return _h('div', {
162
162
  ref: 'sandbox',
163
- class: '__histoire-sandbox htw-overflow-auto',
164
163
  })
165
164
  },
166
165
  })
@@ -15,13 +15,13 @@ export async function devCommand (options: DevOptions) {
15
15
  const ctx = await createContext({
16
16
  mode: 'dev',
17
17
  })
18
- const { server, close } = await createServer(ctx, { port: options.port })
18
+ const { server, viteConfigFile, close } = await createServer(ctx, { port: options.port })
19
19
  server.printUrls()
20
20
 
21
21
  // Histoire config watcher
22
22
  let watcher: chokidar.FSWatcher
23
- if (server.config.configFile) {
24
- watcher = chokidar.watch(server.config.configFile, {
23
+ if (viteConfigFile) {
24
+ watcher = chokidar.watch(viteConfigFile, {
25
25
  ignoreInitial: true,
26
26
  })
27
27
  watcher.on('change', () => {
@@ -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',
@@ -149,6 +154,7 @@ export async function loadConfigFile (configFile: string): Promise<Partial<Histo
149
154
  try {
150
155
  const result = jiti(__filename, {
151
156
  esmResolve: true,
157
+ requireCache: false,
152
158
  })(configFile)
153
159
  if (!result.default) {
154
160
  throw new Error(`Expected default export in ${configFile}`)
@@ -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) => {
@@ -17,14 +17,18 @@ export interface CreateServerOptions {
17
17
 
18
18
  export async function createServer (ctx: Context, options: CreateServerOptions = {}) {
19
19
  const getViteServer = async (collecting: boolean) => {
20
- const server = await createViteServer(await getViteConfigWithPlugins(collecting, ctx))
20
+ const { viteConfig, viteConfigFile } = await getViteConfigWithPlugins(collecting, ctx)
21
+ const server = await createViteServer(viteConfig)
21
22
  await server.pluginContainer.buildStart({})
22
- return server
23
+ return {
24
+ server,
25
+ viteConfigFile,
26
+ }
23
27
  }
24
28
 
25
29
  const [
26
- server,
27
- nodeServer,
30
+ { server, viteConfigFile },
31
+ { server: nodeServer },
28
32
  ,
29
33
  { stop: stopMdFileWatcher },
30
34
  ] = await Promise.all([
@@ -65,6 +69,7 @@ export async function createServer (ctx: Context, options: CreateServerOptions =
65
69
  // onStoryChange debouncing
66
70
  let queued = false
67
71
  let queuedFiles: ServerStoryFile[] = []
72
+ let currentFiles: ServerStoryFile[] = []
68
73
  let queueTimer
69
74
  let collecting = false
70
75
  let didAllStoriesYet = false
@@ -112,6 +117,9 @@ export async function createServer (ctx: Context, options: CreateServerOptions =
112
117
  clearTimeout(queueTimer)
113
118
  // Debounce
114
119
  queueTimer = setTimeout(collect, 100)
120
+ } else if (!changedFile && !currentFiles.length) {
121
+ // Full collect in progress
122
+ queued = false
115
123
  }
116
124
  }
117
125
  })
@@ -121,7 +129,7 @@ export async function createServer (ctx: Context, options: CreateServerOptions =
121
129
 
122
130
  clearCache()
123
131
 
124
- const currentFiles = queuedFiles.slice()
132
+ currentFiles = queuedFiles.slice()
125
133
  queuedFiles = []
126
134
  queued = false
127
135
 
@@ -195,6 +203,7 @@ export async function createServer (ctx: Context, options: CreateServerOptions =
195
203
 
196
204
  return {
197
205
  server,
206
+ viteConfigFile,
198
207
  close,
199
208
  }
200
209
  }
package/src/node/vite.ts CHANGED
@@ -1,17 +1,14 @@
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,
11
9
  } from 'vite'
12
10
  import { lookup as lookupMime } from 'mrmime'
13
11
  import fs from 'fs-extra'
14
- import ViteInspect from 'vite-plugin-inspect'
15
12
  import { APP_PATH, TEMP_PATH } from './alias.js'
16
13
  import { Context } from './context.js'
17
14
  import { notifyStoryChange } from './stories.js'
@@ -60,14 +57,11 @@ export const RESOLVED_MARKDOWN_FILES = `/__resolved__${MARKDOWN_FILES}`
60
57
 
61
58
  const ID_SEPARATOR = '__-__'
62
59
 
63
- export async function resolveViteConfig (ctx: Context): Promise<ResolvedConfig> {
64
- const command = ctx.mode === 'dev' ? 'serve' : 'build'
65
- let viteConfig = (await resolveViteConfigInternal({}, command)) as unknown
66
- viteConfig = mergeHistoireViteConfig(viteConfig, ctx)
67
- return viteConfig as ResolvedConfig
68
- }
60
+ const PLUGINS_HAVE_DEV = [
61
+ '@histoire/plugin-vue',
62
+ ]
69
63
 
70
- async function mergeHistoireViteConfig (viteConfig: InlineConfig, ctx: Context) {
64
+ export async function mergeHistoireViteConfig (viteConfig: InlineConfig, ctx: Context) {
71
65
  if (ctx.config.vite) {
72
66
  const command = ctx.mode === 'dev' ? 'serve' : 'build'
73
67
  const overrides = typeof ctx.config.vite === 'function'
@@ -102,9 +96,12 @@ async function mergeHistoireViteConfig (viteConfig: InlineConfig, ctx: Context)
102
96
  return viteConfig
103
97
  }
104
98
 
105
- export async function getViteConfigWithPlugins (isServer: boolean, ctx: Context): Promise<InlineConfig> {
106
- const resolvedViteConfig = await resolveViteConfig(ctx)
99
+ export interface ViteConfigWithPlugins {
100
+ viteConfig: InlineConfig
101
+ viteConfigFile: string | null
102
+ }
107
103
 
104
+ export async function getViteConfigWithPlugins (isServer: boolean, ctx: Context): Promise<ViteConfigWithPlugins> {
108
105
  const userViteConfigFile = await loadViteConfigFromFile({ command: ctx.mode === 'dev' ? 'serve' : 'build', mode: ctx.mode })
109
106
  const userViteConfig = mergeViteConfig(userViteConfigFile?.config ?? {}, { server: { port: 6006 } })
110
107
 
@@ -124,8 +121,6 @@ export async function getViteConfigWithPlugins (isServer: boolean, ctx: Context)
124
121
  return result
125
122
  }
126
123
 
127
- plugins.push(ViteInspect())
128
-
129
124
  plugins.push({
130
125
  name: 'histoire-vite-plugin',
131
126
 
@@ -136,7 +131,7 @@ export async function getViteConfigWithPlugins (isServer: boolean, ctx: Context)
136
131
  'vue',
137
132
  ],
138
133
  alias: {
139
- 'histoire-style': join(APP_PATH, 'style.css'),
134
+ 'histoire-style': join(APP_PATH, process.env.HISTOIRE_DEV ? 'app/style/main.pcss' : 'style.css'),
140
135
  },
141
136
  },
142
137
  optimizeDeps: {
@@ -161,8 +156,13 @@ export async function getViteConfigWithPlugins (isServer: boolean, ctx: Context)
161
156
  allow: [
162
157
  APP_PATH,
163
158
  TEMP_PATH,
164
- resolvedViteConfig.root,
159
+ ctx.resolvedViteConfig.root,
165
160
  process.cwd(),
161
+ ...process.env.HISTOIRE_DEV
162
+ ? [
163
+ '../../packages/histoire-vendors',
164
+ ]
165
+ : [],
166
166
  ],
167
167
  },
168
168
  watch: {
@@ -193,7 +193,7 @@ export async function getViteConfigWithPlugins (isServer: boolean, ctx: Context)
193
193
  file = setupFileConfig
194
194
  } else if (isServer && 'server' in setupFileConfig) {
195
195
  file = setupFileConfig.server
196
- } else if ('browser' in setupFileConfig) {
196
+ } else if (!isServer && 'browser' in setupFileConfig) {
197
197
  file = setupFileConfig.browser
198
198
  }
199
199
  if (file) {
@@ -352,7 +352,7 @@ if (import.meta.hot) {
352
352
  }
353
353
 
354
354
  if (id === RESOLVED_SUPPORT_PLUGINS_CLIENT) {
355
- const plugins = ctx.supportPlugins.map(p => `'${p.id}': () => import(${JSON.stringify(require.resolve(`${p.moduleName}/client`, {
355
+ 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' : ''}`, {
356
356
  paths: [ctx.root, import.meta.url],
357
357
  }))})`)
358
358
  return `export const clientSupportPlugins = {
@@ -361,7 +361,7 @@ if (import.meta.hot) {
361
361
  }
362
362
 
363
363
  if (id === RESOLVED_SUPPORT_PLUGINS_COLLECT) {
364
- const plugins = ctx.supportPlugins.map(p => `'${p.id}': () => import(${JSON.stringify(require.resolve(`${p.moduleName}/collect`, {
364
+ 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' : ''}`, {
365
365
  paths: [ctx.root, import.meta.url],
366
366
  }))})`)
367
367
  return `export const collectSupportPlugins = {
@@ -371,7 +371,7 @@ if (import.meta.hot) {
371
371
 
372
372
  if (id === RESOLVED_MARKDOWN_FILES) {
373
373
  const filesJs = ctx.markdownFiles.map(f => `${JSON.stringify(f.relativePath)}: () => import(${JSON.stringify(`virtual:md:${f.id}`)})`).join(',')
374
- return `import { reactive } from ${getInjectedImport('@histoire/vendors/vue')}
374
+ return `import { reactive } from ${process.env.HISTOIRE_DEV ? `'vue'` : getInjectedImport('@histoire/vendors/vue')}
375
375
  export const markdownFiles = reactive({${filesJs}})
376
376
  if (import.meta.hot) {
377
377
  if (!window.__hst_md_hmr) {
@@ -468,7 +468,7 @@ if (import.meta.hot) {
468
468
  }
469
469
  }
470
470
  </script>
471
- <script type="module" src="/@fs/${APP_PATH}/bundle-sandbox.js"></script>
471
+ <script type="module" src="/@fs/${APP_PATH}/bundle-sandbox${process.env.HISTOIRE_DEV ? '-dev' : ''}.js"></script>
472
472
  </body>
473
473
  </html>`
474
474
  // Apply Vite HTML transforms. This injects the Vite HMR client, and
@@ -500,7 +500,7 @@ if (import.meta.hot) {
500
500
  </head>
501
501
  <body>
502
502
  <div id="app"></div>
503
- <script type="module" src="/@fs/${APP_PATH}/bundle-main.js"></script>
503
+ <script type="module" src="/@fs/${APP_PATH}/bundle-main${process.env.HISTOIRE_DEV ? '-dev' : ''}.js"></script>
504
504
  </body>
505
505
  </html>`
506
506
  // Apply Vite HTML transforms. This injects the Vite HMR client, and
@@ -530,7 +530,7 @@ if (import.meta.hot) {
530
530
  transform (code, id) {
531
531
  if (exclude.some(r => r.test(id))) return
532
532
  if (include.some(r => r.test(id))) {
533
- const file = relative(resolvedViteConfig.root, id)
533
+ const file = relative(ctx.resolvedViteConfig.root, id)
534
534
  const index = code.indexOf('export default')
535
535
  const result = `${code.substring(0, index)}_sfc_main.__file = '${file}'\n${code.substring(index)}`
536
536
  return result
@@ -539,8 +539,50 @@ if (import.meta.hot) {
539
539
  })
540
540
  }
541
541
 
542
- return mergeViteConfig(inlineConfig, {
542
+ if (process.env.HISTOIRE_DEV && !isServer) {
543
+ plugins.push({
544
+ name: 'histoire-dev-plugin',
545
+ config () {
546
+ // Examples context
547
+ return {
548
+ resolve: {
549
+ alias: [
550
+ ...[
551
+ ['floating-vue/dist/style.css', 'node_modules/floating-vue/dist/style.css'],
552
+ ['floating-vue', 'floating-vue'],
553
+ ['@iconify/vue', 'iconify'],
554
+ ['pinia', 'pinia'],
555
+ ['scroll-into-view-if-needed', 'scroll'],
556
+ ['vue-router', 'vue-router'],
557
+ ['@vueuse/core', 'vue-use'],
558
+ ['vue', 'vue'],
559
+ ].reduce((acc, [name, entry]) => {
560
+ acc.push({
561
+ find: new RegExp(`^${name.replace(/\//g, '\\/')}$`),
562
+ replacement: `@histoire/vendors/${entry}`,
563
+ })
564
+ acc.push({
565
+ find: new RegExp(`^${name.replace(/\//g, '\\/')}\\/`),
566
+ replacement: `@histoire/vendors/${entry}/`,
567
+ })
568
+ return acc
569
+ }, [] as any[]),
570
+
571
+ { find: /@histoire\/controls$/, replacement: '@histoire/controls/src/index.ts' },
572
+ ],
573
+ },
574
+ }
575
+ },
576
+ })
577
+ }
578
+
579
+ const viteConfig = mergeViteConfig(inlineConfig, {
543
580
  configFile: false,
544
581
  plugins,
545
582
  }) as InlineConfig
583
+
584
+ return {
585
+ viteConfig,
586
+ viteConfigFile: userViteConfigFile?.path ?? null,
587
+ }
546
588
  }