histoire 0.4.4 → 0.5.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 (77) hide show
  1. package/dist/bundled/HomeView.js +1 -0
  2. package/dist/bundled/MobileOverlay.js +3 -1
  3. package/dist/bundled/SandboxVue3.js +649 -0
  4. package/dist/bundled/SearchPane.js +2 -0
  5. package/dist/bundled/StoryView.js +551 -622
  6. package/dist/bundled/global-components.js +16 -6
  7. package/dist/bundled/index2.js +114 -43
  8. package/dist/bundled/sandbox.js +3 -11
  9. package/dist/bundled/state.js +55 -0
  10. package/dist/bundled/story.js +1 -1
  11. package/dist/client/app/App.vue +18 -0
  12. package/dist/client/app/codegen/serialize-js.js +1 -1
  13. package/dist/client/app/codegen/vue3.d.ts +2 -0
  14. package/dist/client/app/codegen/vue3.js +37 -12
  15. package/dist/client/app/components/app/InitialLoading.vue +46 -0
  16. package/dist/client/app/components/app/MobileOverlay.vue +1 -1
  17. package/dist/client/app/components/base/BaseSelect.vue +72 -0
  18. package/dist/client/app/components/exposed/Story.vue +2 -1
  19. package/dist/client/app/components/exposed/Variant.vue +4 -4
  20. package/dist/client/app/components/panel/ControlsComponentPropItem.vue +96 -0
  21. package/dist/client/app/components/panel/ControlsComponentProps.vue +33 -0
  22. package/dist/client/app/components/panel/StatePresets.vue +195 -0
  23. package/dist/client/app/components/panel/StoryControls.vue +31 -2
  24. package/dist/client/app/components/sandbox/SandboxVue3.vue +70 -2
  25. package/dist/client/app/components/story/StoryVariantSinglePreviewRemote.vue +2 -14
  26. package/dist/client/app/index.js +5 -0
  27. package/dist/client/app/sandbox.js +2 -11
  28. package/dist/client/app/style/transitions.pcss +12 -0
  29. package/dist/client/app/types.d.ts +11 -0
  30. package/dist/client/app/util/mapping.js +11 -1
  31. package/dist/client/app/util/state.d.ts +5 -0
  32. package/dist/client/app/util/state.js +55 -0
  33. package/dist/client/app/util/variant.d.ts +1 -1
  34. package/dist/node/build.js +4 -6
  35. package/dist/node/collect/index.js +6 -0
  36. package/dist/node/collect/worker.js +0 -4
  37. package/dist/node/commands/preview.js +1 -1
  38. package/dist/node/config.d.ts +23 -23
  39. package/dist/node/plugin.d.ts +2 -2
  40. package/dist/node/server.js +66 -47
  41. package/dist/node/vite.d.ts +1 -1
  42. package/dist/node/vite.js +10 -2
  43. package/dist/style.css +162 -50
  44. package/package.json +4 -4
  45. package/src/client/app/App.vue +18 -0
  46. package/src/client/app/codegen/serialize-js.ts +1 -1
  47. package/src/client/app/codegen/vue3.ts +40 -12
  48. package/src/client/app/components/app/InitialLoading.vue +46 -0
  49. package/src/client/app/components/app/MobileOverlay.vue +1 -1
  50. package/src/client/app/components/base/BaseSelect.vue +72 -0
  51. package/src/client/app/components/exposed/Story.vue +2 -1
  52. package/src/client/app/components/exposed/Variant.vue +4 -4
  53. package/src/client/app/components/panel/ControlsComponentPropItem.vue +96 -0
  54. package/src/client/app/components/panel/ControlsComponentProps.vue +33 -0
  55. package/src/client/app/components/panel/StatePresets.vue +195 -0
  56. package/src/client/app/components/panel/StoryControls.vue +31 -2
  57. package/src/client/app/components/sandbox/SandboxVue3.vue +70 -2
  58. package/src/client/app/components/story/StoryVariantSinglePreviewRemote.vue +2 -14
  59. package/src/client/app/index.ts +6 -0
  60. package/src/client/app/sandbox.ts +2 -10
  61. package/src/client/app/style/transitions.pcss +12 -0
  62. package/src/client/app/types.ts +13 -0
  63. package/src/client/app/util/mapping.ts +12 -1
  64. package/src/client/app/util/state.ts +61 -0
  65. package/src/client/app/util/variant.ts +1 -1
  66. package/src/node/build.ts +4 -6
  67. package/src/node/collect/index.ts +7 -0
  68. package/src/node/collect/worker.ts +0 -4
  69. package/src/node/commands/preview.ts +1 -1
  70. package/src/node/server.ts +72 -49
  71. package/src/node/vite.ts +11 -2
  72. package/vite.config.ts +25 -0
  73. package/dist/bundled/dark.js +0 -4
  74. package/dist/bundled/reactivity.js +0 -96
  75. package/dist/client/app/util/reactivity.d.ts +0 -1
  76. package/dist/client/app/util/reactivity.js +0 -16
  77. package/src/client/app/util/reactivity.ts +0 -22
@@ -1,5 +1,4 @@
1
- // @ts-nocheck
2
- // @TODO remove no-check and fix vnode type errors
1
+ // @TODO remove @ts-ignore
3
2
  import { vModelText, vModelCheckbox, vModelSelect, vModelRadio, vModelDynamic, Text } from 'vue';
4
3
  import { pascal } from 'case';
5
4
  import { createAutoBuildingObject, indent } from './util';
@@ -9,14 +8,16 @@ export async function generateSourceCode(variant) {
9
8
  const vnode = variant.slots().default?.({ state: variant.state ?? {} }) ?? [];
10
9
  const list = Array.isArray(vnode) ? vnode : [vnode];
11
10
  const lines = [];
12
- for (const vnode of list) {
13
- lines.push(...(await printVNode(vnode)).lines);
11
+ for (const n in list) {
12
+ const vnode = list[n];
13
+ lines.push(...(await printVNode(vnode, variant.state?._hPropState?.[n])).lines);
14
14
  }
15
15
  return lines.join('\n');
16
16
  }
17
- async function printVNode(vnode) {
17
+ async function printVNode(vnode, propsOverrides = null) {
18
18
  if (vnode.type === Text) {
19
19
  return {
20
+ // @ts-ignore
20
21
  lines: [vnode.children],
21
22
  isText: true,
22
23
  };
@@ -24,7 +25,9 @@ async function printVNode(vnode) {
24
25
  const lines = [];
25
26
  if (typeof vnode.type === 'object' || typeof vnode.type === 'string') {
26
27
  // Wait for async component
28
+ // @ts-ignore
27
29
  if (vnode.type?.__asyncLoader && !vnode.type.__asyncResolved) {
30
+ // @ts-ignore
28
31
  await vnode.type.__asyncLoader();
29
32
  }
30
33
  const attrs = [];
@@ -78,8 +81,10 @@ async function printVNode(vnode) {
78
81
  }
79
82
  }
80
83
  genDirective('model', dir, valueCode);
84
+ // @ts-ignore
81
85
  }
82
86
  else if (dir.instance._ || dir.instance.$) {
87
+ // @ts-ignore
83
88
  const target = dir.instance.$ ?? dir.instance._;
84
89
  let dirName;
85
90
  for (const directives of [target.directives, target.appContext.directives]) {
@@ -99,11 +104,8 @@ async function printVNode(vnode) {
99
104
  }
100
105
  }
101
106
  // Attributes
102
- for (const prop in vnode.props) {
103
- if (skipProps.includes(prop)) {
104
- continue;
105
- }
106
- const value = vnode.props[prop];
107
+ function addAttr(prop, value) {
108
+ // @ts-ignore
107
109
  if (typeof value !== 'string' || vnode.dynamicProps?.includes(prop)) {
108
110
  let directive = ':';
109
111
  if (prop.startsWith('on')) {
@@ -112,6 +114,7 @@ async function printVNode(vnode) {
112
114
  const arg = directive === '@' ? `${prop[2].toLowerCase()}${prop.slice(3)}` : prop;
113
115
  // v-model on component
114
116
  const vmodelListener = `onUpdate:${prop}`;
117
+ // @ts-ignore
115
118
  if (directive === ':' && vnode.dynamicProps?.includes(vmodelListener)) {
116
119
  // Listener
117
120
  skipProps.push(vmodelListener);
@@ -132,7 +135,7 @@ async function printVNode(vnode) {
132
135
  modifiers,
133
136
  value,
134
137
  }, valueCode);
135
- continue;
138
+ return;
136
139
  }
137
140
  let serialized;
138
141
  if (typeof value === 'string' && value.startsWith('{{') && value.endsWith('}}')) {
@@ -172,6 +175,18 @@ async function printVNode(vnode) {
172
175
  attrs.push([`${prop}="${value}"`]);
173
176
  }
174
177
  }
178
+ for (const prop in vnode.props) {
179
+ if (skipProps.includes(prop) || (propsOverrides && prop in propsOverrides)) {
180
+ continue;
181
+ }
182
+ const value = vnode.props[prop];
183
+ addAttr(prop, value);
184
+ }
185
+ if (propsOverrides) {
186
+ for (const prop in propsOverrides) {
187
+ addAttr(prop, propsOverrides[prop]);
188
+ }
189
+ }
175
190
  if (attrs.length > 1) {
176
191
  multilineAttrs = true;
177
192
  }
@@ -192,6 +207,7 @@ async function printVNode(vnode) {
192
207
  else if (Array.isArray(vnode.children)) {
193
208
  let isAllChildText;
194
209
  for (const child of vnode.children) {
210
+ // @ts-ignore
195
211
  const result = await printVNode(child);
196
212
  if (result.isText) {
197
213
  if (isAllChildText === undefined) {
@@ -226,6 +242,7 @@ async function printVNode(vnode) {
226
242
  return () => false;
227
243
  }
228
244
  });
245
+ // @ts-ignore
229
246
  const children = vnode.children[key](autoObject.proxy);
230
247
  const slotLines = [];
231
248
  for (const child of children) {
@@ -286,6 +303,7 @@ async function printVNode(vnode) {
286
303
  }
287
304
  }
288
305
  else if (vnode?.shapeFlag & 1 << 4) {
306
+ // @ts-ignore
289
307
  for (const child of vnode.children) {
290
308
  lines.push(...(await printVNode(child)).lines);
291
309
  }
@@ -294,18 +312,24 @@ async function printVNode(vnode) {
294
312
  lines,
295
313
  };
296
314
  }
297
- function getTagName(vnode) {
315
+ export function getTagName(vnode) {
298
316
  if (typeof vnode.type === 'string') {
299
317
  return vnode.type;
318
+ // @ts-ignore
300
319
  }
301
320
  else if (vnode.type?.__asyncResolved) {
321
+ // @ts-ignore
302
322
  const asyncComp = vnode.type?.__asyncResolved;
303
323
  return asyncComp.name ?? getNameFromFile(asyncComp.__file);
324
+ // @ts-ignore
304
325
  }
305
326
  else if (vnode.type?.name) {
327
+ // @ts-ignore
306
328
  return vnode.type.name;
329
+ // @ts-ignore
307
330
  }
308
331
  else if (vnode.type?.__file) {
332
+ // @ts-ignore
309
333
  return getNameFromFile(vnode.type.__file);
310
334
  }
311
335
  return 'Anonymous';
@@ -321,6 +345,7 @@ function serializeAndCleanJs(value) {
321
345
  const isAutoBuildingObject = !!value?.__autoBuildingObject;
322
346
  const result = serializeJs(value);
323
347
  if (isAutoBuildingObject) {
348
+ // @ts-ignore
324
349
  return [cleanupExpression(result.__autoBuildingObjectGetKey)];
325
350
  }
326
351
  else {
@@ -0,0 +1,46 @@
1
+ <script lang="ts" setup>
2
+ import { reactive } from 'vue'
3
+
4
+ const progress = reactive({
5
+ loaded: 0,
6
+ total: 0,
7
+ })
8
+
9
+ const maxCols = window.innerWidth / 20
10
+
11
+ // @ts-expect-error vite hot api
12
+ if (import.meta.hot) {
13
+ // @ts-expect-error vite hot api
14
+ import.meta.hot.on('histoire:stories-loading-progress', (data) => {
15
+ progress.loaded = data.loadedFileCount
16
+ progress.total = data.totalFileCount
17
+ })
18
+ }
19
+ </script>
20
+
21
+ <template>
22
+ <div class="htw-fixed htw-inset-0 htw-bg-white dark:htw-bg-gray-700 htw-flex htw-flex-col htw-gap-6 htw-items-center htw-justify-center">
23
+ <transition name="__histoire-fade">
24
+ <div
25
+ v-if="progress.total > 0"
26
+ class="htw-grid htw-gap-2"
27
+ :style="{
28
+ gridTemplateColumns: `repeat(${Math.min(Math.ceil(Math.sqrt(progress.total)), maxCols)}, minmax(0, 1fr))`,
29
+ }"
30
+ >
31
+ <div
32
+ v-for="n in progress.total"
33
+ :key="n"
34
+ class="htw-bg-primary-500/10 htw-rounded-full"
35
+ >
36
+ <div
37
+ class="htw-w-3 htw-h-3 htw-bg-primary-500 htw-rounded-full htw-duration-150 htw-ease-out"
38
+ :class="{
39
+ 'htw-transition-transform htw-scale-0': n >= progress.loaded,
40
+ }"
41
+ />
42
+ </div>
43
+ </div>
44
+ </transition>
45
+ </div>
46
+ </template>
@@ -10,7 +10,7 @@ const emits = defineEmits<{(e: 'close'): void}>()
10
10
  </script>
11
11
 
12
12
  <template>
13
- <transition name="__histoire-fade">
13
+ <transition name="__histoire-fade-bottom">
14
14
  <div
15
15
  v-if="opened"
16
16
  class="htw-absolute htw-z-10 htw-bg-white dark:htw-bg-gray-700 htw-w-screen htw-h-screen htw-inset-0 htw-overflow-hidden htw-flex htw-flex-col"
@@ -0,0 +1,72 @@
1
+ <script lang="ts" setup>
2
+ import { Dropdown as VDropdown } from 'floating-vue'
3
+ import { computed, ComputedRef } from 'vue'
4
+ import { Icon } from '@iconify/vue'
5
+
6
+ const props = defineProps<{
7
+ modelValue: string
8
+ options: Record<string, string> | Array<string>
9
+ }>()
10
+
11
+ const emits = defineEmits<{
12
+ (e: 'update:modelValue', value: string): void
13
+ (e: 'select', value: string): void
14
+ }>()
15
+
16
+ const formattedOptions: ComputedRef<Record<string, string>> = computed(() => {
17
+ if (Array.isArray(props.options)) {
18
+ return Object.fromEntries(props.options.map((value) => [value, value]))
19
+ }
20
+ return props.options
21
+ })
22
+
23
+ const selectedLabel = computed(() => formattedOptions.value[props.modelValue])
24
+
25
+ function selectValue (value: string, hide: () => void) {
26
+ emits('update:modelValue', value)
27
+ emits('select', value)
28
+ hide()
29
+ }
30
+ </script>
31
+
32
+ <template>
33
+ <VDropdown
34
+ auto-size
35
+ >
36
+ <div
37
+ class="htw-cursor-pointer htw-w-full htw-outline-none htw-px-2 htw-h-[27px] -htw-my-1 htw-border htw-border-solid htw-border-black/25 dark:htw-border-white/25 hover:htw-border-primary-500 dark:hover:htw-border-primary-500 htw-rounded-sm htw-flex htw-gap-2 htw-items-center htw-leading-normal"
38
+ >
39
+ <div class="htw-flex-1 htw-truncate">
40
+ <slot :label="selectedLabel">
41
+ {{ selectedLabel }}
42
+ </slot>
43
+ </div>
44
+ <Icon
45
+ icon="carbon:chevron-sort"
46
+ class="htw-w-4 htw-h-4 htw-flex-none htw-ml-auto"
47
+ />
48
+ </div>
49
+ <template #popper="{ hide }">
50
+ <div class="htw-flex htw-flex-col htw-bg-gray-50 dark:htw-bg-gray-700">
51
+ <div
52
+ v-for="( label, value ) in formattedOptions"
53
+ v-bind="{ ...$attrs, class: null, style: null }"
54
+ :key="label"
55
+ class="htw-px-2 htw-py-1 htw-cursor-pointer hover:htw-bg-primary-100 dark:hover:htw-bg-primary-700"
56
+ :class="{
57
+ 'htw-bg-primary-200 dark:htw-bg-primary-800': props.modelValue === value,
58
+ }"
59
+ @click="selectValue(value, hide)"
60
+ >
61
+ <slot
62
+ name="option"
63
+ :label="label"
64
+ :value="value"
65
+ >
66
+ {{ label }}
67
+ </slot>
68
+ </div>
69
+ </div>
70
+ </template>
71
+ </VDropdown>
72
+ </template>
@@ -46,7 +46,8 @@ export default defineComponent({
46
46
  for (const key in storyComponent.devtoolsRawSetupState) {
47
47
  addImplicitState(key, storyComponent.devtoolsRawSetupState[key])
48
48
  }
49
- provide('implicitState', () => implicitState)
49
+ // Shallow copy to prevent sharing object with different variants
50
+ provide('implicitState', () => ({ ...implicitState }))
50
51
 
51
52
  function updateStory () {
52
53
  Object.assign(attrs.story, {
@@ -1,6 +1,7 @@
1
1
  <script lang="ts">
2
2
  import { defineComponent, getCurrentInstance, inject, PropType, useAttrs, watch } from 'vue'
3
3
  import { Variant } from '../../types'
4
+ import { applyStateToVariant } from '../../util/state'
4
5
 
5
6
  // const logLocation = location.href.includes('__sandbox') ? '[Sandbox]' : '[Host]'
6
7
 
@@ -41,9 +42,7 @@ export default defineComponent({
41
42
  const implicitState = inject<() => any>('implicitState')
42
43
 
43
44
  watch(() => implicitState, value => {
44
- if (typeof props.initState !== 'function') {
45
- attrs.variant.state = value()
46
- }
45
+ applyStateToVariant(attrs.variant, value())
47
46
  }, {
48
47
  immediate: true,
49
48
  })
@@ -52,7 +51,8 @@ export default defineComponent({
52
51
  Object.assign(attrs.variant, {
53
52
  initState: async () => {
54
53
  if (typeof props.initState === 'function') {
55
- attrs.variant.state = await props.initState()
54
+ const state = await props.initState()
55
+ applyStateToVariant(attrs.variant, state)
56
56
  }
57
57
  },
58
58
  slots: () => vm.proxy.$slots,
@@ -0,0 +1,96 @@
1
+ <script lang="ts" setup>
2
+ import { computed, ref } from 'vue'
3
+ import { Icon } from '@iconify/vue'
4
+ import type { Variant, PropDefinition, AutoPropComponentDefinition } from '../../types'
5
+
6
+ const props = defineProps<{
7
+ variant: Variant
8
+ component: AutoPropComponentDefinition
9
+ definition: PropDefinition
10
+ }>()
11
+
12
+ const comp = computed(() => {
13
+ switch (props.definition.types?.[0]) {
14
+ case 'string':
15
+ return 'HstText'
16
+ case 'number':
17
+ return 'HstNumber'
18
+ case 'boolean':
19
+ return 'HstCheckbox'
20
+ case 'object':
21
+ default:
22
+ return 'HstTextarea'
23
+ }
24
+ })
25
+
26
+ const isJSON = computed(() => comp.value === 'HstTextarea')
27
+
28
+ const invalidValue = ref('')
29
+
30
+ const model = computed({
31
+ get: () => {
32
+ if (invalidValue.value) {
33
+ return invalidValue.value
34
+ }
35
+ let val = props.variant.state._hPropState[props.component.index]?.[props.definition.name]
36
+ if (val && isJSON.value) {
37
+ val = JSON.stringify(val, null, 2)
38
+ }
39
+ return val
40
+ },
41
+ set: (value) => {
42
+ invalidValue.value = ''
43
+ if (isJSON.value) {
44
+ try {
45
+ value = JSON.parse(value)
46
+ } catch (e) {
47
+ invalidValue.value = value
48
+ return
49
+ }
50
+ }
51
+ if (!props.variant.state._hPropState[props.component.index]) {
52
+ // eslint-disable-next-line vue/no-mutating-props
53
+ props.variant.state._hPropState[props.component.index] = {}
54
+ }
55
+ // eslint-disable-next-line vue/no-mutating-props
56
+ props.variant.state._hPropState[props.component.index][props.definition.name] = value
57
+ },
58
+ })
59
+
60
+ function reset () {
61
+ if (props.variant.state._hPropState[props.component.index]) {
62
+ delete props.variant.state._hPropState[props.component.index][props.definition.name]
63
+ }
64
+ }
65
+
66
+ const canReset = computed(() => props.variant.state?._hPropState?.[props.component.index] && props.definition.name in props.variant.state._hPropState[props.component.index])
67
+ </script>
68
+
69
+ <template>
70
+ <component
71
+ :is="comp"
72
+ v-if="comp"
73
+ v-model="model"
74
+ :title="definition.name"
75
+ :placeholder="isJSON ? 'Enter JSON' : null"
76
+ >
77
+ <template #actions>
78
+ <Icon
79
+ v-if="invalidValue"
80
+ v-tooltip="'JSON error'"
81
+ icon="carbon:warning-alt"
82
+ class="htw-text-orange-500"
83
+ />
84
+
85
+ <Icon
86
+ v-tooltip="'Remove override'"
87
+ icon="carbon:erase"
88
+ class="htw-cursor-pointer htw-w-4 htw-h-4 hover:htw-text-primary-500 dark:hover:htw-text-primary-400 htw-text-gray-900 dark:htw-text-gray-100"
89
+ :class="[
90
+ canReset ? 'htw-opacity-50 hover:htw-opacity-100' : 'htw-opacity-25 htw-pointer-events-none',
91
+ ]"
92
+ @click.stop="reset()"
93
+ />
94
+ </template>
95
+ </component>
96
+ </template>
@@ -0,0 +1,33 @@
1
+ <script lang="ts" setup>
2
+ import type { AutoPropComponentDefinition, Variant } from '../../types'
3
+ import { Icon } from '@iconify/vue'
4
+ import ControlsComponentPropItem from './ControlsComponentPropItem.vue'
5
+
6
+ defineProps<{
7
+ variant: Variant
8
+ definition: AutoPropComponentDefinition
9
+ }>()
10
+ </script>
11
+
12
+ <template>
13
+ <div>
14
+ <div class="htw-font-mono htw-p-2 htw-flex htw-items-center htw-gap-1">
15
+ <Icon
16
+ v-tooltip="'Auto-detected props'"
17
+ icon="carbon:flash"
18
+ class="htw-w-4 htw-h-4 htw-text-primary-500 htw-flex-none"
19
+ />
20
+ <div>
21
+ <span class="htw-opacity-30">&lt;</span>{{ definition.name }}<span class="htw-opacity-30">&gt;</span>
22
+ </div>
23
+ </div>
24
+
25
+ <ControlsComponentPropItem
26
+ v-for="prop of definition.props"
27
+ :key="prop.name"
28
+ :variant="variant"
29
+ :component="definition"
30
+ :definition="prop"
31
+ />
32
+ </div>
33
+ </template>
@@ -0,0 +1,195 @@
1
+ <script lang="ts" setup>
2
+ import { ref, computed, nextTick, onMounted } from 'vue'
3
+ import { Icon } from '@iconify/vue'
4
+ import { useStorage, onClickOutside, useTimeoutFn } from '@vueuse/core'
5
+ import BaseSelect from '../base/BaseSelect.vue'
6
+ import { applyStateToVariant, clone, omit, toRawDeep } from '../../util/state'
7
+ import type { Story, Variant } from '../../types'
8
+
9
+ const DEFAULT_ID = 'default'
10
+
11
+ const props = defineProps<{
12
+ story: Story
13
+ variant: Variant
14
+ }>()
15
+
16
+ const saveId = computed(() => `${props.story.id}:${props.variant.id}`)
17
+
18
+ const omitKeys = ['_hPropDefs']
19
+
20
+ const defaultState = clone(omit(toRawDeep(props.variant.state), omitKeys))
21
+
22
+ const selectedOption = useStorage<string>(
23
+ `_histoire-presets/${saveId.value}/selected`,
24
+ DEFAULT_ID,
25
+ )
26
+
27
+ const presetStates = useStorage<Map<string, { state: Record<string, unknown>, label: string }>>(
28
+ `_histoire-presets/${saveId.value}/states`,
29
+ new Map(),
30
+ )
31
+
32
+ const presetsOptions = computed(() => {
33
+ const options = { [DEFAULT_ID]: 'Initial state' }
34
+ presetStates.value.forEach((value, key) => {
35
+ options[key] = value.label
36
+ })
37
+ return options
38
+ })
39
+
40
+ function resetState () {
41
+ selectedOption.value = DEFAULT_ID
42
+ applyStateToVariant(props.variant, clone(defaultState))
43
+ }
44
+
45
+ function applyPreset (id) {
46
+ if (id === DEFAULT_ID) {
47
+ resetState()
48
+ } else if (presetStates.value.has(id)) {
49
+ applyStateToVariant(props.variant, clone(presetStates.value.get(id).state))
50
+ }
51
+ }
52
+
53
+ onMounted(() => {
54
+ if (selectedOption.value !== DEFAULT_ID) {
55
+ applyPreset(selectedOption.value)
56
+ }
57
+ })
58
+
59
+ const input = ref<HTMLInputElement>()
60
+ const select = ref<HTMLInputElement>()
61
+ const canEdit = computed(() => selectedOption.value !== DEFAULT_ID)
62
+ const isEditing = ref(false)
63
+
64
+ async function createPreset () {
65
+ const id = (new Date()).getTime().toString()
66
+
67
+ presetStates.value.set(id, { state: clone(omit(toRawDeep(props.variant.state), omitKeys)), label: 'New preset' })
68
+ selectedOption.value = id
69
+ isEditing.value = true
70
+ await nextTick()
71
+ input.value.select()
72
+ }
73
+
74
+ const savedNotif = ref(false)
75
+ const savedTimeout = useTimeoutFn(() => {
76
+ savedNotif.value = false
77
+ }, 1000)
78
+
79
+ async function savePreset () {
80
+ if (!canEdit.value) return
81
+
82
+ const preset = presetStates.value.get(selectedOption.value)
83
+ preset.state = clone(omit(toRawDeep(props.variant.state), omitKeys))
84
+ savedNotif.value = true
85
+ savedTimeout.start()
86
+ }
87
+
88
+ function deletePreset (id) {
89
+ if (!confirm('Are you sure you want to delete this preset?')) {
90
+ return
91
+ }
92
+
93
+ if (selectedOption.value === id) {
94
+ resetState()
95
+ }
96
+ presetStates.value.delete(id)
97
+ }
98
+
99
+ async function startEditing () {
100
+ if (!canEdit.value) {
101
+ return
102
+ }
103
+
104
+ isEditing.value = true
105
+ await nextTick()
106
+ input.value.select()
107
+ }
108
+
109
+ function stopEditing () {
110
+ isEditing.value = false
111
+ }
112
+
113
+ onClickOutside(select, stopEditing)
114
+ </script>
115
+
116
+ <template>
117
+ <div class="htw-flex htw-gap-2 htw-w-full htw-items-center">
118
+ <div
119
+ ref="select"
120
+ class="htw-flex-1 htw-min-w-0"
121
+ >
122
+ <BaseSelect
123
+ v-model="selectedOption"
124
+ :options="presetsOptions"
125
+ @dblclick="startEditing()"
126
+ @keydown.enter="stopEditing()"
127
+ @keydown.escape="stopEditing()"
128
+ @select="id => applyPreset(id)"
129
+ >
130
+ <template #default="{ label }">
131
+ <input
132
+ v-if="isEditing"
133
+ ref="input"
134
+ v-model="presetStates.get(selectedOption).label"
135
+ type="text"
136
+ class="htw-text-inherit htw-bg-transparent htw-w-full htw-h-full htw-outline-none"
137
+ @click.stop.prevent
138
+ >
139
+
140
+ <div
141
+ v-else
142
+ class="htw-flex htw-items-center htw-gap-2"
143
+ >
144
+ <span class="htw-flex-1 htw-truncate">
145
+ {{ label }}
146
+ </span>
147
+ <Icon
148
+ v-if="canEdit"
149
+ v-tooltip="'Rename this preset'"
150
+ icon="carbon:edit"
151
+ class="htw-flex-none htw-cursor-pointer htw-w-4 htw-h-4 hover:htw-text-primary-500 htw-opacity-50 hover:htw-opacity-100 dark:hover:htw-text-primary-400 htw-text-gray-900 dark:htw-text-gray-100"
152
+ @click.stop="startEditing()"
153
+ />
154
+ </div>
155
+ </template>
156
+
157
+ <template #option="{ label, value }">
158
+ <div class="htw-flex htw-gap-2 htw-items-center">
159
+ <span
160
+ class="htw-flex-1 htw-truncate"
161
+ >{{ label }}</span>
162
+ <Icon
163
+ v-if="value !== DEFAULT_ID"
164
+ v-tooltip="'Delete this preset'"
165
+ icon="carbon:trash-can"
166
+ class="htw-flex-none htw-cursor-pointer htw-w-4 htw-h-4 hover:htw-text-primary-500 htw-opacity-50 hover:htw-opacity-100 dark:hover:htw-text-primary-400 htw-text-gray-900 dark:htw-text-gray-100"
167
+ @click.stop="deletePreset(value)"
168
+ />
169
+ </div>
170
+ </template>
171
+ </BaseSelect>
172
+ </div>
173
+ <Icon
174
+ v-tooltip="savedNotif ? 'Saved!' : canEdit ? 'Save to preset' : null"
175
+ :icon="savedNotif ? 'carbon:checkmark' : 'carbon:save'"
176
+ class="htw-cursor-pointer htw-w-4 htw-h-4 hover:htw-text-primary-500 dark:hover:htw-text-primary-400 htw-text-gray-900 dark:htw-text-gray-100"
177
+ :class="[
178
+ canEdit ? 'htw-opacity-50 hover:htw-opacity-100' : 'htw-opacity-25 htw-pointer-events-none',
179
+ ]"
180
+ @click="savePreset()"
181
+ />
182
+ <Icon
183
+ v-tooltip="'Create new preset'"
184
+ icon="carbon:add-alt"
185
+ class="htw-cursor-pointer htw-w-4 htw-h-4 hover:htw-text-primary-500 htw-opacity-50 hover:htw-opacity-100 dark:hover:htw-text-primary-400 htw-text-gray-900 dark:htw-text-gray-100"
186
+ @click="createPreset()"
187
+ />
188
+ <Icon
189
+ v-tooltip="'Reset to initial state'"
190
+ icon="carbon:reset"
191
+ class="htw-cursor-pointer htw-w-4 htw-h-4 hover:htw-text-primary-500 htw-opacity-50 hover:htw-opacity-100 dark:hover:htw-text-primary-400 htw-text-gray-900 dark:htw-text-gray-100"
192
+ @click="resetState()"
193
+ />
194
+ </div>
195
+ </template>