histoire 0.2.5 → 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 (156) hide show
  1. package/dist/client/app/App.vue +8 -3
  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/base/BaseEmpty.vue +17 -1
  6. package/dist/client/app/components/exposed/Story.vue +22 -1
  7. package/dist/client/app/components/exposed/Variant.vue +13 -1
  8. package/dist/client/app/components/sandbox/SandboxVue3.vue +6 -4
  9. package/dist/client/app/components/sandbox/lib.js +2 -1
  10. package/dist/client/app/components/search/SearchLoading.vue +16 -0
  11. package/dist/client/app/components/search/SearchModal.vue +12 -149
  12. package/dist/client/app/components/search/SearchPane.vue +210 -0
  13. package/dist/client/app/components/search/search-data.d.ts +2 -0
  14. package/dist/client/app/components/search/search-data.js +7 -0
  15. package/dist/client/app/components/story/StoryControls.vue +5 -0
  16. package/dist/client/app/components/story/StoryDocs.vue +18 -11
  17. package/dist/client/app/components/story/StoryEvent.vue +53 -0
  18. package/dist/client/app/components/story/StoryEvents.vue +45 -0
  19. package/dist/client/app/components/story/StoryResponsivePreview.vue +41 -8
  20. package/dist/client/app/components/story/StorySidePanel.vue +28 -3
  21. package/dist/client/app/components/story/StorySourceCode.vue +24 -14
  22. package/dist/client/app/components/story/StoryView.vue +16 -2
  23. package/dist/client/app/components/tree/StoryGroup.vue +4 -4
  24. package/dist/client/app/components/tree/StoryListFolder.vue +4 -4
  25. package/dist/client/app/components/tree/StoryListItem.vue +4 -1
  26. package/dist/client/app/router.d.ts +1 -0
  27. package/dist/client/app/router.js +3 -1
  28. package/dist/client/app/sandbox.js +11 -1
  29. package/dist/client/app/stores/events.d.ts +29 -0
  30. package/dist/client/app/stores/events.js +25 -0
  31. package/dist/client/app/stores/folder.d.ts +10 -0
  32. package/dist/client/app/stores/folder.js +47 -0
  33. package/dist/client/app/stores/story.d.ts +14 -8
  34. package/dist/client/app/stores/story.js +20 -33
  35. package/dist/client/app/style/main.pcss +5 -0
  36. package/dist/client/app/style/sandbox.css +2 -0
  37. package/dist/client/app/types.d.ts +1 -0
  38. package/dist/client/app/util/const.d.ts +1 -0
  39. package/dist/client/app/util/const.js +1 -0
  40. package/dist/client/app/util/events.d.ts +1 -0
  41. package/dist/client/app/util/events.js +31 -0
  42. package/dist/client/app/util/mapping.js +2 -2
  43. package/dist/client/index.d.ts +2 -1
  44. package/dist/client/index.js +2 -1
  45. package/dist/client/server/Story.server.vue +13 -2
  46. package/dist/node/alias.d.ts +2 -1
  47. package/dist/node/alias.js +3 -2
  48. package/dist/node/build.js +74 -21
  49. package/dist/node/builtin-plugins/tailwind-tokens.d.ts +5 -0
  50. package/dist/node/builtin-plugins/tailwind-tokens.js +510 -0
  51. package/dist/node/collect/index.js +3 -1
  52. package/dist/node/commands/preview.js +4 -25
  53. package/dist/node/config.d.ts +103 -3
  54. package/dist/node/config.js +40 -23
  55. package/dist/node/context.d.ts +3 -3
  56. package/dist/node/context.js +1 -1
  57. package/dist/node/index.d.ts +1 -0
  58. package/dist/node/index.js +1 -0
  59. package/dist/node/load.d.ts +12 -0
  60. package/dist/node/load.js +42 -0
  61. package/dist/node/plugin.d.ts +67 -11
  62. package/dist/node/plugin.js +42 -245
  63. package/dist/node/preview.d.ts +8 -0
  64. package/dist/node/preview.js +41 -0
  65. package/dist/node/search.d.ts +2 -0
  66. package/dist/node/search.js +68 -0
  67. package/dist/node/server.js +43 -21
  68. package/dist/node/stories.d.ts +2 -0
  69. package/dist/node/stories.js +4 -4
  70. package/dist/node/types.d.ts +1 -0
  71. package/dist/node/util/find-up.d.ts +1 -0
  72. package/dist/node/util/find-up.js +20 -0
  73. package/dist/node/vite.d.ts +13 -0
  74. package/dist/node/vite.js +278 -0
  75. package/dist/style.css +111 -47
  76. package/package.json +5 -3
  77. package/scripts/copy.mjs +2 -1
  78. package/src/client/app/App.vue +8 -3
  79. package/src/client/app/codegen/const.ts +3 -0
  80. package/src/client/app/codegen/vue3.ts +80 -22
  81. package/src/client/app/components/base/BaseEmpty.vue +17 -1
  82. package/src/client/app/components/exposed/Story.vue +22 -1
  83. package/src/client/app/components/exposed/Variant.vue +13 -1
  84. package/src/client/app/components/sandbox/SandboxVue3.vue +6 -4
  85. package/src/client/app/components/sandbox/lib.ts +3 -1
  86. package/src/client/app/components/search/SearchLoading.vue +16 -0
  87. package/src/client/app/components/search/SearchModal.vue +12 -149
  88. package/src/client/app/components/search/SearchPane.vue +210 -0
  89. package/src/client/app/components/search/search-data.ts +9 -0
  90. package/src/client/app/components/story/StoryControls.vue +5 -0
  91. package/src/client/app/components/story/StoryDocs.vue +18 -11
  92. package/src/client/app/components/story/StoryEvent.vue +53 -0
  93. package/src/client/app/components/story/StoryEvents.vue +45 -0
  94. package/src/client/app/components/story/StoryResponsivePreview.vue +41 -8
  95. package/src/client/app/components/story/StorySidePanel.vue +28 -3
  96. package/src/client/app/components/story/StorySourceCode.vue +24 -14
  97. package/src/client/app/components/story/StoryView.vue +16 -2
  98. package/src/client/app/components/tree/StoryGroup.vue +4 -4
  99. package/src/client/app/components/tree/StoryListFolder.vue +4 -4
  100. package/src/client/app/components/tree/StoryListItem.vue +4 -1
  101. package/src/client/app/router.ts +4 -1
  102. package/src/client/app/sandbox.ts +12 -2
  103. package/src/client/app/stores/events.ts +36 -0
  104. package/{dist/client/app/stores/story.ts → src/client/app/stores/folder.ts} +16 -23
  105. package/src/client/app/stores/story.ts +21 -40
  106. package/src/client/app/style/main.pcss +5 -0
  107. package/src/client/app/style/sandbox.css +2 -0
  108. package/src/client/app/types.ts +1 -0
  109. package/src/client/app/util/const.ts +1 -0
  110. package/src/client/app/util/events.ts +30 -0
  111. package/src/client/app/util/mapping.ts +2 -2
  112. package/src/client/index.ts +2 -1
  113. package/src/client/server/Story.server.vue +13 -2
  114. package/src/node/alias.ts +4 -2
  115. package/src/node/build.ts +86 -21
  116. package/src/node/builtin-plugins/tailwind-tokens.ts +521 -0
  117. package/src/node/collect/index.ts +3 -1
  118. package/src/node/commands/preview.ts +4 -33
  119. package/src/node/config.ts +53 -27
  120. package/src/node/context.ts +3 -3
  121. package/src/node/index.ts +1 -0
  122. package/src/node/load.ts +63 -0
  123. package/src/node/plugin.ts +75 -252
  124. package/src/node/preview.ts +56 -0
  125. package/src/node/search.ts +75 -0
  126. package/src/node/server.ts +49 -23
  127. package/src/node/stories.ts +4 -4
  128. package/src/node/types.ts +1 -0
  129. package/src/node/util/find-up.ts +24 -0
  130. package/src/node/vite.ts +296 -0
  131. package/tailwind.config.cjs +1 -0
  132. package/dist/client/app/codegen/serialize-js.ts +0 -119
  133. package/dist/client/app/codegen/util.ts +0 -79
  134. package/dist/client/app/codegen/vue3.ts +0 -276
  135. package/dist/client/app/components/sandbox/lib.ts +0 -8
  136. package/dist/client/app/global-components.ts +0 -13
  137. package/dist/client/app/index.ts +0 -28
  138. package/dist/client/app/router.ts +0 -17
  139. package/dist/client/app/sandbox.ts +0 -94
  140. package/dist/client/app/stores/preview-settings.ts +0 -17
  141. package/dist/client/app/types.ts +0 -78
  142. package/dist/client/app/util/config.ts +0 -6
  143. package/dist/client/app/util/const.ts +0 -3
  144. package/dist/client/app/util/dark.ts +0 -4
  145. package/dist/client/app/util/env.ts +0 -1
  146. package/dist/client/app/util/keyboard.ts +0 -99
  147. package/dist/client/app/util/mapping.ts +0 -48
  148. package/dist/client/app/util/preview-settings.ts +0 -8
  149. package/dist/client/app/util/reactivity.ts +0 -22
  150. package/dist/client/app/util/responsive.ts +0 -3
  151. package/dist/client/app/util/scroll.ts +0 -31
  152. package/dist/client/app/util/tooltip.ts +0 -13
  153. package/dist/client/app/util/variant.ts +0 -20
  154. package/dist/client/index.ts +0 -12
  155. package/dist/client/server/index.ts +0 -32
  156. package/dist/client/shim.d.ts +0 -5
@@ -1,13 +1,21 @@
1
1
  import path from 'pathe'
2
- import fs from 'fs'
3
- import defu from 'defu'
4
- import { createServer, resolveConfig as resolveViteConfig, UserConfig as ViteConfig, ConfigEnv as ViteConfigEnv } from 'vite'
2
+ import { createDefu } from 'defu'
3
+ import {
4
+ createServer,
5
+ resolveConfig as resolveViteConfig,
6
+ UserConfig as ViteConfig,
7
+ ConfigEnv as ViteConfigEnv,
8
+ mergeConfig as mergeViteConfig,
9
+ } from 'vite'
5
10
  import { ViteNodeServer } from 'vite-node/server'
6
11
  import { ViteNodeRunner } from 'vite-node/client'
7
12
  import pc from 'picocolors'
13
+ import type MarkdownIt from 'markdown-it'
8
14
  import { TreeFile } from './tree.js'
9
15
  import { defaultColors } from './colors.js'
10
- import type MarkdownIt from 'markdown-it'
16
+ import { Plugin } from './plugin.js'
17
+ import { findUp } from './util/find-up.js'
18
+ import { tailwindTokens } from './builtin-plugins/tailwind-tokens.js'
11
19
 
12
20
  type CustomizableColors = 'primary' | 'gray'
13
21
  type ColorKeys = '50' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900'
@@ -31,6 +39,7 @@ export interface TreeGroupConfig {
31
39
  }
32
40
 
33
41
  export interface HistoireConfig {
42
+ plugins: Plugin[]
34
43
  /**
35
44
  * Output directory.
36
45
  */
@@ -138,9 +147,14 @@ export interface HistoireConfig {
138
147
  vite?: ViteConfig | ((config: ViteConfig, env: ViteConfigEnv) => void | ViteConfig | Promise<void | ViteConfig>)
139
148
  }
140
149
 
150
+ export type ConfigMode = 'build' | 'dev'
151
+
141
152
  export function getDefaultConfig (): HistoireConfig {
142
153
  return {
143
- outDir: 'histoire-dist',
154
+ plugins: [
155
+ tailwindTokens(),
156
+ ],
157
+ outDir: '.histoire/dist',
144
158
  storyMatch: ['**/*.story.vue'],
145
159
  storyIgnored: [
146
160
  '**/node_modules/**',
@@ -233,25 +247,7 @@ export const configFileNames = [
233
247
  ]
234
248
 
235
249
  export function resolveConfigFile (cwd: string = process.cwd()): string {
236
- let { root } = path.parse(cwd)
237
- let dir = cwd
238
-
239
- // Fix for windows, waiting for pathe to fix this: https://github.com/unjs/pathe/issues/5
240
- if (root === '' && dir[1] === ':') {
241
- root = dir.substring(0, 2)
242
- }
243
-
244
- while (dir !== root) {
245
- for (const fileName of configFileNames) {
246
- const searchPath = path.join(dir, fileName)
247
- if (fs.existsSync(searchPath)) {
248
- return searchPath
249
- }
250
- }
251
- dir = path.dirname(dir)
252
- }
253
-
254
- return null
250
+ return findUp(cwd, configFileNames)
255
251
  }
256
252
 
257
253
  export async function loadConfigFile (configFile: string): Promise<Partial<HistoireConfig>> {
@@ -286,7 +282,29 @@ export async function loadConfigFile (configFile: string): Promise<Partial<Histo
286
282
  }
287
283
  }
288
284
 
289
- export async function resolveConfig (cwd: string = process.cwd()): Promise<HistoireConfig> {
285
+ export const mergeConfig = createDefu((obj: any, key, value) => {
286
+ if (obj[key] && key === 'vite') {
287
+ obj[key] = mergeViteConfig(obj[key], value)
288
+ return true
289
+ }
290
+
291
+ if (obj[key] && key === 'plugins') {
292
+ const initialValue = obj[key] as Plugin[]
293
+ const newValue = obj[key] = [...value]
294
+ const nameMap = newValue.reduce((map, plugin) => {
295
+ map[plugin.name] = true
296
+ return map
297
+ }, {})
298
+ for (const plugin of initialValue) {
299
+ if (!nameMap[plugin.name]) {
300
+ newValue.unshift(plugin)
301
+ }
302
+ }
303
+ return true
304
+ }
305
+ })
306
+
307
+ export async function resolveConfig (cwd: string = process.cwd(), mode: ConfigMode): Promise<HistoireConfig> {
290
308
  let result: Partial<HistoireConfig>
291
309
  const configFile = resolveConfigFile(cwd)
292
310
  if (configFile) {
@@ -294,10 +312,18 @@ export async function resolveConfig (cwd: string = process.cwd()): Promise<Histo
294
312
  }
295
313
  const viteConfig = await resolveViteConfig({}, 'serve')
296
314
  const viteHistoireConfig = (viteConfig.histoire ?? {}) as HistoireConfig
297
- return processConfig(defu(result, viteHistoireConfig, getDefaultConfig()))
315
+ return processConfig(mergeConfig(result, viteHistoireConfig, getDefaultConfig()), mode)
298
316
  }
299
317
 
300
- export function processConfig (config: HistoireConfig): HistoireConfig {
318
+ export async function processConfig (config: HistoireConfig, mode: ConfigMode): Promise<HistoireConfig> {
319
+ for (const plugin of config.plugins) {
320
+ if (plugin.config) {
321
+ const result = await plugin.config(config, mode)
322
+ if (result) {
323
+ config = mergeConfig(result, config)
324
+ }
325
+ }
326
+ }
301
327
  config.outDir = path.resolve(process.cwd(), config.outDir)
302
328
  return config
303
329
  }
@@ -1,11 +1,11 @@
1
1
  import { resolveConfig as resolveViteConfig } from 'vite'
2
- import { resolveConfig, HistoireConfig } from './config.js'
2
+ import { resolveConfig, HistoireConfig, ConfigMode } from './config.js'
3
3
  import type { StoryFile } from './types.js'
4
4
 
5
5
  export interface Context {
6
6
  root: string
7
7
  config: HistoireConfig
8
- mode: 'dev' | 'build'
8
+ mode: ConfigMode
9
9
  storyFiles: StoryFile[]
10
10
  }
11
11
 
@@ -14,7 +14,7 @@ export interface CreateContextOptions {
14
14
  }
15
15
 
16
16
  export async function createContext (options: CreateContextOptions) {
17
- const config = await resolveConfig()
17
+ const config = await resolveConfig(process.cwd(), options.mode)
18
18
  const viteConfig = await resolveViteConfig({}, 'build')
19
19
  return {
20
20
  root: viteConfig.root,
package/src/node/index.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from './config.js'
2
+ export * from './plugin.js'
2
3
  export { defaultColors } from './colors.js'
@@ -0,0 +1,63 @@
1
+ import type { ViteDevServer } from 'vite'
2
+ import { ViteNodeServer } from 'vite-node/server'
3
+ import { ViteNodeRunner } from 'vite-node/client'
4
+ import pc from 'picocolors'
5
+ import { resolve } from 'pathe'
6
+
7
+ export interface UseModuleLoaderOptions {
8
+ server: ViteDevServer
9
+ throws?: boolean
10
+ }
11
+
12
+ export interface ModuleLoader {
13
+ clearCache: () => void
14
+ loadModule: (file: string) => Promise<any>
15
+ destroy: () => void
16
+ }
17
+
18
+ let _load: ModuleLoader['loadModule']
19
+
20
+ export function useModuleLoader (options: UseModuleLoaderOptions): ModuleLoader {
21
+ const { server } = options
22
+
23
+ const node = new ViteNodeServer(server)
24
+
25
+ const runner = new ViteNodeRunner({
26
+ root: server.config.root,
27
+ base: server.config.base,
28
+ fetchModule: async id => node.fetchModule(id),
29
+ resolveId: (id, importer) => node.resolveId(id, importer),
30
+ })
31
+
32
+ function clearCache () {
33
+ server.moduleGraph.invalidateAll()
34
+ node.fetchCache.clear()
35
+ runner.moduleCache.clear()
36
+ }
37
+
38
+ async function loadModule (file: string) {
39
+ try {
40
+ const result = await runner.executeFile(resolve(file))
41
+ return result
42
+ } catch (e) {
43
+ console.error(pc.red(`Error while loading module ${file}:\n${e.frame ? `${pc.bold(e.message)}\n${e.frame}` : e.stack}`))
44
+ if (options.throws) {
45
+ throw e
46
+ }
47
+ }
48
+ }
49
+
50
+ _load = loadModule
51
+
52
+ async function destroy () {
53
+ // Noop
54
+ }
55
+
56
+ return {
57
+ clearCache,
58
+ loadModule,
59
+ destroy,
60
+ }
61
+ }
62
+
63
+ export const loadModule: ModuleLoader['loadModule'] = (...args) => _load?.(...args)
@@ -1,270 +1,93 @@
1
- import { createRequire } from 'module'
2
- import { relative, dirname } from 'pathe'
3
- import { resolveConfig as resolveViteConfig, Plugin as VitePlugin } from 'vite'
4
- import { lookup as lookupMime } from 'mrmime'
5
- import { APP_PATH, DIST_CLIENT_PATH } from './alias.js'
6
- import { Context } from './context.js'
7
- import { notifyStoryChange } from './stories.js'
8
- import { makeTree } from './tree.js'
9
- import { parseColor } from './colors.js'
10
- import { createMarkdownRenderer } from './markdown.js'
11
-
12
- const require = createRequire(import.meta.url)
13
-
14
- export const STORIES_ID = '$histoire-stories'
15
- export const RESOLVED_STORIES_ID = `/${STORIES_ID}-resolved`
16
- export const SETUP_ID = '$histoire-setup'
17
- export const NOOP_ID = '/$histoire-noop'
18
- export const CONFIG_ID = '$histoire-config'
19
- export const RESOLVED_CONFIG_ID = `/${CONFIG_ID}-resolved`
20
- export const THEME_ID = '$histoire-theme'
21
- export const RESOLVED_THEME_ID = `/${THEME_ID}-resolved.css`
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 type { ConfigMode, HistoireConfig } from './config.js'
7
+ import type { Context } from './context.js'
8
+ import type { ModuleLoader } from './load.js'
9
+ import { addStory, removeStory } from './stories.js'
10
+ import type { Story, Variant } from './types.js'
11
+
12
+ export interface Plugin {
13
+ /**
14
+ * Name of the plugin
15
+ */
16
+ name: string
17
+ /**
18
+ * Modify histoire config. The hook can either mutate the passed config or
19
+ * return a partial config object that will be deeply merged into the existing
20
+ * config.
21
+ *
22
+ * Note: User plugins are resolved before running this hook so injecting other
23
+ * plugins inside the `config` hook will have no effect.
24
+ */
25
+ config?: (config: HistoireConfig, mode: ConfigMode) => Partial<HistoireConfig> | null | void | Promise<Partial<HistoireConfig> | null | void>
26
+ /**
27
+ * Use this hook to read and store the final resolved histoire config.
28
+ */
29
+ configResolved?: (config: HistoireConfig) => void | Promise<void>
30
+ /**
31
+ * Use this hook to do processing during development. The `onCleanup` hook
32
+ * should handle cleanup tasks when development server is closed.
33
+ */
34
+ onDev?: (api: DevPluginApi, onCleanup: (cb: () => void | Promise<void>) => void) => void | Promise<void>
35
+ /**
36
+ * Use this hook to do processing during production build.
37
+ */
38
+ onBuild?: (api: BuildPluginApi) => void | Promise<void>
39
+ }
22
40
 
23
- export async function createVitePlugins (ctx: Context): Promise<VitePlugin[]> {
24
- const viteConfig = await resolveViteConfig({}, ctx.mode === 'dev' ? 'serve' : 'build')
25
- const hasVuePlugin = viteConfig.plugins.find(p => p.name === 'vite:vue')
41
+ export class BasePluginApi {
42
+ colors = pc
43
+ path = path
44
+ fs = fs
26
45
 
27
- const plugins: VitePlugin[] = []
46
+ // eslint-disable-next-line no-useless-constructor
47
+ constructor (
48
+ protected ctx: Context,
49
+ protected plugin: Plugin,
50
+ public moduleLoader: ModuleLoader,
51
+ ) { }
28
52
 
29
- if (!hasVuePlugin) {
30
- plugins.push((await import('@vitejs/plugin-vue')).default())
53
+ get pluginTempDir () {
54
+ return path.resolve(TEMP_PATH, 'plugins', this.plugin.name)
31
55
  }
32
56
 
33
- if (ctx.config.vite) {
34
- plugins.push({
35
- name: 'histoire-vite-config-override',
36
- config (config, env) {
37
- return typeof ctx.config.vite === 'function' ? ctx.config.vite(config, env) : ctx.config.vite
38
- },
39
- })
57
+ log (...msg) {
58
+ console.log(this.colors.gray(`[Plugin:${this.plugin.name}]`), ...msg)
40
59
  }
41
60
 
42
- plugins.push({
43
- name: 'histoire-vite-plugin',
44
-
45
- config () {
46
- return {
47
- optimizeDeps: {
48
- // force include vue to avoid duplicated copies when linked + optimized
49
- include: [
50
- 'vue',
51
- dirname(require.resolve('@vue/runtime-core/package.json')),
52
- dirname(require.resolve('shiki/package.json')),
53
- dirname(require.resolve('vscode-textmate/package.json')),
54
- dirname(require.resolve('vscode-oniguruma/package.json')),
55
- dirname(require.resolve('case/package.json')),
56
- ],
57
- },
58
- server: {
59
- fs: {
60
- allow: [DIST_CLIENT_PATH, viteConfig.root, process.cwd()],
61
- },
62
- },
63
- }
64
- },
65
-
66
- async resolveId (id, importer) {
67
- if (id.startsWith(STORIES_ID)) {
68
- return RESOLVED_STORIES_ID
69
- }
70
- if (id.startsWith(SETUP_ID)) {
71
- if (ctx.config.setupFile) {
72
- return this.resolve(ctx.config.setupFile, importer, {
73
- skipSelf: true,
74
- })
75
- } else {
76
- return NOOP_ID
77
- }
78
- }
79
- if (id.startsWith(CONFIG_ID)) {
80
- return RESOLVED_CONFIG_ID
81
- }
82
- if (id.startsWith(THEME_ID)) {
83
- return RESOLVED_THEME_ID
84
- }
85
- },
86
-
87
- load (id) {
88
- if (id === RESOLVED_STORIES_ID) {
89
- const resolvedStories = ctx.storyFiles.filter(s => !!s.story)
90
- const files = resolvedStories.map((file, index) => {
91
- return {
92
- id: file.id,
93
- path: file.treePath,
94
- story: file.story,
95
- framework: 'vue3',
96
- index,
97
- }
98
- })
99
- return `import { defineAsyncComponent } from 'vue'
100
- ${resolvedStories.map((file, index) => `const Comp${index} = defineAsyncComponent(() => import('${file.path}'))`).join('\n')}
101
- export let files = [${files.map((file) => `{${JSON.stringify(file).slice(1, -1)}, component: Comp${file.index}}`).join(',\n')}]
102
- export let tree = ${JSON.stringify(makeTree(ctx.config, resolvedStories))}
103
- const handlers = []
104
- export function onUpdate (cb) {
105
- handlers.push(cb)
106
- }
107
- if (import.meta.hot) {
108
- import.meta.hot.accept(newModule => {
109
- files = newModule.files
110
- tree = newModule.tree
111
- handlers.forEach(h => {
112
- h(newModule.files, newModule.tree)
113
- newModule.onUpdate(h)
114
- })
115
- })
116
- }`
117
- }
118
- if (id === NOOP_ID) {
119
- return `export default () => {}`
120
- }
121
- if (id === RESOLVED_CONFIG_ID) {
122
- let js = `export const config = ${JSON.stringify(ctx.config)}\n`
123
- if (ctx.config.theme?.logo) {
124
- for (const key in ctx.config.theme.logo) {
125
- js += `import Logo_${key} from '${ctx.config.theme.logo[key]}'\n`
126
- }
127
- }
128
- js += `export const logos = {${Object.keys(ctx.config.theme?.logo ?? {}).map(key => `${key}: Logo_${key}`).join(', ')}}\n`
129
- return js
130
- }
131
- if (id === RESOLVED_THEME_ID) {
132
- let css = '*, ::before, ::after {'
133
- // Colors
134
- for (const color in ctx.config.theme?.colors ?? {}) {
135
- for (const key in ctx.config.theme.colors[color]) {
136
- css += `--_histoire-color-${color}-${key}: ${parseColor(ctx.config.theme.colors[color][key]).color.join(' ')};`
137
- }
138
- }
139
- css += '}'
140
- return css
141
- }
142
- },
143
-
144
- handleHotUpdate (updateContext) {
145
- const story = ctx.storyFiles.find(file => file.path === updateContext.file)
146
- if (story) {
147
- notifyStoryChange(story)
148
- }
149
- },
150
-
151
- configureServer (server) {
152
- server.middlewares.use(async (req, res, next) => {
153
- if (req.url!.startsWith('/__sandbox')) {
154
- res.statusCode = 200
155
- let html = `
156
- <!DOCTYPE html>
157
- <html>
158
- <head>
159
- <title></title>
160
- <meta charset="utf-8">
161
- <meta name="viewport" content="width=device-width,initial-scale=1">
162
- <meta name="description" content="">
163
- </head>
164
- <body>
165
- <div id="app"></div>
166
- <script>
167
- // Hide spammy vite messages
168
- const origConsoleLog = console.log
169
- console.log = (...args) => {
170
- if (typeof args[0] !== 'string' || !args[0].startsWith('[vite] connect')) {
171
- origConsoleLog(...args)
172
- }
61
+ warn (...msg) {
62
+ console.warn(this.colors.yellow(`[Plugin:${this.plugin.name}]`), ...msg)
173
63
  }
174
- </script>
175
- <script type="module" src="/@fs/${APP_PATH}/sandbox.js"></script>
176
- </body>
177
- </html>`
178
- // Apply Vite HTML transforms. This injects the Vite HMR client, and
179
- // also applies HTML transforms from Vite plugins
180
- html = await server.transformIndexHtml(req.url, html)
181
- res.end(html)
182
- return
183
- }
184
- next()
185
- })
186
-
187
- // serve our index.html after vite history fallback
188
- return () => {
189
- server.middlewares.use(async (req, res, next) => {
190
- if (req.url!.endsWith('.html')) {
191
- res.statusCode = 200
192
-
193
- let html = `
194
- <!DOCTYPE html>
195
- <html>
196
- <head>
197
- <title></title>
198
- <link rel="icon" href=""/>
199
- <meta charset="utf-8">
200
- <meta name="viewport" content="width=device-width,initial-scale=1">
201
- <meta name="description" content="">
202
- ${ctx.config.theme?.favicon ? `<link rel="icon" type="${lookupMime(ctx.config.theme.favicon)}" href="${ctx.config.theme.favicon}"/>` : ''}
203
- </head>
204
- <body>
205
- <div id="app"></div>
206
- <script type="module" src="/@fs/${APP_PATH}/index.js"></script>
207
- </body>
208
- </html>`
209
- // Apply Vite HTML transforms. This injects the Vite HMR client, and
210
- // also applies HTML transforms from Vite plugins
211
- html = await server.transformIndexHtml(req.url, html)
212
- res.end(html)
213
- return
214
- }
215
- next()
216
- })
217
- }
218
- },
219
- })
220
-
221
- // Custom blocks
222
- plugins.push(...await createCustomBlocksPlugins(ctx))
223
64
 
224
- if (ctx.mode === 'build') {
225
- // Add file name in build mode to have components names instead of <Anonymous>
226
- const include = [/\.vue$/]
227
- const exclude = [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/]
228
- plugins.push({
229
- name: 'histoire-file-name-plugin',
230
- enforce: 'post',
65
+ error (...msg) {
66
+ console.error(this.colors.red(`[Plugin:${this.plugin.name}]`), ...msg)
67
+ }
231
68
 
232
- transform (code, id) {
233
- if (exclude.some(r => r.test(id))) return
234
- if (include.some(r => r.test(id))) {
235
- const file = relative(viteConfig.root, id)
236
- const index = code.indexOf('export default')
237
- const result = `${code.substring(0, index)}_sfc_main.__file = '${file}'\n${code.substring(index)}`
238
- return result
239
- }
240
- },
241
- })
69
+ addStoryFile (file: string) {
70
+ removeStory(file)
71
+ addStory(file)
242
72
  }
73
+ }
243
74
 
244
- return plugins
75
+ export class DevPluginApi extends BasePluginApi {
76
+ watcher = chokidar
245
77
  }
246
78
 
247
- async function createCustomBlocksPlugins (ctx) {
248
- const plugins: VitePlugin[] = []
79
+ export type BuildEndCallback = () => Promise<void> | void
80
+ export type PreviewStoryCallback = (payload: { file: string, story: Story, variant: Variant, url: string }) => Promise<void> | void
249
81
 
250
- let md = await createMarkdownRenderer()
251
- if (ctx.config.markdown) {
252
- const result = await ctx.config.markdown(md)
253
- if (result) {
254
- md = result
255
- }
82
+ export class BuildPluginApi extends BasePluginApi {
83
+ buildEndCallbacks: BuildEndCallback[] = []
84
+ previewStoryCallbacks: PreviewStoryCallback[] = []
85
+
86
+ onBuildEnd (cb: BuildEndCallback) {
87
+ this.buildEndCallbacks.push(cb)
256
88
  }
257
- plugins.push({
258
- name: 'histoire-vue-docs-block',
259
- transform (code, id) {
260
- if (!id.includes('?vue&type=docs')) return
261
- if (!id.includes('lang.md')) return
262
- const html = md.render(code)
263
- return `export default Comp => {
264
- Comp.doc = ${JSON.stringify(html)}
265
- }`
266
- },
267
- })
268
89
 
269
- return plugins
90
+ onPreviewStory (cb: PreviewStoryCallback) {
91
+ this.previewStoryCallbacks.push(cb)
92
+ }
270
93
  }
@@ -0,0 +1,56 @@
1
+ import http from 'http'
2
+ import connect from 'connect'
3
+ import sirv from 'sirv'
4
+ import type { ResolvedConfig as ViteConfig } from 'vite'
5
+ import type { Context } from './context.js'
6
+
7
+ interface ReturnPayload {
8
+ baseUrl: string
9
+ close: () => Promise<void>
10
+ }
11
+
12
+ export async function startPreview (viteConfig: ViteConfig, port: number | null, ctx: Context): Promise<ReturnPayload> {
13
+ const app = connect()
14
+
15
+ app.use(
16
+ viteConfig.base,
17
+ sirv(ctx.config.outDir, {
18
+ dev: true,
19
+ etag: true,
20
+ single: true,
21
+ }),
22
+ )
23
+
24
+ let finalPort = port ?? 3000
25
+
26
+ const httpServer = http.createServer(app)
27
+
28
+ return new Promise((resolve, reject) => {
29
+ function onError (e: Error & { code?: string }) {
30
+ if (e.code === 'EADDRINUSE') {
31
+ httpServer.listen(++finalPort)
32
+ } else {
33
+ reject(e)
34
+ }
35
+ }
36
+
37
+ httpServer.on('error', onError)
38
+
39
+ httpServer.listen(finalPort, () => {
40
+ httpServer.off('error', onError)
41
+ const baseUrl = `http://localhost:${finalPort}${viteConfig.base}`
42
+ resolve({
43
+ baseUrl,
44
+ close: () => new Promise((resolve, reject) => {
45
+ httpServer.close((err) => {
46
+ if (err) {
47
+ reject(err)
48
+ } else {
49
+ resolve()
50
+ }
51
+ })
52
+ }),
53
+ })
54
+ })
55
+ })
56
+ }