histoire 0.2.3 → 0.3.0

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.
Files changed (178) hide show
  1. package/dist/client/app/App.vue +9 -4
  2. package/dist/client/app/codegen/const.d.ts +1 -0
  3. package/dist/client/app/codegen/const.js +3 -0
  4. package/dist/client/app/codegen/vue3.js +82 -21
  5. package/dist/client/app/components/app/AppHeader.vue +2 -2
  6. package/dist/client/app/components/app/Breadcrumb.vue +1 -1
  7. package/dist/client/app/components/base/BaseEmpty.vue +17 -1
  8. package/dist/client/app/components/base/BaseListItemLink.vue +1 -1
  9. package/dist/client/app/components/base/BaseTab.vue +1 -1
  10. package/dist/client/app/components/exposed/Story.vue +22 -1
  11. package/dist/client/app/components/exposed/Variant.vue +13 -1
  12. package/dist/client/app/components/sandbox/SandboxVue3.vue +6 -4
  13. package/dist/client/app/components/sandbox/lib.js +2 -1
  14. package/dist/client/app/components/search/SearchItem.vue +1 -0
  15. package/dist/client/app/components/search/SearchLoading.vue +16 -0
  16. package/dist/client/app/components/search/SearchModal.vue +12 -148
  17. package/dist/client/app/components/search/SearchPane.vue +210 -0
  18. package/dist/client/app/components/search/search-data.d.ts +2 -0
  19. package/dist/client/app/components/search/search-data.js +7 -0
  20. package/dist/client/app/components/story/StoryControls.vue +5 -0
  21. package/dist/client/app/components/story/StoryDocs.vue +18 -11
  22. package/dist/client/app/components/story/StoryEvent.vue +53 -0
  23. package/dist/client/app/components/story/StoryEvents.vue +45 -0
  24. package/dist/client/app/components/story/StoryResponsivePreview.vue +41 -8
  25. package/dist/client/app/components/story/StorySidePanel.vue +28 -3
  26. package/dist/client/app/components/story/StorySourceCode.vue +24 -14
  27. package/dist/client/app/components/story/StoryView.vue +16 -2
  28. package/dist/client/app/components/story/toolbar/StoryVariantNewTab.vue +1 -1
  29. package/dist/client/app/components/tree/StoryGroup.vue +75 -0
  30. package/dist/client/app/components/{story → tree}/StoryList.vue +8 -2
  31. package/{src/client/app/components/story → dist/client/app/components/tree}/StoryListFolder.vue +10 -8
  32. package/{src/client/app/components/story → dist/client/app/components/tree}/StoryListItem.vue +7 -4
  33. package/dist/client/app/router.d.ts +1 -0
  34. package/dist/client/app/router.js +3 -1
  35. package/dist/client/app/sandbox.js +11 -1
  36. package/dist/client/app/stores/events.d.ts +29 -0
  37. package/dist/client/app/stores/events.js +25 -0
  38. package/dist/client/app/stores/folder.d.ts +10 -0
  39. package/dist/client/app/stores/folder.js +47 -0
  40. package/dist/client/app/stores/story.d.ts +20 -8
  41. package/dist/client/app/stores/story.js +20 -28
  42. package/dist/client/app/style/floating-vue.pcss +3 -1
  43. package/dist/client/app/style/main.pcss +5 -0
  44. package/dist/client/app/style/sandbox.css +2 -0
  45. package/dist/client/app/types.d.ts +9 -1
  46. package/dist/client/app/util/const.d.ts +1 -0
  47. package/dist/client/app/util/const.js +1 -0
  48. package/dist/client/app/util/events.d.ts +1 -0
  49. package/dist/client/app/util/events.js +31 -0
  50. package/dist/client/app/util/mapping.js +2 -2
  51. package/dist/client/index.d.ts +2 -1
  52. package/dist/client/index.js +2 -1
  53. package/dist/client/server/Story.server.vue +21 -4
  54. package/dist/node/alias.d.ts +2 -1
  55. package/dist/node/alias.js +3 -2
  56. package/dist/node/build.js +74 -21
  57. package/dist/node/builtin-plugins/tailwind-tokens.d.ts +5 -0
  58. package/dist/node/builtin-plugins/tailwind-tokens.js +510 -0
  59. package/dist/node/collect/index.js +5 -3
  60. package/dist/node/commands/preview.js +4 -25
  61. package/dist/node/config.d.ts +111 -5
  62. package/dist/node/config.js +40 -23
  63. package/dist/node/context.d.ts +3 -3
  64. package/dist/node/context.js +1 -1
  65. package/dist/node/index.d.ts +1 -0
  66. package/dist/node/index.js +1 -0
  67. package/dist/node/load.d.ts +12 -0
  68. package/dist/node/load.js +42 -0
  69. package/dist/node/plugin.d.ts +67 -11
  70. package/dist/node/plugin.js +42 -245
  71. package/dist/node/preview.d.ts +8 -0
  72. package/dist/node/preview.js +41 -0
  73. package/dist/node/search.d.ts +2 -0
  74. package/dist/node/search.js +68 -0
  75. package/dist/node/server.js +43 -21
  76. package/dist/node/stories.d.ts +2 -0
  77. package/dist/node/stories.js +9 -4
  78. package/dist/node/tree.d.ts +16 -12
  79. package/dist/node/tree.js +45 -5
  80. package/dist/node/types.d.ts +11 -0
  81. package/dist/node/util/find-up.d.ts +1 -0
  82. package/dist/node/util/find-up.js +20 -0
  83. package/dist/node/vite.d.ts +13 -0
  84. package/dist/node/vite.js +278 -0
  85. package/dist/style.css +179 -36
  86. package/package.json +5 -3
  87. package/scripts/copy.mjs +2 -1
  88. package/src/client/app/App.vue +9 -4
  89. package/src/client/app/codegen/const.ts +3 -0
  90. package/src/client/app/codegen/vue3.ts +80 -22
  91. package/src/client/app/components/app/AppHeader.vue +2 -2
  92. package/src/client/app/components/app/Breadcrumb.vue +1 -1
  93. package/src/client/app/components/base/BaseEmpty.vue +17 -1
  94. package/src/client/app/components/base/BaseListItemLink.vue +1 -1
  95. package/src/client/app/components/base/BaseTab.vue +1 -1
  96. package/src/client/app/components/exposed/Story.vue +22 -1
  97. package/src/client/app/components/exposed/Variant.vue +13 -1
  98. package/src/client/app/components/sandbox/SandboxVue3.vue +6 -4
  99. package/src/client/app/components/sandbox/lib.ts +3 -1
  100. package/src/client/app/components/search/SearchItem.vue +1 -0
  101. package/src/client/app/components/search/SearchLoading.vue +16 -0
  102. package/src/client/app/components/search/SearchModal.vue +12 -148
  103. package/src/client/app/components/search/SearchPane.vue +210 -0
  104. package/src/client/app/components/search/search-data.ts +9 -0
  105. package/src/client/app/components/story/StoryControls.vue +5 -0
  106. package/src/client/app/components/story/StoryDocs.vue +18 -11
  107. package/src/client/app/components/story/StoryEvent.vue +53 -0
  108. package/src/client/app/components/story/StoryEvents.vue +45 -0
  109. package/src/client/app/components/story/StoryResponsivePreview.vue +41 -8
  110. package/src/client/app/components/story/StorySidePanel.vue +28 -3
  111. package/src/client/app/components/story/StorySourceCode.vue +24 -14
  112. package/src/client/app/components/story/StoryView.vue +16 -2
  113. package/src/client/app/components/story/toolbar/StoryVariantNewTab.vue +1 -1
  114. package/src/client/app/components/tree/StoryGroup.vue +75 -0
  115. package/src/client/app/components/{story → tree}/StoryList.vue +8 -2
  116. package/{dist/client/app/components/story → src/client/app/components/tree}/StoryListFolder.vue +10 -8
  117. package/{dist/client/app/components/story → src/client/app/components/tree}/StoryListItem.vue +7 -4
  118. package/src/client/app/router.ts +4 -1
  119. package/src/client/app/sandbox.ts +12 -2
  120. package/src/client/app/stores/events.ts +36 -0
  121. package/src/client/app/stores/folder.ts +59 -0
  122. package/src/client/app/stores/story.ts +20 -35
  123. package/src/client/app/style/floating-vue.pcss +3 -1
  124. package/src/client/app/style/main.pcss +5 -0
  125. package/src/client/app/style/sandbox.css +2 -0
  126. package/src/client/app/types.ts +10 -1
  127. package/src/client/app/util/const.ts +1 -0
  128. package/src/client/app/util/events.ts +30 -0
  129. package/src/client/app/util/mapping.ts +2 -2
  130. package/src/client/index.ts +2 -1
  131. package/src/client/server/Story.server.vue +21 -4
  132. package/src/node/alias.ts +4 -2
  133. package/src/node/build.ts +86 -21
  134. package/src/node/builtin-plugins/tailwind-tokens.ts +521 -0
  135. package/src/node/collect/index.ts +6 -4
  136. package/src/node/commands/preview.ts +4 -33
  137. package/src/node/config.ts +62 -29
  138. package/src/node/context.ts +3 -3
  139. package/src/node/index.ts +1 -0
  140. package/src/node/load.ts +63 -0
  141. package/src/node/plugin.ts +75 -252
  142. package/src/node/preview.ts +56 -0
  143. package/src/node/search.ts +75 -0
  144. package/src/node/server.ts +49 -23
  145. package/src/node/stories.ts +9 -4
  146. package/src/node/tree.spec.ts +35 -17
  147. package/src/node/tree.ts +64 -10
  148. package/src/node/types.ts +12 -0
  149. package/src/node/util/find-up.ts +24 -0
  150. package/src/node/vite.ts +296 -0
  151. package/tailwind.config.cjs +1 -0
  152. package/tsconfig.json +2 -0
  153. package/dist/client/app/codegen/serialize-js.ts +0 -119
  154. package/dist/client/app/codegen/util.ts +0 -79
  155. package/dist/client/app/codegen/vue3.ts +0 -276
  156. package/dist/client/app/components/sandbox/lib.ts +0 -8
  157. package/dist/client/app/global-components.ts +0 -13
  158. package/dist/client/app/index.ts +0 -28
  159. package/dist/client/app/router.ts +0 -17
  160. package/dist/client/app/sandbox.ts +0 -94
  161. package/dist/client/app/stores/preview-settings.ts +0 -17
  162. package/dist/client/app/stores/story.ts +0 -62
  163. package/dist/client/app/types.ts +0 -70
  164. package/dist/client/app/util/config.ts +0 -6
  165. package/dist/client/app/util/const.ts +0 -3
  166. package/dist/client/app/util/dark.ts +0 -4
  167. package/dist/client/app/util/env.ts +0 -1
  168. package/dist/client/app/util/keyboard.ts +0 -99
  169. package/dist/client/app/util/mapping.ts +0 -48
  170. package/dist/client/app/util/preview-settings.ts +0 -8
  171. package/dist/client/app/util/reactivity.ts +0 -22
  172. package/dist/client/app/util/responsive.ts +0 -3
  173. package/dist/client/app/util/scroll.ts +0 -31
  174. package/dist/client/app/util/tooltip.ts +0 -13
  175. package/dist/client/app/util/variant.ts +0 -20
  176. package/dist/client/index.ts +0 -12
  177. package/dist/client/server/index.ts +0 -32
  178. package/dist/client/shim.d.ts +0 -5
@@ -1,252 +1,49 @@
1
- import { createRequire } from 'module';
2
- import { relative, dirname } from 'pathe';
3
- import { resolveConfig as resolveViteConfig } from 'vite';
4
- import { lookup as lookupMime } from 'mrmime';
5
- import { APP_PATH, DIST_CLIENT_PATH } from './alias.js';
6
- import { notifyStoryChange } from './stories.js';
7
- import { makeTree } from './tree.js';
8
- import { parseColor } from './colors.js';
9
- import { createMarkdownRenderer } from './markdown.js';
10
- const require = createRequire(import.meta.url);
11
- export const STORIES_ID = '$histoire-stories';
12
- export const RESOLVED_STORIES_ID = `/${STORIES_ID}-resolved`;
13
- export const SETUP_ID = '$histoire-setup';
14
- export const NOOP_ID = '/$histoire-noop';
15
- export const CONFIG_ID = '$histoire-config';
16
- export const RESOLVED_CONFIG_ID = `/${CONFIG_ID}-resolved`;
17
- export const THEME_ID = '$histoire-theme';
18
- export const RESOLVED_THEME_ID = `/${THEME_ID}-resolved.css`;
19
- export async function createVitePlugins(ctx) {
20
- const viteConfig = await resolveViteConfig({}, ctx.mode === 'dev' ? 'serve' : 'build');
21
- const hasVuePlugin = viteConfig.plugins.find(p => p.name === 'vite:vue');
22
- const plugins = [];
23
- if (!hasVuePlugin) {
24
- plugins.push((await import('@vitejs/plugin-vue')).default());
1
+ import chokidar from 'chokidar';
2
+ import path from 'pathe';
3
+ import fs from 'fs-extra';
4
+ import pc from 'picocolors';
5
+ import { TEMP_PATH } from './alias.js';
6
+ import { addStory, removeStory } from './stories.js';
7
+ export class BasePluginApi {
8
+ ctx;
9
+ plugin;
10
+ moduleLoader;
11
+ colors = pc;
12
+ path = path;
13
+ fs = fs;
14
+ // eslint-disable-next-line no-useless-constructor
15
+ constructor(ctx, plugin, moduleLoader) {
16
+ this.ctx = ctx;
17
+ this.plugin = plugin;
18
+ this.moduleLoader = moduleLoader;
25
19
  }
26
- if (ctx.config.vite) {
27
- plugins.push({
28
- name: 'histoire-vite-config-override',
29
- config(config, env) {
30
- return typeof ctx.config.vite === 'function' ? ctx.config.vite(config, env) : ctx.config.vite;
31
- },
32
- });
20
+ get pluginTempDir() {
21
+ return path.resolve(TEMP_PATH, 'plugins', this.plugin.name);
33
22
  }
34
- plugins.push({
35
- name: 'histoire-vite-plugin',
36
- config() {
37
- return {
38
- optimizeDeps: {
39
- // force include vue to avoid duplicated copies when linked + optimized
40
- include: [
41
- 'vue',
42
- dirname(require.resolve('@vue/runtime-core/package.json')),
43
- dirname(require.resolve('shiki/package.json')),
44
- dirname(require.resolve('vscode-textmate/package.json')),
45
- dirname(require.resolve('vscode-oniguruma/package.json')),
46
- dirname(require.resolve('case/package.json')),
47
- ],
48
- },
49
- server: {
50
- fs: {
51
- allow: [DIST_CLIENT_PATH, viteConfig.root, process.cwd()],
52
- },
53
- },
54
- };
55
- },
56
- async resolveId(id, importer) {
57
- if (id.startsWith(STORIES_ID)) {
58
- return RESOLVED_STORIES_ID;
59
- }
60
- if (id.startsWith(SETUP_ID)) {
61
- if (ctx.config.setupFile) {
62
- return this.resolve(ctx.config.setupFile, importer, {
63
- skipSelf: true,
64
- });
65
- }
66
- else {
67
- return NOOP_ID;
68
- }
69
- }
70
- if (id.startsWith(CONFIG_ID)) {
71
- return RESOLVED_CONFIG_ID;
72
- }
73
- if (id.startsWith(THEME_ID)) {
74
- return RESOLVED_THEME_ID;
75
- }
76
- },
77
- load(id) {
78
- if (id === RESOLVED_STORIES_ID) {
79
- const resolvedStories = ctx.storyFiles.filter(s => !!s.story);
80
- const files = resolvedStories.map((file, index) => {
81
- return {
82
- id: file.id,
83
- path: file.treePath,
84
- story: file.story,
85
- framework: 'vue3',
86
- index,
87
- };
88
- });
89
- return `import { defineAsyncComponent } from 'vue'
90
- ${resolvedStories.map((file, index) => `const Comp${index} = defineAsyncComponent(() => import('${file.path}'))`).join('\n')}
91
- export let files = [${files.map((file) => `{${JSON.stringify(file).slice(1, -1)}, component: Comp${file.index}}`).join(',\n')}]
92
- export let tree = ${JSON.stringify(makeTree(ctx.config, files))}
93
- const handlers = []
94
- export function onUpdate (cb) {
95
- handlers.push(cb)
96
- }
97
- if (import.meta.hot) {
98
- import.meta.hot.accept(newModule => {
99
- files = newModule.files
100
- tree = newModule.tree
101
- handlers.forEach(h => {
102
- h(newModule.files, newModule.tree)
103
- newModule.onUpdate(h)
104
- })
105
- })
106
- }`;
107
- }
108
- if (id === NOOP_ID) {
109
- return `export default () => {}`;
110
- }
111
- if (id === RESOLVED_CONFIG_ID) {
112
- let js = `export const config = ${JSON.stringify(ctx.config)}\n`;
113
- if (ctx.config.theme?.logo) {
114
- for (const key in ctx.config.theme.logo) {
115
- js += `import Logo_${key} from '${ctx.config.theme.logo[key]}'\n`;
116
- }
117
- }
118
- js += `export const logos = {${Object.keys(ctx.config.theme?.logo ?? {}).map(key => `${key}: Logo_${key}`).join(', ')}}\n`;
119
- return js;
120
- }
121
- if (id === RESOLVED_THEME_ID) {
122
- let css = '*, ::before, ::after {';
123
- // Colors
124
- for (const color in ctx.config.theme?.colors ?? {}) {
125
- for (const key in ctx.config.theme.colors[color]) {
126
- css += `--_histoire-color-${color}-${key}: ${parseColor(ctx.config.theme.colors[color][key]).color.join(' ')};`;
127
- }
128
- }
129
- css += '}';
130
- return css;
131
- }
132
- },
133
- handleHotUpdate(updateContext) {
134
- const story = ctx.storyFiles.find(file => file.path === updateContext.file);
135
- if (story) {
136
- notifyStoryChange(story);
137
- }
138
- },
139
- configureServer(server) {
140
- server.middlewares.use(async (req, res, next) => {
141
- if (req.url.startsWith('/__sandbox')) {
142
- res.statusCode = 200;
143
- let html = `
144
- <!DOCTYPE html>
145
- <html>
146
- <head>
147
- <title></title>
148
- <meta charset="utf-8">
149
- <meta name="viewport" content="width=device-width,initial-scale=1">
150
- <meta name="description" content="">
151
- </head>
152
- <body>
153
- <div id="app"></div>
154
- <script>
155
- // Hide spammy vite messages
156
- const origConsoleLog = console.log
157
- console.log = (...args) => {
158
- if (typeof args[0] !== 'string' || !args[0].startsWith('[vite] connect')) {
159
- origConsoleLog(...args)
23
+ log(...msg) {
24
+ console.log(this.colors.gray(`[Plugin:${this.plugin.name}]`), ...msg);
25
+ }
26
+ warn(...msg) {
27
+ console.warn(this.colors.yellow(`[Plugin:${this.plugin.name}]`), ...msg);
28
+ }
29
+ error(...msg) {
30
+ console.error(this.colors.red(`[Plugin:${this.plugin.name}]`), ...msg);
160
31
  }
161
- }
162
- </script>
163
- <script type="module" src="/@fs/${APP_PATH}/sandbox.js"></script>
164
- </body>
165
- </html>`;
166
- // Apply Vite HTML transforms. This injects the Vite HMR client, and
167
- // also applies HTML transforms from Vite plugins
168
- html = await server.transformIndexHtml(req.url, html);
169
- res.end(html);
170
- return;
171
- }
172
- next();
173
- });
174
- // serve our index.html after vite history fallback
175
- return () => {
176
- server.middlewares.use(async (req, res, next) => {
177
- if (req.url.endsWith('.html')) {
178
- res.statusCode = 200;
179
- let html = `
180
- <!DOCTYPE html>
181
- <html>
182
- <head>
183
- <title></title>
184
- <link rel="icon" href=""/>
185
- <meta charset="utf-8">
186
- <meta name="viewport" content="width=device-width,initial-scale=1">
187
- <meta name="description" content="">
188
- ${ctx.config.theme?.favicon ? `<link rel="icon" type="${lookupMime(ctx.config.theme.favicon)}" href="${ctx.config.theme.favicon}"/>` : ''}
189
- </head>
190
- <body>
191
- <div id="app"></div>
192
- <script type="module" src="/@fs/${APP_PATH}/index.js"></script>
193
- </body>
194
- </html>`;
195
- // Apply Vite HTML transforms. This injects the Vite HMR client, and
196
- // also applies HTML transforms from Vite plugins
197
- html = await server.transformIndexHtml(req.url, html);
198
- res.end(html);
199
- return;
200
- }
201
- next();
202
- });
203
- };
204
- },
205
- });
206
- // Custom blocks
207
- plugins.push(...await createCustomBlocksPlugins(ctx));
208
- if (ctx.mode === 'build') {
209
- // Add file name in build mode to have components names instead of <Anonymous>
210
- const include = [/\.vue$/];
211
- const exclude = [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/];
212
- plugins.push({
213
- name: 'histoire-file-name-plugin',
214
- enforce: 'post',
215
- transform(code, id) {
216
- if (exclude.some(r => r.test(id)))
217
- return;
218
- if (include.some(r => r.test(id))) {
219
- const file = relative(viteConfig.root, id);
220
- const index = code.indexOf('export default');
221
- const result = `${code.substring(0, index)}_sfc_main.__file = '${file}'\n${code.substring(index)}`;
222
- return result;
223
- }
224
- },
225
- });
32
+ addStoryFile(file) {
33
+ removeStory(file);
34
+ addStory(file);
226
35
  }
227
- return plugins;
228
36
  }
229
- async function createCustomBlocksPlugins(ctx) {
230
- const plugins = [];
231
- let md = await createMarkdownRenderer();
232
- if (ctx.config.markdown) {
233
- const result = await ctx.config.markdown(md);
234
- if (result) {
235
- md = result;
236
- }
37
+ export class DevPluginApi extends BasePluginApi {
38
+ watcher = chokidar;
39
+ }
40
+ export class BuildPluginApi extends BasePluginApi {
41
+ buildEndCallbacks = [];
42
+ previewStoryCallbacks = [];
43
+ onBuildEnd(cb) {
44
+ this.buildEndCallbacks.push(cb);
45
+ }
46
+ onPreviewStory(cb) {
47
+ this.previewStoryCallbacks.push(cb);
237
48
  }
238
- plugins.push({
239
- name: 'histoire-vue-docs-block',
240
- transform(code, id) {
241
- if (!id.includes('?vue&type=docs'))
242
- return;
243
- if (!id.includes('lang.md'))
244
- return;
245
- const html = md.render(code);
246
- return `export default Comp => {
247
- Comp.doc = ${JSON.stringify(html)}
248
- }`;
249
- },
250
- });
251
- return plugins;
252
49
  }
@@ -0,0 +1,8 @@
1
+ import type { ResolvedConfig as ViteConfig } from 'vite';
2
+ import type { Context } from './context.js';
3
+ interface ReturnPayload {
4
+ baseUrl: string;
5
+ close: () => Promise<void>;
6
+ }
7
+ export declare function startPreview(viteConfig: ViteConfig, port: number | null, ctx: Context): Promise<ReturnPayload>;
8
+ export {};
@@ -0,0 +1,41 @@
1
+ import http from 'http';
2
+ import connect from 'connect';
3
+ import sirv from 'sirv';
4
+ export async function startPreview(viteConfig, port, ctx) {
5
+ const app = connect();
6
+ app.use(viteConfig.base, sirv(ctx.config.outDir, {
7
+ dev: true,
8
+ etag: true,
9
+ single: true,
10
+ }));
11
+ let finalPort = port ?? 3000;
12
+ const httpServer = http.createServer(app);
13
+ return new Promise((resolve, reject) => {
14
+ function onError(e) {
15
+ if (e.code === 'EADDRINUSE') {
16
+ httpServer.listen(++finalPort);
17
+ }
18
+ else {
19
+ reject(e);
20
+ }
21
+ }
22
+ httpServer.on('error', onError);
23
+ httpServer.listen(finalPort, () => {
24
+ httpServer.off('error', onError);
25
+ const baseUrl = `http://localhost:${finalPort}${viteConfig.base}`;
26
+ resolve({
27
+ baseUrl,
28
+ close: () => new Promise((resolve, reject) => {
29
+ httpServer.close((err) => {
30
+ if (err) {
31
+ reject(err);
32
+ }
33
+ else {
34
+ resolve();
35
+ }
36
+ });
37
+ }),
38
+ });
39
+ });
40
+ });
41
+ }
@@ -0,0 +1,2 @@
1
+ import { Context } from './context.js';
2
+ export declare function generateSearchData(ctx: Context): Promise<unknown>;
@@ -0,0 +1,68 @@
1
+ import { createRequire } from 'module';
2
+ import flexsearch from 'flexsearch';
3
+ import path from 'pathe';
4
+ import { loadModule } from './load.js';
5
+ const require = createRequire(import.meta.url);
6
+ export async function generateSearchData(ctx) {
7
+ const flexsearchRoot = path.dirname(require.resolve('flexsearch/package.json'));
8
+ const searchIndex = new flexsearch.Document({
9
+ preset: 'match',
10
+ document: {
11
+ id: 'id',
12
+ index: [
13
+ 'title',
14
+ 'docs',
15
+ ],
16
+ store: [
17
+ 'kind',
18
+ ],
19
+ },
20
+ charset: await loadModule(`${flexsearchRoot}/dist/module/lang/latin/advanced.js`),
21
+ language: await loadModule(`${flexsearchRoot}/dist/module/lang/en.js`),
22
+ tokenize: 'full',
23
+ });
24
+ for (const storyFile of ctx.storyFiles) {
25
+ if (storyFile.story) {
26
+ searchIndex.add({
27
+ id: storyFile.story.id,
28
+ kind: 'story',
29
+ title: storyFile.story.title,
30
+ docs: '', // @TODO
31
+ });
32
+ for (const variant of storyFile.story.variants) {
33
+ searchIndex.add({
34
+ id: `${storyFile.story.id}:${variant.id}`,
35
+ kind: 'variant',
36
+ title: `${storyFile.story.title} ${variant.title}`,
37
+ docs: '', // @TODO
38
+ });
39
+ }
40
+ }
41
+ }
42
+ return exportSearchIndex(searchIndex);
43
+ }
44
+ const exportKeys = new Set([
45
+ 'reg',
46
+ 'title.cfg',
47
+ 'title.map',
48
+ 'title.ctx',
49
+ 'docs.cfg',
50
+ 'docs.map',
51
+ 'docs.ctx',
52
+ 'tag',
53
+ 'store',
54
+ ]);
55
+ async function exportSearchIndex(index) {
56
+ // eslint-disable-next-line no-async-promise-executor
57
+ return new Promise(async (resolve, reject) => {
58
+ const exportedData = {};
59
+ const exportedKeys = new Set();
60
+ await index.export((key, data) => {
61
+ exportedData[key] = data;
62
+ exportedKeys.add(key);
63
+ if (exportedKeys.size === exportKeys.size) {
64
+ resolve(exportedData);
65
+ }
66
+ });
67
+ });
68
+ }
@@ -1,9 +1,10 @@
1
1
  import { createServer as createViteServer } from 'vite';
2
- import { createVitePlugins, RESOLVED_STORIES_ID } from './plugin.js';
2
+ import { createVitePlugins, RESOLVED_SEARCH_DATA_ID, RESOLVED_STORIES_ID } from './vite.js';
3
3
  import { notifyStoryChange, onStoryChange, watchStories } from './stories.js';
4
4
  import { useCollectStories } from './collect/index.js';
5
+ import { DevPluginApi } from './plugin.js';
6
+ import { useModuleLoader } from './load.js';
5
7
  export async function createServer(ctx, port) {
6
- await watchStories(ctx);
7
8
  const server = await createViteServer({
8
9
  plugins: await createVitePlugins(ctx),
9
10
  server: {
@@ -13,6 +14,20 @@ export async function createServer(ctx, port) {
13
14
  },
14
15
  });
15
16
  await server.pluginContainer.buildStart({});
17
+ const moduleLoader = useModuleLoader({
18
+ server,
19
+ });
20
+ const pluginOnCleanups = [];
21
+ for (const plugin of ctx.config.plugins) {
22
+ if (plugin.onDev) {
23
+ const api = new DevPluginApi(ctx, plugin, moduleLoader);
24
+ const onCleanup = (cb) => {
25
+ pluginOnCleanups.push(cb);
26
+ };
27
+ await plugin.onDev(api, onCleanup);
28
+ }
29
+ }
30
+ await watchStories(ctx);
16
31
  // Wait for pre-bundling (in `listen()`)
17
32
  await server.listen(port);
18
33
  const { clearCache, executeStoryFile, destroy: destroyCollectStories, } = useCollectStories({
@@ -56,28 +71,35 @@ export async function createServer(ctx, port) {
56
71
  }
57
72
  queuedFiles = [];
58
73
  queueResolve();
59
- // Invalidate stories data module
60
- const mod = server.moduleGraph.getModuleById(RESOLVED_STORIES_ID);
61
- if (!mod) {
62
- return;
74
+ // Invalidate modules
75
+ function invalidateModule(id) {
76
+ const mod = server.moduleGraph.getModuleById(id);
77
+ if (!mod) {
78
+ return;
79
+ }
80
+ server.moduleGraph.invalidateModule(mod);
81
+ // Send HMR update
82
+ const timestamp = Date.now();
83
+ mod.lastHMRTimestamp = timestamp;
84
+ server.ws.send({
85
+ type: 'update',
86
+ updates: [
87
+ {
88
+ type: 'js-update',
89
+ acceptedPath: mod.url,
90
+ path: mod.url,
91
+ timestamp: timestamp,
92
+ },
93
+ ],
94
+ });
63
95
  }
64
- server.moduleGraph.invalidateModule(mod);
65
- // Send stories data HMR update
66
- const timestamp = Date.now();
67
- mod.lastHMRTimestamp = timestamp;
68
- server.ws.send({
69
- type: 'update',
70
- updates: [
71
- {
72
- type: 'js-update',
73
- acceptedPath: mod.url,
74
- path: mod.url,
75
- timestamp: timestamp,
76
- },
77
- ],
78
- });
96
+ invalidateModule(RESOLVED_STORIES_ID);
97
+ invalidateModule(RESOLVED_SEARCH_DATA_ID);
79
98
  });
80
99
  async function close() {
100
+ for (const cb of pluginOnCleanups) {
101
+ await cb();
102
+ }
81
103
  await server.close();
82
104
  await destroyCollectStories();
83
105
  }
@@ -5,5 +5,7 @@ declare type StoryChangeHandler = (file?: StoryFile) => unknown;
5
5
  export declare function onStoryChange(handler: StoryChangeHandler): void;
6
6
  export declare function watchStories(newContext: Context): Promise<chokidar.FSWatcher>;
7
7
  export declare function notifyStoryChange(file?: StoryFile): void;
8
+ export declare function addStory(relativeFilePath: string): StoryFile;
9
+ export declare function removeStory(relativeFilePath: string): void;
8
10
  export declare function findAllStories(newContext: Context): Promise<void>;
9
11
  export {};
@@ -1,7 +1,7 @@
1
1
  import chokidar from 'chokidar';
2
2
  import { globby } from 'globby';
3
3
  import Case from 'case';
4
- import { join } from 'pathe';
4
+ import { resolve, basename } from 'pathe';
5
5
  const handlers = [];
6
6
  let context;
7
7
  export function onStoryChange(handler) {
@@ -30,20 +30,25 @@ export function notifyStoryChange(file) {
30
30
  }
31
31
  }
32
32
  function getAbsoluteFilePath(relativeFilePath) {
33
- return join(context.root, relativeFilePath);
33
+ return resolve(context.root, relativeFilePath);
34
34
  }
35
- function addStory(relativeFilePath) {
35
+ export function addStory(relativeFilePath) {
36
36
  const absoluteFilePath = getAbsoluteFilePath(relativeFilePath);
37
37
  const fileId = Case.kebab(relativeFilePath);
38
+ let fileName = basename(relativeFilePath);
39
+ if (fileName.includes('.')) {
40
+ fileName = fileName.substring(0, fileName.indexOf('.'));
41
+ }
38
42
  const file = {
39
43
  id: fileId,
40
44
  path: absoluteFilePath,
45
+ fileName,
41
46
  moduleId: `/${relativeFilePath}`,
42
47
  };
43
48
  context.storyFiles.push(file);
44
49
  return file;
45
50
  }
46
- function removeStory(relativeFilePath) {
51
+ export function removeStory(relativeFilePath) {
47
52
  const fileId = Case.kebab(relativeFilePath);
48
53
  const index = context.storyFiles.findIndex((file) => file.id === fileId);
49
54
  if (index !== -1)
@@ -1,19 +1,23 @@
1
- import { HistoireConfig } from './config.js';
2
- export declare type TreeFile = {
1
+ import type { HistoireConfig } from './config.js';
2
+ import type { StoryFile } from './types.js';
3
+ export interface TreeFile {
3
4
  title: string;
4
5
  path: string;
5
- };
6
- export declare type TreeLeaf = {
6
+ }
7
+ export interface TreeLeaf {
7
8
  title: string;
8
9
  index: number;
9
- };
10
- export declare type TreeFolder = {
10
+ }
11
+ export interface TreeFolder {
11
12
  title: string;
12
13
  children: (TreeFolder | TreeLeaf)[];
13
- };
14
- export declare type Tree = (TreeFolder | TreeLeaf)[];
14
+ }
15
+ export interface TreeGroup {
16
+ group: true;
17
+ id: string;
18
+ title: string;
19
+ children: (TreeFolder | TreeLeaf)[];
20
+ }
21
+ export declare type Tree = (TreeGroup | TreeFolder | TreeLeaf)[];
15
22
  export declare function createPath(config: HistoireConfig, file: TreeFile): string[];
16
- export declare function makeTree(config: HistoireConfig, files: {
17
- path: string[];
18
- index: number;
19
- }[]): Tree;
23
+ export declare function makeTree(config: HistoireConfig, files: StoryFile[]): Tree;
package/dist/node/tree.js CHANGED
@@ -1,3 +1,4 @@
1
+ import pc from 'picocolors';
1
2
  export function createPath(config, file) {
2
3
  if (config.tree.file === 'title') {
3
4
  return file.title.split('/');
@@ -11,15 +12,54 @@ export function createPath(config, file) {
11
12
  return config.tree.file(file);
12
13
  }
13
14
  export function makeTree(config, files) {
14
- const treeObject = {};
15
- for (const file of files) {
16
- setPath(file.path, file.index, treeObject);
17
- }
15
+ const groups = config.tree?.groups?.map(g => ({
16
+ groupConfig: g,
17
+ treeObject: {},
18
+ })) || [];
19
+ const defaultGroup = {
20
+ treeObject: {},
21
+ };
22
+ groups.push(defaultGroup);
23
+ files.forEach((file, index) => {
24
+ const group = getGroup(file);
25
+ setPath(file.treePath, index, group.treeObject);
26
+ });
18
27
  let sortingFunction = (a, b) => a.localeCompare(b);
19
28
  if (config.tree.order !== 'asc') {
20
29
  sortingFunction = config.tree.order;
21
30
  }
22
- return buildTree(treeObject);
31
+ const result = [];
32
+ for (const group of groups) {
33
+ if (group === defaultGroup) {
34
+ result.push(...buildTree(group.treeObject));
35
+ }
36
+ else {
37
+ result.push({
38
+ group: true,
39
+ id: group.groupConfig.id,
40
+ title: group.groupConfig.title,
41
+ children: buildTree(group.treeObject),
42
+ });
43
+ }
44
+ }
45
+ return result;
46
+ function getGroup(file) {
47
+ if (file.story?.group) {
48
+ const group = groups.find(g => g.groupConfig?.id === file.story.group);
49
+ if (group) {
50
+ return group;
51
+ }
52
+ else {
53
+ console.error(pc.red(`Group ${file.story.group} not found for story ${file.path}`));
54
+ }
55
+ }
56
+ for (const group of groups) {
57
+ if (group.groupConfig?.include && group.groupConfig.include(file.treeFile)) {
58
+ return group;
59
+ }
60
+ }
61
+ return defaultGroup;
62
+ }
23
63
  function setPath(path, value, tree) {
24
64
  path.reduce((subtree, key, i) => {
25
65
  if (i === path.length - 1) {