@m3ui-vue/m3ui-vue 1.0.0 → 1.0.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 +42 -15
- package/dist/{MTextField-TZ7lfr09.js → MTextField-BPbFeI9M.js} +76 -73
- package/dist/MTextField-BPbFeI9M.js.map +1 -0
- package/dist/api.json +1 -1
- package/dist/chart.js +1 -1
- package/dist/chart.js.map +1 -1
- package/dist/components/MNavigationDrawer.vue.d.ts +9 -6
- package/dist/components/MShader.vue.d.ts +9 -3
- package/dist/components/MTransition.vue.d.ts +0 -9
- package/dist/composables/_hydration.d.ts +4 -0
- package/dist/composables/_springAnimation.d.ts +17 -0
- package/dist/composables/themeInitScript.d.ts +21 -0
- package/dist/composables/useColorPalette.d.ts +4 -0
- package/dist/composables/useTheme.d.ts +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/m3ui-vue.css +1 -1
- package/dist/m3ui.js +3017 -2782
- package/dist/m3ui.js.map +1 -1
- package/dist/plugin.d.ts +7 -0
- package/dist/rich-text-editor.js +1 -1
- package/dist/styles.css +1 -1
- package/package.json +1 -1
- package/src/__tests__/MAppBarWithSearch.test.ts +12 -0
- package/src/__tests__/MBottomSheetScaffold.test.ts +21 -0
- package/src/__tests__/MNavigationDrawer.test.ts +185 -0
- package/src/__tests__/MNavigationRail.test.ts +17 -1
- package/src/__tests__/MPullToRefresh.test.ts +18 -1
- package/src/__tests__/MShader.test.ts +16 -0
- package/src/__tests__/MTransition.test.ts +12 -0
- package/src/__tests__/hydration.test.ts +86 -0
- package/src/__tests__/sheets.test.ts +19 -15
- package/src/__tests__/ssr.test.ts +109 -0
- package/src/__tests__/themeInitScript.test.ts +104 -0
- package/src/components/MBottomSheetScaffold.vue +23 -2
- package/src/components/MChart.vue +3 -2
- package/src/components/MContextMenu.vue +34 -33
- package/src/components/MLightbox.vue +6 -1
- package/src/components/MMenu.vue +34 -33
- package/src/components/MNavigationDrawer.vue +297 -37
- package/src/components/MNavigationRail.vue +69 -15
- package/src/components/MPullToRefresh.vue +18 -0
- package/src/components/MSearchBar.vue +8 -4
- package/src/components/MShader.vue +11 -3
- package/src/components/MTransition.vue +36 -41
- package/src/composables/_hydration.ts +10 -0
- package/src/composables/_springAnimation.ts +74 -0
- package/src/composables/_useSheetMotion.ts +101 -88
- package/src/composables/themeInitScript.ts +49 -0
- package/src/composables/useColorPalette.ts +10 -6
- package/src/composables/useTheme.ts +12 -6
- package/src/composables/useWindowSizeClass.ts +14 -4
- package/src/index.ts +2 -0
- package/src/plugin.ts +24 -11
- package/dist/MTextField-TZ7lfr09.js.map +0 -1
|
@@ -25,18 +25,24 @@ export type ShaderStatus = 'loading' | 'ready' | 'error' | 'fallback'
|
|
|
25
25
|
const props = withDefaults(
|
|
26
26
|
defineProps<{
|
|
27
27
|
/** GLSL fragment shader body (Shadertoy-style): must define `mainImage(out vec4 fragColor, in vec2 fragCoord)`.
|
|
28
|
-
* Runs on WebGL2. Always required as the compatible baseline.
|
|
28
|
+
* Runs on WebGL2. Always required as the compatible baseline. Don't write the `#version`, the precision or any
|
|
29
|
+
* uniform: the component puts them in front of your code, with Shadertoy's `iTime` (seconds, stops while
|
|
30
|
+
* paused), `iResolution` (canvas size in device pixels), `iMouse` and `iFrame`, plus one per `uniforms` key. */
|
|
29
31
|
code: string
|
|
30
32
|
/** Optional WGSL fragment shader module, e.g. `@fragment fn fs_main(@builtin(position) pos: vec4f) -> @location(0) vec4f`.
|
|
31
33
|
* Runs on WebGPU when available. Must declare its own bindings — see docs for the required uniform buffer layout. */
|
|
32
34
|
wgsl?: string
|
|
33
35
|
/** Which backend to use. 'auto' picks WebGPU when `wgsl` is set and supported, else WebGL2. */
|
|
34
36
|
renderer?: ShaderRenderer
|
|
35
|
-
/** Custom uniforms.
|
|
37
|
+
/** Custom uniforms, read every frame. In GLSL each key is declared for you, as a `float` for a number or a
|
|
38
|
+
* `vec2`–`vec4` for an array; in WGSL they're binding 1, one `vec4f` per key in this order. Keys and shapes
|
|
39
|
+
* are fixed when the shader compiles (on mount, or when `code`/`wgsl`/`renderer` change); values can change
|
|
40
|
+
* freely, e.g. to drive the shader from your own clock instead of `iTime`. */
|
|
36
41
|
uniforms?: Record<string, number | number[]>
|
|
37
42
|
/** Freezes the render loop and the shader clock */
|
|
38
43
|
paused?: boolean
|
|
39
|
-
/** Device pixel
|
|
44
|
+
/** Device pixels per CSS pixel to render at. Defaults to devicePixelRatio, capped at 2 for performance. Lower it to
|
|
45
|
+
* render fewer pixels (a "quality" setting); the canvas is resized when it changes. */
|
|
40
46
|
pixelRatio?: number
|
|
41
47
|
}>(),
|
|
42
48
|
{ renderer: 'auto' },
|
|
@@ -532,6 +538,8 @@ watch(
|
|
|
532
538
|
},
|
|
533
539
|
)
|
|
534
540
|
|
|
541
|
+
watch(() => props.pixelRatio, () => resize())
|
|
542
|
+
|
|
535
543
|
watch(
|
|
536
544
|
() => props.paused,
|
|
537
545
|
(isPaused) => {
|
|
@@ -8,6 +8,8 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @slot default The current view; give it a `key` that changes with it
|
|
10
10
|
*/
|
|
11
|
+
import { sampleSpring, playSamples } from '../composables/_springAnimation'
|
|
12
|
+
|
|
11
13
|
const props = withDefaults(defineProps<{
|
|
12
14
|
/** `shared-axis` (horizontal, for forward/back navigation) or `fade-through` (unrelated destinations) */
|
|
13
15
|
type?: 'shared-axis' | 'fade-through'
|
|
@@ -18,8 +20,7 @@ const props = withDefaults(defineProps<{
|
|
|
18
20
|
}>(), { type: 'shared-axis', reverse: false, appear: false })
|
|
19
21
|
|
|
20
22
|
// slideIn/OutHorizontally and scaleIn/Out default to spring(stiffness = StiffnessMediumLow), no bounce
|
|
21
|
-
const
|
|
22
|
-
const DAMPING = 2 * Math.sqrt(STIFFNESS)
|
|
23
|
+
const SPRING = { dampingRatio: 1, stiffness: 400 }
|
|
23
24
|
// HorizontalSharedAxis
|
|
24
25
|
const SLIDE_FRACTION = 0.2
|
|
25
26
|
const AXIS_FADE = { duration: 90, delay: 50 }
|
|
@@ -30,54 +31,50 @@ const INITIAL_SCALE = 0.8
|
|
|
30
31
|
const TARGET_SCALE = 1.05
|
|
31
32
|
|
|
32
33
|
interface Motion {
|
|
33
|
-
/** Spring from `from` to `to` (an x offset
|
|
34
|
+
/** Spring from `from` to `to` (an x offset as a fraction of the view's width, or a scale) */
|
|
34
35
|
from: number
|
|
35
36
|
to: number
|
|
36
|
-
|
|
37
|
+
transform: (value: number) => string
|
|
37
38
|
/** Linear opacity tween */
|
|
38
39
|
fade: { from: number; to: number; duration: number; delay: number }
|
|
39
40
|
}
|
|
40
41
|
|
|
41
42
|
const running = new WeakMap<Element, () => void>()
|
|
42
43
|
|
|
44
|
+
// Played as Web Animations (see _springAnimation.ts), which the compositor runs, so the entering view mounting
|
|
45
|
+
// (the busiest moment of a navigation) doesn't jank the transition
|
|
43
46
|
function run(el: HTMLElement, m: Motion, done: () => void) {
|
|
44
47
|
running.get(el)?.()
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
48
|
+
const samples = sampleSpring(m.from, m.to, 0, SPRING, 0.001)
|
|
49
|
+
const move = playSamples(el, samples, (v) => ({ transform: m.transform(v) }))
|
|
50
|
+
const fade = typeof el.animate === 'function'
|
|
51
|
+
? el.animate([{ opacity: String(m.fade.from) }, { opacity: String(m.fade.to) }], {
|
|
52
|
+
duration: m.fade.duration,
|
|
53
|
+
delay: m.fade.delay,
|
|
54
|
+
easing: 'linear',
|
|
55
|
+
// Holds the starting opacity through the delay
|
|
56
|
+
fill: 'backwards',
|
|
57
|
+
})
|
|
58
|
+
: null
|
|
59
|
+
fade?.finished.catch(() => {})
|
|
60
|
+
// The end state goes inline underneath
|
|
61
|
+
el.style.transform = m.transform(m.to)
|
|
62
|
+
el.style.opacity = String(m.fade.to)
|
|
63
|
+
let ended = false
|
|
51
64
|
const finish = () => {
|
|
52
|
-
|
|
65
|
+
if (ended) return
|
|
66
|
+
ended = true
|
|
67
|
+
move?.cancel()
|
|
68
|
+
fade?.cancel()
|
|
53
69
|
running.delete(el)
|
|
54
70
|
done()
|
|
55
71
|
}
|
|
56
72
|
running.set(el, finish)
|
|
57
|
-
|
|
58
|
-
let dt = Math.min((now - last) / 1000, 1 / 30)
|
|
59
|
-
last = now
|
|
60
|
-
while (dt > 0) {
|
|
61
|
-
const h = Math.min(dt, 0.004)
|
|
62
|
-
dt -= h
|
|
63
|
-
velocity += (-STIFFNESS * (value - m.to) - DAMPING * velocity) * h
|
|
64
|
-
value += velocity * h
|
|
65
|
-
}
|
|
66
|
-
const springDone = Math.abs(value - m.to) < threshold && Math.abs(velocity) < threshold * 10
|
|
67
|
-
if (springDone) value = m.to
|
|
68
|
-
m.apply(value, el)
|
|
69
|
-
const t = Math.min(1, Math.max(0, (now - start - m.fade.delay) / m.fade.duration))
|
|
70
|
-
el.style.opacity = String(m.fade.from + (m.fade.to - m.fade.from) * t)
|
|
71
|
-
if (springDone && t >= 1) finish()
|
|
72
|
-
else raf = requestAnimationFrame(frame)
|
|
73
|
-
}
|
|
74
|
-
m.apply(m.from, el)
|
|
75
|
-
el.style.opacity = String(m.fade.from)
|
|
76
|
-
raf = requestAnimationFrame(frame)
|
|
73
|
+
Promise.all([move?.finished, fade?.finished]).then(finish, () => {})
|
|
77
74
|
}
|
|
78
75
|
|
|
79
|
-
const translate = (x: number
|
|
80
|
-
const scale = (
|
|
76
|
+
const translate = (x: number) => `translateX(${x * 100}%)`
|
|
77
|
+
const scale = (v: number) => `scale(${v})`
|
|
81
78
|
|
|
82
79
|
function clear(el: HTMLElement) {
|
|
83
80
|
el.style.transform = ''
|
|
@@ -89,16 +86,15 @@ function onEnter(element: Element, done: () => void) {
|
|
|
89
86
|
const el = element as HTMLElement
|
|
90
87
|
const finish = () => { clear(el); done() }
|
|
91
88
|
if (props.type === 'fade-through') {
|
|
92
|
-
run(el, { from: INITIAL_SCALE, to: 1,
|
|
89
|
+
run(el, { from: INITIAL_SCALE, to: 1, transform: scale, fade: { from: 0, to: 1, duration: FADE_IN, delay: FADE_OUT } }, finish)
|
|
93
90
|
return
|
|
94
91
|
}
|
|
95
|
-
const w = el.offsetWidth
|
|
96
92
|
// Backward: the entering view sits under the leaving one (targetContentZIndex = -10)
|
|
97
93
|
if (props.reverse) el.style.zIndex = '-1'
|
|
98
94
|
run(el, {
|
|
99
|
-
from: (props.reverse ? -1 : 1) *
|
|
95
|
+
from: (props.reverse ? -1 : 1) * SLIDE_FRACTION,
|
|
100
96
|
to: 0,
|
|
101
|
-
|
|
97
|
+
transform: translate,
|
|
102
98
|
fade: { from: 0, to: 1, ...AXIS_FADE },
|
|
103
99
|
}, finish)
|
|
104
100
|
}
|
|
@@ -107,14 +103,13 @@ function onLeave(element: Element, done: () => void) {
|
|
|
107
103
|
const el = element as HTMLElement
|
|
108
104
|
const finish = () => { clear(el); done() }
|
|
109
105
|
if (props.type === 'fade-through') {
|
|
110
|
-
run(el, { from: 1, to: TARGET_SCALE,
|
|
106
|
+
run(el, { from: 1, to: TARGET_SCALE, transform: scale, fade: { from: 1, to: 0, duration: FADE_OUT, delay: 0 } }, finish)
|
|
111
107
|
return
|
|
112
108
|
}
|
|
113
|
-
const w = el.offsetWidth
|
|
114
109
|
run(el, {
|
|
115
110
|
from: 0,
|
|
116
|
-
to: (props.reverse ? 1 : -1) *
|
|
117
|
-
|
|
111
|
+
to: (props.reverse ? 1 : -1) * SLIDE_FRACTION,
|
|
112
|
+
transform: translate,
|
|
118
113
|
fade: { from: 1, to: 0, ...AXIS_FADE },
|
|
119
114
|
}, finish)
|
|
120
115
|
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { getCurrentInstance, inject, type InjectionKey } from 'vue'
|
|
2
|
+
|
|
3
|
+
// Internal: `createM3UI({ isHydrating })`. A server-rendered app's first client render has to match the server's
|
|
4
|
+
// HTML, so what the server can't know (the window's size) starts from the server's value until the app is mounted.
|
|
5
|
+
export const M3_HYDRATING_KEY: InjectionKey<() => boolean> = Symbol('m3-hydrating')
|
|
6
|
+
|
|
7
|
+
/** Whether the calling component is being hydrated from server-rendered HTML (false outside a component's setup). */
|
|
8
|
+
export function isHydrating(): boolean {
|
|
9
|
+
return getCurrentInstance() ? inject(M3_HYDRATING_KEY, null)?.() ?? false : false
|
|
10
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { SpringSpec } from './motion'
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* Internal (not exported from index.ts): springs played as Web Animations.
|
|
5
|
+
*
|
|
6
|
+
* The library's springs normally step in a rAF loop (see CLAUDE.md). That loop runs on the main thread, and an
|
|
7
|
+
* enter/exit animation starts exactly when the main thread is busiest: mounting the panel's content, re-laying
|
|
8
|
+
* out the page for a scroll lock. On phones that janked visibly (MNavigationDrawer's open, where the old CSS
|
|
9
|
+
* transition hadn't, since the compositor runs those). So enter/exit/settle springs are simulated up front, one
|
|
10
|
+
* sample per 60Hz frame, and played as a linear Web Animation of transform/opacity, which the compositor runs
|
|
11
|
+
* too. Same curve, bounce and release velocity as the loop; only a finger-driven drag writes styles directly.
|
|
12
|
+
*
|
|
13
|
+
* Pattern: write the end state inline, then play the samples over it (an animation beats inline styles), so
|
|
14
|
+
* nothing jumps when it ends; to interrupt, read `sampleAt(samples, anim.currentTime)`, write that inline and
|
|
15
|
+
* cancel.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
export const SAMPLE_MS = 1000 / 60
|
|
19
|
+
// Stiff springs (FastEffects, 3800) diverge at a 16ms Euler step: integrate in 4ms substeps
|
|
20
|
+
const SUBSTEP = 0.004
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The spring from `from` to `to`, starting at `velocity` (units/s), one sample per 60Hz frame until it's within
|
|
24
|
+
* `epsilon` of `to` (and slower than `epsilon * 10` per second). The last sample is exactly `to`.
|
|
25
|
+
*/
|
|
26
|
+
export function sampleSpring(from: number, to: number, velocity: number, spring: SpringSpec, epsilon: number): number[] {
|
|
27
|
+
const out = [from]
|
|
28
|
+
let pos = from
|
|
29
|
+
let vel = velocity
|
|
30
|
+
const damping = 2 * spring.dampingRatio * Math.sqrt(spring.stiffness)
|
|
31
|
+
for (let i = 0; i < 600; i++) {
|
|
32
|
+
for (let left = SAMPLE_MS / 1000; left > 1e-9; left -= SUBSTEP) {
|
|
33
|
+
const h = Math.min(SUBSTEP, left)
|
|
34
|
+
vel += (-spring.stiffness * (pos - to) - damping * vel) * h
|
|
35
|
+
pos += vel * h
|
|
36
|
+
}
|
|
37
|
+
out.push(pos)
|
|
38
|
+
if (Math.abs(pos - to) < epsilon && Math.abs(vel) < epsilon * 10) break
|
|
39
|
+
}
|
|
40
|
+
out[out.length - 1] = to
|
|
41
|
+
return out
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The value `samples` has `time` ms into playback (an Animation's currentTime), linear between frames */
|
|
45
|
+
export function sampleAt(samples: number[], time: CSSNumberish | null | undefined): number {
|
|
46
|
+
const t = Number(time ?? 0) / SAMPLE_MS
|
|
47
|
+
const i = Math.floor(t)
|
|
48
|
+
if (i >= samples.length - 1) return samples[samples.length - 1]!
|
|
49
|
+
if (i < 0) return samples[0]!
|
|
50
|
+
return samples[i]! + (samples[i + 1]! - samples[i]!) * (t - i)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** How long `samples` play, in ms */
|
|
54
|
+
export const samplesDuration = (samples: number[]) => (samples.length - 1) * SAMPLE_MS
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Plays `samples` on `el` as a linear Web Animation, each mapped to a keyframe. Null when there's nothing to
|
|
58
|
+
* play or no Web Animations API (the inline end state then simply stands).
|
|
59
|
+
*/
|
|
60
|
+
export function playSamples(
|
|
61
|
+
el: Element | null | undefined,
|
|
62
|
+
samples: number[],
|
|
63
|
+
keyframe: (value: number) => Keyframe,
|
|
64
|
+
delay = 0,
|
|
65
|
+
): Animation | null {
|
|
66
|
+
if (!el || typeof (el as HTMLElement).animate !== 'function' || samples.length < 2) return null
|
|
67
|
+
const anim = (el as HTMLElement).animate(samples.map(keyframe), { duration: samplesDuration(samples), delay, easing: 'linear' })
|
|
68
|
+
// cancel() rejects `finished`; nothing has to wait on it
|
|
69
|
+
anim.finished.catch(() => {})
|
|
70
|
+
return anim
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export const prefersReducedMotion = () =>
|
|
74
|
+
typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { onBeforeUnmount } from 'vue'
|
|
2
|
+
import { motionSprings, type SpringSpec } from './motion'
|
|
3
|
+
import { sampleSpring, sampleAt, playSamples, prefersReducedMotion } from './_springAnimation'
|
|
2
4
|
|
|
3
5
|
/*
|
|
4
6
|
* Internal (not exported from index.ts): enter/exit/drag motion for modal sheets
|
|
@@ -8,99 +10,114 @@ import { onBeforeUnmount } from 'vue'
|
|
|
8
10
|
* (1.0 / 1600). The panel slides only, no opacity fade. A drag release springs from where
|
|
9
11
|
* the finger left it, carrying its velocity, either back open or out.
|
|
10
12
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
13
|
+
* The springs play as Web Animations (see _springAnimation.ts), on the compositor, so the
|
|
14
|
+
* enter isn't janked by the sheet's content mounting at the same moment; only the drag writes
|
|
15
|
+
* the transform directly. The offset is a fraction of the panel's size, so entering never reads
|
|
16
|
+
* layout. The panel's transform must never also be bound reactively in the template, which is
|
|
17
|
+
* what silently killed the old CSS enter animation.
|
|
14
18
|
*
|
|
15
19
|
* Wire it to a `<Transition :css="false" @enter @leave>` around a root holding
|
|
16
20
|
* `[data-sheet-panel]` and `[data-sheet-scrim]`.
|
|
17
21
|
*/
|
|
18
22
|
|
|
19
|
-
|
|
20
|
-
const
|
|
21
|
-
const
|
|
22
|
-
const DEFAULT_EFFECTS: Spring = { damping: 1, stiffness: 1600 }
|
|
23
|
+
const DEFAULT_SPATIAL = motionSprings.standard.defaultSpatial
|
|
24
|
+
const FAST_EFFECTS = motionSprings.standard.fastEffects
|
|
25
|
+
const DEFAULT_EFFECTS = motionSprings.standard.defaultEffects
|
|
23
26
|
|
|
24
27
|
/** Past this many px, or this fast (px/s) toward closing, a released drag dismisses. */
|
|
25
28
|
const DISMISS_DISTANCE = 100
|
|
26
29
|
const DISMISS_VELOCITY = 1000
|
|
27
30
|
|
|
28
|
-
// Semi-implicit Euler in fixed 4ms substeps: FastEffects' stiffness (3800) is unstable at
|
|
29
|
-
// a dropped frame's 33ms step (it diverges instead of settling).
|
|
30
|
-
const SUBSTEP = 0.004
|
|
31
|
-
function step(s: { pos: number; vel: number }, target: number, spring: Spring, dt: number) {
|
|
32
|
-
for (let left = dt; left > 0; left -= SUBSTEP) {
|
|
33
|
-
const h = Math.min(SUBSTEP, left)
|
|
34
|
-
const accel = -spring.stiffness * (s.pos - target) - 2 * spring.damping * Math.sqrt(spring.stiffness) * s.vel
|
|
35
|
-
s.vel += accel * h
|
|
36
|
-
s.pos += s.vel * h
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
|
|
40
31
|
export function useSheetMotion(axis: 'x' | 'y', onDismiss: () => void) {
|
|
41
32
|
let panel: HTMLElement | null = null
|
|
42
33
|
let scrim: HTMLElement | null = null
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
let
|
|
34
|
+
// 0 = open, 1 = off-screen (a fraction of the panel's size); alpha is the scrim's opacity
|
|
35
|
+
let offset = 0
|
|
36
|
+
let alpha = 0
|
|
46
37
|
let alphaTarget = 0
|
|
47
|
-
let
|
|
38
|
+
let velocity = 0
|
|
39
|
+
let offsetAnim: Animation | null = null
|
|
40
|
+
let alphaAnim: Animation | null = null
|
|
41
|
+
let offsetSamples: number[] = []
|
|
42
|
+
let alphaSamples: number[] = []
|
|
48
43
|
let settled: (() => void) | null = null
|
|
49
|
-
let raf = 0
|
|
50
|
-
let last = 0
|
|
51
44
|
|
|
52
45
|
let dragging = false
|
|
53
46
|
let dragStart = 0
|
|
54
47
|
let dragOrigin = 0
|
|
48
|
+
let size = 1
|
|
55
49
|
let lastMove = { at: 0, pos: 0 }
|
|
50
|
+
let dragVelocity = 0
|
|
56
51
|
|
|
57
|
-
const
|
|
58
|
-
const reducedMotion = () =>
|
|
59
|
-
typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches
|
|
52
|
+
const translate = (f: number) => (axis === 'y' ? `translateY(${f * 100}%)` : `translateX(${f * 100}%)`)
|
|
60
53
|
|
|
61
54
|
function write() {
|
|
62
|
-
if (panel) panel.style.transform =
|
|
63
|
-
if (scrim) scrim.style.opacity = String(Math.min(1, Math.max(0, alpha
|
|
55
|
+
if (panel) panel.style.transform = translate(offset)
|
|
56
|
+
if (scrim) scrim.style.opacity = String(Math.min(1, Math.max(0, alpha)))
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function stopOffset() {
|
|
60
|
+
if (!offsetAnim) return
|
|
61
|
+
offset = sampleAt(offsetSamples, offsetAnim.currentTime)
|
|
62
|
+
if (panel) panel.style.transform = translate(offset)
|
|
63
|
+
offsetAnim.cancel()
|
|
64
|
+
offsetAnim = null
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function stopAlpha() {
|
|
68
|
+
if (!alphaAnim) return
|
|
69
|
+
alpha = sampleAt(alphaSamples, alphaAnim.currentTime)
|
|
70
|
+
if (scrim) scrim.style.opacity = String(Math.min(1, Math.max(0, alpha)))
|
|
71
|
+
alphaAnim.cancel()
|
|
72
|
+
alphaAnim = null
|
|
64
73
|
}
|
|
65
74
|
|
|
66
|
-
function
|
|
67
|
-
|
|
75
|
+
function maybeSettle() {
|
|
76
|
+
if (offsetAnim || alphaAnim || dragging) return
|
|
68
77
|
const cb = settled
|
|
69
78
|
settled = null
|
|
70
79
|
cb?.()
|
|
71
80
|
}
|
|
72
81
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
const offsetDone = dragging || (Math.abs(offset.pos - offsetTarget) < 0.5 && Math.abs(offset.vel) < 5)
|
|
79
|
-
const alphaDone = Math.abs(alpha.pos - alphaTarget) < 0.002 && Math.abs(alpha.vel) < 0.05
|
|
80
|
-
if (offsetDone && alphaDone) {
|
|
81
|
-
if (!dragging) offset.pos = offsetTarget
|
|
82
|
-
alpha.pos = alphaTarget
|
|
83
|
-
offset.vel = alpha.vel = 0
|
|
84
|
-
write()
|
|
85
|
-
if (!dragging) return finish()
|
|
86
|
-
raf = 0
|
|
87
|
-
return
|
|
82
|
+
// Without `done`, a pending Transition callback (an enter interrupted by a drag) is kept for this run
|
|
83
|
+
function animate(offsetTo: number, spring: SpringSpec, alphaTo: number, done?: () => void) {
|
|
84
|
+
if (done) {
|
|
85
|
+
settled?.()
|
|
86
|
+
settled = done
|
|
88
87
|
}
|
|
88
|
+
stopOffset()
|
|
89
|
+
const fromOffset = offset
|
|
90
|
+
const v = velocity
|
|
91
|
+
velocity = 0
|
|
92
|
+
// The scrim keeps its running fade when its target doesn't change (a drag released back open)
|
|
93
|
+
const restartAlpha = alphaTo !== alphaTarget || !alphaAnim
|
|
94
|
+
if (restartAlpha) stopAlpha()
|
|
95
|
+
const fromAlpha = alpha
|
|
96
|
+
alphaTarget = alphaTo
|
|
97
|
+
// End states inline underneath, so nothing jumps when the animations end
|
|
98
|
+
offset = offsetTo
|
|
99
|
+
if (restartAlpha) alpha = alphaTo
|
|
89
100
|
write()
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
if (reducedMotion()) {
|
|
95
|
-
offset.pos = offsetTarget
|
|
96
|
-
alpha.pos = alphaTarget
|
|
97
|
-
offset.vel = alpha.vel = 0
|
|
101
|
+
if (prefersReducedMotion()) {
|
|
102
|
+
alphaAnim?.cancel()
|
|
103
|
+
alphaAnim = null
|
|
104
|
+
alpha = alphaTo
|
|
98
105
|
write()
|
|
99
|
-
return
|
|
106
|
+
return maybeSettle()
|
|
107
|
+
}
|
|
108
|
+
if (fromOffset !== offsetTo) {
|
|
109
|
+
offsetSamples = sampleSpring(fromOffset, offsetTo, v, spring, 0.001)
|
|
110
|
+
const a = playSamples(panel, offsetSamples, (f) => ({ transform: translate(f) }))
|
|
111
|
+
offsetAnim = a
|
|
112
|
+
if (a) a.onfinish = () => { if (offsetAnim === a) { offsetAnim = null; maybeSettle() } }
|
|
113
|
+
}
|
|
114
|
+
if (restartAlpha && fromAlpha !== alphaTo) {
|
|
115
|
+
alphaSamples = sampleSpring(fromAlpha, alphaTo, 0, DEFAULT_EFFECTS, 0.002)
|
|
116
|
+
const a = playSamples(scrim, alphaSamples, (o) => ({ opacity: String(Math.min(1, Math.max(0, o))) }))
|
|
117
|
+
alphaAnim = a
|
|
118
|
+
if (a) a.onfinish = () => { if (alphaAnim === a) { alphaAnim = null; maybeSettle() } }
|
|
100
119
|
}
|
|
101
|
-
|
|
102
|
-
last = performance.now()
|
|
103
|
-
raf = requestAnimationFrame(frame)
|
|
120
|
+
maybeSettle()
|
|
104
121
|
}
|
|
105
122
|
|
|
106
123
|
function bind(el: Element) {
|
|
@@ -112,69 +129,65 @@ export function useSheetMotion(axis: 'x' | 'y', onDismiss: () => void) {
|
|
|
112
129
|
// Reopened mid-exit: let the old element go now instead of leaving it in the DOM.
|
|
113
130
|
settled?.()
|
|
114
131
|
settled = null
|
|
115
|
-
|
|
116
|
-
|
|
132
|
+
offsetAnim?.cancel()
|
|
133
|
+
alphaAnim?.cancel()
|
|
134
|
+
offsetAnim = alphaAnim = null
|
|
117
135
|
bind(el)
|
|
118
|
-
offset
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
offsetTarget = 0
|
|
123
|
-
alphaTarget = 1
|
|
124
|
-
offsetSpring = DEFAULT_SPATIAL
|
|
125
|
-
settled = done
|
|
136
|
+
offset = 1
|
|
137
|
+
alpha = 0
|
|
138
|
+
alphaTarget = 0
|
|
139
|
+
velocity = 0
|
|
126
140
|
write()
|
|
127
|
-
|
|
141
|
+
animate(0, DEFAULT_SPATIAL, 1, done)
|
|
128
142
|
}
|
|
129
143
|
|
|
130
144
|
function onLeave(el: Element, done: () => void) {
|
|
131
145
|
bind(el)
|
|
132
146
|
dragging = false
|
|
133
|
-
|
|
134
|
-
alphaTarget = 0
|
|
135
|
-
offsetSpring = FAST_EFFECTS
|
|
136
|
-
settled = done
|
|
137
|
-
run()
|
|
147
|
+
animate(1, FAST_EFFECTS, 0, done)
|
|
138
148
|
}
|
|
139
149
|
|
|
140
150
|
function onDragStart(e: PointerEvent) {
|
|
141
151
|
// A sheet mounted already open never ran onEnter: find its elements from the handle.
|
|
142
152
|
const root = (e.currentTarget as HTMLElement).closest('[data-sheet-panel]')?.parentElement
|
|
143
153
|
if (root) bind(root)
|
|
154
|
+
stopOffset()
|
|
144
155
|
dragging = true
|
|
156
|
+
size = (panel ? (axis === 'y' ? panel.offsetHeight : panel.offsetWidth) : 0) || 1
|
|
145
157
|
dragStart = axis === 'y' ? e.clientY : e.clientX
|
|
146
|
-
dragOrigin = offset
|
|
147
|
-
|
|
148
|
-
lastMove = { at: performance.now(), pos:
|
|
158
|
+
dragOrigin = offset * size
|
|
159
|
+
dragVelocity = 0
|
|
160
|
+
lastMove = { at: performance.now(), pos: dragOrigin }
|
|
149
161
|
;(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId)
|
|
150
162
|
}
|
|
151
163
|
|
|
152
164
|
function onDragMove(e: PointerEvent) {
|
|
153
165
|
if (!dragging) return
|
|
154
166
|
const now = performance.now()
|
|
155
|
-
|
|
167
|
+
const pos = Math.max(0, dragOrigin + (axis === 'y' ? e.clientY : e.clientX) - dragStart)
|
|
156
168
|
const dt = (now - lastMove.at) / 1000
|
|
157
|
-
if (dt > 0)
|
|
158
|
-
lastMove = { at: now, pos
|
|
159
|
-
|
|
169
|
+
if (dt > 0) dragVelocity = (pos - lastMove.pos) / dt
|
|
170
|
+
lastMove = { at: now, pos }
|
|
171
|
+
offset = pos / size
|
|
172
|
+
if (panel) panel.style.transform = translate(offset)
|
|
160
173
|
}
|
|
161
174
|
|
|
162
175
|
function onDragEnd() {
|
|
163
176
|
if (!dragging) return
|
|
164
177
|
dragging = false
|
|
165
178
|
// A pause before lifting the finger means no fling.
|
|
166
|
-
if (performance.now() - lastMove.at > 100)
|
|
167
|
-
|
|
179
|
+
if (performance.now() - lastMove.at > 100) dragVelocity = 0
|
|
180
|
+
velocity = dragVelocity / size
|
|
181
|
+
if (offset * size > DISMISS_DISTANCE || dragVelocity > DISMISS_VELOCITY) {
|
|
168
182
|
onDismiss()
|
|
169
183
|
} else {
|
|
170
|
-
|
|
171
|
-
offsetSpring = DEFAULT_SPATIAL
|
|
172
|
-
run()
|
|
184
|
+
animate(0, DEFAULT_SPATIAL, alphaTarget)
|
|
173
185
|
}
|
|
174
186
|
}
|
|
175
187
|
|
|
176
188
|
onBeforeUnmount(() => {
|
|
177
|
-
|
|
189
|
+
offsetAnim?.cancel()
|
|
190
|
+
alphaAnim?.cancel()
|
|
178
191
|
})
|
|
179
192
|
|
|
180
193
|
return { onEnter, onLeave, onDragStart, onDragMove, onDragEnd }
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { THEME_KEY } from './useTheme'
|
|
2
|
+
import { CONTRAST_KEY, CSS_KEY, PALETTE_KEY, STYLE_ID, type ContrastLevel } from './useColorPalette'
|
|
3
|
+
|
|
4
|
+
export interface ThemeInitOptions {
|
|
5
|
+
/** `createM3UI`'s `palette`: the first-visit default, or forced with `persistPalette: false`. */
|
|
6
|
+
palette?: string
|
|
7
|
+
/** `createM3UI`'s `contrast`, with the same rules as `palette`. */
|
|
8
|
+
contrast?: ContrastLevel
|
|
9
|
+
/** `createM3UI`'s `persistPalette`. */
|
|
10
|
+
persistPalette?: boolean
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* A script to inline in `<head>` of a server-rendered page (Nuxt, Vite SSR), so dark mode, the palette and the
|
|
15
|
+
* contrast level are on `<html>` before the first paint instead of when the app's JS loads. It does what
|
|
16
|
+
* `useTheme` and `useColorPalette` do when they load in the browser (the stored choice, or the given
|
|
17
|
+
* `createM3UI` defaults), so pass it the same options as the plugin. A `seed` default can't be generated this
|
|
18
|
+
* early: its first visit still shows the baseline until the app loads (later visits use the cached CSS).
|
|
19
|
+
*
|
|
20
|
+
* ```ts
|
|
21
|
+
* useHead({ script: [{ innerHTML: themeInitScript({ palette: 'red' }) }] })
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
export function themeInitScript(options: ThemeInitOptions = {}): string {
|
|
25
|
+
const config = JSON.stringify({
|
|
26
|
+
keys: { theme: THEME_KEY, palette: PALETTE_KEY, contrast: CONTRAST_KEY, css: CSS_KEY },
|
|
27
|
+
styleId: STYLE_ID,
|
|
28
|
+
palette: options.palette ?? null,
|
|
29
|
+
contrast: options.contrast ?? null,
|
|
30
|
+
force: options.persistPalette === false,
|
|
31
|
+
}).replace(/</g, '\\u003c')
|
|
32
|
+
// Plain ES5, no dependencies: it runs before anything else. Storage can throw (blocked site data).
|
|
33
|
+
return `(function(o){
|
|
34
|
+
var d=document.documentElement;
|
|
35
|
+
function get(k){try{return localStorage.getItem(k)}catch(e){return null}}
|
|
36
|
+
function mq(q){return !!(window.matchMedia&&window.matchMedia(q).matches)}
|
|
37
|
+
var t=get(o.keys.theme)||'system';
|
|
38
|
+
d.classList.toggle('dark',t==='dark'||(t==='system'&&mq('(prefers-color-scheme: dark)')));
|
|
39
|
+
var saved=get(o.keys.palette);
|
|
40
|
+
var p=o.force&&o.palette?o.palette:(saved||o.palette);
|
|
41
|
+
if(p&&p===saved){try{var c=JSON.parse(get(o.keys.css));if(c&&c.id===p){var s=document.createElement('style');s.id=o.styleId;s.textContent=c.css;document.head.appendChild(s)}}catch(e){}}
|
|
42
|
+
if(p&&p!=='purple')d.setAttribute('data-palette',p);
|
|
43
|
+
var levels=['standard','medium','high','system'];
|
|
44
|
+
var stored=get(o.keys.contrast);
|
|
45
|
+
var l=o.force&&o.contrast?o.contrast:stored!=null?(levels.indexOf(stored)>-1?stored:'standard'):(o.contrast||'standard');
|
|
46
|
+
if(l==='system')l=mq('(prefers-contrast: more)')?'high':'standard';
|
|
47
|
+
if(l!=='standard')d.setAttribute('data-contrast',l);
|
|
48
|
+
})(${config})`
|
|
49
|
+
}
|
|
@@ -65,11 +65,11 @@ export interface ActiveSeed extends SeedOptions {
|
|
|
65
65
|
seed: string
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
-
const PALETTE_KEY = 'm3-palette'
|
|
68
|
+
export const PALETTE_KEY = 'm3-palette'
|
|
69
69
|
const SEED_KEY = 'm3-seed'
|
|
70
|
-
const CONTRAST_KEY = 'm3-contrast'
|
|
70
|
+
export const CONTRAST_KEY = 'm3-contrast'
|
|
71
71
|
// The generated CSS of the active palette, so a reload applies it before the generator has loaded
|
|
72
|
-
const CSS_KEY = 'm3-palette-css'
|
|
72
|
+
export const CSS_KEY = 'm3-palette-css'
|
|
73
73
|
|
|
74
74
|
function read<T>(key: string): T | null {
|
|
75
75
|
try {
|
|
@@ -126,6 +126,7 @@ function applyContrast(level: Exclude<ContrastLevel, 'system'>) {
|
|
|
126
126
|
const persistEnabled = ref(true)
|
|
127
127
|
|
|
128
128
|
function applyAttribute(id: string) {
|
|
129
|
+
if (typeof document === 'undefined') return
|
|
129
130
|
if (id === 'purple') document.documentElement.removeAttribute('data-palette')
|
|
130
131
|
else document.documentElement.setAttribute('data-palette', id)
|
|
131
132
|
}
|
|
@@ -134,9 +135,10 @@ function applyAttribute(id: string) {
|
|
|
134
135
|
// One <style> element holds the generated CSS of the active palette (a seed, or a custom palette
|
|
135
136
|
// without CSS of its own).
|
|
136
137
|
|
|
137
|
-
const STYLE_ID = 'm3-dynamic-palette'
|
|
138
|
+
export const STYLE_ID = 'm3-dynamic-palette'
|
|
138
139
|
|
|
139
140
|
function injectCss(css: string) {
|
|
141
|
+
if (typeof document === 'undefined') return
|
|
140
142
|
let el = document.getElementById(STYLE_ID) as HTMLStyleElement | null
|
|
141
143
|
if (!el) {
|
|
142
144
|
el = document.createElement('style')
|
|
@@ -148,6 +150,7 @@ function injectCss(css: string) {
|
|
|
148
150
|
|
|
149
151
|
/** Whether a stylesheet (other than our generated one) already styles `[data-palette='<id>']`. */
|
|
150
152
|
function hasPaletteCss(id: string): boolean {
|
|
153
|
+
if (typeof document === 'undefined') return false
|
|
151
154
|
const needles = [`[data-palette="${id}"]`, `[data-palette='${id}']`, `[data-palette=${id}]`]
|
|
152
155
|
const scan = (rules: CSSRuleList): boolean => {
|
|
153
156
|
for (const rule of Array.from(rules)) {
|
|
@@ -289,8 +292,9 @@ export function useColorPalette() {
|
|
|
289
292
|
}
|
|
290
293
|
}
|
|
291
294
|
|
|
292
|
-
// Apply on module load so the palette is visible before any component mounts, a generated one included
|
|
293
|
-
|
|
295
|
+
// Apply on module load so the palette is visible before any component mounts, a generated one included (not on
|
|
296
|
+
// the server: the client does it when the module loads there)
|
|
297
|
+
if (typeof document !== 'undefined') {
|
|
294
298
|
const saved = read<string>(PALETTE_KEY)
|
|
295
299
|
const cached = read<{ id: string; css: string }>(CSS_KEY)
|
|
296
300
|
if (saved && cached && cached.id === saved) injectCss(cached.css)
|