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,7 +1,10 @@
1
1
  import { createRouter, createWebHistory } from 'vue-router'
2
2
 
3
+ // @ts-expect-error env not defined
4
+ export const base = import.meta.env.BASE_URL
5
+
3
6
  export const router = createRouter({
4
- history: createWebHistory(),
7
+ history: createWebHistory(base),
5
8
  routes: [
6
9
  {
7
10
  path: '/',
@@ -1,6 +1,6 @@
1
1
  import './style/sandbox.css'
2
2
  import { parseQuery } from 'vue-router'
3
- import { computed, createApp, h, onMounted, ref, watch } from 'vue'
3
+ import { computed, createApp, h, onMounted, ref, watch, isRef } from 'vue'
4
4
  import { createPinia } from 'pinia'
5
5
  import { registerGlobalComponents } from './global-components'
6
6
  import SandboxVue3 from './components/sandbox/SandboxVue3.vue'
@@ -18,6 +18,8 @@ const query = parseQuery(window.location.search)
18
18
  const file = ref<StoryFile>(mapFile(files.find(f => f.id === query.storyId)))
19
19
 
20
20
  const app = createApp({
21
+ name: 'SandboxApp',
22
+
21
23
  setup () {
22
24
  const story = computed(() => file.value.story)
23
25
  const variant = computed(() => story.value?.variants.find(v => v.id === query.variantId))
@@ -29,7 +31,15 @@ const app = createApp({
29
31
  if (event.data?.type === STATE_SYNC) {
30
32
  if (!mounted) return
31
33
  synced = true
32
- Object.assign(variant.value.state, event.data.state)
34
+ if (variant.value.state) {
35
+ for (const key in event.data.state) {
36
+ if (typeof variant.value.state[key] === 'object') {
37
+ Object.assign(variant.value.state[key], event.data.state[key])
38
+ } else {
39
+ variant.value.state[key] = event.data.state[key]
40
+ }
41
+ }
42
+ }
33
43
  } else if (event.data?.type === PREVIEW_SETTINGS_SYNC) {
34
44
  applyPreviewSettings(event.data.settings)
35
45
  }
@@ -0,0 +1,36 @@
1
+ import { defineStore } from 'pinia'
2
+ import { ref, reactive, watch } from 'vue'
3
+ import { useStoryStore } from './story.js'
4
+
5
+ export type HstEvent = {
6
+ name: string
7
+ argument: unknown
8
+ }
9
+
10
+ export const useEventsStore = defineStore('events', () => {
11
+ const storyStore = useStoryStore()
12
+
13
+ const events = reactive<Array<HstEvent>>([])
14
+ const unseen = ref(0)
15
+
16
+ function addEvent (event: HstEvent) {
17
+ events.push(event)
18
+ unseen.value++
19
+ }
20
+
21
+ function reset () {
22
+ events.length = 0
23
+ unseen.value = 0
24
+ }
25
+
26
+ watch(() => storyStore.currentVariant, () => {
27
+ reset()
28
+ })
29
+
30
+ return {
31
+ addEvent,
32
+ reset,
33
+ events,
34
+ unseen,
35
+ }
36
+ })
@@ -1,19 +1,9 @@
1
1
  import { defineStore } from 'pinia'
2
- import { computed, ref, watch } from 'vue'
3
- import { router } from '../router'
4
- import { Story } from '../types'
2
+ import { watch } from 'vue'
5
3
  import { useStorage } from '@vueuse/core'
4
+ import { useStoryStore } from './story'
6
5
 
7
- export const useStoryStore = defineStore('story', () => {
8
- const stories = ref<Story[]>([])
9
- function setStories (value: Story[]) {
10
- stories.value = value
11
- }
12
-
13
- const currentStory = computed(() => stories.value.find(s => s.id === router.currentRoute.value.params.storyId))
14
-
15
- const currentVariant = computed(() => currentStory.value?.variants.find(v => v.id === router.currentRoute.value.query.variantId))
16
-
6
+ export const useFolderStore = defineStore('folder', () => {
17
7
  const openedFolders = useStorage<Map<string, boolean>>(
18
8
  '_histoire-tree-state',
19
9
  new Map(),
@@ -29,14 +19,19 @@ export const useStoryStore = defineStore('story', () => {
29
19
  const currentValue = openedFolders.value.get(stringPath)
30
20
 
31
21
  if (currentValue == null) {
32
- openedFolders.value.set(stringPath, defaultToggleValue)
22
+ setFolderOpen(stringPath, defaultToggleValue)
33
23
  } else if (currentValue) {
34
- openedFolders.value.set(stringPath, false)
24
+ setFolderOpen(stringPath, false)
35
25
  } else {
36
- openedFolders.value.set(stringPath, true)
26
+ setFolderOpen(stringPath, true)
37
27
  }
38
28
  }
39
29
 
30
+ function setFolderOpen (path: Array<string> | string, value: boolean) {
31
+ const stringPath = typeof path === 'string' ? path : getStringPath(path)
32
+ openedFolders.value.set(stringPath, value)
33
+ }
34
+
40
35
  function isFolderOpened (path: Array<string>, defaultValue = false) {
41
36
  const value = openedFolders.value.get(getStringPath(path))
42
37
  if (value == null) {
@@ -47,19 +42,17 @@ export const useStoryStore = defineStore('story', () => {
47
42
 
48
43
  function openFileFolders (path: Array<string>) {
49
44
  for (let pathLength = 1; pathLength < path.length; pathLength++) {
50
- toggleFolder(path.slice(0, pathLength), true)
45
+ setFolderOpen(path.slice(0, pathLength), true)
51
46
  }
52
47
  }
53
48
 
54
- watch(currentStory, () => {
55
- openFileFolders(currentStory.value.file.path)
49
+ const storyStore = useStoryStore()
50
+
51
+ watch(() => storyStore.currentStory, (story) => {
52
+ openFileFolders(story.file.path)
56
53
  })
57
54
 
58
55
  return {
59
- stories,
60
- setStories,
61
- currentStory,
62
- currentVariant,
63
56
  isFolderOpened,
64
57
  toggleFolder,
65
58
  }
@@ -1,8 +1,7 @@
1
1
  import { defineStore } from 'pinia'
2
- import { computed, ref, watch } from 'vue'
2
+ import { computed, ref } from 'vue'
3
3
  import { router } from '../router'
4
- import { Story } from '../types'
5
- import { useStorage } from '@vueuse/core'
4
+ import { Story, Variant } from '../types'
6
5
 
7
6
  export const useStoryStore = defineStore('story', () => {
8
7
  const stories = ref<Story[]>([])
@@ -14,53 +13,35 @@ export const useStoryStore = defineStore('story', () => {
14
13
 
15
14
  const currentVariant = computed(() => currentStory.value?.variants.find(v => v.id === router.currentRoute.value.query.variantId))
16
15
 
17
- const openedFolders = useStorage<Map<string, boolean>>(
18
- '_histoire-tree-state',
19
- new Map(),
20
- )
21
-
22
- function getStringPath (path: Array<string>) {
23
- return path.join('␜')
24
- }
25
-
26
- function toggleFolder (path: Array<string>, defaultToggleValue = true) {
27
- const stringPath = getStringPath(path)
28
-
29
- const currentValue = openedFolders.value.get(stringPath)
30
-
31
- if (currentValue == null) {
32
- openedFolders.value.set(stringPath, defaultToggleValue)
33
- } else if (currentValue) {
34
- openedFolders.value.set(stringPath, false)
35
- } else {
36
- openedFolders.value.set(stringPath, true)
16
+ const maps = computed(() => {
17
+ const storyMap = new Map<string, Story>()
18
+ const variantMap = new Map<string, Variant>()
19
+ for (const story of stories.value) {
20
+ storyMap.set(story.id, story)
21
+ for (const variant of story.variants) {
22
+ variantMap.set(`${story.id}:${variant.id}`, variant)
23
+ }
37
24
  }
38
- }
39
-
40
- function isFolderOpened (path: Array<string>, defaultValue = false) {
41
- const value = openedFolders.value.get(getStringPath(path))
42
- if (value == null) {
43
- return defaultValue
25
+ return {
26
+ stories: storyMap,
27
+ variants: variantMap,
44
28
  }
45
- return value
46
- }
29
+ })
47
30
 
48
- function openFileFolders (path: Array<string>) {
49
- for (let pathLength = 1; pathLength < path.length; pathLength++) {
50
- toggleFolder(path.slice(0, pathLength), true)
51
- }
31
+ function getStoryById (id: string) {
32
+ return maps.value.stories.get(id)
52
33
  }
53
34
 
54
- watch(currentStory, () => {
55
- openFileFolders(currentStory.value.file.path)
56
- })
35
+ function getVariantById (idWithStoryId: string) {
36
+ return maps.value.variants.get(idWithStoryId)
37
+ }
57
38
 
58
39
  return {
59
40
  stories,
60
41
  setStories,
61
42
  currentStory,
62
43
  currentVariant,
63
- isFolderOpened,
64
- toggleFolder,
44
+ getStoryById,
45
+ getVariantById,
65
46
  }
66
47
  })
@@ -1,5 +1,6 @@
1
1
  @import url('https://fonts.googleapis.com/css2?family=Lato&display=swap');
2
2
  @import 'floating-vue/dist/style.css';
3
+ @import '@histoire/controls/dist/style.css';
3
4
 
4
5
  @import 'floating-vue.pcss';
5
6
  @import 'transitions.pcss';
@@ -78,4 +79,8 @@ body {
78
79
  }
79
80
  }
80
81
  }
82
+
83
+ hr {
84
+ margin: 1rem 0;
85
+ }
81
86
  }
@@ -1,3 +1,5 @@
1
+ @import '@histoire/controls/dist/style.css';
2
+
1
3
  html,
2
4
  body {
3
5
  background: transparent !important;
@@ -21,6 +21,7 @@ export interface Story {
21
21
  }
22
22
  icon?: string
23
23
  iconColor?: string
24
+ docsOnly?: boolean
24
25
  file?: StoryFile
25
26
  lastSelectedVariant?: Variant
26
27
  }
@@ -1,3 +1,4 @@
1
1
  export const STATE_SYNC = '__histoire:state-sync'
2
2
  export const SANDBOX_READY = '__histoire:sandbox-ready'
3
+ export const EVENT_SEND = '__histoire:event'
3
4
  export const PREVIEW_SETTINGS_SYNC = '__histoire:preview-settings-sync'
@@ -0,0 +1,30 @@
1
+ import { useEventsStore } from '../stores/events.js'
2
+ import { EVENT_SEND } from './const'
3
+
4
+ export function hstEvent (name: string, argument) {
5
+ console.log('[histoire] Event fired', { name, argument })
6
+ const event = {
7
+ name,
8
+ argument: JSON.parse(stringifyEvent(argument)), // Needed for HTMLEvent that can't be cloned
9
+ }
10
+ if (location.href.includes('__sandbox')) {
11
+ window.parent?.postMessage({
12
+ type: EVENT_SEND,
13
+ event,
14
+ })
15
+ } else {
16
+ useEventsStore().addEvent(event)
17
+ }
18
+ }
19
+
20
+ function stringifyEvent (e) {
21
+ const obj = {}
22
+ for (const k in e) {
23
+ obj[k] = e[k]
24
+ }
25
+ return JSON.stringify(obj, (k, v) => {
26
+ if (v instanceof Node) return 'Node'
27
+ if (v instanceof Window) return 'Window'
28
+ return v
29
+ }, ' ')
30
+ }
@@ -21,7 +21,7 @@ export function mapFile (file: StoryFile, existingFile?: StoryFile): StoryFile {
21
21
  for (const key in existingVariant) {
22
22
  if (typeof existingVariant[key] !== 'undefined') {
23
23
  if (key === 'state') {
24
- Object.assign(variant.state, existingVariant.state)
24
+ variant.state = existingVariant.state
25
25
  continue
26
26
  }
27
27
  variant[key] = existingVariant[key]
@@ -40,7 +40,7 @@ export function mapFile (file: StoryFile, existingFile?: StoryFile): StoryFile {
40
40
  export function mapVariant (variant: Variant): Variant {
41
41
  return {
42
42
  ...variant,
43
- state: {},
43
+ state: null,
44
44
  initState: null,
45
45
  slots: () => ({}),
46
46
  previewReady: false,
@@ -1,5 +1,6 @@
1
1
  import type { App } from 'vue'
2
2
  import type { Story, Variant } from './app/types.js'
3
+ export { hstEvent } from './app/util/events'
3
4
 
4
5
  export type Vue3StorySetupHandler = (payload: {
5
6
  app: App
@@ -7,6 +8,6 @@ export type Vue3StorySetupHandler = (payload: {
7
8
  variant: Variant
8
9
  }) => Promise<void> | void
9
10
 
10
- export function defineVue3StorySetup (handler: Vue3StorySetupHandler): Vue3StorySetupHandler {
11
+ export function defineSetupVue3 (handler: Vue3StorySetupHandler): Vue3StorySetupHandler {
11
12
  return handler
12
13
  }
@@ -11,6 +11,11 @@ export default defineComponent({
11
11
  default: null,
12
12
  },
13
13
 
14
+ id: {
15
+ type: String,
16
+ default: null,
17
+ },
18
+
14
19
  group: {
15
20
  type: String,
16
21
  default: null,
@@ -30,6 +35,11 @@ export default defineComponent({
30
35
  type: String,
31
36
  default: null,
32
37
  },
38
+
39
+ docsOnly: {
40
+ type: Boolean,
41
+ default: false,
42
+ },
33
43
  },
34
44
 
35
45
  setup (props) {
@@ -40,12 +50,13 @@ export default defineComponent({
40
50
  // Story
41
51
 
42
52
  const story: Story = {
43
- id: attrs.data.id,
53
+ id: props.id ?? attrs.data.id,
44
54
  title: props.title ?? attrs.data.fileName,
45
55
  group: props.group,
46
56
  layout: props.layout,
47
57
  icon: props.icon,
48
58
  iconColor: props.iconColor,
59
+ docsOnly: props.docsOnly,
49
60
  variants: [],
50
61
  }
51
62
  const addStory = inject('addStory', null)
@@ -76,7 +87,7 @@ export default defineComponent({
76
87
  render () {
77
88
  let suppressError = false
78
89
  try {
79
- return this.$slots.default({
90
+ return this.$slots.default?.({
80
91
  get state () {
81
92
  // No variant tags
82
93
  suppressError = true
package/src/node/alias.ts CHANGED
@@ -3,5 +3,7 @@ import { fileURLToPath } from 'url'
3
3
 
4
4
  const __dirname = dirname(fileURLToPath(import.meta.url))
5
5
 
6
- export const DIST_CLIENT_PATH = join(__dirname, '../client')
7
- export const APP_PATH = join(DIST_CLIENT_PATH, 'app')
6
+ export const DIST_PATH = join(__dirname, '../')
7
+ export const APP_PATH = join(DIST_PATH, 'client', 'app')
8
+
9
+ export const TEMP_PATH = join(process.cwd(), 'node_modules', '.histoire')
package/src/node/build.ts CHANGED
@@ -1,15 +1,18 @@
1
1
  import { join } from 'pathe'
2
- import { build as viteBuild, createServer as createViteServer } from 'vite'
2
+ import { build as viteBuild, createServer as createViteServer, ResolvedConfig as ViteConfig, resolveConfig as resolveViteConfig } from 'vite'
3
3
  import fs from 'fs-extra'
4
4
  import { lookup as lookupMime } from 'mrmime'
5
5
  import pc from 'picocolors'
6
6
  import { performance } from 'perf_hooks'
7
7
  import { APP_PATH } from './alias.js'
8
8
  import { Context } from './context.js'
9
- import { createVitePlugins } from './plugin.js'
9
+ import { createVitePlugins } from './vite.js'
10
10
  import { findAllStories } from './stories.js'
11
11
  import type { RollupOutput } from 'rollup'
12
12
  import { useCollectStories } from './collect/index.js'
13
+ import { BuildEndCallback, BuildPluginApi, PreviewStoryCallback } from './plugin.js'
14
+ import { useModuleLoader } from './load.js'
15
+ import { startPreview } from './preview.js'
13
16
 
14
17
  const PRELOAD_MODULES = [
15
18
  'vendor',
@@ -25,11 +28,27 @@ export async function build (ctx: Context) {
25
28
  const startTime = performance.now()
26
29
  await findAllStories(ctx)
27
30
 
28
- // Collect story data
29
31
  const server = await createViteServer({
30
32
  plugins: await createVitePlugins(ctx),
31
33
  })
32
34
  await server.pluginContainer.buildStart({})
35
+
36
+ const moduleLoader = useModuleLoader({
37
+ server,
38
+ throws: true,
39
+ })
40
+ const buildEndCallbacks: BuildEndCallback[] = []
41
+ const previewStoryCallbacks: PreviewStoryCallback[] = []
42
+ for (const plugin of ctx.config.plugins) {
43
+ if (plugin.onBuild) {
44
+ const api = new BuildPluginApi(ctx, plugin, moduleLoader)
45
+ await plugin.onBuild(api)
46
+ buildEndCallbacks.push(...api.buildEndCallbacks)
47
+ previewStoryCallbacks.push(...api.previewStoryCallbacks)
48
+ }
49
+ }
50
+
51
+ // Collect story data
33
52
  const { executeStoryFile, destroy: destroyCollectStories } = useCollectStories({
34
53
  server,
35
54
  throws: true,
@@ -37,7 +56,6 @@ export async function build (ctx: Context) {
37
56
  for (const storyFile of ctx.storyFiles) {
38
57
  await executeStoryFile(storyFile)
39
58
  }
40
- await server.close()
41
59
  await destroyCollectStories()
42
60
 
43
61
  const storyCount = ctx.storyFiles.reduce((sum, file) => sum + (file.story?.variants.length ? 1 : 0), 0)
@@ -49,8 +67,8 @@ export async function build (ctx: Context) {
49
67
  build: {
50
68
  rollupOptions: {
51
69
  input: [
52
- join(APP_PATH, 'index.ts'),
53
- join(APP_PATH, 'sandbox.ts'),
70
+ join(APP_PATH, 'index.js'),
71
+ join(APP_PATH, 'sandbox.js'),
54
72
  ],
55
73
  output: {
56
74
  manualChunks (id) {
@@ -63,57 +81,104 @@ export async function build (ctx: Context) {
63
81
  outDir: ctx.config.outDir,
64
82
  emptyOutDir: true,
65
83
  cssCodeSplit: false,
84
+ minify: false,
66
85
  },
67
86
  })
68
87
  const result = Array.isArray(results) ? results[0] : results as RollupOutput
69
88
 
89
+ const resolvedViteConfig = await resolveViteConfig({
90
+ plugins: await createVitePlugins(ctx),
91
+ }, 'build')
92
+
70
93
  const styleOutput = result.output.find(o => o.name === 'style.css' && o.type === 'asset')
71
94
 
72
95
  // Preload
73
96
  const preloadOutputs = result.output.filter(o => PRELOAD_MODULES.includes(o.name) && o.type === 'chunk')
74
- const preloadHtml = generateScriptLinks(preloadOutputs.map(o => o.fileName), 'preload')
97
+ const preloadHtml = generateScriptLinks(preloadOutputs.map(o => o.fileName), 'preload', ctx, resolvedViteConfig)
75
98
 
76
99
  // Prefetch
77
100
  const prefetchOutputs = result.output.filter(o => PREFETCHED_MODULES.includes(o.name) && o.type === 'chunk')
78
- const prefetchHtml = generateScriptLinks(prefetchOutputs.map(o => o.fileName), 'prefetch')
101
+ const prefetchHtml = generateScriptLinks(prefetchOutputs.map(o => o.fileName), 'prefetch', ctx, resolvedViteConfig)
79
102
 
80
103
  // Index
81
104
  const indexOutput = result.output.find(o => o.name === 'index' && o.type === 'chunk')
82
- await writeHtml(indexOutput.fileName, styleOutput.fileName, 'index.html', {
105
+ const indexHtml = generateEntryHtml(indexOutput.fileName, styleOutput.fileName, {
83
106
  HEAD: `${preloadHtml}${prefetchHtml}`,
84
- }, ctx)
107
+ }, ctx, resolvedViteConfig)
108
+ await writeFile('index.html', indexHtml, ctx)
85
109
 
86
110
  // Sandbox
87
111
  const sandboxOutput = result.output.find(o => o.name === 'sandbox' && o.type === 'chunk')
88
- await writeHtml(sandboxOutput.fileName, styleOutput.fileName, '__sandbox.html', {}, ctx)
112
+ const sandboxHtml = generateEntryHtml(sandboxOutput.fileName, styleOutput.fileName, {}, ctx, resolvedViteConfig)
113
+ await writeFile('__sandbox.html', sandboxHtml, ctx)
89
114
 
90
115
  const duration = performance.now() - startTime
91
116
  if (emptyStoryCount) {
92
117
  console.warn(pc.yellow(`⚠️ ${emptyStoryCount} empty story file`))
93
118
  }
94
119
  console.log(pc.green(`✅ Built ${storyCount} stories (${variantCount} variants) in ${Math.round(duration / 1000 * 100) / 100}s`))
120
+
121
+ // Render
122
+ if (previewStoryCallbacks.length) {
123
+ const { baseUrl, close } = await startPreview(resolvedViteConfig, null, ctx)
124
+ for (const storyFile of ctx.storyFiles) {
125
+ const story = storyFile.story
126
+ for (const variant of story.variants) {
127
+ const query = new URLSearchParams()
128
+ query.append('storyId', story.id)
129
+ query.append('variantId', variant.id)
130
+ const url = `${baseUrl}__sandbox?${query.toString()}`
131
+ for (const fn of previewStoryCallbacks) {
132
+ await fn({
133
+ file: storyFile.path,
134
+ story,
135
+ variant,
136
+ url,
137
+ })
138
+ }
139
+ }
140
+ }
141
+ await close()
142
+ }
143
+
144
+ await server.close()
145
+
146
+ for (const fn of buildEndCallbacks) {
147
+ await fn()
148
+ }
95
149
  }
96
150
 
97
- async function writeHtml (jsEntryFile: string, cssEntryFile: string, htmlFileName: string, variables: { HEAD?: string }, ctx: Context) {
98
- const code = `<!DOCTYPE html>
151
+ function generateBaseHtml (head: string, body: string, ctx: Context) {
152
+ return `<!DOCTYPE html>
99
153
  <html>
100
154
  <head>
101
155
  <title>${ctx.config.theme.title}</title>
102
156
  <meta charset="utf-8">
103
157
  <meta name="viewport" content="width=device-width,initial-scale=1">
104
158
  <meta name="description" content="">
105
- <link rel="stylesheet" href="/${cssEntryFile}">
106
- ${ctx.config.theme?.favicon ? `<link rel="icon" type="${lookupMime(ctx.config.theme.favicon)}" href="${ctx.config.theme.favicon}"/>` : ''}
107
- ${variables.HEAD ?? ''}
159
+ ${head}
108
160
  </head>
109
161
  <body>
110
- <div id="app"></div>
111
- <script type="module" src="/${jsEntryFile}"></script>
162
+ ${body}
112
163
  </body>
113
164
  </html>`
114
- await fs.writeFile(join(ctx.config.outDir, htmlFileName), code, 'utf8')
115
165
  }
116
166
 
117
- function generateScriptLinks (prefetchScripts: string[], rel: string) {
118
- return prefetchScripts.map(s => `<link rel="${rel}" href="${s}" as="script" crossOrigin="anonymous">`).join('')
167
+ function generateEntryHtml (jsEntryFile: string, cssEntryFile: string, variables: { HEAD?: string }, ctx: Context, resolvedViteConfig: ViteConfig) {
168
+ return generateBaseHtml(
169
+ `<link rel="stylesheet" href="${resolvedViteConfig.base}${cssEntryFile}">
170
+ ${ctx.config.theme?.favicon ? `<link rel="icon" type="${lookupMime(ctx.config.theme.favicon)}" href="${ctx.config.theme.favicon}"/>` : ''}
171
+ ${variables.HEAD ?? ''}`,
172
+ `<div id="app"></div>
173
+ <script type="module" src="${resolvedViteConfig.base}${jsEntryFile}"></script>`,
174
+ ctx,
175
+ )
176
+ }
177
+
178
+ async function writeFile (fileName: string, content: string, ctx: Context) {
179
+ await fs.writeFile(join(ctx.config.outDir, fileName), content, 'utf8')
180
+ }
181
+
182
+ function generateScriptLinks (prefetchScripts: string[], rel: string, ctx: Context, resolvedViteConfig: ViteConfig) {
183
+ return prefetchScripts.map(s => `<link rel="${rel}" href="${resolvedViteConfig.base}${s}" as="script" crossOrigin="anonymous">`).join('')
119
184
  }