@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.
Files changed (54) hide show
  1. package/dist/API.md +42 -15
  2. package/dist/{MTextField-TZ7lfr09.js → MTextField-BPbFeI9M.js} +76 -73
  3. package/dist/MTextField-BPbFeI9M.js.map +1 -0
  4. package/dist/api.json +1 -1
  5. package/dist/chart.js +1 -1
  6. package/dist/chart.js.map +1 -1
  7. package/dist/components/MNavigationDrawer.vue.d.ts +9 -6
  8. package/dist/components/MShader.vue.d.ts +9 -3
  9. package/dist/components/MTransition.vue.d.ts +0 -9
  10. package/dist/composables/_hydration.d.ts +4 -0
  11. package/dist/composables/_springAnimation.d.ts +17 -0
  12. package/dist/composables/themeInitScript.d.ts +21 -0
  13. package/dist/composables/useColorPalette.d.ts +4 -0
  14. package/dist/composables/useTheme.d.ts +1 -0
  15. package/dist/index.d.ts +2 -0
  16. package/dist/m3ui-vue.css +1 -1
  17. package/dist/m3ui.js +3017 -2782
  18. package/dist/m3ui.js.map +1 -1
  19. package/dist/plugin.d.ts +7 -0
  20. package/dist/rich-text-editor.js +1 -1
  21. package/dist/styles.css +1 -1
  22. package/package.json +1 -1
  23. package/src/__tests__/MAppBarWithSearch.test.ts +12 -0
  24. package/src/__tests__/MBottomSheetScaffold.test.ts +21 -0
  25. package/src/__tests__/MNavigationDrawer.test.ts +185 -0
  26. package/src/__tests__/MNavigationRail.test.ts +17 -1
  27. package/src/__tests__/MPullToRefresh.test.ts +18 -1
  28. package/src/__tests__/MShader.test.ts +16 -0
  29. package/src/__tests__/MTransition.test.ts +12 -0
  30. package/src/__tests__/hydration.test.ts +86 -0
  31. package/src/__tests__/sheets.test.ts +19 -15
  32. package/src/__tests__/ssr.test.ts +109 -0
  33. package/src/__tests__/themeInitScript.test.ts +104 -0
  34. package/src/components/MBottomSheetScaffold.vue +23 -2
  35. package/src/components/MChart.vue +3 -2
  36. package/src/components/MContextMenu.vue +34 -33
  37. package/src/components/MLightbox.vue +6 -1
  38. package/src/components/MMenu.vue +34 -33
  39. package/src/components/MNavigationDrawer.vue +297 -37
  40. package/src/components/MNavigationRail.vue +69 -15
  41. package/src/components/MPullToRefresh.vue +18 -0
  42. package/src/components/MSearchBar.vue +8 -4
  43. package/src/components/MShader.vue +11 -3
  44. package/src/components/MTransition.vue +36 -41
  45. package/src/composables/_hydration.ts +10 -0
  46. package/src/composables/_springAnimation.ts +74 -0
  47. package/src/composables/_useSheetMotion.ts +101 -88
  48. package/src/composables/themeInitScript.ts +49 -0
  49. package/src/composables/useColorPalette.ts +10 -6
  50. package/src/composables/useTheme.ts +12 -6
  51. package/src/composables/useWindowSizeClass.ts +14 -4
  52. package/src/index.ts +2 -0
  53. package/src/plugin.ts +24 -11
  54. package/dist/MTextField-TZ7lfr09.js.map +0 -1
@@ -27,20 +27,23 @@ describe.each([
27
27
  const w = mount(Comp as any, { props: { modelValue: false }, attachTo: document.body, global: { stubs: { transition: false } } })
28
28
  await w.setProps({ modelValue: true })
29
29
  await nextTick()
30
- expect(panel()!.style.transform).toBe(`${fn}(${size}px)`)
31
- expect(scrim()!.style.opacity).toBe('0')
32
-
33
- vi.advanceTimersByTime(80)
34
- const mid = parseFloat(panel()!.style.transform.match(/\(([-\d.]+)px/)![1]!)
35
- expect(mid).toBeGreaterThan(0)
36
- expect(mid).toBeLessThan(size)
37
-
38
- vi.advanceTimersByTime(1500)
39
- expect(panel()!.style.transform).toBe(`${fn}(0px)`)
30
+ // Played as Web Animations over the open state written inline
31
+ expect(panel()!.style.transform).toBe(`${fn}(0%)`)
40
32
  expect(scrim()!.style.opacity).toBe('1')
33
+ const [slide] = panel()!.getAnimations()
34
+ const frames = (slide!.effect as KeyframeEffect).getKeyframes()
35
+ expect(frames[0]!.transform).toBe(`${fn}(100%)`)
36
+ expect(frames[frames.length - 1]!.transform).toBe(`${fn}(0%)`)
37
+ const [fade] = scrim()!.getAnimations()
38
+ expect((fade!.effect as KeyframeEffect).getKeyframes()[0]!.opacity).toBe('0')
41
39
 
40
+ slide!.finish()
41
+ fade!.finish()
42
42
  await w.setProps({ modelValue: false })
43
- vi.advanceTimersByTime(1500)
43
+ await nextTick()
44
+ expect(panel()!.style.transform).toBe(`${fn}(100%)`)
45
+ panel()!.getAnimations().forEach((a) => a.finish())
46
+ scrim()!.getAnimations().forEach((a) => a.finish())
44
47
  await nextTick()
45
48
  expect(panel()).toBeNull()
46
49
  w.unmount()
@@ -49,7 +52,8 @@ describe.each([
49
52
  it('a short drag springs back; a long one dismisses', async () => {
50
53
  const w = mount(Comp as any, { props: { modelValue: true }, attachTo: document.body, global: { stubs: { transition: false } } })
51
54
  await nextTick()
52
- vi.advanceTimersByTime(1500)
55
+ panel()!.getAnimations().forEach((a) => a.finish())
56
+ scrim()!.getAnimations().forEach((a) => a.finish())
53
57
  const handle = (fn === 'translateY'
54
58
  ? panel()!.querySelector('.cursor-grab')
55
59
  : panel()!.querySelector('.cursor-ew-resize')) as HTMLElement
@@ -59,11 +63,11 @@ describe.each([
59
63
  handle.dispatchEvent(new PointerEvent('pointerdown', { ...at(0), pointerId: 1 }))
60
64
  vi.advanceTimersByTime(16)
61
65
  handle.dispatchEvent(new PointerEvent('pointermove', { ...at(40), pointerId: 1 }))
62
- expect(panel()!.style.transform).toBe(`${fn}(40px)`)
66
+ expect(panel()!.style.transform).toBe(`${fn}(${(40 / size) * 100}%)`)
63
67
  vi.advanceTimersByTime(200)
64
68
  handle.dispatchEvent(new PointerEvent('pointerup', { pointerId: 1 }))
65
- vi.advanceTimersByTime(1500)
66
- expect(panel()!.style.transform).toBe(`${fn}(0px)`)
69
+ expect(panel()!.style.transform).toBe(`${fn}(0%)`)
70
+ expect(panel()!.getAnimations().filter((a) => a.playState === 'running')).toHaveLength(1)
67
71
  expect(w.emitted('update:modelValue')).toBeUndefined()
68
72
 
69
73
  handle.dispatchEvent(new PointerEvent('pointerdown', { ...at(0), pointerId: 1 }))
@@ -0,0 +1,109 @@
1
+ // @vitest-environment node
2
+ import { beforeAll, describe, expect, it, vi } from 'vitest'
3
+ import { createSSRApp, h, type Component } from 'vue'
4
+ import { renderToString } from 'vue/server-renderer'
5
+
6
+ // What Nuxt's server sees: no window, no document, no localStorage. The import itself has to work, since
7
+ // one bundle carries every module (and its module-level code) whatever the app imports.
8
+ vi.stubGlobal('localStorage', undefined)
9
+
10
+ let lib: typeof import('../index')
11
+
12
+ beforeAll(async () => {
13
+ expect(typeof window).toBe('undefined')
14
+ expect(typeof document).toBe('undefined')
15
+ lib = await import('../index')
16
+ })
17
+
18
+ const items = [{ src: 'a.jpg', alt: 'a' }, { src: 'b.jpg', alt: 'b' }]
19
+
20
+ // Props for components that need some to render at all; everything else gets the generic set below.
21
+ const props: Record<string, Record<string, unknown>> = {
22
+ MDataTable: { columns: [{ key: 'a', label: 'A' }], rows: [{ a: 1 }] },
23
+ MTable: { columns: [{ key: 'a', label: 'A' }], rows: [{ a: 1 }] },
24
+ MVirtualTable: { columns: [{ key: 'a', label: 'A' }], rows: [{ a: 1 }] },
25
+ MTreeTable: { columns: [{ key: 'a', label: 'A' }], rows: [] },
26
+ MTree: { nodes: [{ id: 1, label: 'a' }] },
27
+ MKbd: { keys: 'Ctrl+K' },
28
+ MPasswordMeter: { value: 'abc' },
29
+ MRelativeTime: { value: new Date(0) },
30
+ MResult: { status: 'success', title: 't' },
31
+ MShape: { shape: 'Circle' },
32
+ MTour: { steps: [{ target: '#x', title: 't' }] },
33
+ }
34
+
35
+ // Overlays rendered open, where the open/scroll-lock code runs
36
+ const open = ['MDialog', 'MConfirmDialog', 'MBottomSheet', 'MSideSheet', 'MNavigationDrawer', 'MDatePickerModal',
37
+ 'MTimePickerModal', 'MColorPickerModal', 'MDateRangePickerModal', 'MLightbox', 'MCommandPalette',
38
+ 'MSpotlightSearch', 'MOverlay', 'MLoadingOverlay', 'MWindow', 'MMenu', 'MSnackbar', 'MNavigationRail']
39
+
40
+ async function render(component: Component, componentProps: Record<string, unknown>, options?: object) {
41
+ const app = createSSRApp({ render: () => h(component, componentProps, { default: () => 'x' }) })
42
+ if (options) app.use(lib.createM3UI(options))
43
+ return renderToString(app)
44
+ }
45
+
46
+ describe('SSR', () => {
47
+ it('renders every component without a DOM', async () => {
48
+ const failed: string[] = []
49
+ const names = Object.keys(lib).filter((k) => /^M[A-Z]/.test(k))
50
+ expect(names.length).toBeGreaterThan(100)
51
+ for (const name of names) {
52
+ try {
53
+ await render((lib as Record<string, Component>)[name]!, props[name] ?? { modelValue: '', label: 'x', items: [], options: [] })
54
+ } catch (e) {
55
+ failed.push(`${name}: ${(e as Error).message}`)
56
+ }
57
+ }
58
+ expect(failed).toEqual([])
59
+ })
60
+
61
+ it.each(open)('renders %s open', async (name) => {
62
+ const html = await render((lib as Record<string, Component>)[name]!, { modelValue: true, open: true, items, title: 't', message: 'm' })
63
+ expect(typeof html).toBe('string')
64
+ })
65
+
66
+ // Components living in their own entry (heavy optional peers)
67
+ it.each([
68
+ ['chart', 'MChart', { type: 'bar', data: { labels: ['a'], datasets: [{ data: [1] }] } }],
69
+ ['code-editor', 'MCodeEditor', { modelValue: 'x' }],
70
+ ['code-editor', 'MJsonEditor', { modelValue: '{}' }],
71
+ ['markdown', 'MMarkdown', { source: '# hi' }],
72
+ ['rich-text-editor', 'MRichTextEditor', { modelValue: '<p>x</p>' }],
73
+ ['terminal', 'MTerminal', {}],
74
+ ['qrcode', 'MQRCode', { value: 'x' }],
75
+ ['barcode', 'MBarcode', { value: '123456' }],
76
+ ] as const)('renders %s/%s', async (entry, name, componentProps) => {
77
+ const mod = await import(`../${entry}.ts`)
78
+ await expect(render(mod[name], componentProps)).resolves.toBeTypeOf('string')
79
+ })
80
+
81
+ it.each([
82
+ {},
83
+ { palette: 'red' },
84
+ { palette: 'red', persistPalette: false },
85
+ { seed: '#6750a4' },
86
+ { contrast: 'high' },
87
+ { themeColor: 'surface' },
88
+ { locale: { close: 'Cerrar' } },
89
+ { customPalettes: [{ id: 'mine', label: 'Mine', seed: '#ff0000' }] },
90
+ ])('installs createM3UI(%o)', async (options) => {
91
+ await expect(render(lib.MButton, {}, options)).resolves.toContain('button')
92
+ })
93
+
94
+ it('applies the app locale', async () => {
95
+ expect(await render(lib.MPagination, { modelValue: 1, total: 50 }, { locale: lib.defaultLocale })).toBeTruthy()
96
+ })
97
+
98
+ it.each(['useTheme', 'useColorPalette', 'useDevice', 'useLocale', 'useWindowSizeClass', 'useToast', 'useNotification'] as const)(
99
+ '%s() works in setup', async (name) => {
100
+ const app = createSSRApp({
101
+ setup() {
102
+ ;(lib[name] as () => unknown)()
103
+ return () => h('div')
104
+ },
105
+ })
106
+ await expect(renderToString(app)).resolves.toBe('<div></div>')
107
+ },
108
+ )
109
+ })
@@ -0,0 +1,104 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest'
2
+ import { themeInitScript, type ThemeInitOptions } from '../composables/themeInitScript'
3
+
4
+ const html = document.documentElement
5
+
6
+ function run(options?: ThemeInitOptions) {
7
+ new Function(themeInitScript(options))()
8
+ }
9
+
10
+ function matchMedia(matches: Record<string, boolean>) {
11
+ vi.stubGlobal('matchMedia', (q: string) => ({ matches: !!matches[q], media: q }))
12
+ }
13
+
14
+ afterEach(() => {
15
+ vi.unstubAllGlobals()
16
+ localStorage.clear()
17
+ html.className = ''
18
+ html.removeAttribute('data-palette')
19
+ html.removeAttribute('data-contrast')
20
+ document.getElementById('m3-dynamic-palette')?.remove()
21
+ })
22
+
23
+ describe('themeInitScript', () => {
24
+ it('applies nothing on a first visit with no defaults', () => {
25
+ matchMedia({})
26
+ run()
27
+ expect(html.classList.contains('dark')).toBe(false)
28
+ expect(html.hasAttribute('data-palette')).toBe(false)
29
+ expect(html.hasAttribute('data-contrast')).toBe(false)
30
+ })
31
+
32
+ it('follows the stored theme, and the OS for system', () => {
33
+ matchMedia({ '(prefers-color-scheme: dark)': true })
34
+ run()
35
+ expect(html.classList.contains('dark')).toBe(true)
36
+ localStorage.setItem('m3-theme', 'light')
37
+ run()
38
+ expect(html.classList.contains('dark')).toBe(false)
39
+ matchMedia({})
40
+ localStorage.setItem('m3-theme', 'dark')
41
+ run()
42
+ expect(html.classList.contains('dark')).toBe(true)
43
+ })
44
+
45
+ it('uses the palette default only on a first visit', () => {
46
+ run({ palette: 'red' })
47
+ expect(html.getAttribute('data-palette')).toBe('red')
48
+ localStorage.setItem('m3-palette', 'blue')
49
+ run({ palette: 'red' })
50
+ expect(html.getAttribute('data-palette')).toBe('blue')
51
+ })
52
+
53
+ it('forces the palette with persistPalette: false', () => {
54
+ localStorage.setItem('m3-palette', 'blue')
55
+ run({ palette: 'red', persistPalette: false })
56
+ expect(html.getAttribute('data-palette')).toBe('red')
57
+ })
58
+
59
+ it('leaves purple as the baseline (no attribute)', () => {
60
+ localStorage.setItem('m3-palette', 'purple')
61
+ run({ palette: 'red' })
62
+ expect(html.hasAttribute('data-palette')).toBe(false)
63
+ })
64
+
65
+ it('injects the cached CSS of a generated palette', () => {
66
+ localStorage.setItem('m3-palette', 'seed')
67
+ localStorage.setItem('m3-palette-css', JSON.stringify({ id: 'seed', css: '[data-palette=seed]{}' }))
68
+ run()
69
+ expect(html.getAttribute('data-palette')).toBe('seed')
70
+ expect(document.getElementById('m3-dynamic-palette')?.textContent).toBe('[data-palette=seed]{}')
71
+ })
72
+
73
+ it('ignores cached CSS of another palette', () => {
74
+ localStorage.setItem('m3-palette', 'red')
75
+ localStorage.setItem('m3-palette-css', JSON.stringify({ id: 'seed', css: 'x' }))
76
+ run()
77
+ expect(document.getElementById('m3-dynamic-palette')).toBeNull()
78
+ })
79
+
80
+ it('applies the contrast level: stored, default, forced, system', () => {
81
+ matchMedia({ '(prefers-contrast: more)': true })
82
+ run({ contrast: 'medium' })
83
+ expect(html.getAttribute('data-contrast')).toBe('medium')
84
+ html.removeAttribute('data-contrast')
85
+ localStorage.setItem('m3-contrast', 'standard')
86
+ run({ contrast: 'medium' })
87
+ expect(html.hasAttribute('data-contrast')).toBe(false)
88
+ run({ contrast: 'medium', persistPalette: false })
89
+ expect(html.getAttribute('data-contrast')).toBe('medium')
90
+ localStorage.setItem('m3-contrast', 'system')
91
+ run()
92
+ expect(html.getAttribute('data-contrast')).toBe('high')
93
+ })
94
+
95
+ it('survives blocked storage', () => {
96
+ vi.stubGlobal('localStorage', { getItem: () => { throw new Error('blocked') } })
97
+ expect(() => run({ palette: 'red' })).not.toThrow()
98
+ expect(html.getAttribute('data-palette')).toBe('red')
99
+ })
100
+
101
+ it('escapes the options it inlines', () => {
102
+ expect(themeInitScript({ palette: '</script><script>alert(1)' })).not.toContain('</script>')
103
+ })
104
+ })
@@ -83,6 +83,23 @@ function write() {
83
83
  if (sheetEl.value) sheetEl.value.style.transform = `translateY(${y}px)`
84
84
  // The content scrolls only once the sheet is fully up; until then a drag on it moves the sheet
85
85
  if (contentEl.value) contentEl.value.style.overflowY = settled.value === 'expanded' && target === null ? 'auto' : 'hidden'
86
+ updateContentTouchAction()
87
+ }
88
+
89
+ // Wherever touch-action lets the browser pan along the sheet's drag, Chrome treats that drag as a possible scroll
90
+ // and delivers it at 60Hz on a 120Hz phone, so the sheet moves every other frame (see CLAUDE.md). So the sheet is
91
+ // touch-action: none, and the content allows only the scroll that can actually happen: none while it can't
92
+ // scroll, only the finger moving up (pan-down) while it's at its top (down drags the sheet), both ways elsewhere.
93
+ // Browsers without directional pan values (Safari) keep pan-y there.
94
+ function updateContentTouchAction() {
95
+ const content = contentEl.value
96
+ if (!content || !props.swipeEnabled) return
97
+ let action = 'none'
98
+ if (settled.value === 'expanded' && target === null && content.scrollHeight > content.clientHeight) {
99
+ const directional = typeof CSS !== 'undefined' && !!CSS.supports?.('touch-action', 'pan-down')
100
+ action = content.scrollTop <= 0 && directional ? 'pan-down' : 'pan-y'
101
+ }
102
+ if (content.style.touchAction !== action) content.style.touchAction = action
86
103
  }
87
104
 
88
105
  function frame(now: number) {
@@ -240,6 +257,7 @@ let observer: ResizeObserver | null = null
240
257
  onMounted(() => {
241
258
  measure()
242
259
  sheetEl.value?.addEventListener('touchmove', onTouchMove, { passive: false })
260
+ contentEl.value?.addEventListener('scroll', updateContentTouchAction, { passive: true })
243
261
  if (typeof ResizeObserver !== 'undefined') {
244
262
  observer = new ResizeObserver(() => measure())
245
263
  if (sheetEl.value) observer.observe(sheetEl.value)
@@ -250,6 +268,7 @@ onUnmounted(() => {
250
268
  cancelAnimationFrame(raf)
251
269
  observer?.disconnect()
252
270
  sheetEl.value?.removeEventListener('touchmove', onTouchMove)
271
+ contentEl.value?.removeEventListener('scroll', updateContentTouchAction)
253
272
  })
254
273
  </script>
255
274
 
@@ -267,7 +286,8 @@ onUnmounted(() => {
267
286
  <div
268
287
  ref="sheetEl"
269
288
  role="region"
270
- class="absolute inset-x-0 bottom-0 z-10 mx-auto flex max-h-full w-full touch-pan-y select-none flex-col rounded-t-[28px] bg-surface-container-low text-on-surface shadow-elevation-1 after:absolute after:inset-x-0 after:top-full after:h-24 after:bg-surface-container-low"
289
+ class="absolute inset-x-0 bottom-0 z-10 mx-auto flex max-h-full w-full select-none flex-col rounded-t-[28px] bg-surface-container-low text-on-surface shadow-elevation-1 after:absolute after:inset-x-0 after:top-full after:h-24 after:bg-surface-container-low"
290
+ :class="swipeEnabled ? 'touch-none' : 'touch-pan-y'"
271
291
  :style="{ maxWidth: `${maxWidth}px` }"
272
292
  @pointerdown="onPointerDown"
273
293
  @pointermove="onPointerMove"
@@ -287,7 +307,8 @@ onUnmounted(() => {
287
307
  <span class="h-1 w-8 rounded-full bg-on-surface-variant" />
288
308
  </button>
289
309
  </div>
290
- <!-- touch-action stops at a scroll container, so the content needs its own pan-y -->
310
+ <!-- touch-action stops at a scroll container, so the content needs its own (pan-y, narrowed by
311
+ updateContentTouchAction while the sheet can be dragged) -->
291
312
  <div ref="contentEl" class="min-h-0 flex-1 touch-pan-y select-text overflow-y-hidden">
292
313
  <slot name="sheet" />
293
314
  </div>
@@ -30,8 +30,9 @@ const chartComponent = shallowRef<Component | null>(null)
30
30
  const componentMap = shallowRef<Record<string, Component>>({})
31
31
 
32
32
  function getM3Colors() {
33
- const style = getComputedStyle(document.documentElement)
34
- const get = (v: string) => style.getPropertyValue(v).trim()
33
+ // No DOM on the server (SSR): the chart only draws on the client, which reads them again in onMounted
34
+ const style = typeof document === 'undefined' ? null : getComputedStyle(document.documentElement)
35
+ const get = (v: string) => style?.getPropertyValue(v).trim() ?? ''
35
36
  return {
36
37
  primary: get('--color-primary'),
37
38
  onSurface: get('--color-on-surface'),
@@ -185,16 +185,15 @@ function openTrajectory() {
185
185
  // hook on the same still-mounted element without waiting for `done()`. Both
186
186
  // `currentIdx` (how far along the trajectory we are, so a reversal continues
187
187
  // smoothly from wherever it currently is instead of snapping back to a fixed
188
- // start) and `cancelActive` (so the previous rAF loop actually stops instead
189
- // of running alongside the new one, fighting over the same style every
190
- // frame) have to live outside this function to survive that interruption.
188
+ // start) and `cancelActive` (so the previous animation actually stops instead
189
+ // of running alongside the new one, fighting over the same style) have to live outside this function to survive that interruption.
191
190
  let currentIdx = 0
192
191
  let cancelActive: (() => void) | null = null
193
- // Set only while a close is playing: stops the loop *and* calls its `done()`.
192
+ // Set only while a close is playing: stops the animation *and* calls its `done()`.
194
193
  // Used on unmount — a menu item that navigates away (e.g. "Log out" ->
195
194
  // router.push) unmounts this component mid-close, and Vue only removes the
196
195
  // Teleported panel from <body> inside the leave's `done()`, so merely
197
- // cancelling the loop there left the half-closed panel stranded on screen.
196
+ // cancelling the animation there left the half-closed panel stranded on screen.
198
197
  let finishLeave: (() => void) | null = null
199
198
 
200
199
  function playTrajectory(el: Element, done: () => void, opening: boolean) {
@@ -202,37 +201,39 @@ function playTrajectory(el: Element, done: () => void, opening: boolean) {
202
201
  const htmlEl = el as HTMLElement
203
202
  const samples = openTrajectory()
204
203
  const last = samples.length - 1
205
- const direction = opening ? 1 : -1
206
- const target = opening ? last : 0
207
- let lastTime = 0
208
- let rafId = 0
209
- let cancelled = false
210
-
211
- function apply(idx: number) {
212
- const sample = samples[Math.round(Math.max(0, Math.min(last, idx)))]!
213
- htmlEl.style.transform = `scale(${sample.scale})`
214
- htmlEl.style.opacity = String(Math.min(1, Math.max(0, sample.alpha)))
204
+ const from = Math.round(Math.max(0, Math.min(last, currentIdx)))
205
+ const to = opening ? last : 0
206
+ const step = opening ? 1 : -1
207
+ const frames: { scale: number, alpha: number }[] = []
208
+ for (let i = from; opening ? i <= to : i >= to; i += step) frames.push(samples[i]!)
209
+ const style = (s: { scale: number, alpha: number }) => ({
210
+ transform: `scale(${s.scale})`,
211
+ opacity: String(Math.min(1, Math.max(0, s.alpha))),
212
+ })
213
+ // Played as a Web Animation (see _springAnimation.ts), which the compositor runs, so the open isn't janked by
214
+ // the panel's content mounting at the same moment. The end state goes inline underneath it.
215
+ Object.assign(htmlEl.style, style(samples[to]!))
216
+ let ended = false
217
+ function complete() {
218
+ if (ended) return
219
+ ended = true
220
+ currentIdx = to
221
+ cancelActive = null
222
+ finishLeave = null
223
+ done()
215
224
  }
216
-
217
- function step(now: number) {
218
- if (cancelled) return
219
- const dtSteps = lastTime ? (now - lastTime) / 1000 / trajectoryStep : 1
220
- lastTime = now
221
- currentIdx = Math.max(0, Math.min(last, currentIdx + direction * dtSteps))
222
- apply(currentIdx)
223
- if ((opening && currentIdx >= target) || (!opening && currentIdx <= target)) {
224
- cancelActive = null
225
- finishLeave = null
226
- done()
227
- return
228
- }
229
- rafId = requestAnimationFrame(step)
225
+ if (frames.length < 2 || typeof htmlEl.animate !== 'function') return complete()
226
+ const anim = htmlEl.animate(frames.map(style), { duration: (frames.length - 1) * trajectoryStep * 1000, easing: 'linear' })
227
+ anim.finished.catch(() => {})
228
+ anim.onfinish = complete
229
+ cancelActive = () => {
230
+ // Remember where it got to, so the reversal continues from there
231
+ const t = Number(anim.currentTime ?? 0) / (trajectoryStep * 1000)
232
+ currentIdx = Math.max(0, Math.min(last, from + step * t))
233
+ ended = true
234
+ anim.cancel()
230
235
  }
231
-
232
- cancelActive = () => { cancelled = true; cancelAnimationFrame(rafId) }
233
236
  finishLeave = opening ? null : () => { cancelActive?.(); cancelActive = null; finishLeave = null; done() }
234
- apply(currentIdx)
235
- rafId = requestAnimationFrame(step)
236
237
  }
237
238
  function panelEnter(el: Element, done: () => void) {
238
239
  playTrajectory(el, done, true)
@@ -336,7 +336,12 @@ function hide() {
336
336
  animate()
337
337
  }
338
338
 
339
- watch(() => props.modelValue, (v) => (v ? !rendered.value && show() : rendered.value && hide()), { immediate: true })
339
+ // Not on the server (SSR): it renders closed there, and an open one opens on the client
340
+ watch(() => props.modelValue, (v) => {
341
+ if (typeof document === 'undefined') return
342
+ if (v) !rendered.value && show()
343
+ else rendered.value && hide()
344
+ }, { immediate: true })
340
345
  watch(() => props.index, (v) => {
341
346
  if (v === currentIndex.value || !galleryItems.value[v]) return
342
347
  // Closed, or still opening (a consumer usually sets the index and opens in the same tick): show
@@ -170,16 +170,15 @@ function openTrajectory() {
170
170
  // hook on the same still-mounted element without waiting for `done()`. Both
171
171
  // `currentIdx` (how far along the trajectory we are, so a reversal continues
172
172
  // smoothly from wherever it currently is instead of snapping back to a fixed
173
- // start) and `cancelActive` (so the previous rAF loop actually stops instead
174
- // of running alongside the new one, fighting over the same style every
175
- // frame) have to live outside this function to survive that interruption.
173
+ // start) and `cancelActive` (so the previous animation actually stops instead
174
+ // of running alongside the new one, fighting over the same style) have to live outside this function to survive that interruption.
176
175
  let currentIdx = 0
177
176
  let cancelActive: (() => void) | null = null
178
- // Set only while a close is playing: stops the loop *and* calls its `done()`.
177
+ // Set only while a close is playing: stops the animation *and* calls its `done()`.
179
178
  // Used on unmount — a menu item that navigates away (e.g. "Log out" ->
180
179
  // router.push) unmounts this component mid-close, and Vue only removes the
181
180
  // Teleported panel from <body> inside the leave's `done()`, so merely
182
- // cancelling the loop there left the half-closed panel stranded on screen.
181
+ // cancelling the animation there left the half-closed panel stranded on screen.
183
182
  let finishLeave: (() => void) | null = null
184
183
 
185
184
  function playTrajectory(el: Element, done: () => void, opening: boolean) {
@@ -187,37 +186,39 @@ function playTrajectory(el: Element, done: () => void, opening: boolean) {
187
186
  const htmlEl = el as HTMLElement
188
187
  const samples = openTrajectory()
189
188
  const last = samples.length - 1
190
- const direction = opening ? 1 : -1
191
- const target = opening ? last : 0
192
- let lastTime = 0
193
- let rafId = 0
194
- let cancelled = false
195
-
196
- function apply(idx: number) {
197
- const sample = samples[Math.round(Math.max(0, Math.min(last, idx)))]!
198
- htmlEl.style.transform = `scale(${sample.scale})`
199
- htmlEl.style.opacity = String(Math.min(1, Math.max(0, sample.alpha)))
189
+ const from = Math.round(Math.max(0, Math.min(last, currentIdx)))
190
+ const to = opening ? last : 0
191
+ const step = opening ? 1 : -1
192
+ const frames: { scale: number, alpha: number }[] = []
193
+ for (let i = from; opening ? i <= to : i >= to; i += step) frames.push(samples[i]!)
194
+ const style = (s: { scale: number, alpha: number }) => ({
195
+ transform: `scale(${s.scale})`,
196
+ opacity: String(Math.min(1, Math.max(0, s.alpha))),
197
+ })
198
+ // Played as a Web Animation (see _springAnimation.ts), which the compositor runs, so the open isn't janked by
199
+ // the panel's content mounting at the same moment. The end state goes inline underneath it.
200
+ Object.assign(htmlEl.style, style(samples[to]!))
201
+ let ended = false
202
+ function complete() {
203
+ if (ended) return
204
+ ended = true
205
+ currentIdx = to
206
+ cancelActive = null
207
+ finishLeave = null
208
+ done()
200
209
  }
201
-
202
- function step(now: number) {
203
- if (cancelled) return
204
- const dtSteps = lastTime ? (now - lastTime) / 1000 / trajectoryStep : 1
205
- lastTime = now
206
- currentIdx = Math.max(0, Math.min(last, currentIdx + direction * dtSteps))
207
- apply(currentIdx)
208
- if ((opening && currentIdx >= target) || (!opening && currentIdx <= target)) {
209
- cancelActive = null
210
- finishLeave = null
211
- done()
212
- return
213
- }
214
- rafId = requestAnimationFrame(step)
210
+ if (frames.length < 2 || typeof htmlEl.animate !== 'function') return complete()
211
+ const anim = htmlEl.animate(frames.map(style), { duration: (frames.length - 1) * trajectoryStep * 1000, easing: 'linear' })
212
+ anim.finished.catch(() => {})
213
+ anim.onfinish = complete
214
+ cancelActive = () => {
215
+ // Remember where it got to, so the reversal continues from there
216
+ const t = Number(anim.currentTime ?? 0) / (trajectoryStep * 1000)
217
+ currentIdx = Math.max(0, Math.min(last, from + step * t))
218
+ ended = true
219
+ anim.cancel()
215
220
  }
216
-
217
- cancelActive = () => { cancelled = true; cancelAnimationFrame(rafId) }
218
221
  finishLeave = opening ? null : () => { cancelActive?.(); cancelActive = null; finishLeave = null; done() }
219
- apply(currentIdx)
220
- rafId = requestAnimationFrame(step)
221
222
  }
222
223
  function panelEnter(el: Element, done: () => void) {
223
224
  playTrajectory(el, done, true)