histoire 0.2.4 → 0.3.1

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/Breadcrumb.vue +1 -1
  6. package/dist/client/app/components/base/BaseEmpty.vue +17 -1
  7. package/dist/client/app/components/exposed/Story.vue +22 -1
  8. package/dist/client/app/components/exposed/Variant.vue +13 -1
  9. package/dist/client/app/components/sandbox/SandboxVue3.vue +6 -4
  10. package/dist/client/app/components/sandbox/lib.js +2 -1
  11. package/dist/client/app/components/search/SearchItem.vue +1 -0
  12. package/dist/client/app/components/search/SearchLoading.vue +16 -0
  13. package/dist/client/app/components/search/SearchModal.vue +12 -149
  14. package/dist/client/app/components/search/SearchPane.vue +210 -0
  15. package/dist/client/app/components/search/search-data.d.ts +2 -0
  16. package/dist/client/app/components/search/search-data.js +7 -0
  17. package/dist/client/app/components/story/StoryControls.vue +5 -0
  18. package/dist/client/app/components/story/StoryDocs.vue +18 -11
  19. package/dist/client/app/components/story/StoryEvent.vue +53 -0
  20. package/dist/client/app/components/story/StoryEvents.vue +45 -0
  21. package/dist/client/app/components/story/StoryResponsivePreview.vue +41 -8
  22. package/dist/client/app/components/story/StorySidePanel.vue +28 -3
  23. package/dist/client/app/components/story/StorySourceCode.vue +24 -14
  24. package/dist/client/app/components/story/StoryView.vue +16 -2
  25. package/dist/client/app/components/tree/StoryGroup.vue +75 -0
  26. package/dist/client/app/components/{story → tree}/StoryList.vue +8 -2
  27. package/{src/client/app/components/story → dist/client/app/components/tree}/StoryListFolder.vue +10 -8
  28. package/{src/client/app/components/story → dist/client/app/components/tree}/StoryListItem.vue +7 -4
  29. package/dist/client/app/router.d.ts +1 -0
  30. package/dist/client/app/router.js +3 -1
  31. package/dist/client/app/sandbox.js +11 -1
  32. package/dist/client/app/stores/events.d.ts +29 -0
  33. package/dist/client/app/stores/events.js +25 -0
  34. package/dist/client/app/stores/folder.d.ts +10 -0
  35. package/dist/client/app/stores/folder.js +47 -0
  36. package/dist/client/app/stores/story.d.ts +20 -8
  37. package/dist/client/app/stores/story.js +20 -28
  38. package/dist/client/app/style/floating-vue.pcss +3 -1
  39. package/dist/client/app/style/main.pcss +5 -0
  40. package/dist/client/app/style/sandbox.css +2 -0
  41. package/dist/client/app/types.d.ts +9 -1
  42. package/dist/client/app/util/const.d.ts +1 -0
  43. package/dist/client/app/util/const.js +1 -0
  44. package/dist/client/app/util/events.d.ts +1 -0
  45. package/dist/client/app/util/events.js +31 -0
  46. package/dist/client/app/util/mapping.js +2 -2
  47. package/dist/client/index.d.ts +4 -3
  48. package/dist/client/index.js +2 -1
  49. package/dist/client/server/index.d.ts +7 -2
  50. package/dist/client/server/index.js +8 -26
  51. package/{src/client/server/Story.server.vue → dist/client/server/vue3/Story.vue} +21 -4
  52. package/dist/client/server/{Variant.server.vue → vue3/Variant.vue} +0 -0
  53. package/dist/client/server/vue3/run.d.ts +2 -0
  54. package/dist/client/server/vue3/run.js +32 -0
  55. package/dist/node/alias.d.ts +2 -1
  56. package/dist/node/alias.js +3 -2
  57. package/dist/node/build.js +74 -21
  58. package/dist/node/builtin-plugins/tailwind-tokens.d.ts +5 -0
  59. package/dist/node/builtin-plugins/tailwind-tokens.js +510 -0
  60. package/dist/node/collect/index.js +5 -3
  61. package/dist/node/collect/worker.js +6 -2
  62. package/dist/node/commands/preview.js +4 -25
  63. package/dist/node/config.d.ts +111 -5
  64. package/dist/node/config.js +40 -23
  65. package/dist/node/context.d.ts +3 -3
  66. package/dist/node/context.js +1 -1
  67. package/dist/node/index.d.ts +1 -0
  68. package/dist/node/index.js +1 -0
  69. package/dist/node/load.d.ts +12 -0
  70. package/dist/node/load.js +42 -0
  71. package/dist/node/plugin.d.ts +67 -11
  72. package/dist/node/plugin.js +42 -245
  73. package/dist/node/preview.d.ts +8 -0
  74. package/dist/node/preview.js +41 -0
  75. package/dist/node/search.d.ts +2 -0
  76. package/dist/node/search.js +68 -0
  77. package/dist/node/server.js +43 -21
  78. package/dist/node/stories.d.ts +2 -0
  79. package/dist/node/stories.js +9 -4
  80. package/dist/node/tree.d.ts +16 -12
  81. package/dist/node/tree.js +45 -5
  82. package/dist/node/types.d.ts +11 -0
  83. package/dist/node/util/find-up.d.ts +1 -0
  84. package/dist/node/util/find-up.js +20 -0
  85. package/dist/node/vite.d.ts +13 -0
  86. package/dist/node/vite.js +278 -0
  87. package/dist/style.css +174 -36
  88. package/package.json +7 -6
  89. package/scripts/copy.mjs +2 -1
  90. package/src/client/app/App.vue +9 -4
  91. package/src/client/app/codegen/const.ts +3 -0
  92. package/src/client/app/codegen/vue3.ts +80 -22
  93. package/src/client/app/components/app/Breadcrumb.vue +1 -1
  94. package/src/client/app/components/base/BaseEmpty.vue +17 -1
  95. package/src/client/app/components/exposed/Story.vue +22 -1
  96. package/src/client/app/components/exposed/Variant.vue +13 -1
  97. package/src/client/app/components/sandbox/SandboxVue3.vue +6 -4
  98. package/src/client/app/components/sandbox/lib.ts +3 -1
  99. package/src/client/app/components/search/SearchItem.vue +1 -0
  100. package/src/client/app/components/search/SearchLoading.vue +16 -0
  101. package/src/client/app/components/search/SearchModal.vue +12 -149
  102. package/src/client/app/components/search/SearchPane.vue +210 -0
  103. package/src/client/app/components/search/search-data.ts +9 -0
  104. package/src/client/app/components/story/StoryControls.vue +5 -0
  105. package/src/client/app/components/story/StoryDocs.vue +18 -11
  106. package/src/client/app/components/story/StoryEvent.vue +53 -0
  107. package/src/client/app/components/story/StoryEvents.vue +45 -0
  108. package/src/client/app/components/story/StoryResponsivePreview.vue +41 -8
  109. package/src/client/app/components/story/StorySidePanel.vue +28 -3
  110. package/src/client/app/components/story/StorySourceCode.vue +24 -14
  111. package/src/client/app/components/story/StoryView.vue +16 -2
  112. package/src/client/app/components/tree/StoryGroup.vue +75 -0
  113. package/src/client/app/components/{story → tree}/StoryList.vue +8 -2
  114. package/{dist/client/app/components/story → src/client/app/components/tree}/StoryListFolder.vue +10 -8
  115. package/{dist/client/app/components/story → src/client/app/components/tree}/StoryListItem.vue +7 -4
  116. package/src/client/app/router.ts +4 -1
  117. package/src/client/app/sandbox.ts +12 -2
  118. package/src/client/app/stores/events.ts +36 -0
  119. package/src/client/app/stores/folder.ts +59 -0
  120. package/src/client/app/stores/story.ts +20 -35
  121. package/src/client/app/style/floating-vue.pcss +3 -1
  122. package/src/client/app/style/main.pcss +5 -0
  123. package/src/client/app/style/sandbox.css +2 -0
  124. package/src/client/app/types.ts +10 -1
  125. package/src/client/app/util/const.ts +1 -0
  126. package/src/client/app/util/events.ts +30 -0
  127. package/src/client/app/util/mapping.ts +2 -2
  128. package/src/client/index.ts +4 -3
  129. package/src/client/server/index.ts +14 -27
  130. package/{dist/client/server/Story.server.vue → src/client/server/vue3/Story.vue} +21 -4
  131. package/src/client/server/{Variant.server.vue → vue3/Variant.vue} +0 -0
  132. package/{dist/client/server/index.ts → src/client/server/vue3/run.ts} +10 -4
  133. package/src/node/alias.ts +4 -2
  134. package/src/node/build.ts +86 -21
  135. package/src/node/builtin-plugins/tailwind-tokens.ts +521 -0
  136. package/src/node/collect/index.ts +6 -4
  137. package/src/node/collect/worker.ts +7 -2
  138. package/src/node/commands/preview.ts +4 -33
  139. package/src/node/config.ts +62 -29
  140. package/src/node/context.ts +3 -3
  141. package/src/node/index.ts +1 -0
  142. package/src/node/load.ts +63 -0
  143. package/src/node/plugin.ts +75 -252
  144. package/src/node/preview.ts +56 -0
  145. package/src/node/search.ts +75 -0
  146. package/src/node/server.ts +49 -23
  147. package/src/node/stories.ts +9 -4
  148. package/src/node/tree.spec.ts +35 -17
  149. package/src/node/tree.ts +64 -10
  150. package/src/node/types.ts +12 -0
  151. package/src/node/util/find-up.ts +24 -0
  152. package/src/node/vite.ts +296 -0
  153. package/tailwind.config.cjs +1 -0
  154. package/dist/client/app/codegen/serialize-js.ts +0 -119
  155. package/dist/client/app/codegen/util.ts +0 -79
  156. package/dist/client/app/codegen/vue3.ts +0 -276
  157. package/dist/client/app/components/sandbox/lib.ts +0 -8
  158. package/dist/client/app/global-components.ts +0 -13
  159. package/dist/client/app/index.ts +0 -28
  160. package/dist/client/app/router.ts +0 -17
  161. package/dist/client/app/sandbox.ts +0 -94
  162. package/dist/client/app/stores/preview-settings.ts +0 -17
  163. package/dist/client/app/stores/story.ts +0 -62
  164. package/dist/client/app/types.ts +0 -70
  165. package/dist/client/app/util/config.ts +0 -6
  166. package/dist/client/app/util/const.ts +0 -3
  167. package/dist/client/app/util/dark.ts +0 -4
  168. package/dist/client/app/util/env.ts +0 -1
  169. package/dist/client/app/util/keyboard.ts +0 -99
  170. package/dist/client/app/util/mapping.ts +0 -48
  171. package/dist/client/app/util/preview-settings.ts +0 -8
  172. package/dist/client/app/util/reactivity.ts +0 -22
  173. package/dist/client/app/util/responsive.ts +0 -3
  174. package/dist/client/app/util/scroll.ts +0 -31
  175. package/dist/client/app/util/tooltip.ts +0 -13
  176. package/dist/client/app/util/variant.ts +0 -20
  177. package/dist/client/index.ts +0 -12
  178. package/dist/client/shim.d.ts +0 -5
@@ -1,30 +1,45 @@
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'
14
22
  type GrayColorKeys = ColorKeys | '750' | '850' | '950'
15
23
 
16
- interface ResponsivePreset {
24
+ export interface ResponsivePreset {
17
25
  label: string
18
26
  width: number
19
27
  height: number
20
28
  }
21
29
 
22
- interface BackgroundPreset {
30
+ export interface BackgroundPreset {
23
31
  label: string
24
32
  color: string
25
33
  }
26
34
 
35
+ export interface TreeGroupConfig {
36
+ title: string
37
+ id?: string
38
+ include?: (file: TreeFile) => boolean
39
+ }
40
+
27
41
  export interface HistoireConfig {
42
+ plugins: Plugin[]
28
43
  /**
29
44
  * Output directory.
30
45
  */
@@ -48,6 +63,7 @@ export interface HistoireConfig {
48
63
  */
49
64
  file?: 'title' | 'path' | ((file: TreeFile) => string[])
50
65
  order?: 'asc' | ((a: string, b: string) => number)
66
+ groups?: TreeGroupConfig[]
51
67
  }
52
68
  /**
53
69
  * Customize the look of the histoire book.
@@ -131,9 +147,14 @@ export interface HistoireConfig {
131
147
  vite?: ViteConfig | ((config: ViteConfig, env: ViteConfigEnv) => void | ViteConfig | Promise<void | ViteConfig>)
132
148
  }
133
149
 
150
+ export type ConfigMode = 'build' | 'dev'
151
+
134
152
  export function getDefaultConfig (): HistoireConfig {
135
153
  return {
136
- outDir: 'histoire-dist',
154
+ plugins: [
155
+ tailwindTokens(),
156
+ ],
157
+ outDir: '.histoire/dist',
137
158
  storyMatch: ['**/*.story.vue'],
138
159
  storyIgnored: [
139
160
  '**/node_modules/**',
@@ -226,25 +247,7 @@ export const configFileNames = [
226
247
  ]
227
248
 
228
249
  export function resolveConfigFile (cwd: string = process.cwd()): string {
229
- let { root } = path.parse(cwd)
230
- let dir = cwd
231
-
232
- // Fix for windows, waiting for pathe to fix this: https://github.com/unjs/pathe/issues/5
233
- if (root === '' && dir[1] === ':') {
234
- root = dir.substring(0, 2)
235
- }
236
-
237
- while (dir !== root) {
238
- for (const fileName of configFileNames) {
239
- const searchPath = path.join(dir, fileName)
240
- if (fs.existsSync(searchPath)) {
241
- return searchPath
242
- }
243
- }
244
- dir = path.dirname(dir)
245
- }
246
-
247
- return null
250
+ return findUp(cwd, configFileNames)
248
251
  }
249
252
 
250
253
  export async function loadConfigFile (configFile: string): Promise<Partial<HistoireConfig>> {
@@ -279,7 +282,29 @@ export async function loadConfigFile (configFile: string): Promise<Partial<Histo
279
282
  }
280
283
  }
281
284
 
282
- 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> {
283
308
  let result: Partial<HistoireConfig>
284
309
  const configFile = resolveConfigFile(cwd)
285
310
  if (configFile) {
@@ -287,10 +312,18 @@ export async function resolveConfig (cwd: string = process.cwd()): Promise<Histo
287
312
  }
288
313
  const viteConfig = await resolveViteConfig({}, 'serve')
289
314
  const viteHistoireConfig = (viteConfig.histoire ?? {}) as HistoireConfig
290
- return processConfig(defu(result, viteHistoireConfig, getDefaultConfig()))
315
+ return processConfig(mergeConfig(result, viteHistoireConfig, getDefaultConfig()), mode)
291
316
  }
292
317
 
293
- 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
+ }
294
327
  config.outDir = path.resolve(process.cwd(), config.outDir)
295
328
  return config
296
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, files))}
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
+ }