@m3ui-vue/m3ui-vue 1.2.1 → 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.
- package/dist/API.md +152 -11
- package/dist/{MMenuItem-DI351kIf.js → MMenuItem-D4Gx_l3F.js} +2 -2
- package/dist/{MMenuItem-DI351kIf.js.map → MMenuItem-D4Gx_l3F.js.map} +1 -1
- package/dist/{MSlider-BnEy5ieZ.js → MSlider-Dx_S3vJ9.js} +227 -221
- package/dist/{MSlider-BnEy5ieZ.js.map → MSlider-Dx_S3vJ9.js.map} +1 -1
- package/dist/{MTextField-BBmkaIbO.js → MTextField-Bz8JIsnl.js} +4 -4
- package/dist/{MTextField-BBmkaIbO.js.map → MTextField-Bz8JIsnl.js.map} +1 -1
- package/dist/api.json +1 -1
- package/dist/chart.js +1 -1
- package/dist/components/MMap.vue.d.ts +1 -1
- package/dist/components/MSlider.vue.d.ts +2 -2
- package/dist/composables/_effectCanvas.d.ts +23 -0
- package/dist/composables/_storageKeys.d.ts +9 -0
- package/dist/composables/themeInitScript.d.ts +2 -0
- package/dist/composables/useConfetti.d.ts +19 -8
- package/dist/composables/useFireworks.d.ts +37 -0
- package/dist/composables/useReactions.d.ts +32 -0
- package/dist/composables/viewportHints.d.ts +2 -0
- package/dist/directives/vSparkle.d.ts +27 -0
- package/dist/index.d.ts +7 -1
- package/dist/m3ui.js +5403 -5022
- package/dist/m3ui.js.map +1 -1
- package/dist/map.js +572 -572
- package/dist/map.js.map +1 -1
- package/dist/plugin.d.ts +10 -0
- package/dist/rich-text-editor.js +2 -2
- package/dist/{useThemeTokens-Bv-Uv8eX.js → useThemeTokens-y0HZpyhL.js} +23 -8
- package/dist/useThemeTokens-y0HZpyhL.js.map +1 -0
- package/package.json +1 -1
- package/src/__tests__/MSlider.test.ts +36 -0
- package/src/__tests__/plugin.test.ts +56 -1
- package/src/__tests__/ssr.test.ts +1 -1
- package/src/__tests__/themeInitScript.test.ts +10 -0
- package/src/__tests__/useConfetti.test.ts +33 -2
- package/src/__tests__/useFireworks.test.ts +104 -0
- package/src/__tests__/useReactions.test.ts +51 -0
- package/src/__tests__/vSparkle.test.ts +83 -0
- package/src/components/MEmojiSelector.vue +3 -2
- package/src/components/MMap.vue +3 -2
- package/src/components/MSlider.vue +22 -4
- package/src/components/MTextField.vue +8 -4
- package/src/composables/_colorUtils.ts +4 -2
- package/src/composables/_effectCanvas.ts +109 -0
- package/src/composables/_ssrState.ts +2 -2
- package/src/composables/_storageKeys.ts +28 -0
- package/src/composables/themeInitScript.ts +5 -2
- package/src/composables/useColorPalette.ts +36 -8
- package/src/composables/useConfetti.ts +84 -107
- package/src/composables/useFireworks.ts +360 -0
- package/src/composables/useReactions.ts +131 -0
- package/src/composables/useTheme.ts +21 -4
- package/src/composables/viewportHints.ts +6 -5
- package/src/directives/vSparkle.ts +180 -0
- package/src/index.ts +7 -1
- package/src/plugin.ts +21 -5
- package/dist/useThemeTokens-Bv-Uv8eX.js.map +0 -1
|
@@ -18,7 +18,7 @@ const props = withDefaults(
|
|
|
18
18
|
min?: number
|
|
19
19
|
/** Maximum value */
|
|
20
20
|
max?: number
|
|
21
|
-
/** Step increment */
|
|
21
|
+
/** Step increment: the values emitted snap to it; while dragging (without stops) the thumb still follows the pointer smoothly and settles on its step when released */
|
|
22
22
|
step?: number
|
|
23
23
|
/** Disables the slider */
|
|
24
24
|
disabled?: boolean
|
|
@@ -34,7 +34,7 @@ const props = withDefaults(
|
|
|
34
34
|
size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl'
|
|
35
35
|
/** Standard, centered (from middle), or range (two thumbs) */
|
|
36
36
|
variant?: 'standard' | 'centered' | 'range'
|
|
37
|
-
/** Show stop dots at each step (max 30 visible) */
|
|
37
|
+
/** Show stop dots at each step (max 30 visible), and make a dragged thumb snap from step to step instead of following the pointer smoothly (a discrete slider) */
|
|
38
38
|
stops?: boolean
|
|
39
39
|
/** Material Symbol icon shown before the slider — hides once the fill reaches it */
|
|
40
40
|
icon?: string
|
|
@@ -105,8 +105,21 @@ function toPct(v: number) {
|
|
|
105
105
|
return range === 0 ? 0 : ((v - props.min) / range) * 100
|
|
106
106
|
}
|
|
107
107
|
|
|
108
|
-
|
|
109
|
-
|
|
108
|
+
// Where the pointer is along the track (0–1) while dragging. Without stops the dragged thumb follows it smoothly
|
|
109
|
+
// instead of jumping from step to step (the value emitted still snaps to `step`) and settles on its step when
|
|
110
|
+
// released; with stops it snaps as it goes, like Compose's discrete slider
|
|
111
|
+
const pointerRatio = ref<number | null>(null)
|
|
112
|
+
const freePct = computed(() => (!props.stops && dragging.value !== false && pointerRatio.value !== null ? pointerRatio.value * 100 : null))
|
|
113
|
+
const pctLo = computed(() => {
|
|
114
|
+
const f = freePct.value
|
|
115
|
+
if (f !== null && (dragging.value === 'single' || dragging.value === 0)) return isRange.value ? Math.min(f, toPct(val.value.hi)) : f
|
|
116
|
+
return toPct(val.value.lo)
|
|
117
|
+
})
|
|
118
|
+
const pctHi = computed(() => {
|
|
119
|
+
const f = freePct.value
|
|
120
|
+
if (f !== null && dragging.value === 1) return Math.max(f, toPct(val.value.lo))
|
|
121
|
+
return toPct(val.value.hi)
|
|
122
|
+
})
|
|
110
123
|
const centerPct = computed(() => toPct(0))
|
|
111
124
|
|
|
112
125
|
// Start/end anchor dots hide once the fill has actually covered their spot —
|
|
@@ -270,6 +283,8 @@ function onPointerDown(e: PointerEvent) {
|
|
|
270
283
|
dragging.value = 'single'
|
|
271
284
|
emit('update:modelValue', v)
|
|
272
285
|
}
|
|
286
|
+
// Two overlapping thumbs follow the pointer only once its direction has picked one
|
|
287
|
+
pointerRatio.value = overlapPress ? null : ratioFromEvent(e)
|
|
273
288
|
window.addEventListener('pointermove', onPointerMove)
|
|
274
289
|
window.addEventListener('pointerup', onPointerUp)
|
|
275
290
|
window.addEventListener('pointercancel', onPointerUp)
|
|
@@ -285,14 +300,17 @@ function onPointerMove(e: PointerEvent) {
|
|
|
285
300
|
dragging.value = v > val.value.lo ? 1 : 0
|
|
286
301
|
focusThumb(dragging.value)
|
|
287
302
|
}
|
|
303
|
+
pointerRatio.value = ratioFromEvent(e)
|
|
288
304
|
emit('update:modelValue', rangeValue(dragging.value as 0 | 1, v))
|
|
289
305
|
} else {
|
|
306
|
+
pointerRatio.value = ratioFromEvent(e)
|
|
290
307
|
emit('update:modelValue', v)
|
|
291
308
|
}
|
|
292
309
|
}
|
|
293
310
|
|
|
294
311
|
function onPointerUp() {
|
|
295
312
|
dragging.value = false
|
|
313
|
+
pointerRatio.value = null
|
|
296
314
|
overlapPress = false
|
|
297
315
|
window.removeEventListener('pointermove', onPointerMove)
|
|
298
316
|
window.removeEventListener('pointerup', onPointerUp)
|
|
@@ -112,11 +112,15 @@ const inputClasses = computed(() => {
|
|
|
112
112
|
|
|
113
113
|
return [
|
|
114
114
|
...base,
|
|
115
|
-
|
|
115
|
+
// Multiline: the label's 24px band is a transparent top border rather than padding, so text scrolled up is
|
|
116
|
+
// clipped below the label (at the padding box) instead of running behind it; the background still fills it
|
|
117
|
+
props.multiline
|
|
118
|
+
? "rounded-t-xs bg-surface-container-highest border-b border-t-24 border-t-transparent pb-2"
|
|
119
|
+
: "rounded-t-xs bg-surface-container-highest border-b pt-6 pb-2",
|
|
116
120
|
props.error
|
|
117
|
-
? "border-error focus:border-b-2 focus:border-error"
|
|
118
|
-
: "border-on-surface-variant hover:border-on-surface focus:border-b-2 focus:border-primary",
|
|
119
|
-
"disabled:border-on-surface/38 disabled:bg-[color-mix(in_srgb,var(--color-on-surface)_4%,var(--color-surface-container-highest))]",
|
|
121
|
+
? "border-b-error focus:border-b-2 focus:border-b-error"
|
|
122
|
+
: "border-b-on-surface-variant hover:border-b-on-surface focus:border-b-2 focus:border-b-primary",
|
|
123
|
+
"disabled:border-b-on-surface/38 disabled:bg-[color-mix(in_srgb,var(--color-on-surface)_4%,var(--color-surface-container-highest))]",
|
|
120
124
|
].join(" ");
|
|
121
125
|
});
|
|
122
126
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Internal color math shared by MColorPicker and MColorPickerModal (through _MColorPanel).
|
|
2
2
|
// Not exported from index.ts.
|
|
3
3
|
import { ref } from 'vue'
|
|
4
|
+
import { onStoragePrefix, storageKey } from './_storageKeys'
|
|
4
5
|
|
|
5
6
|
export interface Rgba { r: number; g: number; b: number; a: number }
|
|
6
7
|
/** h 0–360, s/v 0–100 */
|
|
@@ -83,7 +84,7 @@ const RECENT_KEY = 'm3-color-recent'
|
|
|
83
84
|
|
|
84
85
|
function readRecents(): string[] {
|
|
85
86
|
try {
|
|
86
|
-
const v = JSON.parse(localStorage.getItem(RECENT_KEY) ?? '[]')
|
|
87
|
+
const v = JSON.parse(localStorage.getItem(storageKey(RECENT_KEY)) ?? '[]')
|
|
87
88
|
return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string' && !!parseHex(x)) : []
|
|
88
89
|
} catch {
|
|
89
90
|
return []
|
|
@@ -91,12 +92,13 @@ function readRecents(): string[] {
|
|
|
91
92
|
}
|
|
92
93
|
|
|
93
94
|
export const recentColors = ref<string[]>(readRecents())
|
|
95
|
+
onStoragePrefix(() => { recentColors.value = readRecents() })
|
|
94
96
|
|
|
95
97
|
export function pushRecentColor(hex: string, limit: number) {
|
|
96
98
|
const c = normalizeHex(hex)
|
|
97
99
|
if (!c) return
|
|
98
100
|
recentColors.value = [c, ...recentColors.value.filter((x) => x !== c)].slice(0, Math.max(limit, 0))
|
|
99
|
-
try { localStorage.setItem(RECENT_KEY, JSON.stringify(recentColors.value)) } catch { /* storage blocked */ }
|
|
101
|
+
try { localStorage.setItem(storageKey(RECENT_KEY), JSON.stringify(recentColors.value)) } catch { /* storage blocked */ }
|
|
100
102
|
}
|
|
101
103
|
|
|
102
104
|
/** Default swatches for both pickers: the Material 2014 palette's 500 tones plus grey, black and white (3 rows of 7) */
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// One canvas over the page shared by the canvas effects (useConfetti, useFireworks): created when the first one
|
|
2
|
+
// starts, removed when the last one ends. It never takes pointer events and assistive technology ignores it. Each
|
|
3
|
+
// effect is a layer stepped once per frame in one rAF loop, after the canvas has been cleared.
|
|
4
|
+
|
|
5
|
+
export interface EffectLayer {
|
|
6
|
+
/** Advances and draws one frame (`dt` in seconds, `dpr` the canvas' pixel ratio); false once it has nothing left. */
|
|
7
|
+
step(ctx: CanvasRenderingContext2D, dt: number, dpr: number, now: number): boolean
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
let canvas: HTMLCanvasElement | null = null
|
|
11
|
+
let ctx: CanvasRenderingContext2D | null = null
|
|
12
|
+
const layers = new Set<EffectLayer>()
|
|
13
|
+
let raf = 0
|
|
14
|
+
let last = 0
|
|
15
|
+
|
|
16
|
+
function resize() {
|
|
17
|
+
if (!canvas) return
|
|
18
|
+
const dpr = window.devicePixelRatio || 1
|
|
19
|
+
canvas.width = Math.round(window.innerWidth * dpr)
|
|
20
|
+
canvas.height = Math.round(window.innerHeight * dpr)
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function ensureCanvas() {
|
|
24
|
+
if (canvas) return ctx
|
|
25
|
+
canvas = document.createElement('canvas')
|
|
26
|
+
canvas.setAttribute('aria-hidden', 'true')
|
|
27
|
+
canvas.style.cssText = 'position:fixed;inset:0;width:100vw;height:100vh;pointer-events:none;z-index:2147483000'
|
|
28
|
+
document.body.appendChild(canvas)
|
|
29
|
+
ctx = canvas.getContext('2d')
|
|
30
|
+
if (!ctx) {
|
|
31
|
+
teardown()
|
|
32
|
+
return null
|
|
33
|
+
}
|
|
34
|
+
resize()
|
|
35
|
+
window.addEventListener('resize', resize)
|
|
36
|
+
return ctx
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function teardown() {
|
|
40
|
+
cancelAnimationFrame(raf)
|
|
41
|
+
raf = 0
|
|
42
|
+
window.removeEventListener('resize', resize)
|
|
43
|
+
canvas?.remove()
|
|
44
|
+
canvas = null
|
|
45
|
+
ctx = null
|
|
46
|
+
layers.clear()
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function frame(now: number) {
|
|
50
|
+
const dt = Math.min((now - last) / 1000, 1 / 30)
|
|
51
|
+
last = now
|
|
52
|
+
if (!ctx || !canvas) return teardown()
|
|
53
|
+
const dpr = canvas.width / window.innerWidth
|
|
54
|
+
ctx.setTransform(1, 0, 0, 1, 0, 0)
|
|
55
|
+
ctx.clearRect(0, 0, canvas.width, canvas.height)
|
|
56
|
+
for (const layer of layers) {
|
|
57
|
+
ctx.globalAlpha = 1
|
|
58
|
+
if (!layer.step(ctx, dt, dpr, now)) layers.delete(layer)
|
|
59
|
+
}
|
|
60
|
+
if (!layers.size) return teardown()
|
|
61
|
+
raf = requestAnimationFrame(frame)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Makes sure a layer is drawn (it stays until its `step` returns false). False when there's no 2D canvas. */
|
|
65
|
+
export function runLayer(layer: EffectLayer): boolean {
|
|
66
|
+
if (!ensureCanvas()) return false
|
|
67
|
+
layers.add(layer)
|
|
68
|
+
if (!raf) {
|
|
69
|
+
last = performance.now()
|
|
70
|
+
raf = requestAnimationFrame(frame)
|
|
71
|
+
}
|
|
72
|
+
return true
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Stops every effect and removes the canvas. Internal, for tests. */
|
|
76
|
+
export function __resetEffectCanvas() {
|
|
77
|
+
teardown()
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The theme's colors for effects, read at an element (so an MScheme around it gives its scheme's). */
|
|
81
|
+
export function themeColors(el: Element, roles: string[]) {
|
|
82
|
+
const style = getComputedStyle(el)
|
|
83
|
+
const colors = roles.map((role) => style.getPropertyValue(`--color-${role}`).trim()).filter(Boolean)
|
|
84
|
+
return colors.length ? colors : ['#6750a4', '#625b71', '#7d5260', '#eaddff', '#ffd8e4']
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Whether the system asks for reduced motion. */
|
|
88
|
+
export function reducedMotion() {
|
|
89
|
+
return !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Where an effect starts: the pointer of an event, an element's center, or a point in viewport pixels */
|
|
93
|
+
export type EffectOrigin = MouseEvent | PointerEvent | Element | { x: number; y: number }
|
|
94
|
+
|
|
95
|
+
/** The point an effect starts from (viewport px) and the element whose theme colors it takes. */
|
|
96
|
+
export function originPoint(origin: EffectOrigin | undefined): { x: number; y: number; el: Element } {
|
|
97
|
+
if (origin && 'clientX' in origin) {
|
|
98
|
+
const el = (origin.currentTarget as Element | null) ?? (origin.target as Element | null) ?? document.documentElement
|
|
99
|
+
// A click from the keyboard (Enter, Space) has no pointer position: burst from the element instead
|
|
100
|
+
if (origin.detail === 0 && origin.clientX === 0 && origin.clientY === 0) return originPoint(el)
|
|
101
|
+
return { x: origin.clientX, y: origin.clientY, el }
|
|
102
|
+
}
|
|
103
|
+
if (origin instanceof Element) {
|
|
104
|
+
const r = origin.getBoundingClientRect()
|
|
105
|
+
return { x: r.left + r.width / 2, y: r.top + r.height / 2, el: origin }
|
|
106
|
+
}
|
|
107
|
+
if (origin) return { ...origin, el: document.documentElement }
|
|
108
|
+
return { x: window.innerWidth / 2, y: window.innerHeight * 0.6, el: document.documentElement }
|
|
109
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { computed, hasInjectionContext, inject, onMounted, ref, type InjectionKey, type Ref } from 'vue'
|
|
2
2
|
import { isHydrating } from './_hydration'
|
|
3
|
-
import { VIEWPORT_KEY } from './_storageKeys'
|
|
3
|
+
import { VIEWPORT_KEY, storageKey } from './_storageKeys'
|
|
4
4
|
import type { Theme } from './useTheme'
|
|
5
5
|
import type { ContrastLevel } from './useColorPalette'
|
|
6
6
|
|
|
@@ -55,7 +55,7 @@ let trackingViewport = false
|
|
|
55
55
|
export function trackViewport() {
|
|
56
56
|
if (!cookiesEnabled || trackingViewport || typeof window === 'undefined') return
|
|
57
57
|
trackingViewport = true
|
|
58
|
-
const write = () => writeCookie(VIEWPORT_KEY, `${window.innerWidth}x${window.innerHeight}`)
|
|
58
|
+
const write = () => writeCookie(storageKey(VIEWPORT_KEY), `${window.innerWidth}x${window.innerHeight}`)
|
|
59
59
|
let timer: ReturnType<typeof setTimeout> | undefined
|
|
60
60
|
write()
|
|
61
61
|
window.addEventListener('resize', () => {
|
|
@@ -4,3 +4,31 @@ export const THEME_KEY = 'm3-theme'
|
|
|
4
4
|
export const STYLE_ID = 'm3-dynamic-palette'
|
|
5
5
|
// The window's size, a cookie only (createM3UI({ cookies: true })): `<width>x<height>`
|
|
6
6
|
export const VIEWPORT_KEY = 'm3-viewport'
|
|
7
|
+
|
|
8
|
+
// ── Prefix ──────────────────────────────────────────────────────────────────────────────────────
|
|
9
|
+
// `createM3UI({ storagePrefix: 'admin' })`: every key the library stores (localStorage and cookies) becomes
|
|
10
|
+
// `admin-m3-…`, so apps on the same origin under different paths keep their own theme, palette and the rest
|
|
11
|
+
// (localStorage is per origin and our cookies are on `Path=/`, so without it they share one).
|
|
12
|
+
|
|
13
|
+
let prefix = ''
|
|
14
|
+
const reloaders = new Set<() => void>()
|
|
15
|
+
|
|
16
|
+
/** The name a key is stored under: the base key with the app's prefix, if any. */
|
|
17
|
+
export function storageKey(base: string, storagePrefix = prefix): string {
|
|
18
|
+
return storagePrefix ? `${storagePrefix}-${base}` : base
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Sets the prefix and has every module that read its stored state on load (theme, palette, recent colors…) read
|
|
23
|
+
* it again under the new keys. `createM3UI` calls it before applying anything else.
|
|
24
|
+
*/
|
|
25
|
+
export function setStoragePrefix(next: string) {
|
|
26
|
+
if (next === prefix) return
|
|
27
|
+
prefix = next
|
|
28
|
+
for (const reload of reloaders) reload()
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Registers what a module does to read its stored state again when the prefix changes. */
|
|
32
|
+
export function onStoragePrefix(reload: () => void) {
|
|
33
|
+
reloaders.add(reload)
|
|
34
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { THEME_KEY } from './
|
|
1
|
+
import { THEME_KEY, storageKey } from './_storageKeys'
|
|
2
2
|
import { CONTRAST_KEY, CSS_KEY, PALETTE_KEY, STYLE_ID, type ContrastLevel, type PaletteId } from './useColorPalette'
|
|
3
3
|
|
|
4
4
|
export interface ThemeInitOptions {
|
|
@@ -8,6 +8,8 @@ export interface ThemeInitOptions {
|
|
|
8
8
|
contrast?: ContrastLevel
|
|
9
9
|
/** `createM3UI`'s `persistPalette`. */
|
|
10
10
|
persistPalette?: boolean
|
|
11
|
+
/** `createM3UI`'s `storagePrefix`. */
|
|
12
|
+
storagePrefix?: string
|
|
11
13
|
}
|
|
12
14
|
|
|
13
15
|
/**
|
|
@@ -24,7 +26,8 @@ export interface ThemeInitOptions {
|
|
|
24
26
|
*/
|
|
25
27
|
export function themeInitScript(options: ThemeInitOptions = {}): string {
|
|
26
28
|
const config = JSON.stringify({
|
|
27
|
-
keys: { theme: THEME_KEY, palette: PALETTE_KEY, contrast: CONTRAST_KEY, css: CSS_KEY }
|
|
29
|
+
keys: Object.fromEntries(Object.entries({ theme: THEME_KEY, palette: PALETTE_KEY, contrast: CONTRAST_KEY, css: CSS_KEY })
|
|
30
|
+
.map(([name, key]) => [name, storageKey(key, options.storagePrefix ?? '')])),
|
|
28
31
|
styleId: STYLE_ID,
|
|
29
32
|
palette: options.palette ?? null,
|
|
30
33
|
contrast: options.contrast ?? null,
|
|
@@ -2,7 +2,7 @@ import { computed, readonly, ref, watch, watchEffect, type Ref } from 'vue'
|
|
|
2
2
|
import { generateScheme, schemeToCss, type SeedOptions } from './dynamicColor'
|
|
3
3
|
import { themeTransition } from './_themeTransition'
|
|
4
4
|
import { initialState, readCookie, ssrValue, writeCookie } from './_ssrState'
|
|
5
|
-
import { STYLE_ID } from './_storageKeys'
|
|
5
|
+
import { STYLE_ID, onStoragePrefix, storageKey } from './_storageKeys'
|
|
6
6
|
|
|
7
7
|
export interface Palette {
|
|
8
8
|
id: string
|
|
@@ -82,18 +82,20 @@ export const CSS_KEY = 'm3-palette-css'
|
|
|
82
82
|
function read<T>(key: string): T | null {
|
|
83
83
|
try {
|
|
84
84
|
// The palette and the contrast level fall back to their cookies (createM3UI({ cookies })) when storage has none
|
|
85
|
-
const
|
|
85
|
+
const name = storageKey(key)
|
|
86
|
+
const v = localStorage.getItem(name) ?? (key === PALETTE_KEY || key === CONTRAST_KEY ? readCookie(name) : null)
|
|
86
87
|
return v == null ? null : (key === PALETTE_KEY || key === CONTRAST_KEY ? v : JSON.parse(v)) as T
|
|
87
88
|
} catch {
|
|
88
89
|
return null
|
|
89
90
|
}
|
|
90
91
|
}
|
|
91
92
|
function write(key: string, value: unknown) {
|
|
93
|
+
const name = storageKey(key)
|
|
92
94
|
// The palette and the contrast level also go in cookies (createM3UI({ cookies: true })) for a server to read
|
|
93
|
-
if (key === PALETTE_KEY || key === CONTRAST_KEY) writeCookie(
|
|
95
|
+
if (key === PALETTE_KEY || key === CONTRAST_KEY) writeCookie(name, value == null ? null : String(value))
|
|
94
96
|
try {
|
|
95
|
-
if (value == null) localStorage.removeItem(
|
|
96
|
-
else localStorage.setItem(
|
|
97
|
+
if (value == null) localStorage.removeItem(name)
|
|
98
|
+
else localStorage.setItem(name, typeof value === 'string' ? value : JSON.stringify(value))
|
|
97
99
|
} catch { /* storage blocked */ }
|
|
98
100
|
}
|
|
99
101
|
|
|
@@ -107,8 +109,11 @@ const activeSeed = ref<ActiveSeed | null>(read<ActiveSeed>(SEED_KEY))
|
|
|
107
109
|
*/
|
|
108
110
|
export type ContrastLevel = 'standard' | 'medium' | 'high' | 'system'
|
|
109
111
|
const CONTRAST_LEVELS: readonly ContrastLevel[] = ['standard', 'medium', 'high', 'system']
|
|
110
|
-
|
|
111
|
-
const
|
|
112
|
+
function readContrast(): ContrastLevel {
|
|
113
|
+
const stored = read<string>(CONTRAST_KEY)
|
|
114
|
+
return CONTRAST_LEVELS.includes(stored as ContrastLevel) ? stored as ContrastLevel : 'standard'
|
|
115
|
+
}
|
|
116
|
+
const contrast = ref<ContrastLevel>(readContrast())
|
|
112
117
|
const systemMore = ref(false)
|
|
113
118
|
if (typeof window !== 'undefined' && window.matchMedia) {
|
|
114
119
|
const mq = window.matchMedia('(prefers-contrast: more)')
|
|
@@ -238,7 +243,14 @@ async function selectContrast(level: ContrastLevel, persist = persistEnabled.val
|
|
|
238
243
|
|
|
239
244
|
// Applied on every change of the effective level (a setting or the OS preference), for every palette kind. A
|
|
240
245
|
// generated palette is regenerated first, then swapped in with the attribute in one transition.
|
|
246
|
+
// Set while createM3UI({ storagePrefix }) loads another stored level: it's applied right away, with no transition
|
|
247
|
+
let skipContrastWatch = false
|
|
248
|
+
|
|
241
249
|
watch(activeContrast, async () => {
|
|
250
|
+
if (skipContrastWatch) {
|
|
251
|
+
skipContrastWatch = false
|
|
252
|
+
return
|
|
253
|
+
}
|
|
242
254
|
const id = current.value
|
|
243
255
|
let css: string | null | undefined
|
|
244
256
|
if (id === SEED_PALETTE && activeSeed.value) css = await generateCss(SEED_PALETTE, activeSeed.value)
|
|
@@ -308,7 +320,7 @@ export function useColorPalette() {
|
|
|
308
320
|
|
|
309
321
|
// Apply on module load so the palette is visible before any component mounts, a generated one included (not on
|
|
310
322
|
// the server: the client does it when the module loads there)
|
|
311
|
-
|
|
323
|
+
function applyStored() {
|
|
312
324
|
const saved = read<string>(PALETTE_KEY)
|
|
313
325
|
const cached = read<{ id: string; css: string }>(CSS_KEY)
|
|
314
326
|
if (saved && cached && cached.id === saved) injectCss(cached.css)
|
|
@@ -316,6 +328,22 @@ if (typeof document !== 'undefined') {
|
|
|
316
328
|
applyContrast(activeContrast.value)
|
|
317
329
|
}
|
|
318
330
|
|
|
331
|
+
if (typeof document !== 'undefined') applyStored()
|
|
332
|
+
|
|
333
|
+
// createM3UI({ storagePrefix }): this app's own stored palette, seed and contrast, applied before anything renders
|
|
334
|
+
onStoragePrefix(() => {
|
|
335
|
+
if (typeof document === 'undefined') return
|
|
336
|
+
generation++
|
|
337
|
+
current.value = read<string>(PALETTE_KEY) ?? 'purple'
|
|
338
|
+
activeSeed.value = read<ActiveSeed>(SEED_KEY)
|
|
339
|
+
const before = activeContrast.value
|
|
340
|
+
contrast.value = readContrast()
|
|
341
|
+
if (activeContrast.value !== before) skipContrastWatch = true
|
|
342
|
+
document.getElementById(STYLE_ID)?.remove()
|
|
343
|
+
applyAttribute(current.value)
|
|
344
|
+
applyStored()
|
|
345
|
+
})
|
|
346
|
+
|
|
319
347
|
/**
|
|
320
348
|
* Internal: used by `createM3UI({ palette, persistPalette: false })` to force a palette on boot,
|
|
321
349
|
* bypassing whatever is already in localStorage, without waiting for a component to call
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
// Confetti: a burst of Material 3's expressive shapes (MShape's) in the theme's colors, for the end of a flow (an
|
|
2
|
-
// order placed, a task done).
|
|
3
|
-
// piece has fallen
|
|
4
|
-
//
|
|
2
|
+
// order placed, a task done). Drawn on the effects' shared canvas (_effectCanvas), which goes away when the last
|
|
3
|
+
// piece has fallen. Simple physics (gravity, air drag, spin and a flip that flattens each piece as it turns). Nothing
|
|
4
|
+
// happens under reduced motion.
|
|
5
5
|
import { getShape, toSvgPath, type ShapeName } from 'shape-morph'
|
|
6
|
+
import { __resetEffectCanvas, originPoint, reducedMotion, runLayer, themeColors, type EffectLayer, type EffectOrigin } from './_effectCanvas'
|
|
6
7
|
|
|
7
8
|
export interface ConfettiOptions {
|
|
8
9
|
/** How many pieces (default 80; 160 for `from: 'top'`) */
|
|
@@ -21,10 +22,18 @@ export interface ConfettiOptions {
|
|
|
21
22
|
velocity?: number
|
|
22
23
|
/** Piece size in px (default 14) */
|
|
23
24
|
size?: number
|
|
25
|
+
/**
|
|
26
|
+
* Keep it going for this long, in ms: a rain that keeps falling (`from: 'top'`) or a fountain from the point,
|
|
27
|
+
* `count` then being pieces per second. `Infinity` runs until the returned `stop()`. Unset: one burst
|
|
28
|
+
*/
|
|
29
|
+
duration?: number
|
|
24
30
|
}
|
|
25
31
|
|
|
32
|
+
/** Stops a running confetti before its `duration` ends; the pieces already out finish falling. */
|
|
33
|
+
export type StopConfetti = () => void
|
|
34
|
+
|
|
26
35
|
/** Where a burst starts: the pointer of an event, an element's center, or a point in viewport pixels */
|
|
27
|
-
export type ConfettiOrigin =
|
|
36
|
+
export type ConfettiOrigin = EffectOrigin
|
|
28
37
|
|
|
29
38
|
const DEFAULT_SHAPES: ShapeName[] = ['Cookie4Sided', 'Sunny', 'Clover4Leaf', 'Heart', 'Pill', 'Triangle', 'SoftBurst', 'Circle', 'Gem', 'Flower']
|
|
30
39
|
const ROLES = ['primary', 'secondary', 'tertiary', 'primary-container', 'tertiary-container']
|
|
@@ -58,117 +67,73 @@ function pathFor(shape: ShapeName) {
|
|
|
58
67
|
return path
|
|
59
68
|
}
|
|
60
69
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
function ensureCanvas() {
|
|
68
|
-
if (canvas) return ctx
|
|
69
|
-
canvas = document.createElement('canvas')
|
|
70
|
-
canvas.setAttribute('aria-hidden', 'true')
|
|
71
|
-
canvas.style.cssText = 'position:fixed;inset:0;width:100vw;height:100vh;pointer-events:none;z-index:2147483000'
|
|
72
|
-
document.body.appendChild(canvas)
|
|
73
|
-
ctx = canvas.getContext('2d')
|
|
74
|
-
if (!ctx) {
|
|
75
|
-
teardown()
|
|
76
|
-
return null
|
|
77
|
-
}
|
|
78
|
-
resize()
|
|
79
|
-
window.addEventListener('resize', resize)
|
|
80
|
-
return ctx
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
function resize() {
|
|
84
|
-
if (!canvas) return
|
|
85
|
-
const dpr = window.devicePixelRatio || 1
|
|
86
|
-
canvas.width = Math.round(window.innerWidth * dpr)
|
|
87
|
-
canvas.height = Math.round(window.innerHeight * dpr)
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
function teardown() {
|
|
91
|
-
cancelAnimationFrame(raf)
|
|
92
|
-
raf = 0
|
|
93
|
-
window.removeEventListener('resize', resize)
|
|
94
|
-
canvas?.remove()
|
|
95
|
-
canvas = null
|
|
96
|
-
ctx = null
|
|
97
|
-
pieces = []
|
|
70
|
+
// A confetti with a `duration`: it adds `rate` pieces per second (fractions carried over) until `until`
|
|
71
|
+
interface Emitter {
|
|
72
|
+
until: number
|
|
73
|
+
rate: number
|
|
74
|
+
carry: number
|
|
75
|
+
spawn: () => Piece
|
|
98
76
|
}
|
|
99
77
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
last = now
|
|
103
|
-
const height = window.innerHeight
|
|
104
|
-
pieces = pieces.filter((p) => p.age < p.life && p.y < height + 60)
|
|
105
|
-
if (!pieces.length || !ctx || !canvas) {
|
|
106
|
-
teardown()
|
|
107
|
-
return
|
|
108
|
-
}
|
|
109
|
-
const dpr = canvas.width / window.innerWidth
|
|
110
|
-
ctx.setTransform(1, 0, 0, 1, 0, 0)
|
|
111
|
-
ctx.clearRect(0, 0, canvas.width, canvas.height)
|
|
112
|
-
for (const p of pieces) {
|
|
113
|
-
p.age += dt
|
|
114
|
-
p.vx -= p.vx * DRAG * dt
|
|
115
|
-
p.vy += (GRAVITY - p.vy * DRAG) * dt
|
|
116
|
-
p.x += p.vx * dt
|
|
117
|
-
p.y += p.vy * dt
|
|
118
|
-
p.rot += p.spin * dt
|
|
119
|
-
p.flip += p.flipSpeed * dt
|
|
120
|
-
const fade = Math.min(1, (p.life - p.age) / 0.6)
|
|
121
|
-
ctx.globalAlpha = Math.max(0, fade)
|
|
122
|
-
ctx.fillStyle = p.color
|
|
123
|
-
const scale = (p.size / SIZE) * dpr
|
|
124
|
-
ctx.setTransform(scale * Math.cos(p.rot), scale * Math.sin(p.rot), -scale * Math.sin(p.rot) * Math.cos(p.flip), scale * Math.cos(p.rot) * Math.cos(p.flip), p.x * dpr, p.y * dpr)
|
|
125
|
-
ctx.translate(-SIZE / 2, -SIZE / 2)
|
|
126
|
-
ctx.fill(p.path)
|
|
127
|
-
}
|
|
128
|
-
raf = requestAnimationFrame(frame)
|
|
129
|
-
}
|
|
78
|
+
let pieces: Piece[] = []
|
|
79
|
+
let emitters: Emitter[] = []
|
|
130
80
|
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
const
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
81
|
+
const layer: EffectLayer = {
|
|
82
|
+
step(ctx, dt, dpr, now) {
|
|
83
|
+
const height = window.innerHeight
|
|
84
|
+
emitters = emitters.filter((e) => e.until > now)
|
|
85
|
+
for (const e of emitters) {
|
|
86
|
+
e.carry += e.rate * dt
|
|
87
|
+
for (; e.carry >= 1; e.carry--) pieces.push(e.spawn())
|
|
88
|
+
}
|
|
89
|
+
pieces = pieces.filter((p) => p.age < p.life && p.y < height + 60)
|
|
90
|
+
for (const p of pieces) {
|
|
91
|
+
p.age += dt
|
|
92
|
+
p.vx -= p.vx * DRAG * dt
|
|
93
|
+
p.vy += (GRAVITY - p.vy * DRAG) * dt
|
|
94
|
+
p.x += p.vx * dt
|
|
95
|
+
p.y += p.vy * dt
|
|
96
|
+
p.rot += p.spin * dt
|
|
97
|
+
p.flip += p.flipSpeed * dt
|
|
98
|
+
const fade = Math.min(1, (p.life - p.age) / 0.6)
|
|
99
|
+
ctx.globalAlpha = Math.max(0, fade)
|
|
100
|
+
ctx.fillStyle = p.color
|
|
101
|
+
const scale = (p.size / SIZE) * dpr
|
|
102
|
+
ctx.setTransform(scale * Math.cos(p.rot), scale * Math.sin(p.rot), -scale * Math.sin(p.rot) * Math.cos(p.flip), scale * Math.cos(p.rot) * Math.cos(p.flip), p.x * dpr, p.y * dpr)
|
|
103
|
+
ctx.translate(-SIZE / 2, -SIZE / 2)
|
|
104
|
+
ctx.fill(p.path)
|
|
105
|
+
}
|
|
106
|
+
return pieces.length > 0 || emitters.length > 0
|
|
107
|
+
},
|
|
144
108
|
}
|
|
145
109
|
|
|
146
|
-
function themeColors(el: Element) {
|
|
147
|
-
const style = getComputedStyle(el)
|
|
148
|
-
const colors = ROLES.map((role) => style.getPropertyValue(`--color-${role}`).trim()).filter(Boolean)
|
|
149
|
-
return colors.length ? colors : ['#6750a4', '#625b71', '#7d5260', '#eaddff', '#ffd8e4']
|
|
150
|
-
}
|
|
151
110
|
|
|
152
|
-
/**
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
111
|
+
/**
|
|
112
|
+
* Fires confetti: one burst, or with `duration` a rain or fountain that keeps going (stop it early with the returned
|
|
113
|
+
* function). Browser only; does nothing under reduced motion.
|
|
114
|
+
*/
|
|
115
|
+
export function fireConfetti(origin?: ConfettiOrigin, options: ConfettiOptions = {}): StopConfetti {
|
|
116
|
+
const noop = () => {}
|
|
117
|
+
if (typeof window === 'undefined') return noop
|
|
118
|
+
if (reducedMotion()) return noop
|
|
156
119
|
const top = options.from === 'top'
|
|
157
120
|
const point = originPoint(origin)
|
|
158
|
-
const colors = options.colors?.length ? options.colors : themeColors(point.el)
|
|
121
|
+
const colors = options.colors?.length ? options.colors : themeColors(point.el, ROLES)
|
|
159
122
|
const shapes = options.shapes?.length ? options.shapes : DEFAULT_SHAPES
|
|
160
123
|
const count = options.count ?? (top ? 160 : 80)
|
|
161
124
|
const spread = ((options.spread ?? 70) * Math.PI) / 180
|
|
162
125
|
const angle = ((options.angle ?? 0) * Math.PI) / 180
|
|
163
126
|
const speed = options.velocity ?? 950
|
|
164
127
|
const size = options.size ?? 14
|
|
165
|
-
|
|
166
|
-
|
|
128
|
+
// A rain with a duration starts its pieces just above the screen (they keep coming), a single one spread over a
|
|
129
|
+
// band above it (they all come at once)
|
|
130
|
+
const band = options.duration ? 0.05 : 0.4
|
|
131
|
+
const spawn = (): Piece => {
|
|
167
132
|
const dir = angle + (Math.random() - 0.5) * spread
|
|
168
133
|
const v = top ? 100 + Math.random() * 200 : speed * (0.55 + Math.random() * 0.6)
|
|
169
|
-
|
|
134
|
+
return {
|
|
170
135
|
x: top ? Math.random() * window.innerWidth : point.x,
|
|
171
|
-
y: top ? -20 - Math.random() * window.innerHeight *
|
|
136
|
+
y: top ? -20 - Math.random() * window.innerHeight * band : point.y,
|
|
172
137
|
vx: top ? (Math.random() - 0.5) * 200 : Math.sin(dir) * v,
|
|
173
138
|
vy: top ? v : -Math.cos(dir) * v,
|
|
174
139
|
rot: Math.random() * Math.PI * 2,
|
|
@@ -180,25 +145,37 @@ export function fireConfetti(origin?: ConfettiOrigin, options: ConfettiOptions =
|
|
|
180
145
|
color: colors[Math.floor(Math.random() * colors.length)]!,
|
|
181
146
|
age: 0,
|
|
182
147
|
life: top ? 4 + Math.random() * 1.5 : 2.4 + Math.random() * 1.2,
|
|
183
|
-
}
|
|
148
|
+
}
|
|
184
149
|
}
|
|
185
|
-
if (!
|
|
186
|
-
|
|
187
|
-
|
|
150
|
+
if (!runLayer(layer)) return noop
|
|
151
|
+
let emitter: Emitter | null = null
|
|
152
|
+
if (options.duration && options.duration > 0) {
|
|
153
|
+
emitter = { until: performance.now() + options.duration, rate: count, carry: 0, spawn }
|
|
154
|
+
emitters.push(emitter)
|
|
155
|
+
} else {
|
|
156
|
+
for (let i = 0; i < count; i++) pieces.push(spawn())
|
|
157
|
+
}
|
|
158
|
+
return () => {
|
|
159
|
+
if (emitter) emitter.until = 0
|
|
188
160
|
}
|
|
189
161
|
}
|
|
190
162
|
|
|
191
|
-
/**
|
|
163
|
+
/**
|
|
164
|
+
* Confetti for a component: `fire(event)` from the pointer, `fire(el)` from an element, `fire({ from: 'top' })`,
|
|
165
|
+
* `fire({ from: 'top', duration: 5000 })` for a rain that lasts. Returns a function that stops it early.
|
|
166
|
+
*/
|
|
192
167
|
export function useConfetti() {
|
|
193
|
-
function fire(origin?: ConfettiOrigin | ConfettiOptions, options?: ConfettiOptions) {
|
|
168
|
+
function fire(origin?: ConfettiOrigin | ConfettiOptions, options?: ConfettiOptions): StopConfetti {
|
|
194
169
|
const isOrigin = origin instanceof Event || (typeof Element !== 'undefined' && origin instanceof Element) || (origin && 'x' in origin && 'y' in origin && !('from' in origin))
|
|
195
|
-
if (isOrigin) fireConfetti(origin as ConfettiOrigin, options)
|
|
196
|
-
|
|
170
|
+
if (isOrigin) return fireConfetti(origin as ConfettiOrigin, options)
|
|
171
|
+
return fireConfetti(undefined, { ...(origin as ConfettiOptions | undefined), ...options })
|
|
197
172
|
}
|
|
198
173
|
return { fire }
|
|
199
174
|
}
|
|
200
175
|
|
|
201
176
|
/** Stops every burst and removes the canvas. Internal, for tests; not exported from index.ts. */
|
|
202
177
|
export function __resetConfetti() {
|
|
203
|
-
|
|
178
|
+
pieces = []
|
|
179
|
+
emitters = []
|
|
180
|
+
__resetEffectCanvas()
|
|
204
181
|
}
|