@m3ui-vue/m3ui-vue 1.2.0 → 1.2.2

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 (58) hide show
  1. package/dist/API.md +152 -11
  2. package/dist/{MMenuItem-DI351kIf.js → MMenuItem-D4Gx_l3F.js} +2 -2
  3. package/dist/{MMenuItem-DI351kIf.js.map → MMenuItem-D4Gx_l3F.js.map} +1 -1
  4. package/dist/{MSlider-BnEy5ieZ.js → MSlider-Dx_S3vJ9.js} +227 -221
  5. package/dist/{MSlider-BnEy5ieZ.js.map → MSlider-Dx_S3vJ9.js.map} +1 -1
  6. package/dist/{MTextField-BBmkaIbO.js → MTextField-Bz8JIsnl.js} +4 -4
  7. package/dist/{MTextField-BBmkaIbO.js.map → MTextField-Bz8JIsnl.js.map} +1 -1
  8. package/dist/api.json +1 -1
  9. package/dist/chart.js +1 -1
  10. package/dist/components/MMap.vue.d.ts +1 -1
  11. package/dist/components/MSlider.vue.d.ts +2 -2
  12. package/dist/composables/_effectCanvas.d.ts +23 -0
  13. package/dist/composables/_storageKeys.d.ts +9 -0
  14. package/dist/composables/themeInitScript.d.ts +2 -0
  15. package/dist/composables/useConfetti.d.ts +19 -8
  16. package/dist/composables/useFireworks.d.ts +37 -0
  17. package/dist/composables/useReactions.d.ts +32 -0
  18. package/dist/composables/viewportHints.d.ts +2 -0
  19. package/dist/directives/vSparkle.d.ts +27 -0
  20. package/dist/index.d.ts +7 -1
  21. package/dist/m3ui.js +5404 -5023
  22. package/dist/m3ui.js.map +1 -1
  23. package/dist/map.js +572 -572
  24. package/dist/map.js.map +1 -1
  25. package/dist/plugin.d.ts +10 -0
  26. package/dist/rich-text-editor.js +2 -2
  27. package/dist/{useThemeTokens-Bv-Uv8eX.js → useThemeTokens-y0HZpyhL.js} +23 -8
  28. package/dist/useThemeTokens-y0HZpyhL.js.map +1 -0
  29. package/package.json +1 -1
  30. package/src/__tests__/MSegmentedButton.test.ts +10 -0
  31. package/src/__tests__/MSlider.test.ts +36 -0
  32. package/src/__tests__/plugin.test.ts +56 -1
  33. package/src/__tests__/ssr.test.ts +1 -1
  34. package/src/__tests__/themeInitScript.test.ts +10 -0
  35. package/src/__tests__/useConfetti.test.ts +33 -2
  36. package/src/__tests__/useFireworks.test.ts +104 -0
  37. package/src/__tests__/useReactions.test.ts +51 -0
  38. package/src/__tests__/vSparkle.test.ts +83 -0
  39. package/src/components/MEmojiSelector.vue +3 -2
  40. package/src/components/MMap.vue +3 -2
  41. package/src/components/MSegmentedButton.vue +1 -1
  42. package/src/components/MSlider.vue +22 -4
  43. package/src/components/MTextField.vue +8 -4
  44. package/src/composables/_colorUtils.ts +4 -2
  45. package/src/composables/_effectCanvas.ts +109 -0
  46. package/src/composables/_ssrState.ts +2 -2
  47. package/src/composables/_storageKeys.ts +28 -0
  48. package/src/composables/themeInitScript.ts +5 -2
  49. package/src/composables/useColorPalette.ts +36 -8
  50. package/src/composables/useConfetti.ts +84 -107
  51. package/src/composables/useFireworks.ts +360 -0
  52. package/src/composables/useReactions.ts +131 -0
  53. package/src/composables/useTheme.ts +21 -4
  54. package/src/composables/viewportHints.ts +6 -5
  55. package/src/directives/vSparkle.ts +180 -0
  56. package/src/index.ts +7 -1
  57. package/src/plugin.ts +21 -5
  58. package/dist/useThemeTokens-Bv-Uv8eX.js.map +0 -1
@@ -0,0 +1,180 @@
1
+ import type { Directive } from 'vue'
2
+ import { getShape, toSvgPath, type ShapeName } from 'shape-morph'
3
+
4
+ /** Options for `v-sparkle`. */
5
+ export interface SparkleOptions {
6
+ /** No sparkles while true */
7
+ disabled?: boolean
8
+ /** `'always'` (default) sparkles all the time; `'hover'` only while the pointer is over it or focus is in it */
9
+ trigger?: 'always' | 'hover'
10
+ /** Any CSS colors, one picked per sparkle. Default: the theme's primary and tertiary where the element is */
11
+ color?: string | string[]
12
+ /** Sparkle size in px, each one a bit bigger or smaller (default 14) */
13
+ size?: number
14
+ /** Sparkles per second (default 3) */
15
+ rate?: number
16
+ /** MShape's shapes instead of the four-pointed star */
17
+ shapes?: ShapeName[]
18
+ }
19
+
20
+ /** `v-sparkle` value: nothing or `true` (on), `false` (off), `'hover'`, a CSS color, or an options object. */
21
+ export type SparkleValue = boolean | string | SparkleOptions | null | undefined
22
+
23
+ function normalize(value: SparkleValue): SparkleOptions {
24
+ if (value === false) return { disabled: true }
25
+ if (value === 'hover' || value === 'always') return { trigger: value }
26
+ if (typeof value === 'string') return { color: value }
27
+ if (value === true || value == null) return {}
28
+ return value
29
+ }
30
+
31
+ // The classic four-pointed sparkle, in a 100×100 box like MShape's paths
32
+ const STAR = 'M50 0C54 34 66 46 100 50C66 54 54 66 50 100C46 66 34 54 0 50C34 46 46 34 50 0Z'
33
+ const SVG_NS = 'http://www.w3.org/2000/svg'
34
+ const paths = new Map<string, string>()
35
+ function pathFor(shape: ShapeName) {
36
+ let d = paths.get(shape)
37
+ if (!d) paths.set(shape, (d = toSvgPath(getShape(shape), 100)))
38
+ return d
39
+ }
40
+
41
+ interface SparkleState {
42
+ options: SparkleOptions
43
+ layer: HTMLElement | null
44
+ timer: ReturnType<typeof setTimeout> | undefined
45
+ hovering: boolean
46
+ visible: boolean
47
+ observer: IntersectionObserver | null
48
+ on: Record<string, () => void>
49
+ }
50
+
51
+ const states = new WeakMap<HTMLElement, SparkleState>()
52
+
53
+ function spawn(el: HTMLElement, state: SparkleState) {
54
+ if (!state.layer) {
55
+ const { position } = getComputedStyle(el)
56
+ if (!position || position === 'static') el.style.position = 'relative'
57
+ const layer = document.createElement('span')
58
+ layer.className = 'm3-sparkle-layer'
59
+ layer.setAttribute('aria-hidden', 'true')
60
+ layer.style.cssText = 'position:absolute;inset:0;pointer-events:none;overflow:visible;z-index:1'
61
+ el.appendChild(layer)
62
+ state.layer = layer
63
+ }
64
+ const { options } = state
65
+ const colors = options.color ? [options.color].flat() : ['var(--color-primary)', 'var(--color-tertiary)']
66
+ const size = (options.size ?? 14) * (0.6 + Math.random() * 0.8)
67
+ const svg = document.createElementNS(SVG_NS, 'svg')
68
+ svg.setAttribute('viewBox', '0 0 100 100')
69
+ svg.setAttribute('width', `${size}`)
70
+ svg.setAttribute('height', `${size}`)
71
+ // Anywhere over the element, a little past its edges
72
+ svg.style.cssText = `position:absolute;left:${-10 + Math.random() * 120}%;top:${-15 + Math.random() * 130}%;margin:${-size / 2}px 0 0 ${-size / 2}px;overflow:visible`
73
+ const path = document.createElementNS(SVG_NS, 'path')
74
+ const shapes = options.shapes
75
+ path.setAttribute('d', shapes?.length ? pathFor(shapes[Math.floor(Math.random() * shapes.length)]!) : STAR)
76
+ path.style.fill = colors[Math.floor(Math.random() * colors.length)]!
77
+ svg.appendChild(path)
78
+ state.layer.appendChild(svg)
79
+ const turn = (Math.random() < 0.5 ? -1 : 1) * (60 + Math.random() * 60)
80
+ const anim = svg.animate(
81
+ [
82
+ { transform: 'scale(0) rotate(0deg)' },
83
+ { transform: `scale(1) rotate(${turn / 2}deg)`, offset: 0.45 },
84
+ { transform: `scale(0) rotate(${turn}deg)` },
85
+ ],
86
+ { duration: 700 + Math.random() * 300, easing: 'ease-in-out', fill: 'both' },
87
+ )
88
+ const remove = () => svg.remove()
89
+ anim.addEventListener('finish', remove, { once: true })
90
+ anim.addEventListener('cancel', remove, { once: true })
91
+ }
92
+
93
+ function active(state: SparkleState) {
94
+ const { options } = state
95
+ if (options.disabled || !state.visible) return false
96
+ if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return false
97
+ return options.trigger === 'hover' ? state.hovering : true
98
+ }
99
+
100
+ // One sparkle at a time at random intervals around 1/rate, while active
101
+ function schedule(el: HTMLElement, state: SparkleState, now = false) {
102
+ clearTimeout(state.timer)
103
+ state.timer = undefined
104
+ if (!active(state)) return
105
+ if (now) spawn(el, state)
106
+ const every = 1000 / Math.max(0.1, state.options.rate ?? 3)
107
+ state.timer = setTimeout(() => {
108
+ // A hidden tab keeps the timer (throttled) but draws nothing
109
+ if (active(state) && !document.hidden) spawn(el, state)
110
+ schedule(el, state)
111
+ }, every * (0.5 + Math.random()))
112
+ }
113
+
114
+ function stop(state: SparkleState) {
115
+ clearTimeout(state.timer)
116
+ state.timer = undefined
117
+ }
118
+
119
+ /**
120
+ * Sparkles that twinkle over an element, to draw the eye to something new or special: `v-sparkle`,
121
+ * `v-sparkle="'hover'"`, `v-sparkle="'#f5b400'"` or `v-sparkle="{ trigger, color, size, rate, shapes, disabled }"`.
122
+ * They're drawn in a layer over the element (a statically positioned one is made `position: relative`), hidden from
123
+ * assistive technology, and pause while it's off screen or the tab is hidden; none under reduced motion.
124
+ * Registered globally as `v-sparkle` by `createM3UI()`; import `vSparkle` to use it without the plugin.
125
+ */
126
+ export const vSparkle: Directive<HTMLElement, SparkleValue> = {
127
+ mounted(el, binding) {
128
+ const state: SparkleState = {
129
+ options: normalize(binding.value),
130
+ layer: null,
131
+ timer: undefined,
132
+ hovering: false,
133
+ visible: true,
134
+ observer: null,
135
+ on: {},
136
+ }
137
+ const hover = (value: boolean) => () => {
138
+ state.hovering = value
139
+ if (value) schedule(el, state, true)
140
+ else if (!active(state)) stop(state)
141
+ }
142
+ state.on = {
143
+ pointerenter: hover(true),
144
+ pointerleave: hover(false),
145
+ focusin: hover(true),
146
+ focusout: hover(false),
147
+ }
148
+ for (const [type, fn] of Object.entries(state.on)) el.addEventListener(type, fn)
149
+ if (typeof IntersectionObserver !== 'undefined') {
150
+ state.observer = new IntersectionObserver(([entry]) => {
151
+ state.visible = !!entry?.isIntersecting
152
+ if (state.visible) schedule(el, state)
153
+ else stop(state)
154
+ })
155
+ state.observer.observe(el)
156
+ }
157
+ states.set(el, state)
158
+ schedule(el, state)
159
+ },
160
+ updated(el, binding) {
161
+ const state = states.get(el)
162
+ if (!state) return
163
+ const next = normalize(binding.value)
164
+ // An inline object literal is a new object on every render: only a real change reschedules
165
+ if (JSON.stringify(next) === JSON.stringify(state.options)) return
166
+ state.options = next
167
+ schedule(el, state)
168
+ },
169
+ beforeUnmount(el) {
170
+ const state = states.get(el)
171
+ if (!state) return
172
+ stop(state)
173
+ state.observer?.disconnect()
174
+ for (const [type, fn] of Object.entries(state.on)) el.removeEventListener(type, fn)
175
+ state.layer?.remove()
176
+ states.delete(el)
177
+ },
178
+ // Nothing on the server: the sparkles start once mounted in the browser
179
+ getSSRProps: () => ({}),
180
+ }
package/src/index.ts CHANGED
@@ -8,7 +8,11 @@ export { useTheme } from './composables/useTheme'
8
8
  export type { Theme } from './composables/useTheme'
9
9
  export { useColorPalette, palettes } from './composables/useColorPalette'
10
10
  export { useConfetti, fireConfetti } from './composables/useConfetti'
11
- export type { ConfettiOptions, ConfettiOrigin } from './composables/useConfetti'
11
+ export type { ConfettiOptions, ConfettiOrigin, StopConfetti } from './composables/useConfetti'
12
+ export { useFireworks, launchFireworks } from './composables/useFireworks'
13
+ export type { FireworkShape, FireworksOptions, StopFireworks } from './composables/useFireworks'
14
+ export { useReactions, fireReaction } from './composables/useReactions'
15
+ export type { ReactionContent, ReactionOptions, ReactionOrigin } from './composables/useReactions'
12
16
  export { useContainerTransform } from './composables/useContainerTransform'
13
17
  export type { ContainerTransformController, ContainerTransformOrigin } from './composables/useContainerTransform'
14
18
  export type { Palette, PaletteId, ActiveSeed, ContrastLevel } from './composables/useColorPalette'
@@ -62,6 +66,8 @@ export { vClickOutside } from './directives/vClickOutside'
62
66
  export type { ClickOutsideOptions, ClickOutsideValue } from './directives/vClickOutside'
63
67
  export { vSkeleton } from './directives/vSkeleton'
64
68
  export type { SkeletonOptions, SkeletonValue } from './directives/vSkeleton'
69
+ export { vSparkle } from './directives/vSparkle'
70
+ export type { SparkleOptions, SparkleValue } from './directives/vSparkle'
65
71
 
66
72
  // Components
67
73
  export { default as MAbsolute } from './components/MAbsolute.vue'
package/src/plugin.ts CHANGED
@@ -16,9 +16,10 @@ import { vLongPress } from './directives/vLongPress'
16
16
  import { vSwipe } from './directives/vSwipe'
17
17
  import { vClickOutside } from './directives/vClickOutside'
18
18
  import { vSkeleton } from './directives/vSkeleton'
19
+ import { vSparkle } from './directives/vSparkle'
19
20
  import { M3_HYDRATING_KEY } from './composables/_hydration'
20
21
  import { M3_INITIAL_STATE_KEY, enableCookies, readCookie, trackViewport, writeCookie, type M3InitialState, type ResolvedInitialState } from './composables/_ssrState'
21
- import { THEME_KEY } from './composables/_storageKeys'
22
+ import { THEME_KEY, setStoragePrefix, storageKey } from './composables/_storageKeys'
22
23
  import type { Theme } from './composables/useTheme'
23
24
  import { CONTRAST_KEY, PALETTE_KEY, SEED_PALETTE } from './composables/useColorPalette'
24
25
 
@@ -77,6 +78,14 @@ export interface M3UIOptions {
77
78
  * and render with the user's choice and for their screen through `initialState`.
78
79
  */
79
80
  cookies?: boolean
81
+ /**
82
+ * A prefix for every key the library stores in localStorage and cookies (`'admin'` → `admin-m3-theme`,
83
+ * `admin-m3-palette`…), so apps served from the same origin under different paths (`example.com/admin`,
84
+ * `example.com/shop`) each keep their own theme, palette, contrast and recent colors/emoji instead of sharing them.
85
+ * Letters, digits, `-` and `_` (it's also part of the cookie names). Pass the same one to `themeInitScript()` and
86
+ * `viewportFromHeaders()` when you use them.
87
+ */
88
+ storagePrefix?: string
80
89
  /**
81
90
  * Server-side rendering: the user's theme, palette and contrast as the server knows them (from the cookies that
82
91
  * `cookies` writes), on the server and on the client alike. `useTheme()` and `useColorPalette()` report them on
@@ -88,6 +97,10 @@ export interface M3UIOptions {
88
97
  initialState?: M3InitialState
89
98
  }
90
99
 
100
+ function readStored(key: string): string | null {
101
+ try { return localStorage.getItem(storageKey(key)) } catch { return null }
102
+ }
103
+
91
104
  const THEMES: readonly Theme[] = ['light', 'dark', 'system']
92
105
  const CONTRASTS: readonly string[] = ['standard', 'medium', 'high', 'system']
93
106
 
@@ -121,6 +134,9 @@ export function createM3UI(options: M3UIOptions = {}) {
121
134
  app.directive('swipe', vSwipe)
122
135
  app.directive('click-outside', vClickOutside)
123
136
  app.directive('skeleton', vSkeleton)
137
+ app.directive('sparkle', vSparkle)
138
+ // First: the stored choices below (and those the modules read when they loaded) are this app's own
139
+ if (typeof window !== 'undefined') setStoragePrefix(options.storagePrefix ?? '')
124
140
  if (options.isHydrating) app.provide(M3_HYDRATING_KEY, options.isHydrating)
125
141
  if (options.initialState) app.provide(M3_INITIAL_STATE_KEY, resolveInitialState(options))
126
142
  if (options.cookies && typeof window !== 'undefined') enableCookies()
@@ -135,7 +151,7 @@ export function createM3UI(options: M3UIOptions = {}) {
135
151
  if (options.persistPalette === false) {
136
152
  if (options.palette) __forcePalette(options.palette, false)
137
153
  else if (options.seed) void __defaultSeed(options.seed, options.seedOptions, false)
138
- } else if (!localStorage.getItem('m3-palette') && !readCookie('m3-palette')) {
154
+ } else if (!readStored(PALETTE_KEY) && !readCookie(storageKey(PALETTE_KEY))) {
139
155
  // `palette`/`seed` are only the first-visit default — once the user picks a palette via
140
156
  // `useColorPalette().set()` (or a seed via `setSeed()`) it's persisted to localStorage, and that choice
141
157
  // must win on every later boot instead of being clobbered back to the plugin's static default.
@@ -148,9 +164,8 @@ export function createM3UI(options: M3UIOptions = {}) {
148
164
  // without a stored value (cleared storage, or set by a server) stays
149
165
  if (options.cookies) {
150
166
  for (const key of [THEME_KEY, PALETTE_KEY, CONTRAST_KEY]) {
151
- let value: string | null = null
152
- try { value = localStorage.getItem(key) } catch { /* storage blocked */ }
153
- if (value != null) writeCookie(key, value)
167
+ const value = readStored(key)
168
+ if (value != null) writeCookie(storageKey(key), value)
154
169
  }
155
170
  trackViewport()
156
171
  }
@@ -176,5 +191,6 @@ declare module 'vue' {
176
191
  vSwipe: typeof vSwipe
177
192
  vClickOutside: typeof vClickOutside
178
193
  vSkeleton: typeof vSkeleton
194
+ vSparkle: typeof vSparkle
179
195
  }
180
196
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"useThemeTokens-Bv-Uv8eX.js","names":[],"sources":["../src/composables/_themeTransition.ts","../src/composables/_storageKeys.ts","../src/composables/useThemeTokens.ts"],"sourcesContent":["// Internal: animates a theme change (dark mode, palette, contrast).\n//\n// Firefox (and any browser without @property) transitions six color properties on every element\n// (`.theme-transitioning` in theme.css): smooth there, but in Chromium it recalculates every element's transitions\n// each frame and stutters. Chromium and WebKit instead transition the color tokens themselves, once, on <html>:\n// registered as <color> with @property they interpolate, and every element follows them through var(). Components'\n// own color transitions (transition-colors) are turned off meanwhile, or they would restart on every frame of the\n// token's change and trail behind the rest (the navbar and buttons did). A view transition was tried first: it\n// cross-fades two snapshots, which looks washed out midway compared to the colors moving.\n\n// The tokens of theme.css, palettes.css and generated palettes\nconst COLOR_TOKENS = [\n 'background', 'on-background', 'surface', 'surface-dim', 'surface-bright', 'surface-variant', 'on-surface',\n 'on-surface-variant', 'surface-container-lowest', 'surface-container-low', 'surface-container',\n 'surface-container-high', 'surface-container-highest', 'inverse-surface', 'inverse-on-surface', 'inverse-primary',\n 'outline', 'outline-variant', 'shadow', 'scrim',\n ...['primary', 'secondary', 'tertiary', 'error', 'success'].flatMap((c) => [c, `on-${c}`, `${c}-container`, `on-${c}-container`]),\n ...['primary', 'secondary', 'tertiary'].flatMap((c) => [`${c}-fixed`, `${c}-fixed-dim`, `on-${c}-fixed`, `on-${c}-fixed-variant`]),\n].map((t) => `--color-${t}`)\n\nconst DURATION = 250\n/** How long a theme switch's color transition takes, in ms (both paths) */\nexport const THEME_TRANSITION_MS = DURATION\nconst STYLE_ID = 'm3-theme-transition'\n\n// Injected only while switching: a registered <color> computes to rgb(), and code reading a token with\n// getPropertyValue() expects it as written\nconst css = COLOR_TOKENS.map((t) => `@property ${t} { syntax: '<color>'; inherits: true; initial-value: transparent; }`).join('\\n')\n + `\\nhtml.theme-switching { transition: ${COLOR_TOKENS.map((t) => `${t} ${DURATION}ms ease`).join(', ')}; }`\n + '\\nhtml.theme-switching *, html.theme-switching *::before, html.theme-switching *::after { transition: none !important; }'\n\n// Gecko: a CSS feature only it has, or its user agent (\"Gecko/<version>\" or \"Firefox/\"; Chromium and WebKit only\n// say \"like Gecko\", and Firefox on iOS is WebKit and says \"FxiOS\")\nconst isGecko = () =>\n (typeof CSS !== 'undefined' && !!CSS.supports?.('-moz-appearance', 'none'))\n || (typeof navigator !== 'undefined' && /\\bGecko\\/\\d|\\bFirefox\\//.test(navigator.userAgent))\nconst hasProperty = () => typeof CSS !== 'undefined' && typeof CSS.registerProperty === 'function'\n\nlet timer: ReturnType<typeof setTimeout> | undefined\n\n/** Runs `apply` (the DOM writes of a theme change) with the theme transition. */\nexport function themeTransition(apply: () => void) {\n if (typeof document === 'undefined') return apply()\n const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches\n if (reduced) return apply()\n const root = document.documentElement\n\n if (!isGecko() && hasProperty()) {\n if (!document.getElementById(STYLE_ID)) {\n const style = document.createElement('style')\n style.id = STYLE_ID\n style.textContent = css\n document.head.appendChild(style)\n }\n root.classList.add('theme-switching')\n // Style flush: the tokens' current values are computed as registered colors and the transition is in place\n // before they change\n void root.offsetHeight\n apply()\n clearTimeout(timer)\n timer = setTimeout(() => {\n root.classList.remove('theme-switching')\n document.getElementById(STYLE_ID)?.remove()\n }, DURATION + 50)\n return\n }\n\n root.classList.add('theme-transitioning')\n // Force a style flush so the transition is in place before the colors change\n void root.offsetHeight\n apply()\n setTimeout(() => root.classList.remove('theme-transitioning'), 300)\n}\n","// Storage keys shared with modules that must not load useTheme (it applies the theme to <html> when it loads)\nexport const THEME_KEY = 'm3-theme'\n// The <style> useColorPalette writes a generated palette's CSS into\nexport const STYLE_ID = 'm3-dynamic-palette'\n// The window's size, a cookie only (createM3UI({ cookies: true })): `<width>x<height>`\nexport const VIEWPORT_KEY = 'm3-viewport'\n","import { onBeforeUnmount, onMounted, ref, type Ref } from 'vue'\nimport { STYLE_ID } from './_storageKeys'\nimport { THEME_TRANSITION_MS } from './_themeTransition'\nimport { cubicBezier } from './motion'\n\nexport interface ThemeTokensOptions {\n /**\n * Updates every animation frame while the theme switch's colors fade, so a canvas redrawn on change fades with\n * the page instead of jumping to the new colors. Off by default: what animates color changes itself (Chart.js,\n * MChart, maps) only needs the final values, and would otherwise redraw ~15 times per switch.\n */\n live?: boolean\n}\n\n// The CSS `ease` the switch uses (_themeTransition.ts, and `.theme-transitioning` in theme.css)\nconst ease = cubicBezier(0.25, 0.1, 0.25, 1)\n\ntype Rgba = [number, number, number, number]\n\n// Hex (#rgb, #rgba, #rrggbb, #rrggbbaa) or rgb()/rgba(), the forms tokens are written in or computed to; null for\n// anything else (that token then switches at once)\nfunction parseColor(value: string): Rgba | null {\n const v = value.trim()\n const hex = /^#([0-9a-f]{3,8})$/i.exec(v)?.[1]\n if (hex && hex.length !== 5 && hex.length !== 7) {\n const full = hex.length <= 4 ? [...hex].map((c) => c + c).join('') : hex\n const n = (i: number) => parseInt(full.slice(i, i + 2), 16)\n return [n(0), n(2), n(4), full.length === 8 ? n(6) / 255 : 1]\n }\n const fn = /^rgba?\\(([^)]+)\\)$/i.exec(v)?.[1]\n if (!fn) return null\n const parts = fn.split(/[\\s,/]+/).filter(Boolean)\n if (parts.length < 3) return null\n const channel = (p: string) => (p.endsWith('%') ? parseFloat(p) * 2.55 : parseFloat(p))\n const alpha = parts[3] == null ? 1 : parts[3].endsWith('%') ? parseFloat(parts[3]) / 100 : parseFloat(parts[3])\n const rgba = [channel(parts[0]!), channel(parts[1]!), channel(parts[2]!), alpha] as Rgba\n return rgba.every(Number.isFinite) ? rgba : null\n}\n\nfunction mix(from: string, to: string, t: number): string {\n const a = parseColor(from)\n const b = parseColor(to)\n if (!a || !b) return t < 1 ? from : to\n const [r, g, bl, al] = a.map((x, i) => x + (b[i]! - x) * t)\n return `rgba(${Math.round(r!)}, ${Math.round(g!)}, ${Math.round(bl!)}, ${+al!.toFixed(3)})`\n}\n\n/**\n * The current values of some color tokens (`['primary', 'surface']` → `--color-primary`…), kept up to date across\n * light/dark, palette, contrast and generated (seed) palette changes: for what can't use CSS variables, like a\n * Chart.js dataset, a canvas or a MapLibre layer's paint. Values settle after the theme switch's color transition;\n * with `{ live: true }` they also follow it frame by frame (as `rgba()` midway). Empty strings on the server.\n *\n * ```ts\n * const colors = useThemeTokens(['primary', 'tertiary', 'outline-variant'] as const)\n * const data = computed(() => ({ datasets: [{ data: sales, borderColor: colors.value.primary }] }))\n * ```\n */\nexport function useThemeTokens<T extends string>(names: readonly T[], options: ThemeTokensOptions = {}): Ref<Record<T, string>> {\n const read = () => {\n const style = getComputedStyle(document.documentElement)\n return Object.fromEntries(names.map((n) => [n, style.getPropertyValue(`--color-${n}`).trim()])) as Record<T, string>\n }\n const tokens = ref(typeof document === 'undefined' ? Object.fromEntries(names.map((n) => [n, ''])) as Record<T, string> : read()) as Ref<Record<T, string>>\n let observer: MutationObserver | undefined\n let settle: ReturnType<typeof setTimeout> | undefined\n let frame = 0\n\n const set = (next: Record<T, string>) => {\n if (names.some((n) => next[n] !== tokens.value[n])) tokens.value = next\n }\n const update = () => set(read())\n\n // Follows a switch already under way. Chromium/WebKit animate the tokens themselves (`theme-switching`), so\n // reading them each frame gives the page's own colors; Firefox fades each element's colors instead\n // (`theme-transitioning`) while the tokens jump, so the same `ease` is replayed here from the old values\n function follow(root: HTMLElement) {\n cancelAnimationFrame(frame)\n const native = root.classList.contains('theme-switching')\n const from = { ...tokens.value }\n const to = native ? null : read()\n const start = performance.now()\n const step = (now: number) => {\n const t = Math.min(1, (now - start) / THEME_TRANSITION_MS)\n // The last frame lands on the values as written, not their rgba() form\n if (to) set(t < 1 ? Object.fromEntries(names.map((n) => [n, mix(from[n], to[n], ease(t))])) as Record<T, string> : to)\n else update()\n if (t < 1) frame = requestAnimationFrame(step)\n }\n frame = requestAnimationFrame(step)\n }\n\n onMounted(() => {\n const root = document.documentElement\n // Dark mode (class), a palette or contrast (attributes), or a generated palette rewriting its <style> in <head>\n const isPaletteStyle = (node: Node | null) => (node instanceof Element ? node : node?.parentElement)?.id === STYLE_ID\n observer = new MutationObserver((records) => {\n if (!records.some((r) => r.target === root || isPaletteStyle(r.target)\n || Array.from(r.addedNodes).some(isPaletteStyle))) return\n if (options.live && (root.classList.contains('theme-switching') || root.classList.contains('theme-transitioning'))) follow(root)\n else update()\n // Chromium animates the tokens on a theme switch (_themeTransition, 250ms): read the settled values too\n clearTimeout(settle)\n settle = setTimeout(update, THEME_TRANSITION_MS + 50)\n })\n observer.observe(root, { attributes: true, attributeFilter: ['class', 'style', 'data-palette', 'data-contrast'] })\n observer.observe(document.head, { childList: true, characterData: true, subtree: true })\n })\n onBeforeUnmount(() => {\n observer?.disconnect()\n clearTimeout(settle)\n cancelAnimationFrame(frame)\n })\n\n return tokens\n}\n"],"mappings":";;;AAWA,IAAM,IAAe;CACnB;CAAc;CAAiB;CAAW;CAAe;CAAkB;CAAmB;CAC9F;CAAsB;CAA4B;CAAyB;CAC3E;CAA0B;CAA6B;CAAmB;CAAsB;CAChG;CAAW;CAAmB;CAAU;CACxC,GAAG;EAAC;EAAW;EAAa;EAAY;EAAS;CAAS,CAAC,CAAC,SAAS,MAAM;EAAC;EAAG,MAAM;EAAK,GAAG,EAAE;EAAa,MAAM,EAAE;CAAW,CAAC;CAChI,GAAG;EAAC;EAAW;EAAa;CAAU,CAAC,CAAC,SAAS,MAAM;EAAC,GAAG,EAAE;EAAS,GAAG,EAAE;EAAa,MAAM,EAAE;EAAS,MAAM,EAAE;CAAe,CAAC;AACnI,CAAC,CAAC,KAAK,MAAM,WAAW,GAAG,GAErB,IAAW,KAGX,IAAW,uBAIX,IAAM,EAAa,KAAK,MAAM,aAAa,EAAE,oEAAoE,CAAC,CAAC,KAAK,IAAI,IAC9H,wCAAwC,EAAa,KAAK,MAAM,GAAG,EAAE,GAAG,EAAS,QAAQ,CAAC,CAAC,KAAK,IAAI,EAAE;yHAKpG,UACH,OAAO,MAAQ,OAAe,CAAC,CAAC,IAAI,WAAW,mBAAmB,MAAM,KACrE,OAAO,YAAc,OAAe,0BAA0B,KAAK,UAAU,SAAS,GACtF,UAAoB,OAAO,MAAQ,OAAe,OAAO,IAAI,oBAAqB,YAEpF;AAGJ,SAAgB,EAAgB,GAAmB;CAGjD,IAFI,OAAO,WAA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