@m3ui-vue/m3ui-vue 0.9.3 → 1.0.0

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 (84) hide show
  1. package/README.md +24 -29
  2. package/dist/API.md +177 -18
  3. package/dist/{MTextField-DKtgPymd.js → MTextField-TZ7lfr09.js} +233 -108
  4. package/dist/MTextField-TZ7lfr09.js.map +1 -0
  5. package/dist/api.json +1 -1
  6. package/dist/code-editor.js +1 -1
  7. package/dist/components/MAppBarWithSearch.vue.d.ts +70 -0
  8. package/dist/components/MBottomAppBar.vue.d.ts +37 -0
  9. package/dist/components/MBottomSheetScaffold.vue.d.ts +40 -0
  10. package/dist/components/MChatBubble.vue.d.ts +1 -1
  11. package/dist/components/MChip.vue.d.ts +19 -2
  12. package/dist/components/MContainer.vue.d.ts +1 -1
  13. package/dist/components/MDataTable.vue.d.ts +1 -1
  14. package/dist/components/MDialog.vue.d.ts +1 -1
  15. package/dist/components/MFab.vue.d.ts +13 -4
  16. package/dist/components/MListItem.vue.d.ts +2 -2
  17. package/dist/components/MLoadingOverlay.vue.d.ts +1 -1
  18. package/dist/components/MNavigationRail.vue.d.ts +6 -0
  19. package/dist/components/MSearchBar.vue.d.ts +5 -3
  20. package/dist/components/MShortNavigationBar.vue.d.ts +1 -1
  21. package/dist/components/MTable.vue.d.ts +1 -1
  22. package/dist/components/MTopAppBar.vue.d.ts +33 -2
  23. package/dist/composables/_searchAppBar.d.ts +6 -0
  24. package/dist/composables/_themeTransition.d.ts +2 -0
  25. package/dist/composables/_useSpring.d.ts +3 -5
  26. package/dist/composables/motion.d.ts +101 -0
  27. package/dist/composables/useColorPalette.d.ts +10 -0
  28. package/dist/composables/useLocale.d.ts +3 -0
  29. package/dist/index.d.ts +8 -1
  30. package/dist/locales/index.js +21 -0
  31. package/dist/locales/index.js.map +1 -1
  32. package/dist/m3ui-vue.css +1 -1
  33. package/dist/m3ui.js +6772 -5931
  34. package/dist/m3ui.js.map +1 -1
  35. package/dist/plugin.d.ts +7 -0
  36. package/dist/rich-text-editor.js +2 -2
  37. package/dist/styles/palettes-contrast.css +7764 -0
  38. package/dist/styles/theme.css +46 -2
  39. package/dist/styles.css +1 -1
  40. package/dist/{useLocale-Cn9MVIdw.js → useLocale-CuvWRZ1h.js} +4 -1
  41. package/dist/useLocale-CuvWRZ1h.js.map +1 -0
  42. package/package.json +3 -1
  43. package/src/__tests__/MAppBarWithSearch.test.ts +96 -0
  44. package/src/__tests__/MBottomAppBar.test.ts +71 -0
  45. package/src/__tests__/MBottomSheetScaffold.test.ts +101 -0
  46. package/src/__tests__/MChip.test.ts +63 -0
  47. package/src/__tests__/MFab.test.ts +36 -0
  48. package/src/__tests__/MNavigationRail.test.ts +77 -0
  49. package/src/__tests__/MTopAppBar.test.ts +99 -0
  50. package/src/__tests__/contrast.test.ts +64 -0
  51. package/src/__tests__/dynamicColor.test.ts +17 -0
  52. package/src/__tests__/motion.test.ts +37 -0
  53. package/src/__tests__/themeTransition.test.ts +119 -0
  54. package/src/components/MAppBarWithSearch.vue +236 -0
  55. package/src/components/MBottomAppBar.vue +181 -0
  56. package/src/components/MBottomSheetScaffold.vue +296 -0
  57. package/src/components/MBreadcrumbs.vue +1 -1
  58. package/src/components/MChip.vue +137 -5
  59. package/src/components/MFab.vue +73 -12
  60. package/src/components/MNavigationDrawer.vue +2 -2
  61. package/src/components/MNavigationRail.vue +135 -8
  62. package/src/components/MSearchBar.vue +28 -12
  63. package/src/components/MTopAppBar.vue +252 -28
  64. package/src/composables/_searchAppBar.ts +9 -0
  65. package/src/composables/_themeColor.ts +11 -4
  66. package/src/composables/_themeTransition.ts +71 -0
  67. package/src/composables/_useSpring.ts +11 -21
  68. package/src/composables/motion.ts +73 -0
  69. package/src/composables/useColorPalette.ts +103 -20
  70. package/src/composables/useLocale.ts +6 -0
  71. package/src/composables/useTheme.ts +4 -12
  72. package/src/index.ts +8 -1
  73. package/src/locales/de.ts +3 -0
  74. package/src/locales/es.ts +3 -0
  75. package/src/locales/fr.ts +3 -0
  76. package/src/locales/ja.ts +3 -0
  77. package/src/locales/ko.ts +3 -0
  78. package/src/locales/pt.ts +3 -0
  79. package/src/locales/zh.ts +3 -0
  80. package/src/plugin.ts +9 -1
  81. package/src/styles/palettes-contrast.css +7764 -0
  82. package/src/styles/theme.css +46 -2
  83. package/dist/MTextField-DKtgPymd.js.map +0 -1
  84. package/dist/useLocale-Cn9MVIdw.js.map +0 -1
@@ -1,22 +1,36 @@
1
1
  <script setup lang="ts">
2
2
  /**
3
3
  * A top app bar in four M3 layouts — center-aligned, small, medium, and large — with a leading navigation icon
4
- * and trailing actions.
4
+ * and trailing actions. Medium and large can be M3 Expressive's flexible bars (bigger titles, a subtitle), and
5
+ * any of them can react to scrolling: change color, hide, or collapse to the small bar.
5
6
  *
6
7
  * @slot navigation Custom leading area (default: an MIconButton built from the navigationIcon prop)
7
8
  * @slot title Custom title content (default: renders the title prop)
9
+ * @slot subtitle Custom subtitle content (default: renders the subtitle prop)
8
10
  * @slot actions Trailing action buttons
9
11
  * @event navigation Emitted when the default navigation icon button is clicked (not emitted when the
10
12
  * #navigation slot is overridden — that content is fully custom)
11
13
  */
14
+ import { computed, onMounted, onUnmounted, ref, useSlots, watch } from 'vue'
12
15
  import MIconButton from './MIconButton.vue'
13
16
  import { useLocale } from '../composables/useLocale'
17
+ import { DEFAULT_EFFECTS } from '../composables/_useSpring'
18
+ import { cubicBezier } from '../composables/motion'
14
19
 
15
- withDefaults(defineProps<{
20
+ const props = withDefaults(defineProps<{
16
21
  /** App bar title */
17
22
  title?: string
23
+ /** A line below the title (Compose's `subtitle`): small, center-aligned and flexible medium/large bars */
24
+ subtitle?: string
18
25
  /** 64dp small/center-aligned row, or a 112dp medium / 152dp large two-row layout with the title below */
19
26
  variant?: 'center' | 'small' | 'medium' | 'large'
27
+ /**
28
+ * Medium/large only: M3 Expressive's MediumFlexibleTopAppBar / LargeFlexibleTopAppBar, with a
29
+ * headline-medium / display-small title and room for a subtitle (112/136dp and 120/152dp tall)
30
+ */
31
+ flexible?: boolean
32
+ /** Medium/large only: where the title row sits (Compose's `titleHorizontalAlignment`) */
33
+ titleAlignment?: 'start' | 'center'
20
34
  /** Leading icon (e.g. menu, arrow_back) */
21
35
  navigationIcon?: string
22
36
  /** Accessible label for the navigation icon button — defaults to the
@@ -30,30 +44,216 @@ withDefaults(defineProps<{
30
44
  elevated?: boolean
31
45
  /** Add a bottom border (border-outline-variant) */
32
46
  bordered?: boolean
33
- }>(), { variant: 'small' })
47
+ /**
48
+ * How the bar reacts to `scrollTarget` scrolling (Compose's TopAppBarDefaults scroll behaviors). `pinned`
49
+ * stays put and takes the scrolled container color once the content moves under it; `enter-always` hides
50
+ * (a medium/large bar collapses to the small one) while the content scrolls down and comes back as soon as
51
+ * it scrolls up; `exit-until-collapsed` collapses a medium/large bar as the content scrolls and expands it
52
+ * only back at the top. The last two make the bar sticky over the content: put it at the top of the
53
+ * scrolling element (or of the page)
54
+ */
55
+ scrollBehavior?: 'pinned' | 'enter-always' | 'exit-until-collapsed'
56
+ /** What `scrollBehavior` follows: an element or a CSS selector for it. Defaults to the window */
57
+ scrollTarget?: HTMLElement | string | null
58
+ }>(), { variant: 'small', flexible: false, titleAlignment: 'start', scrollTarget: null })
34
59
 
35
60
  defineEmits<{ navigation: [] }>()
36
61
 
37
62
  const locale = useLocale()
63
+ const slots = useSlots()
64
+
65
+ const twoRow = computed(() => props.variant === 'medium' || props.variant === 'large')
66
+ const hasSubtitle = computed(() => !!(props.subtitle || slots.subtitle))
67
+ const COLLAPSED = 64
68
+ // AppBarMedium/Large(Flexible)Tokens container heights
69
+ const expandedHeight = computed(() => {
70
+ if (!twoRow.value) return COLLAPSED
71
+ if (!props.flexible) return props.variant === 'large' ? 152 : 112
72
+ if (props.variant === 'large') return hasSubtitle.value ? 152 : 120
73
+ return hasSubtitle.value ? 136 : 112
74
+ })
75
+ const titleClass = computed(() => {
76
+ if (props.variant === 'large') return props.flexible ? 'text-display-small' : 'text-headline-medium'
77
+ return props.flexible ? 'text-headline-medium' : 'text-headline-small'
78
+ })
79
+ const subtitleClass = computed(() => (props.variant === 'large' ? 'text-title-medium' : 'text-label-large'))
80
+
81
+ // ── Scroll behaviors ─────────────────────────────────────────────────────────────────────────────
82
+ // TopAppBarState: heightOffset from 0 (expanded) to heightOffsetLimit (the bottom row gone for a two-row bar,
83
+ // the whole bar for a single row). Compose shrinks the bar in the layout and consumes the scroll first (the
84
+ // nested scroll's pre-scroll), so the content doesn't move while the bar collapses. A web page scrolls
85
+ // natively, so instead the bar is sticky over the content and, as it shrinks, its bottom margin grows by the
86
+ // same amount: it keeps taking its expanded height in the layout, and its bottom edge stays on the content's
87
+ // top edge, one-to-one with the finger.
88
+ const overlay = computed(() => props.scrollBehavior === 'enter-always' || props.scrollBehavior === 'exit-until-collapsed')
89
+ const limit = () => -(twoRow.value ? expandedHeight.value - COLLAPSED : COLLAPSED)
90
+
91
+ const barEl = ref<HTMLElement>()
92
+ const bottomRowEl = ref<HTMLElement>()
93
+ const smallTitleEl = ref<HTMLElement>()
94
+ const bigTitleEl = ref<HTMLElement>()
95
+ const scrolled = ref(false)
96
+ const collapsedHalf = ref(false)
97
+
98
+ let offset = 0
99
+ let vel = 0
100
+ let snapTarget: number | null = null
101
+ let raf = 0
102
+ let last = 0
103
+ let settleTimer = 0
104
+ let lastScroll = 0
105
+ let target: HTMLElement | Window | null = null
106
+
107
+ // TopTitleAlphaEasing = CubicBezierEasing(.8, 0, .8, .15); the container lerps on FastOutLinearInEasing
108
+ const topTitleAlpha = cubicBezier(0.8, 0, 0.8, 0.15)
109
+ const fastOutLinearIn = cubicBezier(0.4, 0, 1, 1)
110
+
111
+ function write() {
112
+ const f = offset === 0 ? 0 : offset / limit()
113
+ collapsedHalf.value = f >= 0.5
114
+ if (barEl.value) {
115
+ barEl.value.style.height = props.scrollBehavior && offset !== 0 ? `${expandedHeight.value + offset}px` : ''
116
+ barEl.value.style.marginBottom = overlay.value && offset !== 0 ? `${-offset}px` : ''
117
+ }
118
+ if (!twoRow.value) return
119
+ if (bottomRowEl.value) bottomRowEl.value.style.height = `${expandedHeight.value - COLLAPSED + offset}px`
120
+ if (smallTitleEl.value) smallTitleEl.value.style.opacity = String(topTitleAlpha(f))
121
+ if (bigTitleEl.value) bigTitleEl.value.style.opacity = String(1 - f)
122
+ // A two-row bar's container follows the collapse continuously (TwoRowsTopAppBar's colorTransitionFraction)
123
+ if (barEl.value) {
124
+ barEl.value.style.backgroundColor = props.elevated || f === 0
125
+ ? ''
126
+ : `color-mix(in srgb, var(--color-surface-container) ${(fastOutLinearIn(f) * 100).toFixed(1)}%, var(--color-surface))`
127
+ }
128
+ }
129
+
130
+ const scrollTop = () => (target instanceof Window ? target.scrollY : target?.scrollTop ?? 0)
131
+
132
+ function stopSnap() {
133
+ cancelAnimationFrame(raf)
134
+ raf = 0
135
+ snapTarget = null
136
+ vel = 0
137
+ }
138
+
139
+ function onScroll() {
140
+ const y = Math.max(0, scrollTop())
141
+ const dy = y - lastScroll
142
+ lastScroll = y
143
+ // SingleRowTopAppBar: the scrolled color as soon as content sits under the bar (overlappedFraction)
144
+ scrolled.value = y > 0
145
+ if (props.scrollBehavior === 'exit-until-collapsed') {
146
+ // Collapses with the content and expands only as the content comes back to its top
147
+ offset = Math.max(limit(), -y)
148
+ write()
149
+ return
150
+ }
151
+ if (props.scrollBehavior !== 'enter-always' || !dy) return
152
+ stopSnap()
153
+ offset = Math.min(0, Math.max(limit(), offset - dy))
154
+ write()
155
+ clearTimeout(settleTimer)
156
+ settleTimer = window.setTimeout(settle, 150)
157
+ }
158
+
159
+ // settleAppBar: a bar left half-way snaps to the closer end (TopAppBarDefaults.snapAnimationSpec, DefaultEffects)
160
+ function settle() {
161
+ const lim = limit()
162
+ if (offset === 0 || offset === lim) return
163
+ snapTarget = offset / lim < 0.5 ? 0 : lim
164
+ last = performance.now()
165
+ raf = requestAnimationFrame(frame)
166
+ }
167
+
168
+ function frame(now: number) {
169
+ if (snapTarget === null) return
170
+ let dt = Math.min((now - last) / 1000, 1 / 30)
171
+ last = now
172
+ const k = DEFAULT_EFFECTS.stiffness
173
+ const c = 2 * DEFAULT_EFFECTS.dampingRatio * Math.sqrt(k)
174
+ while (dt > 0) {
175
+ const h = Math.min(dt, 0.004)
176
+ dt -= h
177
+ vel += (-k * (offset - snapTarget) - c * vel) * h
178
+ offset += vel * h
179
+ }
180
+ if (Math.abs(offset - snapTarget) < 0.5 && Math.abs(vel) < 0.5) {
181
+ offset = snapTarget
182
+ write()
183
+ stopSnap()
184
+ return
185
+ }
186
+ write()
187
+ raf = requestAnimationFrame(frame)
188
+ }
189
+
190
+ function resolveTarget(): HTMLElement | Window | null {
191
+ if (typeof window === 'undefined') return null
192
+ if (!props.scrollTarget) return window
193
+ if (typeof props.scrollTarget === 'string') return document.querySelector<HTMLElement>(props.scrollTarget)
194
+ return props.scrollTarget
195
+ }
196
+
197
+ function attach() {
198
+ detach()
199
+ if (!props.scrollBehavior) return
200
+ target = resolveTarget()
201
+ if (!target) return
202
+ lastScroll = Math.max(0, scrollTop())
203
+ target.addEventListener('scroll', onScroll, { passive: true })
204
+ onScroll()
205
+ }
206
+
207
+ function detach() {
208
+ target?.removeEventListener('scroll', onScroll)
209
+ target = null
210
+ clearTimeout(settleTimer)
211
+ stopSnap()
212
+ offset = 0
213
+ scrolled.value = false
214
+ write()
215
+ }
216
+
217
+ onMounted(() => {
218
+ write()
219
+ attach()
220
+ })
221
+ onUnmounted(detach)
222
+ watch(() => [props.scrollBehavior, props.scrollTarget], attach)
223
+ watch(() => [props.variant, props.flexible, hasSubtitle.value], () => {
224
+ offset = Math.min(0, Math.max(limit(), offset))
225
+ write()
226
+ }, { flush: 'post' })
227
+
228
+ // Single row: elevated, or scrolled under while a scroll behavior is set
229
+ const scrolledLook = computed(() => props.elevated || (!twoRow.value && scrolled.value))
38
230
  </script>
39
231
 
40
232
  <template>
233
+ <!-- Direct children are the rows (consumers target `header > div > button` for the navigation button) -->
41
234
  <header
235
+ ref="barEl"
42
236
  class="flex w-full flex-col transition-[background-color,box-shadow]"
43
237
  :class="[
44
238
  // AppBarTokens: ContainerColor=Surface/Elevation=Level0 at rest, but
45
239
  // OnScrollContainerColor=SurfaceContainer/OnScrollContainerElevation=Level2 together once
46
- // scrolled — `elevated` swaps both, not just the shadow.
47
- elevated ? 'bg-surface-container shadow-elevation-2' : 'bg-surface',
240
+ // scrolled — `elevated` swaps both, not just the shadow. Scrolling only changes the color, as
241
+ // Compose's TopAppBarColors do.
242
+ scrolledLook ? 'bg-surface-container' : 'bg-surface',
243
+ elevated ? 'shadow-elevation-2' : '',
48
244
  bordered ? 'border-b border-outline-variant' : '',
245
+ // Clipped only while it can shrink, so nothing that overflows a static bar today gets cut
246
+ scrollBehavior ? 'overflow-hidden' : '',
247
+ overlay ? 'sticky top-0 z-10' : '',
49
248
  ]"
50
249
  >
51
250
  <!-- Top row — 64dp per M3's TopAppBarSmall/collapsed-Medium/collapsed-Large tokens.
52
251
  px-2: TopAppBarHorizontalPadding (4dp) + the 4dp IconButton() gets for free from
53
252
  Modifier.minimumInteractiveComponentSize() centering its 40dp visible container inside
54
253
  a 48dp touch target — MIconButton doesn't implement that invisible expansion, so it's
55
- folded into this row padding instead to land the icon glyph at the real 16dp inset. -->
56
- <div class="flex h-16 shrink-0 items-center gap-1 px-2">
254
+ folded into this row padding instead to land the icon glyph at the real 16dp inset.
255
+ A single-row bar's row is capped by the (shrinking) bar, keeping its content centered as it hides. -->
256
+ <div class="flex h-16 shrink-0 items-center gap-1 px-2" :class="twoRow ? '' : 'max-h-full'">
57
257
  <!-- Navigation -->
58
258
  <slot name="navigation">
59
259
  <MIconButton
@@ -65,17 +265,36 @@ const locale = useLocale()
65
265
  />
66
266
  </slot>
67
267
 
68
- <!-- Title: center or small variant -->
69
- <h1
70
- v-if="variant === 'center' || variant === 'small'"
71
- class="flex flex-1 items-center truncate px-4 text-title-large text-on-surface"
72
- :class="variant === 'center' ? 'justify-center' : ''"
268
+ <!-- Title: center or small variant, with an optional subtitle -->
269
+ <div
270
+ v-if="!twoRow"
271
+ class="flex min-w-0 flex-1 flex-col justify-center px-4"
272
+ :class="variant === 'center' ? 'items-center text-center' : ''"
73
273
  >
74
- <slot name="title">{{ title }}</slot>
75
- </h1>
274
+ <h1 class="w-full truncate text-title-large text-on-surface">
275
+ <slot name="title">{{ title }}</slot>
276
+ </h1>
277
+ <p v-if="hasSubtitle" class="w-full truncate text-label-medium text-on-surface-variant">
278
+ <slot name="subtitle">{{ subtitle }}</slot>
279
+ </p>
280
+ </div>
76
281
 
77
- <!-- Spacer for medium/large (title is below) -->
78
- <div v-else class="flex-1" />
282
+ <!-- Two-row bars: the small title fades in as the bar collapses (TopTitleAlphaEasing) -->
283
+ <div
284
+ v-else
285
+ ref="smallTitleEl"
286
+ class="flex min-w-0 flex-1 flex-col justify-center px-4"
287
+ :class="titleAlignment === 'center' ? 'items-center text-center' : ''"
288
+ style="opacity: 0"
289
+ :aria-hidden="!collapsedHalf || undefined"
290
+ >
291
+ <span class="w-full truncate text-title-large text-on-surface">
292
+ <slot name="title">{{ title }}</slot>
293
+ </span>
294
+ <span v-if="flexible && hasSubtitle" class="w-full truncate text-label-medium text-on-surface-variant">
295
+ <slot name="subtitle">{{ subtitle }}</slot>
296
+ </span>
297
+ </div>
79
298
 
80
299
  <!-- Trailing actions -->
81
300
  <div v-if="$slots.actions" class="flex items-center gap-1">
@@ -84,20 +303,25 @@ const locale = useLocale()
84
303
  </div>
85
304
 
86
305
  <!-- Large title row for medium/large variants — total container height
87
- 112dp (medium) / 152dp (large) per M3's AppBarMedium/LargeTokens,
88
- i.e. 48px / 88px added below the 64px top row. Bottom padding is
89
- MediumTitleBottomPadding=24dp / LargeTitleBottomPadding=28dp. -->
306
+ 112dp (medium) / 152dp (large) per M3's AppBarMedium/LargeTokens, 112/136dp and 120/152dp for the
307
+ flexible ones (without/with a subtitle). Bottom padding is MediumTitleBottomPadding=24dp /
308
+ LargeTitleBottomPadding=28dp. It shrinks from the top while collapsing, the title anchored to its
309
+ bottom and clipped as it goes. Its height is only ever written by write(): a reactive :style here
310
+ would be re-applied on every re-render and undo the collapse. -->
90
311
  <div
91
- v-if="variant === 'medium' || variant === 'large'"
92
- class="flex items-end px-4"
93
- :class="variant === 'large' ? 'h-[88px] pb-7' : 'h-12 pb-6'"
312
+ v-if="twoRow"
313
+ ref="bottomRowEl"
314
+ class="flex shrink-0 items-end overflow-hidden px-4"
315
+ :class="[variant === 'large' ? 'pb-7' : 'pb-6', titleAlignment === 'center' ? 'justify-center text-center' : '']"
94
316
  >
95
- <h1
96
- class="truncate text-on-surface"
97
- :class="variant === 'large' ? 'text-headline-medium' : 'text-headline-small'"
98
- >
99
- <slot name="title">{{ title }}</slot>
100
- </h1>
317
+ <div ref="bigTitleEl" class="min-w-0" :aria-hidden="collapsedHalf || undefined">
318
+ <h1 class="truncate text-on-surface" :class="titleClass">
319
+ <slot name="title">{{ title }}</slot>
320
+ </h1>
321
+ <p v-if="flexible && hasSubtitle" class="truncate text-on-surface-variant" :class="subtitleClass">
322
+ <slot name="subtitle">{{ subtitle }}</slot>
323
+ </p>
324
+ </div>
101
325
  </div>
102
326
  </header>
103
327
  </template>
@@ -0,0 +1,9 @@
1
+ // Internal (not exported from index.ts): what MAppBarWithSearch hands the MSearchBar inside it
2
+ import type { InjectionKey, Ref } from 'vue'
3
+
4
+ export interface SearchAppBarContext {
5
+ /** Content is scrolled under the app bar: the search bar takes its scrolled container color */
6
+ scrolled: Ref<boolean>
7
+ }
8
+
9
+ export const searchAppBarKey: InjectionKey<SearchAppBarContext> = Symbol('m-search-app-bar')
@@ -2,6 +2,8 @@
2
2
  // role of the active palette, dark mode and seed included. Started by createM3UI({ themeColor }).
3
3
 
4
4
  let observer: MutationObserver | undefined
5
+ // useColorPalette's <style> for generated palettes
6
+ const PALETTE_STYLE_ID = 'm3-dynamic-palette'
5
7
 
6
8
  function metas(): HTMLMetaElement[] {
7
9
  const found = Array.from(document.querySelectorAll<HTMLMetaElement>('meta[name="theme-color"]'))
@@ -26,8 +28,13 @@ export function syncThemeColor(role: string) {
26
28
  if (typeof document === 'undefined') return
27
29
  observer?.disconnect()
28
30
  update(role)
29
- // Palette (data-palette), dark mode and palette switches (class: dark, theme-transitioning) all land on <html>;
30
- // a new seed also toggles theme-transitioning, after its CSS is in place
31
- observer = new MutationObserver(() => update(role))
32
- observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-palette'] })
31
+ // Palette (data-palette), contrast (data-contrast) and dark mode (class) land on <html>; a generated palette
32
+ // (a seed, or the same seed at another contrast) only rewrites the <style> it lives in, inside <head>
33
+ const isPaletteStyle = (node: Node | null) => (node instanceof Element ? node : node?.parentElement)?.id === PALETTE_STYLE_ID
34
+ observer = new MutationObserver((records) => {
35
+ if (records.some((r) => r.target === document.documentElement || isPaletteStyle(r.target)
36
+ || Array.from(r.addedNodes).some(isPaletteStyle))) update(role)
37
+ })
38
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-palette', 'data-contrast'] })
39
+ observer.observe(document.head, { childList: true, characterData: true, subtree: true })
33
40
  }
@@ -0,0 +1,71 @@
1
+ // Internal: animates a theme change (dark mode, palette, contrast).
2
+ //
3
+ // Firefox (and any browser without @property) transitions six color properties on every element
4
+ // (`.theme-transitioning` in theme.css): smooth there, but in Chromium it recalculates every element's transitions
5
+ // each frame and stutters. Chromium and WebKit instead transition the color tokens themselves, once, on <html>:
6
+ // registered as <color> with @property they interpolate, and every element follows them through var(). Components'
7
+ // own color transitions (transition-colors) are turned off meanwhile, or they would restart on every frame of the
8
+ // token's change and trail behind the rest (the navbar and buttons did). A view transition was tried first: it
9
+ // cross-fades two snapshots, which looks washed out midway compared to the colors moving.
10
+
11
+ // The tokens of theme.css, palettes.css and generated palettes
12
+ const COLOR_TOKENS = [
13
+ 'background', 'on-background', 'surface', 'surface-dim', 'surface-bright', 'surface-variant', 'on-surface',
14
+ 'on-surface-variant', 'surface-container-lowest', 'surface-container-low', 'surface-container',
15
+ 'surface-container-high', 'surface-container-highest', 'inverse-surface', 'inverse-on-surface', 'inverse-primary',
16
+ 'outline', 'outline-variant', 'shadow', 'scrim',
17
+ ...['primary', 'secondary', 'tertiary', 'error', 'success'].flatMap((c) => [c, `on-${c}`, `${c}-container`, `on-${c}-container`]),
18
+ ...['primary', 'secondary', 'tertiary'].flatMap((c) => [`${c}-fixed`, `${c}-fixed-dim`, `on-${c}-fixed`, `on-${c}-fixed-variant`]),
19
+ ].map((t) => `--color-${t}`)
20
+
21
+ const DURATION = 250
22
+ const STYLE_ID = 'm3-theme-transition'
23
+
24
+ // Injected only while switching: a registered <color> computes to rgb(), and code reading a token with
25
+ // getPropertyValue() expects it as written
26
+ const css = COLOR_TOKENS.map((t) => `@property ${t} { syntax: '<color>'; inherits: true; initial-value: transparent; }`).join('\n')
27
+ + `\nhtml.theme-switching { transition: ${COLOR_TOKENS.map((t) => `${t} ${DURATION}ms ease`).join(', ')}; }`
28
+ + '\nhtml.theme-switching *, html.theme-switching *::before, html.theme-switching *::after { transition: none !important; }'
29
+
30
+ // Gecko: a CSS feature only it has, or its user agent ("Gecko/<version>" or "Firefox/"; Chromium and WebKit only
31
+ // say "like Gecko", and Firefox on iOS is WebKit and says "FxiOS")
32
+ const isGecko = () =>
33
+ (typeof CSS !== 'undefined' && !!CSS.supports?.('-moz-appearance', 'none'))
34
+ || (typeof navigator !== 'undefined' && /\bGecko\/\d|\bFirefox\//.test(navigator.userAgent))
35
+ const hasProperty = () => typeof CSS !== 'undefined' && typeof CSS.registerProperty === 'function'
36
+
37
+ let timer: ReturnType<typeof setTimeout> | undefined
38
+
39
+ /** Runs `apply` (the DOM writes of a theme change) with the theme transition. */
40
+ export function themeTransition(apply: () => void) {
41
+ if (typeof document === 'undefined') return apply()
42
+ const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches
43
+ if (reduced) return apply()
44
+ const root = document.documentElement
45
+
46
+ if (!isGecko() && hasProperty()) {
47
+ if (!document.getElementById(STYLE_ID)) {
48
+ const style = document.createElement('style')
49
+ style.id = STYLE_ID
50
+ style.textContent = css
51
+ document.head.appendChild(style)
52
+ }
53
+ root.classList.add('theme-switching')
54
+ // Style flush: the tokens' current values are computed as registered colors and the transition is in place
55
+ // before they change
56
+ void root.offsetHeight
57
+ apply()
58
+ clearTimeout(timer)
59
+ timer = setTimeout(() => {
60
+ root.classList.remove('theme-switching')
61
+ document.getElementById(STYLE_ID)?.remove()
62
+ }, DURATION + 50)
63
+ return
64
+ }
65
+
66
+ root.classList.add('theme-transitioning')
67
+ // Force a style flush so the transition is in place before the colors change
68
+ void root.offsetHeight
69
+ apply()
70
+ setTimeout(() => root.classList.remove('theme-transitioning'), 300)
71
+ }
@@ -1,18 +1,20 @@
1
- // Internal: a set of numbers (corner radii, sizes...) that springs toward a target, written to the DOM
2
- // once per frame through `apply`. Same integration as the rest of the library (semi-implicit Euler),
3
- // in fixed 4ms substeps so a stiff spring stays stable on a dropped frame. Not exported from index.ts.
1
+ // A set of numbers (corner radii, sizes...) that springs toward a target, written to the DOM once per
2
+ // frame through `apply`. Same integration as the rest of the library (semi-implicit Euler), in fixed 4ms
3
+ // substeps so a stiff spring stays stable on a dropped frame. `useSpring` is public (index.ts, with the
4
+ // motion tokens); the constants below are the library's internal shorthands for the Standard scheme.
4
5
  import { onMounted, onUnmounted, watch } from 'vue'
6
+ import { cubicBezier, motionSprings, type SpringSpec } from './motion'
5
7
 
6
- export interface SpringSpec { dampingRatio: number; stiffness: number }
8
+ export type { SpringSpec }
7
9
 
8
10
  /** MotionSchemeKeyTokens.FastSpatial in the Standard scheme (StandardMotionTokens.SpringFastSpatial*) */
9
- export const FAST_SPATIAL: SpringSpec = { dampingRatio: 0.9, stiffness: 1400 }
11
+ export const FAST_SPATIAL: SpringSpec = motionSprings.standard.fastSpatial
10
12
  /** MotionSchemeKeyTokens.FastEffects in the Standard scheme */
11
- export const FAST_EFFECTS: SpringSpec = { dampingRatio: 1, stiffness: 3800 }
13
+ export const FAST_EFFECTS: SpringSpec = motionSprings.standard.fastEffects
12
14
  /** MotionSchemeKeyTokens.DefaultEffects in the Standard scheme */
13
- export const DEFAULT_EFFECTS: SpringSpec = { dampingRatio: 1, stiffness: 1600 }
15
+ export const DEFAULT_EFFECTS: SpringSpec = motionSprings.standard.defaultEffects
14
16
  /** MotionSchemeKeyTokens.DefaultSpatial in the Standard scheme */
15
- export const DEFAULT_SPATIAL: SpringSpec = { dampingRatio: 0.9, stiffness: 700 }
17
+ export const DEFAULT_SPATIAL: SpringSpec = motionSprings.standard.defaultSpatial
16
18
 
17
19
  const SUBSTEP = 0.004
18
20
 
@@ -76,16 +78,4 @@ export function useSpring(
76
78
  }
77
79
 
78
80
  /** Compose's FastOutSlowInEasing, cubic-bezier(0.4, 0, 0.2, 1) — the easing of a default tween() */
79
- export function fastOutSlowIn(t: number): number {
80
- if (t <= 0) return 0
81
- if (t >= 1) return 1
82
- // Solve x(u) = t for the curve parameter u (Newton), then return y(u)
83
- let u = t
84
- for (let i = 0; i < 8; i++) {
85
- const x = 3 * u * (1 - u) ** 2 * 0.4 + 3 * u ** 2 * (1 - u) * 0.2 + u ** 3 - t
86
- const dx = 3 * (1 - u) ** 2 * 0.4 + 6 * u * (1 - u) * (0.2 - 0.4) + 3 * u ** 2 * 0.8
87
- if (Math.abs(dx) < 1e-6) break
88
- u -= x / dx
89
- }
90
- return 3 * u ** 2 * (1 - u) + u ** 3
91
- }
81
+ export const fastOutSlowIn = cubicBezier(0.4, 0, 0.2, 1)
@@ -0,0 +1,73 @@
1
+ // Material 3's motion tokens for your own animations, from androidx's MotionTokens, StandardMotionTokens and
2
+ // ExpressiveMotionTokens. The same easings and durations are CSS variables in theme.css (`--ease-*`, which
3
+ // Tailwind turns into `ease-*` utilities, and `--duration-*`); the springs only make sense in JS, with
4
+ // `useSpring` (exported next to these) or your own loop. No imports here: _useSpring builds on this file.
5
+
6
+ /** A spring: dampingRatio 1 settles without overshoot, lower bounces; higher stiffness is faster */
7
+ export interface SpringSpec { dampingRatio: number; stiffness: number }
8
+
9
+ /**
10
+ * Spring specs of the two motion schemes. Spatial springs move things (position, size, shape); effects springs
11
+ * change color and opacity and never overshoot. Standard is the default scheme; Expressive is bouncier, for
12
+ * Expressive components and moments that should feel lively.
13
+ */
14
+ export const motionSprings = {
15
+ standard: {
16
+ fastSpatial: { dampingRatio: 0.9, stiffness: 1400 },
17
+ defaultSpatial: { dampingRatio: 0.9, stiffness: 700 },
18
+ slowSpatial: { dampingRatio: 0.9, stiffness: 300 },
19
+ fastEffects: { dampingRatio: 1, stiffness: 3800 },
20
+ defaultEffects: { dampingRatio: 1, stiffness: 1600 },
21
+ slowEffects: { dampingRatio: 1, stiffness: 800 },
22
+ },
23
+ expressive: {
24
+ fastSpatial: { dampingRatio: 0.6, stiffness: 800 },
25
+ defaultSpatial: { dampingRatio: 0.8, stiffness: 380 },
26
+ slowSpatial: { dampingRatio: 0.8, stiffness: 200 },
27
+ fastEffects: { dampingRatio: 1, stiffness: 3800 },
28
+ defaultEffects: { dampingRatio: 1, stiffness: 1600 },
29
+ slowEffects: { dampingRatio: 1, stiffness: 800 },
30
+ },
31
+ } as const satisfies Record<'standard' | 'expressive', Record<string, SpringSpec>>
32
+
33
+ /** Easing curves as cubic-bezier control points [x1, y1, x2, y2] (theme.css has them as `--ease-*`) */
34
+ export const motionEasings = {
35
+ emphasized: [0.2, 0, 0, 1],
36
+ emphasizedDecelerate: [0.05, 0.7, 0.1, 1],
37
+ emphasizedAccelerate: [0.3, 0, 0.8, 0.15],
38
+ standard: [0.2, 0, 0, 1],
39
+ standardDecelerate: [0, 0, 0, 1],
40
+ standardAccelerate: [0.3, 0, 1, 1],
41
+ legacy: [0.4, 0, 0.2, 1],
42
+ legacyDecelerate: [0, 0, 0.2, 1],
43
+ legacyAccelerate: [0.4, 0, 1, 1],
44
+ linear: [0, 0, 1, 1],
45
+ } as const satisfies Record<string, readonly [number, number, number, number]>
46
+
47
+ /** Durations in ms (theme.css has them as `--duration-short-1` … `--duration-extra-long-4`) */
48
+ export const motionDurations = {
49
+ short1: 50, short2: 100, short3: 150, short4: 200,
50
+ medium1: 250, medium2: 300, medium3: 350, medium4: 400,
51
+ long1: 450, long2: 500, long3: 550, long4: 600,
52
+ extraLong1: 700, extraLong2: 800, extraLong3: 900, extraLong4: 1000,
53
+ } as const
54
+
55
+ /**
56
+ * A cubic-bezier easing as a function of progress (0–1), e.g. `cubicBezier(...motionEasings.emphasized)`, for
57
+ * JS-driven tweens and for mapping a fraction through a curve
58
+ */
59
+ export function cubicBezier(x1: number, y1: number, x2: number, y2: number): (t: number) => number {
60
+ return (t: number) => {
61
+ if (t <= 0) return 0
62
+ if (t >= 1) return 1
63
+ // Solve x(u) = t for the curve parameter u (Newton), then return y(u)
64
+ let u = t
65
+ for (let i = 0; i < 8; i++) {
66
+ const x = 3 * u * (1 - u) ** 2 * x1 + 3 * u ** 2 * (1 - u) * x2 + u ** 3 - t
67
+ const dx = 3 * (1 - u) ** 2 * x1 + 6 * u * (1 - u) * (x2 - x1) + 3 * u ** 2 * (1 - x2)
68
+ if (Math.abs(dx) < 1e-6) break
69
+ u -= x / dx
70
+ }
71
+ return 3 * u * (1 - u) ** 2 * y1 + 3 * u ** 2 * (1 - u) * y2 + u ** 3
72
+ }
73
+ }