@m3ui-vue/m3ui-vue 0.8.1 → 0.8.3

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.
@@ -1,12 +1,244 @@
1
1
  <script setup lang="ts">
2
- import { nextTick, onMounted, onUnmounted, provide, ref } from 'vue'
2
+ import { computed, Fragment, inject, nextTick, onMounted, onUnmounted, provide, ref, useSlots, watch, type VNode } from 'vue'
3
+ import MIcon from './MIcon.vue'
4
+ import MMenuDivider from './MMenuDivider.vue'
5
+
6
+ const props = withDefaults(
7
+ defineProps<{
8
+ /**
9
+ * How items with a `#children` slot behave.
10
+ * `'flyout'` opens a hover-positioned side panel (desktop).
11
+ * `'push'` replaces the panel's own content with the submenu and a
12
+ * back header — no positioning math, works with touch. Useful for mobile.
13
+ */
14
+ submenuMode?: 'flyout' | 'push'
15
+ /**
16
+ * `'standard'` is M3's baseline menu — square-ish 4dp corners
17
+ * (`MenuTokens.ContainerShape`/`CornerExtraSmall`).
18
+ * `'expressive'` is M3's rounder "vertical menu" styling — 16dp corners
19
+ * (`SegmentedMenuTokens.ContainerShape`/`CornerLarge`). Combine with
20
+ * `<MMenuDivider gap />` to split the panel into independently-rounded
21
+ * groups with a visible gap between them, instead of a plain line.
22
+ */
23
+ variant?: 'standard' | 'expressive'
24
+ }>(),
25
+ { submenuMode: 'flyout', variant: 'standard' },
26
+ )
27
+
28
+ const slots = useSlots()
29
+
30
+ function flattenVNodes(vnodes: VNode[]): VNode[] {
31
+ const out: VNode[] = []
32
+ for (const vnode of vnodes) {
33
+ if (vnode.type === Fragment && Array.isArray(vnode.children)) {
34
+ out.push(...flattenVNodes(vnode.children as VNode[]))
35
+ } else {
36
+ out.push(vnode)
37
+ }
38
+ }
39
+ return out
40
+ }
41
+
42
+ function isGapDivider(vnode: VNode): boolean {
43
+ if (vnode.type !== MMenuDivider) return false
44
+ const gap = (vnode.props as { gap?: unknown } | null)?.gap
45
+ return gap === '' || gap === true || gap === 'true'
46
+ }
47
+
48
+ // See MMenu.vue for the same mechanism: splits the default slot's content
49
+ // into groups at each `<MMenuDivider gap />`, for the 'expressive' variant's
50
+ // independently-rounded group boxes.
51
+ const groups = computed(() => {
52
+ if (props.variant !== 'expressive') return null
53
+ const raw = flattenVNodes((slots.default?.() ?? []) as VNode[])
54
+ const result: VNode[][] = [[]]
55
+ for (const vnode of raw) {
56
+ if (isGapDivider(vnode)) result.push([])
57
+ else result[result.length - 1]!.push(vnode)
58
+ }
59
+ return result.filter(g => g.length > 0)
60
+ })
61
+ const isGrouped = computed(() => !!groups.value && groups.value.length > 1)
3
62
 
4
63
  const visible = ref(false)
5
64
  const adjustedPos = ref({ x: 0, y: 0 })
6
65
  const panelEl = ref<HTMLElement | null>(null)
7
66
 
67
+ // See MMenu.vue for why this is needed: a menu nested inside another
68
+ // MMenu/MContextMenu's slot Teleports to <body> independently, so the
69
+ // ancestor's outside-click check needs a shared registry of open panel
70
+ // elements (across the logical component tree, not the DOM tree) instead of
71
+ // checking only its own panel.
72
+ const panelRegistry = inject<Set<HTMLElement>>('m-menu-panel-registry', new Set())
73
+ provide('m-menu-panel-registry', panelRegistry)
74
+
75
+ watch(panelEl, (el, oldEl) => {
76
+ if (oldEl) panelRegistry.delete(oldEl)
77
+ if (el) panelRegistry.add(el)
78
+ })
79
+
80
+ onUnmounted(() => {
81
+ if (panelEl.value) panelRegistry.delete(panelEl.value)
82
+ })
83
+
84
+ // See MMenu.vue for why this is separate from panelRegistry: keeps at most
85
+ // one of this menu's *direct* siblings-under-the-same-parent open at a time.
86
+ const siblingGroup = inject<{ current: (() => void) | null } | null>('m-menu-sibling-group', null)
87
+ provide('m-menu-sibling-group', { current: null })
88
+
89
+ type NavEntry = { icon?: string, header?: () => any, content?: () => any }
90
+ const navStack = ref<NavEntry[]>([])
91
+ const currentNav = computed(() => navStack.value[navStack.value.length - 1])
92
+ const navDirection = ref<'forward' | 'backward'>('forward')
93
+
94
+ // See MMenu.vue: driven by the Web Animations API rather than Vue's
95
+ // CSS-class transition hooks, which never reliably completed here with
96
+ // dynamic (direction-dependent) enter/leave classes on a mode-less Transition.
97
+ const slideDuration = 220
98
+ function navSlideEnter(el: Element, done: () => void) {
99
+ const dir = navDirection.value === 'forward' ? 1 : -1
100
+ const anim = (el as HTMLElement).animate(
101
+ [
102
+ { transform: `translateX(${dir * 100}%)`, opacity: 0.4 },
103
+ { transform: 'translateX(0%)', opacity: 1 },
104
+ ],
105
+ { duration: slideDuration, easing: 'cubic-bezier(0.05,0.7,0.1,1)' },
106
+ )
107
+ anim.onfinish = done
108
+ }
109
+ function navSlideLeave(el: Element, done: () => void) {
110
+ const dir = navDirection.value === 'forward' ? -1 : 1
111
+ const htmlEl = el as HTMLElement
112
+ htmlEl.style.position = 'absolute'
113
+ htmlEl.style.insetInline = '0'
114
+ htmlEl.style.top = '0'
115
+ const anim = htmlEl.animate(
116
+ [
117
+ { transform: 'translateX(0%)', opacity: 1 },
118
+ { transform: `translateX(${dir * 100}%)`, opacity: 0.4 },
119
+ ],
120
+ { duration: slideDuration, easing: 'cubic-bezier(0.3,0,0.8,0.15)' },
121
+ )
122
+ anim.onfinish = done
123
+ }
124
+
125
+ // See MMenu.vue: the real Menu.kt animates the panel's scale/alpha with
126
+ // actual springs (StandardMotionTokens: scale dampingRatio 0.9/stiffness
127
+ // 1400, alpha dampingRatio 1.0/stiffness 3800), not a duration+easing tween.
128
+ // Running close as its own forward spring toward the reversed targets isn't
129
+ // right either — alpha (stiffness 3800) settles much faster than scale
130
+ // (stiffness 1400), so the panel fades to invisible before it finishes
131
+ // shrinking and you never see the shrink. Close needs to be the literal
132
+ // time-reverse of open instead: simulated once (open direction only) and
133
+ // played back forwards for enter, backwards for leave.
134
+ //
135
+ // A damped spring approaches its target exponentially, so it keeps "settling"
136
+ // long after the motion is visually done — with a tight (0.001) tolerance on
137
+ // both position *and* velocity, roughly the last third of the recorded
138
+ // trajectory is values within a fraction of a percent of the target, visually
139
+ // indistinguishable from it. Reversed for close, that flat tail lands at the
140
+ // *start* instead, so nothing visibly happens for the first ~80ms before the
141
+ // close animation actually appears to begin. Trimmed on position alone with a
142
+ // much looser tolerance instead, since that's what's actually visible.
143
+ let cachedTrajectory: { scale: number, alpha: number }[] | null = null
144
+ const trajectoryStep = 1 / 240
145
+ function openTrajectory() {
146
+ if (cachedTrajectory) return cachedTrajectory
147
+ const samples: { scale: number, alpha: number }[] = []
148
+ let scale = 0.8
149
+ let scaleVel = 0
150
+ let alpha = 0
151
+ let alphaVel = 0
152
+ const scaleDamping = 0.9
153
+ const scaleStiffness = 1400
154
+ const alphaDamping = 1.0
155
+ const alphaStiffness = 3800
156
+ for (let t = 0; t < 1; t += trajectoryStep) {
157
+ samples.push({ scale, alpha })
158
+ scaleVel += (-scaleStiffness * (scale - 1) - 2 * scaleDamping * Math.sqrt(scaleStiffness) * scaleVel) * trajectoryStep
159
+ scale += scaleVel * trajectoryStep
160
+ alphaVel += (-alphaStiffness * (alpha - 1) - 2 * alphaDamping * Math.sqrt(alphaStiffness) * alphaVel) * trajectoryStep
161
+ alpha += alphaVel * trajectoryStep
162
+ const visuallySettled = Math.abs(scale - 1) < 0.003 && Math.abs(alpha - 1) < 0.003
163
+ if (visuallySettled) break
164
+ }
165
+ samples.push({ scale: 1, alpha: 1 })
166
+ cachedTrajectory = samples
167
+ return samples
168
+ }
169
+
170
+ // Vue interrupts and reverses this mid-flight when the menu is toggled
171
+ // quickly (close while still opening, or vice versa) — it calls the other
172
+ // hook on the same still-mounted element without waiting for `done()`. Both
173
+ // `currentIdx` (how far along the trajectory we are, so a reversal continues
174
+ // smoothly from wherever it currently is instead of snapping back to a fixed
175
+ // start) and `cancelActive` (so the previous rAF loop actually stops instead
176
+ // of running alongside the new one, fighting over the same style every
177
+ // frame) have to live outside this function to survive that interruption.
178
+ let currentIdx = 0
179
+ let cancelActive: (() => void) | null = null
180
+
181
+ function playTrajectory(el: Element, done: () => void, opening: boolean) {
182
+ cancelActive?.()
183
+ const htmlEl = el as HTMLElement
184
+ const samples = openTrajectory()
185
+ const last = samples.length - 1
186
+ const direction = opening ? 1 : -1
187
+ const target = opening ? last : 0
188
+ let lastTime = 0
189
+ let rafId = 0
190
+ let cancelled = false
191
+
192
+ function apply(idx: number) {
193
+ const sample = samples[Math.round(Math.max(0, Math.min(last, idx)))]!
194
+ htmlEl.style.transform = `scale(${sample.scale})`
195
+ htmlEl.style.opacity = String(Math.min(1, Math.max(0, sample.alpha)))
196
+ }
197
+
198
+ function step(now: number) {
199
+ if (cancelled) return
200
+ const dtSteps = lastTime ? (now - lastTime) / 1000 / trajectoryStep : 1
201
+ lastTime = now
202
+ currentIdx = Math.max(0, Math.min(last, currentIdx + direction * dtSteps))
203
+ apply(currentIdx)
204
+ if ((opening && currentIdx >= target) || (!opening && currentIdx <= target)) {
205
+ cancelActive = null
206
+ done()
207
+ return
208
+ }
209
+ rafId = requestAnimationFrame(step)
210
+ }
211
+
212
+ cancelActive = () => { cancelled = true; cancelAnimationFrame(rafId) }
213
+ apply(currentIdx)
214
+ rafId = requestAnimationFrame(step)
215
+ }
216
+ function panelEnter(el: Element, done: () => void) {
217
+ playTrajectory(el, done, true)
218
+ }
219
+ function panelLeave(el: Element, done: () => void) {
220
+ playTrajectory(el, done, false)
221
+ }
222
+
223
+ function pushNav(entry: NavEntry) {
224
+ navDirection.value = 'forward'
225
+ navStack.value.push(entry)
226
+ nextTick(() => focusableItems()[0]?.focus())
227
+ }
228
+
229
+ function popNav() {
230
+ navDirection.value = 'backward'
231
+ navStack.value.pop()
232
+ nextTick(() => focusableItems()[0]?.focus())
233
+ }
234
+
8
235
  async function showAt(x: number, y: number) {
236
+ if (siblingGroup && siblingGroup.current && siblingGroup.current !== hide) {
237
+ siblingGroup.current()
238
+ }
239
+ if (siblingGroup) siblingGroup.current = hide
9
240
  adjustedPos.value = { x, y }
241
+ navStack.value = []
10
242
  visible.value = true
11
243
  await nextTick()
12
244
  if (!panelEl.value) return
@@ -41,29 +273,44 @@ function show(e: MouseEvent) {
41
273
  }
42
274
 
43
275
  function hide() {
276
+ if (siblingGroup?.current === hide) siblingGroup.current = null
44
277
  visible.value = false
45
278
  }
46
279
 
47
280
  provide('m-menu-close', hide)
281
+ provide('m-menu-nav', { mode: props.submenuMode, push: pushNav })
48
282
  defineExpose({ show, showAt, hide })
49
283
 
50
284
  function onDocMouseDown(e: MouseEvent) {
51
285
  if (!visible.value) return
52
286
  const t = e.target as Node
53
- if (panelEl.value?.contains(t)) return
287
+ for (const panel of panelRegistry) {
288
+ if (panel.contains(t)) return
289
+ }
54
290
  if ((t as Element).closest?.('.m3-submenu')) return
55
291
  hide()
56
292
  }
57
293
 
58
294
  function onKeydown(e: KeyboardEvent) {
59
- if (e.key === 'Escape') { hide(); return }
295
+ if (e.key === 'Escape') {
296
+ if (navStack.value.length) popNav()
297
+ else hide()
298
+ return
299
+ }
60
300
  if (!visible.value) return
61
301
  if (e.key === 'ArrowDown') { e.preventDefault(); moveFocus(1) }
62
302
  else if (e.key === 'ArrowUp') { e.preventDefault(); moveFocus(-1) }
63
303
  }
64
304
 
65
- function onScroll() {
66
- if (visible.value) hide()
305
+ // Scrolling inside its own panel or a nested menu's panel shouldn't close it
306
+ function onScroll(e: Event) {
307
+ if (!visible.value) return
308
+ const t = e.target as Node
309
+ for (const panel of panelRegistry) {
310
+ if (panel.contains(t)) return
311
+ }
312
+ if ((t as Element).closest?.('.m3-submenu')) return
313
+ hide()
67
314
  }
68
315
 
69
316
  onMounted(() => {
@@ -76,6 +323,7 @@ onUnmounted(() => {
76
323
  document.removeEventListener('mousedown', onDocMouseDown)
77
324
  document.removeEventListener('keydown', onKeydown)
78
325
  window.removeEventListener('scroll', onScroll, true)
326
+ cancelActive?.()
79
327
  })
80
328
  </script>
81
329
 
@@ -85,22 +333,55 @@ onUnmounted(() => {
85
333
  </div>
86
334
 
87
335
  <Teleport to="body">
88
- <Transition
89
- enter-active-class="transition-[opacity,transform] duration-150 ease-[cubic-bezier(0.05,0.7,0.1,1)]"
90
- enter-from-class="opacity-0 scale-[0.8]"
91
- enter-to-class="opacity-100 scale-100"
92
- leave-active-class="transition-[opacity,transform] duration-150 ease-[cubic-bezier(0.3,0,0.8,0.15)]"
93
- leave-from-class="opacity-100 scale-100"
94
- leave-to-class="opacity-0 scale-[0.8]"
95
- >
336
+ <Transition :css="false" @enter="panelEnter" @leave="panelLeave">
96
337
  <div
97
338
  v-if="visible"
98
339
  ref="panelEl"
99
- class="fixed z-[500] min-w-48 overflow-hidden rounded-xs bg-surface-container py-1 shadow-elevation-2"
340
+ class="fixed z-[500] min-w-48"
341
+ :class="[
342
+ variant === 'expressive' ? 'rounded-lg' : 'rounded-xs',
343
+ isGrouped ? '' : 'shadow-elevation-2',
344
+ ]"
100
345
  :style="{ left: `${adjustedPos.x}px`, top: `${adjustedPos.y}px`, transformOrigin: 'top left' }"
101
346
  @contextmenu.prevent
102
347
  >
103
- <slot />
348
+ <!-- overflow-hidden (for the rounded-corner clip and to clip the push
349
+ submenu's slide) lives on this inner wrapper, never together with
350
+ shadow-elevation-2 on the same box — overflow-hidden clips an
351
+ element's own box-shadow too, so the two have to be on separate
352
+ elements or the shadow gets cut off -->
353
+ <div
354
+ class="overflow-hidden py-1"
355
+ :class="[
356
+ variant === 'expressive' ? 'rounded-lg' : 'rounded-xs',
357
+ isGrouped ? '' : 'bg-surface-container',
358
+ ]"
359
+ >
360
+ <Transition :css="false" @enter="navSlideEnter" @leave="navSlideLeave">
361
+ <div v-if="currentNav" :key="navStack.length">
362
+ <button
363
+ type="button"
364
+ class="flex w-full items-center gap-3 border-b border-outline-variant px-4 py-2.5 text-left text-body-large text-on-surface outline-none transition-colors hover:bg-on-surface/8 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-secondary"
365
+ @click="popNav"
366
+ >
367
+ <MIcon name="chevron_left" :size="20" class="shrink-0 text-on-surface-variant" />
368
+ <MIcon v-if="currentNav.icon" :name="currentNav.icon" :size="20" class="shrink-0 text-on-surface-variant" />
369
+ <span class="flex-1 truncate"><component :is="() => currentNav?.header?.()" /></span>
370
+ </button>
371
+ <component :is="() => currentNav?.content?.()" />
372
+ </div>
373
+ <div v-else key="root">
374
+ <div v-if="isGrouped" class="flex flex-col gap-1 px-1.5">
375
+ <div v-for="(group, i) in groups" :key="i" class="rounded-lg shadow-elevation-2">
376
+ <div class="overflow-hidden rounded-lg bg-surface-container">
377
+ <component :is="() => group" />
378
+ </div>
379
+ </div>
380
+ </div>
381
+ <slot v-else />
382
+ </div>
383
+ </Transition>
384
+ </div>
104
385
  </div>
105
386
  </Transition>
106
387
  </Teleport>
@@ -153,7 +153,7 @@ function onContainerClick(e: MouseEvent) {
153
153
  background: var(--color-surface-container-highest);
154
154
  padding: 0.15em 0.4em;
155
155
  border-radius: 4px;
156
- font-family: 'Roboto Mono', 'Fira Code', 'Consolas', monospace;
156
+ font-family: var(--font-mono, 'Roboto Mono', monospace);
157
157
  font-size: 0.875em;
158
158
  color: var(--color-primary);
159
159
  }