gooee 0.50.0 → 0.51.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 (171) hide show
  1. package/package.json +4 -2
  2. package/scripts/add.js +28 -6
  3. package/src/components/Accordion/Accordion.vue +62 -0
  4. package/src/components/Accordion/AccordionItem.vue +45 -0
  5. package/src/components/Accordion/accordionContext.ts +6 -0
  6. package/src/components/Alert/Alert.tsx +7 -27
  7. package/src/components/Alert/Alert.vue +59 -0
  8. package/src/components/AlertDialog/AlertDialog.vue +126 -0
  9. package/src/components/AnimatedNumber/AnimatedNumber.vue +36 -0
  10. package/src/components/AspectRatio/AspectRatio.vue +17 -0
  11. package/src/components/Avatar/Avatar.vue +56 -0
  12. package/src/components/AvatarGroup/AvatarGroup.vue +42 -0
  13. package/src/components/Badge/Badge.vue +32 -0
  14. package/src/components/Breadcrumb/Breadcrumb.vue +58 -0
  15. package/src/components/Button/Button.vue +130 -0
  16. package/src/components/ButtonGroup/ButtonGroup.tsx +4 -21
  17. package/src/components/ButtonGroup/ButtonGroup.vue +33 -0
  18. package/src/components/Card/Card.vue +34 -0
  19. package/src/components/Center/Center.vue +32 -0
  20. package/src/components/Checkbox/Checkbox.tsx +8 -25
  21. package/src/components/Checkbox/Checkbox.vue +108 -0
  22. package/src/components/CheckboxGroup/CheckboxGroup.vue +76 -0
  23. package/src/components/Cluster/Cluster.vue +34 -0
  24. package/src/components/CodeBlock/CodeBlock.vue +45 -0
  25. package/src/components/Collapsible/Collapsible.vue +59 -0
  26. package/src/components/Container/Container.vue +22 -0
  27. package/src/components/CopyButton/CopyButton.tsx +3 -49
  28. package/src/components/CopyButton/CopyButton.vue +116 -0
  29. package/src/components/Dial/Dial.tsx +12 -120
  30. package/src/components/Dial/Dial.vue +228 -0
  31. package/src/components/Dialog/Dialog.vue +139 -0
  32. package/src/components/Divider/Divider.vue +27 -0
  33. package/src/components/DropdownMenu/DropdownMenu.tsx +11 -46
  34. package/src/components/DropdownMenu/DropdownMenu.vue +185 -0
  35. package/src/components/EmptyState/EmptyState.vue +33 -0
  36. package/src/components/Fab/Fab.tsx +4 -14
  37. package/src/components/Fab/Fab.vue +115 -0
  38. package/src/components/Fieldset/Fieldset.vue +42 -0
  39. package/src/components/FormField/FormField.tsx +2 -17
  40. package/src/components/FormField/FormField.vue +64 -0
  41. package/src/components/Grid/Grid.vue +43 -0
  42. package/src/components/HoldToConfirm/HoldToConfirm.tsx +13 -143
  43. package/src/components/HoldToConfirm/HoldToConfirm.vue +281 -0
  44. package/src/components/IconButton/IconButton.vue +25 -0
  45. package/src/components/Input/Input.vue +112 -0
  46. package/src/components/InputGroup/InputGroup.vue +102 -0
  47. package/src/components/Kbd/Kbd.tsx +2 -12
  48. package/src/components/Kbd/Kbd.vue +21 -0
  49. package/src/components/Link/Link.vue +38 -0
  50. package/src/components/LivePill/LivePill.tsx +11 -39
  51. package/src/components/LivePill/LivePill.vue +152 -0
  52. package/src/components/Meter/Meter.vue +88 -0
  53. package/src/components/MorphButton/MorphButton.tsx +11 -67
  54. package/src/components/MorphButton/MorphButton.vue +120 -0
  55. package/src/components/NumberInput/NumberInput.tsx +11 -48
  56. package/src/components/NumberInput/NumberInput.vue +184 -0
  57. package/src/components/Pagination/Pagination.tsx +2 -15
  58. package/src/components/Pagination/Pagination.vue +87 -0
  59. package/src/components/Pagination/range.ts +15 -0
  60. package/src/components/PasswordInput/PasswordInput.vue +53 -0
  61. package/src/components/PickerWheel/DateWheel.vue +48 -0
  62. package/src/components/PickerWheel/PickerWheel.tsx +15 -129
  63. package/src/components/PickerWheel/PickerWheel.vue +77 -0
  64. package/src/components/PickerWheel/TimeWheel.vue +50 -0
  65. package/src/components/PickerWheel/WheelColumn.vue +70 -0
  66. package/src/components/Popover/Popover.vue +108 -0
  67. package/src/components/ProgressBar/ProgressBar.vue +48 -0
  68. package/src/components/Prose/Prose.vue +18 -0
  69. package/src/components/Radio/Radio.vue +49 -0
  70. package/src/components/Radio/RadioGroup.vue +69 -0
  71. package/src/components/Retime/Retime.tsx +7 -40
  72. package/src/components/Retime/Retime.vue +64 -0
  73. package/src/components/RulerScrubber/RulerScrubber.tsx +9 -38
  74. package/src/components/RulerScrubber/RulerScrubber.vue +166 -0
  75. package/src/components/ScrollArea/ScrollArea.tsx +17 -129
  76. package/src/components/ScrollArea/ScrollArea.vue +58 -0
  77. package/src/components/SearchInput/SearchInput.tsx +2 -15
  78. package/src/components/SearchInput/SearchInput.vue +70 -0
  79. package/src/components/SegmentedControl/SegmentedControl.tsx +7 -51
  80. package/src/components/SegmentedControl/SegmentedControl.vue +111 -0
  81. package/src/components/Select/Select.tsx +16 -47
  82. package/src/components/Select/Select.vue +236 -0
  83. package/src/components/Sheet/Sheet.tsx +52 -231
  84. package/src/components/Sheet/Sheet.vue +249 -0
  85. package/src/components/Skeleton/Skeleton.vue +38 -0
  86. package/src/components/Slider/Slider.tsx +25 -84
  87. package/src/components/Slider/Slider.vue +113 -0
  88. package/src/components/Spinner/Spinner.vue +30 -0
  89. package/src/components/Split/Split.vue +34 -0
  90. package/src/components/SplitFlap/SplitFlap.tsx +11 -175
  91. package/src/components/SplitFlap/SplitFlap.vue +52 -0
  92. package/src/components/Stack/Stack.vue +22 -0
  93. package/src/components/SwipeDeck/SwipeDeck.tsx +30 -194
  94. package/src/components/SwipeDeck/SwipeDeck.vue +168 -0
  95. package/src/components/Switch/Switch.tsx +6 -75
  96. package/src/components/Switch/Switch.vue +66 -0
  97. package/src/components/Table/Table.module.css +12 -3
  98. package/src/components/Table/Table.tsx +8 -59
  99. package/src/components/Table/Table.vue +274 -0
  100. package/src/components/TableOfContents/TableOfContents.vue +90 -0
  101. package/src/components/Tabs/Tab.vue +37 -0
  102. package/src/components/Tabs/TabList.vue +47 -0
  103. package/src/components/Tabs/TabPanel.vue +26 -0
  104. package/src/components/Tabs/Tabs.module.css +2 -2
  105. package/src/components/Tabs/Tabs.tsx +11 -84
  106. package/src/components/Tabs/Tabs.vue +33 -0
  107. package/src/components/Tabs/tabsContext.ts +15 -0
  108. package/src/components/Tag/Tag.tsx +6 -26
  109. package/src/components/Tag/Tag.vue +63 -0
  110. package/src/components/Textarea/Textarea.tsx +2 -22
  111. package/src/components/Textarea/Textarea.vue +120 -0
  112. package/src/components/ThemeToggle/ThemeToggle.tsx +10 -84
  113. package/src/components/ThemeToggle/ThemeToggle.vue +90 -0
  114. package/src/components/Toast/Toast.tsx +34 -264
  115. package/src/components/Toast/Toast.vue +138 -0
  116. package/src/components/Toast/ToastItem.vue +108 -0
  117. package/src/components/Toggle/Toggle.vue +52 -0
  118. package/src/components/Tooltip/Tooltip.tsx +17 -48
  119. package/src/components/Tooltip/Tooltip.vue +95 -0
  120. package/src/components/VisuallyHidden/VisuallyHidden.vue +17 -0
  121. package/src/internal/FieldMessage.vue +41 -0
  122. package/src/internal/Roll.vue +20 -0
  123. package/src/internal/focus.ts +4 -47
  124. package/src/internal/icons.module.css +39 -27
  125. package/src/internal/layers.ts +7 -61
  126. package/src/internal/motion/alert.ts +17 -0
  127. package/src/internal/motion/buttonGroup.ts +21 -0
  128. package/src/internal/motion/checkbox.ts +39 -0
  129. package/src/internal/motion/collapseOut.ts +26 -0
  130. package/src/internal/motion/copyButton.ts +48 -0
  131. package/src/internal/motion/dial.ts +137 -0
  132. package/src/internal/motion/fab.ts +14 -0
  133. package/src/internal/motion/floating.ts +58 -0
  134. package/src/internal/motion/focus.ts +53 -0
  135. package/src/internal/motion/formField.ts +19 -0
  136. package/src/internal/motion/holdToConfirm.ts +147 -0
  137. package/src/internal/motion/keys.ts +42 -0
  138. package/src/internal/motion/layers.ts +78 -0
  139. package/src/internal/motion/listbox.ts +69 -0
  140. package/src/internal/motion/livePill.ts +71 -0
  141. package/src/internal/motion/menuKeys.ts +58 -0
  142. package/src/internal/motion/morphButton.ts +71 -0
  143. package/src/internal/motion/numberInput.ts +57 -0
  144. package/src/internal/motion/pickerWheel.ts +166 -0
  145. package/src/internal/motion/retime.ts +45 -0
  146. package/src/internal/motion/ruler.ts +57 -0
  147. package/src/internal/motion/scrollArea.ts +133 -0
  148. package/src/internal/motion/scrubLook.ts +15 -0
  149. package/src/internal/motion/segmented.ts +63 -0
  150. package/src/internal/motion/sheetDetents.ts +271 -0
  151. package/src/internal/motion/slider.ts +108 -0
  152. package/src/internal/motion/splitFlap.ts +205 -0
  153. package/src/internal/motion/swipeDeck.ts +236 -0
  154. package/src/internal/motion/switchThumb.ts +83 -0
  155. package/src/internal/motion/table.ts +77 -0
  156. package/src/internal/motion/tabs.ts +105 -0
  157. package/src/internal/motion/textarea.ts +22 -0
  158. package/src/internal/motion/themeIcon.ts +91 -0
  159. package/src/internal/motion/themeReveal.ts +71 -0
  160. package/src/internal/motion/toast.ts +291 -0
  161. package/src/internal/motion/tooltip.ts +58 -0
  162. package/src/internal/themeReveal.ts +3 -61
  163. package/src/internal/useFloating.ts +9 -49
  164. package/src/internal/useScrub.ts +1 -13
  165. package/src/internal/vue/trigger.ts +18 -0
  166. package/src/internal/vue/useFloating.ts +38 -0
  167. package/src/internal/vue/usePresence.ts +21 -0
  168. package/src/internal/vue/useScrub.ts +40 -0
  169. package/src/internal/vueIcons.ts +134 -0
  170. package/src/tokens.css +5 -0
  171. package/src/internal/relativeTime.ts +0 -26
@@ -2,9 +2,8 @@
2
2
 
3
3
  import { useRef, useState, type ReactNode } from 'react'
4
4
  import { cx } from '../../internal/cx'
5
- import { focusables } from '../../internal/focus'
6
5
  import { CheckIcon, XIcon } from '../../internal/icons'
7
- import { easing, motionMs } from '../../internal/motion'
6
+ import { collapseOut, focusPast } from '../../internal/motion/collapseOut'
8
7
  import styles from './Tag.module.css'
9
8
 
10
9
  export type TagLabels = {
@@ -44,34 +43,15 @@ export function Tag({ children, onRemove, removeLabel, selected, onSelectedChang
44
43
  const [leaving, setLeaving] = useState(false)
45
44
  const selectable = selected !== undefined
46
45
 
47
- // The remove button is about to unmount, so focus moves to the next control (or the one before) instead of the body.
48
- const finish = () => {
49
- const el = ref.current
50
- if (el?.contains(document.activeElement)) {
51
- const others = focusables(document.body).filter((n) => !el.contains(n))
52
- const next = others.find((n) => el.compareDocumentPosition(n) & Node.DOCUMENT_POSITION_FOLLOWING)
53
- const prev = [...others].reverse().find((n) => el.compareDocumentPosition(n) & Node.DOCUMENT_POSITION_PRECEDING)
54
- ;(next ?? prev)?.focus({ preventScroll: true })
55
- }
56
- onRemove?.()
57
- }
58
-
59
- // Collapse first so neighbours slide in, then tell the parent
46
+ // Collapse first so neighbours slide in (motion/collapseOut.ts), then tell the parent
60
47
  const remove = () => {
61
48
  const el = ref.current
62
49
  if (!el || leaving) return
63
50
  setLeaving(true)
64
- const ms = motionMs('base')
65
- if (ms === 0 || !el.animate) return finish()
66
- const w = el.offsetWidth
67
- const anim = el.animate(
68
- [
69
- { width: `${w}px`, opacity: 1, transform: 'scale(1)' },
70
- { width: '0px', opacity: 0, transform: 'scale(0.8)', marginInlineEnd: '0px', paddingInline: '0px', borderWidth: '0px' },
71
- ],
72
- { duration: ms, easing: easing('morph'), fill: 'forwards' },
73
- )
74
- anim.onfinish = finish
51
+ collapseOut(el, () => {
52
+ focusPast(el)
53
+ onRemove?.()
54
+ })
75
55
  }
76
56
 
77
57
  const label = typeof children === 'string' ? children : labels.item
@@ -0,0 +1,63 @@
1
+ <script setup lang="ts">
2
+ import { Comment, Text, ref, type VNode } from 'vue'
3
+ import { CheckIcon, XIcon } from '../../internal/vueIcons'
4
+ import { collapseOut, focusPast } from '../../internal/motion/collapseOut'
5
+ import styles from './Tag.module.css'
6
+
7
+ // The Vue Tag: the same look (Tag.module.css) and fold-away removal as the React one.
8
+ export type TagLabels = {
9
+ /** Name of the remove button, built from the tag's text. */
10
+ remove: (name: string) => string
11
+ /** Used as the name when the tag's text is not plain text. */
12
+ item: string
13
+ }
14
+
15
+ const props = defineProps<{
16
+ /** Shows a remove button (listen with @remove). Called after the exit animation ends. */
17
+ onRemove?: () => void
18
+ /** Label for the remove button. Wins over labels.remove, which defaults to "Remove <text>". */
19
+ removeLabel?: string
20
+ /** Screen reader text, so you can translate it. Missing keys use the English defaults. */
21
+ labels?: Partial<TagLabels>
22
+ }>()
23
+
24
+ /** Makes the tag a toggle chip (aria-pressed). Use v-model:selected, or leave it out for a plain tag. */
25
+ const selected = defineModel<boolean | undefined>('selected', { default: undefined })
26
+ const slots = defineSlots<{ default?: () => VNode[]; icon?: () => unknown }>()
27
+
28
+ const root = ref<HTMLElement | null>(null)
29
+ const leaving = ref(false)
30
+
31
+ // The slot's text when it is plain text, so it can name the remove button and fill the title.
32
+ const plain = () => {
33
+ const nodes = (slots.default?.() ?? []).filter((n) => n.type !== Comment)
34
+ return nodes.length && nodes.every((n) => n.type === Text) ? nodes.map((n) => String(n.children)).join('') : undefined
35
+ }
36
+ const removeName = () => props.removeLabel ?? (props.labels?.remove ?? ((name: string) => `Remove ${name}`))(plain() ?? props.labels?.item ?? 'item')
37
+
38
+ const remove = () => {
39
+ const el = root.value
40
+ if (!el || leaving.value) return
41
+ leaving.value = true
42
+ collapseOut(el, () => {
43
+ focusPast(el)
44
+ props.onRemove?.()
45
+ })
46
+ }
47
+ </script>
48
+
49
+ <template>
50
+ <span ref="root" :class="[styles.root, selected && styles.selected]" :data-leaving="leaving || undefined">
51
+ <button v-if="selected !== undefined" type="button" :class="styles.toggle" :aria-pressed="selected" @click="selected = !selected">
52
+ <span :class="styles.check" :data-on="selected || undefined" aria-hidden="true"><CheckIcon /></span>
53
+ <span :class="styles.text" :title="plain()"><slot /></span>
54
+ </button>
55
+ <span v-else :class="styles.static">
56
+ <span v-if="slots.icon" :class="styles.icon"><slot name="icon" /></span>
57
+ <span :class="styles.text" :title="plain()"><slot /></span>
58
+ </span>
59
+ <button v-if="onRemove" type="button" :class="styles.remove" :aria-label="removeName()" @click="remove">
60
+ <XIcon />
61
+ </button>
62
+ </span>
63
+ </template>
@@ -5,6 +5,7 @@ import { cx } from '../../internal/cx'
5
5
  import { FieldMessage } from '../../internal/FieldMessage'
6
6
  import { useEdgeFlow } from '../../internal/liquidMore'
7
7
  import { mergeRefs } from '../../internal/mergeRefs'
8
+ import { growTextarea } from '../../internal/motion/textarea'
8
9
  import styles from './Textarea.module.css'
9
10
 
10
11
  export type TextareaProps = ComponentPropsWithRef<'textarea'> & {
@@ -53,28 +54,7 @@ export function Textarea({
53
54
  useEdgeFlow(inner, boxRef, ':focus', styles.edge)
54
55
  const countRef = useRef<HTMLSpanElement>(null)
55
56
 
56
- const resize = useCallback(() => {
57
- const el = inner.current
58
- if (!el) return
59
- if (countRef.current) countRef.current.textContent = `${el.value.length} / ${maxLength}`
60
- if (!autoGrow) return
61
- const cs = getComputedStyle(el)
62
- const line = parseFloat(cs.lineHeight) || 24
63
- const pad = parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom)
64
- const border = parseFloat(cs.borderTopWidth) + parseFloat(cs.borderBottomWidth)
65
- const prev = el.style.height
66
- el.style.transition = 'none'
67
- el.style.height = 'auto'
68
- const min = line * minRows + pad + border
69
- const max = line * maxRows + pad + border
70
- const next = Math.min(Math.max(el.scrollHeight + border, min), max)
71
- // Restore the old height and force layout, so the transition runs
72
- el.style.height = prev || `${next}px`
73
- void el.offsetHeight
74
- el.style.transition = ''
75
- el.style.height = `${next}px`
76
- el.style.overflowY = el.scrollHeight + border > max ? 'auto' : 'hidden'
77
- }, [autoGrow, minRows, maxRows, maxLength])
57
+ const resize = useCallback(() => growTextarea(inner.current, countRef.current, { autoGrow, minRows, maxRows, maxLength }), [autoGrow, minRows, maxRows, maxLength])
78
58
 
79
59
  useLayoutEffect(resize, [resize, value])
80
60
 
@@ -0,0 +1,120 @@
1
+ <script setup lang="ts">
2
+ import { computed, onBeforeUnmount, onMounted, ref, useAttrs, useId, watch } from 'vue'
3
+ import FieldMessage from '../../internal/FieldMessage.vue'
4
+ import { edgeFlow } from '../../internal/motion/liquidMore'
5
+ import { growTextarea } from '../../internal/motion/textarea'
6
+ import styles from './Textarea.module.css'
7
+
8
+ // The Vue Textarea: the same look (Textarea.module.css), growth and focus edge as the React one.
9
+ // Other attributes, such as name or placeholder, go to the textarea. class and style go to the root.
10
+ defineOptions({ inheritAttrs: false })
11
+
12
+ const props = withDefaults(
13
+ defineProps<{
14
+ /** Visible name of the field, also read by screen readers. */
15
+ label: string
16
+ /** Hint under the field. Hidden while an error shows. */
17
+ help?: string
18
+ /** Error message under the field. Also marks the field invalid. */
19
+ error?: string
20
+ /** Grows with the text. Default true. */
21
+ autoGrow?: boolean
22
+ /** Height in lines when empty. */
23
+ minRows?: number
24
+ /** Most lines it grows to before it scrolls. Only used with autoGrow. */
25
+ maxRows?: number
26
+ /** Shows a live "n / max" count when maxLength is set. */
27
+ showCount?: boolean
28
+ maxLength?: number
29
+ /** The starting text when there is no v-model. */
30
+ defaultValue?: string
31
+ id?: string
32
+ }>(),
33
+ { autoGrow: true, minRows: 3, maxRows: 10 },
34
+ )
35
+ /** The text. Use v-model, or leave it out and the field keeps its own text. */
36
+ const model = defineModel<string>()
37
+ const attrs = useAttrs()
38
+
39
+ const fieldAttrs = computed(() => {
40
+ const { class: _class, style: _style, 'aria-describedby': _d, ...rest } = attrs
41
+ return rest
42
+ })
43
+ const auto = useId()
44
+ const fieldId = computed(() => props.id ?? auto)
45
+ const helpId = computed(() => `${fieldId.value}-help`)
46
+ const errorId = computed(() => `${fieldId.value}-error`)
47
+ const countId = computed(() => `${fieldId.value}-count`)
48
+ const describedBy = computed(
49
+ () => [props.help && !props.error ? helpId.value : null, props.error ? errorId.value : null, props.showCount && props.maxLength ? countId.value : null, attrs['aria-describedby']].filter(Boolean).join(' ') || undefined,
50
+ )
51
+
52
+ const inner = ref<HTMLTextAreaElement | null>(null)
53
+ const box = ref<HTMLElement | null>(null)
54
+ const count = ref<HTMLElement | null>(null)
55
+ defineExpose({ field: inner })
56
+ const resize = () => growTextarea(inner.value, count.value, props)
57
+
58
+ // The text is set on the element, not bound: Vue would also write it to a value attribute, which React does not.
59
+ const show = () => {
60
+ const el = inner.value
61
+ if (!el || model.value === undefined) return
62
+ if (el.value !== model.value) el.value = model.value
63
+ if (el.defaultValue !== model.value) el.defaultValue = model.value
64
+ }
65
+ watch(model, () => {
66
+ show()
67
+ resize()
68
+ })
69
+ watch(() => [props.autoGrow, props.minRows, props.maxRows, props.maxLength], resize)
70
+
71
+ const onInput = (e: Event) => {
72
+ resize()
73
+ if (model.value !== undefined) model.value = (e.target as HTMLTextAreaElement).value
74
+ }
75
+
76
+ // Focus draws the dark edge round the field from where it was pressed (motion/liquidMore.ts).
77
+ let stopEdge = () => {}
78
+ // A native form reset changes the value without an input event.
79
+ let frame = 0
80
+ const onReset = () => {
81
+ frame = requestAnimationFrame(resize)
82
+ }
83
+ onMounted(() => {
84
+ const el = inner.value!
85
+ if (model.value !== undefined) show()
86
+ else if (props.defaultValue !== undefined) el.defaultValue = props.defaultValue
87
+ resize()
88
+ if (box.value) stopEdge = edgeFlow(el, box.value, ':focus', styles.edge)
89
+ el.form?.addEventListener('reset', onReset)
90
+ })
91
+ onBeforeUnmount(() => {
92
+ stopEdge()
93
+ inner.value?.form?.removeEventListener('reset', onReset)
94
+ cancelAnimationFrame(frame)
95
+ })
96
+ </script>
97
+
98
+ <template>
99
+ <div :class="[styles.root, attrs.class]" :style="attrs.style as string | undefined">
100
+ <div :class="styles.labelRow">
101
+ <label :for="fieldId" :class="styles.label">{{ label }}</label>
102
+ <span v-if="showCount && maxLength !== undefined" :id="countId" ref="count" :class="styles.count" aria-live="off" />
103
+ </div>
104
+ <div ref="box" :class="styles.box">
105
+ <textarea
106
+ :id="fieldId"
107
+ ref="inner"
108
+ :rows="minRows"
109
+ :class="styles.textarea"
110
+ :data-invalid="error ? true : undefined"
111
+ :aria-invalid="error ? true : undefined"
112
+ :aria-describedby="describedBy"
113
+ :maxlength="maxLength"
114
+ v-bind="fieldAttrs"
115
+ @input="onInput"
116
+ />
117
+ </div>
118
+ <FieldMessage :help-id="helpId" :error-id="errorId" :help="help" :error="error" />
119
+ </div>
120
+ </template>
@@ -1,8 +1,7 @@
1
1
  'use client'
2
2
 
3
3
  import { useEffect, useLayoutEffect, useRef, useState, type MouseEvent } from 'react'
4
- import { bezier } from '../../internal/feel'
5
- import { morphCurve, motionMs, prefersReducedMotion } from '../../internal/motion'
4
+ import { bodyAt, createThemeIcon, RAYS, raysAt } from '../../internal/motion/themeIcon'
6
5
  import { themeReveal } from '../../internal/themeReveal'
7
6
  import { IconButton } from '../IconButton'
8
7
  import styles from './ThemeToggle.module.css'
@@ -24,56 +23,7 @@ export type ThemeToggleProps = {
24
23
  className?: string
25
24
  }
26
25
 
27
- /** Put in <head>, before the page paints, so a saved dark theme never flashes light first. */
28
- export const themeScript = (storageKey = 'gooee-theme') =>
29
- `try{var t=localStorage.getItem(${JSON.stringify(storageKey)});if(t!=='light'&&t!=='dark')t=matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';document.documentElement.dataset.theme=t}catch(e){}`
30
-
31
- // Sun to moon the way the real moon works: a round disc with a shadow passing over it. The disc stays
32
- // round and grows from the sun's size to the moon's; a second circle, the bite, slides in from the top
33
- // right and carves the crescent. The outline is drawn exactly each frame as "disc minus bite", so every
34
- // frame is a true shape. The rays draw back into the disc and fade first, before it grows into them.
35
- const C = 12
36
- const lerp = (a: number, b: number, t: number) => a + (b - a) * t
37
- const part = (t: number, a: number, b: number) => Math.min(1, Math.max(0, (t - a) / (b - a)))
38
- const f = (n: number) => Math.round(n * 100) / 100
39
- const BITE = 7
40
- const TOWARD = -Math.PI / 4
41
- function bodyAt(t: number) {
42
- const r = lerp(4, 8, part(t, 0.2, 1))
43
- // The bite starts clear of the disc and ends 5.6 from its centre.
44
- const d = lerp(r + BITE + 1, 5.6, part(t, 0.15, 1))
45
- if (d >= r + BITE) return `M${C - r} ${C}A${f(r)} ${f(r)} 0 1 1 ${C + r} ${C}A${f(r)} ${f(r)} 0 1 1 ${C - r} ${C}Z`
46
- const half = Math.acos((r * r + d * d - BITE * BITE) / (2 * r * d))
47
- const at = (o: [number, number], rad: number, ang: number): [number, number] => [o[0] + rad * Math.cos(ang), o[1] + rad * Math.sin(ang)]
48
- const centre: [number, number] = [C, C]
49
- const bite = at(centre, d, TOWARD)
50
- const A = at(centre, r, TOWARD + half)
51
- const B = at(centre, r, TOWARD - half)
52
- // The disc's edge from A the long way round to B, then the bite's edge back to A through the disc.
53
- const outer = 2 * Math.PI - 2 * half
54
- // Of the two ways round the bite from B to A, the one whose middle lies inside the disc.
55
- const angA = Math.atan2(A[1] - bite[1], A[0] - bite[0])
56
- const angB = Math.atan2(B[1] - bite[1], B[0] - bite[0])
57
- const up = (((angA - angB) % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI)
58
- const mid = at(bite, BITE, angB + up / 2)
59
- const sweep = Math.hypot(mid[0] - C, mid[1] - C) < r ? 1 : 0
60
- const inner = sweep ? up : 2 * Math.PI - up
61
- return `M${f(A[0])} ${f(A[1])}A${f(r)} ${f(r)} 0 ${outer > Math.PI ? 1 : 0} 1 ${f(B[0])} ${f(B[1])}A${BITE} ${BITE} 0 ${inner > Math.PI ? 1 : 0} ${sweep} ${f(A[0])} ${f(A[1])}Z`
62
- }
63
- const RAYS = Array.from({ length: 8 }, (_, i) => {
64
- const a = (i * Math.PI) / 4
65
- return `M${f(C + 7 * Math.cos(a))} ${f(C + 7 * Math.sin(a))}L${f(C + 9.5 * Math.cos(a))} ${f(C + 9.5 * Math.sin(a))}`
66
- }).join('')
67
- // The rays draw in toward the disc, turn a little and fade, all within the first 40%.
68
- const raysAt = (t: number) => {
69
- const k = part(t, 0, 0.4)
70
- return { transform: `rotate(${f(-30 * k)}deg) scale(${f(1 - 0.45 * k)})`, opacity: String(f(1 - k)) }
71
- }
72
- function draw(body: SVGPathElement, t: number) {
73
- body.setAttribute('d', bodyAt(t))
74
- const rays = body.nextElementSibling as SVGPathElement | null
75
- if (rays) Object.assign(rays.style, raysAt(t))
76
- }
26
+ export { themeScript } from '../../internal/motion/themeReveal'
77
27
 
78
28
  const pageTheme = (): Theme => (document.documentElement.dataset.theme === 'dark' ? 'dark' : 'light')
79
29
 
@@ -89,42 +39,18 @@ export function ThemeToggle({ theme: themeProp, onThemeChange, storageKey = 'goo
89
39
  }, [controlled])
90
40
 
91
41
  const next: Theme = theme === 'dark' ? 'light' : 'dark'
92
- // Shows the theme the button switches to: the moon in light, the sun in dark. The body morphs on the
93
- // morph curve, in the reveal's time, so the icon and the circle end together; the rays are drawn on
94
- // the same frames.
42
+ // Shows the theme the button switches to: the moon in light, the sun in dark (motion/themeIcon.ts).
95
43
  const body = useRef<SVGPathElement>(null)
96
- const shown = useRef(theme === 'dark' ? 0 : 1)
97
- const aim = useRef(shown.current)
98
- const raf = useRef(0)
99
- const morphTo = (to: number) => {
100
- const el = body.current
101
- aim.current = to
102
- cancelAnimationFrame(raf.current)
103
- if (!el) return
104
- const from = shown.current
105
- const length = motionMs('reveal')
106
- if (from === to || !length || prefersReducedMotion()) {
107
- shown.current = to
108
- draw(el, to)
109
- return
110
- }
111
- const ease = bezier(morphCurve())
112
- const t0 = performance.now()
113
- const step = (now: number) => {
114
- const u = Math.min(1, (now - t0) / length)
115
- shown.current = from + (to - from) * ease(u)
116
- draw(el, shown.current)
117
- if (u < 1) raf.current = requestAnimationFrame(step)
118
- }
119
- raf.current = requestAnimationFrame(step)
120
- }
44
+ const icon = useRef<ReturnType<typeof createThemeIcon>>(null)
45
+ icon.current ??= createThemeIcon(() => body.current, theme === 'dark' ? 0 : 1)
46
+ const morphTo = icon.current.morphTo
121
47
  // A theme set from outside (or the first paint): morph to it, unless a press already started that morph.
122
48
  useLayoutEffect(() => {
123
49
  const to = theme === 'dark' ? 0 : 1
124
- if (aim.current !== to) morphTo(to)
50
+ if (icon.current!.aim !== to) morphTo(to)
125
51
  // eslint-disable-next-line react-hooks/exhaustive-deps
126
52
  }, [theme])
127
- useLayoutEffect(() => () => cancelAnimationFrame(raf.current), [])
53
+ useLayoutEffect(() => () => icon.current!.destroy(), [])
128
54
  // The icon answers the press at once; the theme change, and its circle, start two frames later, so
129
55
  // the first motion is on screen before the page is held still to be photographed.
130
56
  const flip = (e: MouseEvent<HTMLButtonElement>) => {
@@ -159,8 +85,8 @@ export function ThemeToggle({ theme: themeProp, onThemeChange, storageKey = 'goo
159
85
  onClick={flip}
160
86
  icon={
161
87
  <svg className={styles.icon} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.75} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
162
- <path ref={body} d={bodyAt(shown.current)} />
163
- <path className={styles.rays} d={RAYS} style={raysAt(shown.current)} />
88
+ <path ref={body} d={bodyAt(icon.current.shown)} />
89
+ <path className={styles.rays} d={RAYS} style={raysAt(icon.current.shown)} />
164
90
  </svg>
165
91
  }
166
92
  />
@@ -0,0 +1,90 @@
1
+ <script setup lang="ts">
2
+ import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
3
+ import { bodyAt, createThemeIcon, RAYS, raysAt } from '../../internal/motion/themeIcon'
4
+ import { themeReveal } from '../../internal/motion/themeReveal'
5
+ import IconButton from '../IconButton/IconButton.vue'
6
+ import styles from './ThemeToggle.module.css'
7
+
8
+ export type Theme = 'light' | 'dark'
9
+
10
+ // The Vue ThemeToggle: the same button, icon morph and circle reveal as the React one. themeScript, for
11
+ // <head>, is in internal/motion/themeReveal.ts.
12
+ const props = withDefaults(
13
+ defineProps<{
14
+ /** The theme, with v-model:theme. Leave it out and the toggle sets data-theme on <html> itself. */
15
+ theme?: Theme
16
+ /** Where the choice is remembered when the toggle runs the page. Match it in themeScript. */
17
+ storageKey?: string
18
+ /** The new theme grows from the button in a circle over the screen. Turn it off for an instant change. */
19
+ reveal?: boolean
20
+ /** The button's size, the same as IconButton. */
21
+ size?: 'sm' | 'md' | 'lg'
22
+ }>(),
23
+ { theme: undefined, storageKey: 'gooee-theme', reveal: true, size: 'sm' },
24
+ )
25
+ /** update:theme: the new theme on every flip. */
26
+ const emit = defineEmits<{ 'update:theme': [theme: Theme] }>()
27
+
28
+ const controlled = computed(() => props.theme !== undefined)
29
+ const own = ref<Theme>('light')
30
+ const theme = computed(() => props.theme ?? own.value)
31
+ const next = computed<Theme>(() => (theme.value === 'dark' ? 'light' : 'dark'))
32
+
33
+ // Read after mount: the server cannot know the page's theme, and themeScript has already set it.
34
+ onMounted(() => {
35
+ if (!controlled.value) own.value = document.documentElement.dataset.theme === 'dark' ? 'dark' : 'light'
36
+ })
37
+
38
+ // Shows the theme the button switches to: the moon in light, the sun in dark (motion/themeIcon.ts).
39
+ const body = ref<SVGPathElement | null>(null)
40
+ const icon = createThemeIcon(() => body.value, theme.value === 'dark' ? 0 : 1)
41
+ // A theme set from outside (or the first paint): morph to it, unless a press already started that morph.
42
+ watch(
43
+ theme,
44
+ (t) => {
45
+ const to = t === 'dark' ? 0 : 1
46
+ if (icon.aim !== to) icon.morphTo(to)
47
+ },
48
+ { flush: 'post' },
49
+ )
50
+ onBeforeUnmount(icon.destroy)
51
+
52
+ // The theme is in the page once Vue has drawn it, so the view transition photographs the new page.
53
+ const apply = async () => {
54
+ const to = next.value
55
+ if (!controlled.value) {
56
+ document.documentElement.dataset.theme = to
57
+ try {
58
+ localStorage.setItem(props.storageKey, to)
59
+ } catch {
60
+ // Not saved, so it lasts only this visit; the theme still changes.
61
+ }
62
+ own.value = to
63
+ }
64
+ emit('update:theme', to)
65
+ await nextTick()
66
+ }
67
+ // The icon answers the press at once; the theme change, and its circle, start two frames later, so
68
+ // the first motion is on screen before the page is held still to be photographed.
69
+ const flip = (e: MouseEvent) => {
70
+ const origin = e.currentTarget as Element
71
+ icon.morphTo(next.value === 'dark' ? 0 : 1)
72
+ requestAnimationFrame(() =>
73
+ requestAnimationFrame(() => {
74
+ if (props.reveal) themeReveal(origin, apply)
75
+ else void apply()
76
+ }),
77
+ )
78
+ }
79
+ </script>
80
+
81
+ <template>
82
+ <IconButton :label="`Switch to ${next} theme`" variant="secondary" :size="size" @click="flip">
83
+ <template #icon>
84
+ <svg :class="styles.icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
85
+ <path ref="body" :d="bodyAt(icon.shown)" />
86
+ <path :class="styles.rays" :d="RAYS" :style="raysAt(icon.shown)" />
87
+ </svg>
88
+ </template>
89
+ </IconButton>
90
+ </template>