@m3ui-vue/m3ui-vue 1.1.2 → 1.1.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.
Files changed (88) hide show
  1. package/dist/API.md +135 -5
  2. package/dist/{MIcon-DLOkQduI.js → MIcon-Bxh9j135.js} +15 -8
  3. package/dist/MIcon-Bxh9j135.js.map +1 -0
  4. package/dist/{MMenuItem-DVxKEv1W.js → MMenuItem-BckcR0nW.js} +4 -4
  5. package/dist/{MMenuItem-DVxKEv1W.js.map → MMenuItem-BckcR0nW.js.map} +1 -1
  6. package/dist/{MSlider-BXsBv0ox.js → MSlider-LyH_gy8D.js} +56 -47
  7. package/dist/MSlider-LyH_gy8D.js.map +1 -0
  8. package/dist/{MTextField-rML9jnXs.js → MTextField-FCPOTB0o.js} +65 -64
  9. package/dist/{MTextField-rML9jnXs.js.map → MTextField-FCPOTB0o.js.map} +1 -1
  10. package/dist/api.json +1 -1
  11. package/dist/code-editor.js +2 -2
  12. package/dist/components/MAnimatedNumber.vue.d.ts +27 -0
  13. package/dist/components/MIcon.vue.d.ts +2 -0
  14. package/dist/components/MListGroup.vue.d.ts +23 -0
  15. package/dist/components/MScheduler.vue.d.ts +2 -2
  16. package/dist/components/MScheme.vue.d.ts +60 -0
  17. package/dist/components/MSparkline.vue.d.ts +41 -0
  18. package/dist/components/MWindow.vue.d.ts +2 -2
  19. package/dist/components/_MDrawerItemList.vue.d.ts +2 -0
  20. package/dist/composables/_useSegmentRuns.d.ts +8 -0
  21. package/dist/composables/dynamicColor.d.ts +11 -0
  22. package/dist/composables/useColorPalette.d.ts +3 -1
  23. package/dist/composables/useConfetti.d.ts +32 -0
  24. package/dist/composables/useLocale.d.ts +6 -0
  25. package/dist/index.d.ts +7 -1
  26. package/dist/locales/index.js +21 -0
  27. package/dist/locales/index.js.map +1 -1
  28. package/dist/m3ui-vue.css +1 -1
  29. package/dist/m3ui.js +16187 -15377
  30. package/dist/m3ui.js.map +1 -1
  31. package/dist/map.js +45 -45
  32. package/dist/{material-color-utilities-Cktu8DBU.js → material-color-utilities-C_iikgRm.js} +928 -603
  33. package/dist/material-color-utilities-C_iikgRm.js.map +1 -0
  34. package/dist/rich-text-editor.js +4 -4
  35. package/dist/styles.css +1 -1
  36. package/dist/terminal.js +1 -1
  37. package/dist/{useLocale-CqQrhWFl.js → useLocale-SfQHnJfp.js} +4 -1
  38. package/dist/useLocale-SfQHnJfp.js.map +1 -0
  39. package/package.json +1 -1
  40. package/src/__tests__/MAnimatedNumber.test.ts +106 -0
  41. package/src/__tests__/MIcon.test.ts +19 -0
  42. package/src/__tests__/MListItemShape.test.ts +34 -0
  43. package/src/__tests__/MScheme.test.ts +107 -0
  44. package/src/__tests__/MSparkline.test.ts +96 -0
  45. package/src/__tests__/iconButtonNames.test.ts +124 -0
  46. package/src/__tests__/ssr.test.ts +1 -0
  47. package/src/__tests__/useConfetti.test.ts +81 -0
  48. package/src/components/MAnimatedNumber.vue +301 -0
  49. package/src/components/MAutocomplete.vue +34 -4
  50. package/src/components/MBottomSheet.vue +1 -0
  51. package/src/components/MDataTable.vue +1 -1
  52. package/src/components/MIcon.vue +11 -4
  53. package/src/components/MList.vue +8 -30
  54. package/src/components/MListGroup.vue +66 -0
  55. package/src/components/MMaskField.vue +3 -0
  56. package/src/components/MMultiAutocomplete.vue +5 -1
  57. package/src/components/MMultiSelect.vue +19 -9
  58. package/src/components/MScheme.vue +162 -0
  59. package/src/components/MSearchBar.vue +2 -0
  60. package/src/components/MSelect.vue +44 -10
  61. package/src/components/MSideSheet.vue +3 -0
  62. package/src/components/MSimpleCarousel.vue +6 -0
  63. package/src/components/MSparkline.vue +250 -0
  64. package/src/components/MSplitButton.vue +3 -0
  65. package/src/components/MSpotlightSearch.vue +1 -0
  66. package/src/components/MTable.vue +1 -0
  67. package/src/components/MTagInput.vue +4 -0
  68. package/src/components/MTextField.vue +3 -0
  69. package/src/components/MTour.vue +1 -0
  70. package/src/components/MTreeTable.vue +1 -0
  71. package/src/components/_MTreeNode.vue +3 -0
  72. package/src/composables/_useSegmentRuns.ts +39 -0
  73. package/src/composables/dynamicColor.ts +66 -0
  74. package/src/composables/useColorPalette.ts +2 -2
  75. package/src/composables/useConfetti.ts +204 -0
  76. package/src/composables/useLocale.ts +9 -0
  77. package/src/index.ts +7 -1
  78. package/src/locales/de.ts +3 -0
  79. package/src/locales/es.ts +3 -0
  80. package/src/locales/fr.ts +3 -0
  81. package/src/locales/ja.ts +3 -0
  82. package/src/locales/ko.ts +3 -0
  83. package/src/locales/pt.ts +3 -0
  84. package/src/locales/zh.ts +3 -0
  85. package/dist/MIcon-DLOkQduI.js.map +0 -1
  86. package/dist/MSlider-BXsBv0ox.js.map +0 -1
  87. package/dist/material-color-utilities-Cktu8DBU.js.map +0 -1
  88. package/dist/useLocale-CqQrhWFl.js.map +0 -1
@@ -0,0 +1,96 @@
1
+ import { describe, it, expect, afterEach, beforeAll, afterAll } from 'vitest'
2
+ import { mount, type VueWrapper } from '@vue/test-utils'
3
+ import MSparkline from '../components/MSparkline.vue'
4
+
5
+ // happy-dom has no layout: give every element a 100×30 box
6
+ const size = { clientWidth: 100, clientHeight: 30 }
7
+ const saved: Record<string, PropertyDescriptor | undefined> = {}
8
+ beforeAll(() => {
9
+ for (const [key, value] of Object.entries(size)) {
10
+ saved[key] = Object.getOwnPropertyDescriptor(HTMLElement.prototype, key)
11
+ Object.defineProperty(HTMLElement.prototype, key, { configurable: true, get: () => value })
12
+ }
13
+ })
14
+ afterAll(() => {
15
+ for (const key of Object.keys(size)) if (saved[key]) Object.defineProperty(HTMLElement.prototype, key, saved[key]!)
16
+ })
17
+
18
+ let wrapper: VueWrapper | undefined
19
+ afterEach(() => {
20
+ wrapper?.unmount()
21
+ wrapper = undefined
22
+ })
23
+
24
+ const numbers = (d: string) => (d.match(/-?\d+(\.\d+)?/g) ?? []).map(Number)
25
+ const settle = () => new Promise((r) => setTimeout(r, 900))
26
+
27
+ describe('MSparkline', () => {
28
+ it('is an image named by a summary of the data, in the app\'s language', () => {
29
+ wrapper = mount(MSparkline, { props: { data: [12, 9, 21, 18] } })
30
+ expect(wrapper.attributes('role')).toBe('img')
31
+ expect(wrapper.attributes('aria-label')).toBe('From 12 to 18, low 9, high 21')
32
+ expect(wrapper.find('svg').attributes('aria-hidden')).toBe('true')
33
+ })
34
+
35
+ it('takes a label instead of the summary', () => {
36
+ wrapper = mount(MSparkline, { props: { data: [1, 2], label: 'Visits this week' } })
37
+ expect(wrapper.attributes('aria-label')).toBe('Visits this week')
38
+ })
39
+
40
+ it('draws the line through every point, at the box\'s real size', async () => {
41
+ wrapper = mount(MSparkline, { props: { data: [1, 3, 2, 5], smooth: false, showLast: false }, attachTo: document.body })
42
+ await wrapper.vm.$nextTick()
43
+ expect(wrapper.find('svg').attributes('viewBox')).toBe('0 0 100 30')
44
+ const d = wrapper.find('path').attributes('d')!
45
+ expect(d.match(/[ML]/g)).toHaveLength(4)
46
+ const ys = numbers(d).filter((_, i) => i % 2 === 1)
47
+ // Highest value on top (smallest y), lowest at the bottom
48
+ expect(Math.min(...ys)).toBe(ys[3])
49
+ expect(Math.max(...ys)).toBe(ys[0])
50
+ })
51
+
52
+ it('smooths without overshooting the points (monotone)', async () => {
53
+ wrapper = mount(MSparkline, { props: { data: [0, 10, 10, 0], showLast: false }, attachTo: document.body })
54
+ await wrapper.vm.$nextTick()
55
+ const ys = numbers(wrapper.find('path').attributes('d')!).filter((_, i) => i % 2 === 1)
56
+ const top = Math.min(...ys)
57
+ const bottom = Math.max(...ys)
58
+ // Every control point stays between the highest and lowest points
59
+ expect(ys.every((v) => v >= top - 0.01 && v <= bottom + 0.01)).toBe(true)
60
+ expect(top).toBeCloseTo(2, 0)
61
+ })
62
+
63
+ it('draws bars from zero, a dashed baseline, and an area fill', async () => {
64
+ wrapper = mount(MSparkline, { props: { data: [3, -2, 5], type: 'bar', baseline: 4 }, attachTo: document.body })
65
+ await wrapper.vm.$nextTick()
66
+ const rects = wrapper.findAll('rect')
67
+ expect(rects).toHaveLength(3)
68
+ expect(rects.every((r) => Number(r.attributes('height')) > 0)).toBe(true)
69
+ expect(wrapper.find('line').attributes('stroke-dasharray')).toBe('3 3')
70
+ await wrapper.setProps({ type: 'area', baseline: undefined })
71
+ expect(wrapper.find('linearGradient').exists()).toBe(true)
72
+ expect(wrapper.findAll('path')).toHaveLength(2)
73
+ })
74
+
75
+ it('springs to new data and settles exactly where it would have jumped', async () => {
76
+ const jumped = mount(MSparkline, { props: { data: [5, 1, 4], animate: false }, attachTo: document.body })
77
+ await jumped.vm.$nextTick()
78
+ const target = jumped.find('path').attributes('d')
79
+ jumped.unmount()
80
+ wrapper = mount(MSparkline, { props: { data: [1, 4, 2] }, attachTo: document.body })
81
+ await wrapper.setProps({ data: [5, 1, 4] })
82
+ await new Promise((r) => setTimeout(r, 60))
83
+ expect(wrapper.find('path').attributes('d')).not.toBe(target)
84
+ await settle()
85
+ expect(wrapper.find('path').attributes('d')).toBe(target)
86
+ })
87
+
88
+ it('follows the pointer with interactive', async () => {
89
+ wrapper = mount(MSparkline, { props: { data: [1, 2, 3, 4, 5], interactive: true }, attachTo: document.body })
90
+ ;(wrapper.element as HTMLElement).getBoundingClientRect = () => ({ left: 0, top: 0, width: 100, height: 30 }) as DOMRect
91
+ await wrapper.trigger('pointermove', { clientX: 99 })
92
+ await wrapper.trigger('pointermove', { clientX: 1 })
93
+ await wrapper.trigger('pointerleave')
94
+ expect(wrapper.emitted('hover')).toEqual([[4], [0], [null]])
95
+ })
96
+ })
@@ -0,0 +1,124 @@
1
+ import { describe, it, expect, afterEach } from 'vitest'
2
+ import { mount, type VueWrapper } from '@vue/test-utils'
3
+ import { nextTick, type Component } from 'vue'
4
+ import MSelect from '../components/MSelect.vue'
5
+ import MAutocomplete from '../components/MAutocomplete.vue'
6
+ import MMultiSelect from '../components/MMultiSelect.vue'
7
+ import MMultiAutocomplete from '../components/MMultiAutocomplete.vue'
8
+ import MTagInput from '../components/MTagInput.vue'
9
+ import MTextField from '../components/MTextField.vue'
10
+ import MMaskField from '../components/MMaskField.vue'
11
+ import MSearchBar from '../components/MSearchBar.vue'
12
+ import MSimpleCarousel from '../components/MSimpleCarousel.vue'
13
+ import MSplitButton from '../components/MSplitButton.vue'
14
+ import MTree from '../components/MTree.vue'
15
+ import MTreeTable from '../components/MTreeTable.vue'
16
+
17
+ // A button's accessible name, roughly as a browser computes it: aria-label, else its text without what's hidden from
18
+ // assistive technology (MIcon's ligature text), else its title
19
+ function accessibleName(el: Element): string {
20
+ const label = el.getAttribute('aria-label')
21
+ if (label) return label
22
+ const clone = el.cloneNode(true) as Element
23
+ clone.querySelectorAll('[aria-hidden="true"]').forEach((n) => n.remove())
24
+ return clone.textContent?.trim() || el.getAttribute('title') || ''
25
+ }
26
+
27
+ const options = [{ label: 'Lo-fi', value: 'lofi' }, { label: 'Jazz', value: 'jazz' }]
28
+
29
+ const cases: [string, Component, Record<string, unknown>][] = [
30
+ ['MSelect', MSelect, { modelValue: 'lofi', options, label: 'Genre', clearable: true }],
31
+ ['MAutocomplete', MAutocomplete, { modelValue: 'lofi', options, label: 'Genre', clearable: true }],
32
+ ['MMultiSelect', MMultiSelect, { modelValue: ['lofi', 'jazz'], options, label: 'Genres', clearable: true }],
33
+ ['MMultiAutocomplete', MMultiAutocomplete, { modelValue: ['lofi'], options, label: 'Genres', clearable: true }],
34
+ ['MTagInput', MTagInput, { modelValue: ['vue', 'm3'], label: 'Tags', clearable: true }],
35
+ ['MTextField', MTextField, { modelValue: 'hello', label: 'Name', clearable: true }],
36
+ ['MMaskField', MMaskField, { modelValue: '123', label: 'Phone', clearable: true, mask: '###' }],
37
+ ['MSearchBar', MSearchBar, { modelValue: 'tea', clearable: true }],
38
+ ['MSimpleCarousel', MSimpleCarousel, { items: [{ src: 'a.jpg' }, { src: 'b.jpg' }] }],
39
+ ['MSplitButton', MSplitButton, { label: 'Save', items: [{ label: 'Save as', value: 'as' }] }],
40
+ ['MTree', MTree, { nodes: [{ id: 1, label: 'src', children: [{ id: 2, label: 'App.vue' }] }] }],
41
+ ['MTreeTable', MTreeTable, { columns: [{ key: 'name', label: 'Name' }], rows: [{ id: 1, name: 'src', children: [{ id: 2, name: 'App.vue' }] }] }],
42
+ ]
43
+
44
+ describe('icon-only buttons have an accessible name', () => {
45
+ let wrapper: VueWrapper | undefined
46
+ afterEach(() => {
47
+ wrapper?.unmount()
48
+ wrapper = undefined
49
+ document.body.innerHTML = ''
50
+ })
51
+
52
+ for (const [name, component, props] of cases) {
53
+ it(name, async () => {
54
+ wrapper = mount(component, { props, attachTo: document.body })
55
+ await nextTick()
56
+ const buttons = [...document.body.querySelectorAll('button')]
57
+ expect(buttons.length).toBeGreaterThan(0)
58
+ const unnamed = buttons.filter((b) => !accessibleName(b)).map((b) => b.outerHTML.slice(0, 120))
59
+ expect(unnamed).toEqual([])
60
+ })
61
+ }
62
+ })
63
+
64
+ describe('MSelect listbox semantics', () => {
65
+ it('names the combobox by its label and exposes the open list and its options', async () => {
66
+ const wrapper = mount(MSelect, { props: { modelValue: 'jazz', options, label: 'Genre' }, attachTo: document.body })
67
+ const combo = wrapper.find('[role="combobox"]')
68
+ expect(document.getElementById(combo.attributes('aria-labelledby')!)?.textContent?.trim()).toBe('Genre')
69
+ expect(combo.attributes('aria-expanded')).toBe('false')
70
+ await combo.trigger('click')
71
+ const list = document.getElementById(combo.attributes('aria-controls')!)!
72
+ expect(list.getAttribute('role')).toBe('listbox')
73
+ const opts = [...list.querySelectorAll('[role="option"]')]
74
+ expect(opts.map((o) => accessibleName(o))).toEqual(['Lo-fi', 'Jazz'])
75
+ expect(opts.map((o) => o.getAttribute('aria-selected'))).toEqual(['false', 'true'])
76
+ expect(combo.attributes('aria-activedescendant')).toBe(opts[1]!.id)
77
+ wrapper.unmount()
78
+ document.body.innerHTML = ''
79
+ })
80
+ })
81
+
82
+ describe('MAutocomplete listbox semantics', () => {
83
+ it('points the input at the open list and the option the arrow keys are on', async () => {
84
+ const wrapper = mount(MAutocomplete, { props: { modelValue: null, options, label: 'Genre' }, attachTo: document.body })
85
+ const input = wrapper.find('input[role="combobox"]')
86
+ await input.trigger('focus')
87
+ await input.trigger('keydown', { key: 'ArrowDown' })
88
+ await nextTick()
89
+ const list = document.getElementById(input.attributes('aria-controls')!)!
90
+ expect(list.getAttribute('role')).toBe('listbox')
91
+ const opts = [...list.querySelectorAll('[role="option"]')]
92
+ expect(opts).toHaveLength(2)
93
+ expect(input.attributes('aria-activedescendant')).toBe(opts[0]!.id)
94
+ wrapper.unmount()
95
+ document.body.innerHTML = ''
96
+ })
97
+ })
98
+
99
+ describe('MMultiSelect trigger', () => {
100
+ it('is named by its label', () => {
101
+ const wrapper = mount(MMultiSelect, { props: { modelValue: [], options, label: 'Genres' }, attachTo: document.body })
102
+ const trigger = wrapper.find('[role="button"]')
103
+ expect(document.getElementById(trigger.attributes('aria-labelledby')!)?.textContent?.trim()).toBe('Genres')
104
+ wrapper.unmount()
105
+ document.body.innerHTML = ''
106
+ })
107
+ })
108
+
109
+ describe('MSelect keyboard focus', () => {
110
+ // The trigger had no focus style of its own, so the browser drew its outline (white in dark, black in light)
111
+ it('shows M3\'s focused field instead of the browser outline', async () => {
112
+ const wrapper = mount(MSelect, { props: { modelValue: null, options, label: 'Genre', variant: 'outlined' }, attachTo: document.body })
113
+ const combo = wrapper.find('[role="combobox"]')
114
+ expect(combo.classes()).toContain('outline-none')
115
+ expect(combo.classes()).not.toContain('border-primary')
116
+ await combo.trigger('focus')
117
+ expect(combo.classes()).toEqual(expect.arrayContaining(['border-2', 'border-primary']))
118
+ expect(wrapper.find('label').classes()).toContain('text-primary')
119
+ await combo.trigger('blur')
120
+ expect(combo.classes()).not.toContain('border-primary')
121
+ wrapper.unmount()
122
+ document.body.innerHTML = ''
123
+ })
124
+ })
@@ -29,6 +29,7 @@ const props: Record<string, Record<string, unknown>> = {
29
29
  MRelativeTime: { value: new Date(0) },
30
30
  MResult: { status: 'success', title: 't' },
31
31
  MShape: { shape: 'Circle' },
32
+ MSparkline: { data: [3, 1, 4, 1, 5] },
32
33
  MTour: { steps: [{ target: '#x', title: 't' }] },
33
34
  }
34
35
 
@@ -0,0 +1,81 @@
1
+ import { describe, it, expect, afterEach, beforeEach, vi } from 'vitest'
2
+ import { __resetConfetti, fireConfetti, useConfetti } from '../composables/useConfetti'
3
+
4
+ // happy-dom has no 2D canvas: a fake one that records what's drawn
5
+ let fills: string[] = []
6
+ beforeEach(() => {
7
+ fills = []
8
+ vi.stubGlobal('Path2D', class { constructor(public d: string) {} })
9
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockImplementation(function () {
10
+ const ctx = {
11
+ fillStyle: '',
12
+ globalAlpha: 1,
13
+ setTransform: () => {},
14
+ translate: () => {},
15
+ clearRect: () => {},
16
+ fill: () => fills.push(ctx.fillStyle),
17
+ }
18
+ return ctx as unknown as CanvasRenderingContext2D
19
+ })
20
+ })
21
+ afterEach(() => {
22
+ __resetConfetti()
23
+ vi.restoreAllMocks()
24
+ vi.unstubAllGlobals()
25
+ document.querySelectorAll('canvas').forEach((c) => c.remove())
26
+ })
27
+
28
+ const canvas = () => document.querySelector('canvas')
29
+ const frames = (ms: number) => new Promise((r) => setTimeout(r, ms))
30
+
31
+ describe('useConfetti', () => {
32
+ it('draws the pieces on one canvas over the page that ignores the pointer and assistive technology', async () => {
33
+ fireConfetti({ x: 100, y: 100 }, { count: 30 })
34
+ const c = canvas()!
35
+ expect(c.getAttribute('aria-hidden')).toBe('true')
36
+ expect(c.style.pointerEvents).toBe('none')
37
+ expect(c.style.position).toBe('fixed')
38
+ await frames(60)
39
+ expect(fills.length).toBeGreaterThanOrEqual(30)
40
+ // A second burst shares the canvas
41
+ fireConfetti({ x: 100, y: 100 }, { count: 5 })
42
+ expect(document.querySelectorAll('canvas')).toHaveLength(1)
43
+ })
44
+
45
+ it('takes its colors from the origin\'s theme tokens', async () => {
46
+ const el = document.createElement('div')
47
+ el.style.setProperty('--color-primary', '#c83228')
48
+ el.style.setProperty('--color-tertiary', '#e5b92c')
49
+ document.body.appendChild(el)
50
+ fireConfetti(el, { count: 40 })
51
+ await frames(60)
52
+ expect(new Set(fills)).toEqual(new Set(['#c83228', '#e5b92c']))
53
+ el.remove()
54
+ })
55
+
56
+ it('uses the given colors, and removes the canvas once the last piece has fallen', async () => {
57
+ fireConfetti({ x: 10, y: 10 }, { count: 10, colors: ['red'] })
58
+ await frames(60)
59
+ expect(new Set(fills)).toEqual(new Set(['red']))
60
+ await frames(4000)
61
+ expect(canvas()).toBeNull()
62
+ }, 8000)
63
+
64
+ it('does nothing under reduced motion', () => {
65
+ vi.stubGlobal('matchMedia', (q: string) => ({ matches: q.includes('reduce') }))
66
+ fireConfetti({ x: 10, y: 10 })
67
+ expect(canvas()).toBeNull()
68
+ })
69
+
70
+ it('fire() takes an event, an element, a point or just options', async () => {
71
+ const { fire } = useConfetti()
72
+ const button = document.createElement('button')
73
+ document.body.appendChild(button)
74
+ button.addEventListener('click', (e) => fire(e, { count: 3, colors: ['blue'] }))
75
+ button.click()
76
+ fire({ from: 'top', count: 3, colors: ['green'] })
77
+ await frames(60)
78
+ expect(new Set(fills)).toEqual(new Set(['blue', 'green']))
79
+ button.remove()
80
+ })
81
+ })
@@ -0,0 +1,301 @@
1
+ <script setup lang="ts">
2
+ /**
3
+ * A number, time or duration whose digits roll to their new value on a spring when it changes, like an odometer:
4
+ * each digit rolls on its own (up when the value grows, down when it shrinks) and digits that appear or go away open
5
+ * and close. Numbers are formatted with `Intl.NumberFormat` (currency, percent, units, compact), times with
6
+ * `Intl.DateTimeFormat`, both in the app's language; durations as `h:mm:ss`. Tabular figures. Assistive technology
7
+ * reads the formatted value, not the rolling digits. Not an M3 spec component.
8
+ */
9
+ import { computed, onMounted, onUnmounted, onUpdated, watch } from 'vue'
10
+ import { useLocale } from '../composables/useLocale'
11
+ import { motionSprings, type SpringSpec } from '../composables/motion'
12
+
13
+ const props = withDefaults(
14
+ defineProps<{
15
+ /** The value: a number, a `Date` for times, or seconds for a duration */
16
+ value: number | Date
17
+ /**
18
+ * `number` (Intl.NumberFormat), `datetime` (Intl.DateTimeFormat; a `Date` or a timestamp) or `duration`
19
+ * (seconds as `h:mm:ss`, hours only when there are some). Defaults to `datetime` for a `Date`, `number` otherwise
20
+ */
21
+ type?: 'number' | 'datetime' | 'duration'
22
+ /**
23
+ * Intl options for the type: `{ style: 'currency', currency: 'EUR' }`, `{ style: 'percent' }`,
24
+ * `{ style: 'unit', unit: 'kilometer-per-hour' }`, `{ notation: 'compact' }` for numbers; `{ timeStyle: 'medium' }`
25
+ * (the default), `{ hour: '2-digit', minute: '2-digit' }`, `{ dateStyle: 'short' }` for times. Unused for durations
26
+ */
27
+ format?: Intl.NumberFormatOptions | Intl.DateTimeFormatOptions
28
+ /** BCP-47 language for the format (`es-AR` for Argentine pesos and separators); defaults to the app's locale */
29
+ locale?: string
30
+ /** The rolling spring; Standard SlowSpatial by default (an unhurried landing, no visible bounce) */
31
+ spring?: SpringSpec
32
+ /** Roll to new values; false (or the system's reduced motion) jumps to them */
33
+ animate?: boolean
34
+ }>(),
35
+ { animate: true },
36
+ )
37
+
38
+ const t = useLocale()
39
+ const lang = computed(() => props.locale ?? t.lang)
40
+ const kind = computed(() => props.type ?? (props.value instanceof Date ? 'datetime' : 'number'))
41
+ const numeric = computed(() => (props.value instanceof Date ? props.value.getTime() : props.value))
42
+
43
+ type Part = { type: string; value: string }
44
+
45
+ function durationParts(total: number): Part[] {
46
+ const sign = total < 0 ? '-' : ''
47
+ const s = Math.floor(Math.abs(total))
48
+ const h = Math.floor(s / 3600)
49
+ const m = Math.floor((s % 3600) / 60)
50
+ const parts: Part[] = []
51
+ if (sign) parts.push({ type: 'minusSign', value: sign })
52
+ if (h) parts.push({ type: 'hour', value: String(h) }, { type: 'literal', value: ':' })
53
+ parts.push(
54
+ { type: 'minute', value: h ? String(m).padStart(2, '0') : String(m) },
55
+ { type: 'literal', value: ':' },
56
+ { type: 'second', value: String(s % 60).padStart(2, '0') },
57
+ )
58
+ return parts
59
+ }
60
+
61
+ const parts = computed<Part[]>(() => {
62
+ if (kind.value === 'duration') return durationParts(numeric.value)
63
+ if (kind.value === 'datetime') {
64
+ const options = (props.format as Intl.DateTimeFormatOptions | undefined) ?? { timeStyle: 'medium' }
65
+ return new Intl.DateTimeFormat(lang.value, options).formatToParts(numeric.value)
66
+ }
67
+ return new Intl.NumberFormat(lang.value, props.format as Intl.NumberFormatOptions | undefined).formatToParts(numeric.value)
68
+ })
69
+ const text = computed(() => parts.value.map((p) => p.value).join(''))
70
+
71
+ interface Cell {
72
+ key: string
73
+ char: string
74
+ digit?: number
75
+ /** Digits a column cycles through: 10, or 6 for the tens of minutes and seconds */
76
+ base: number
77
+ /** Roll the short way (hours: 12 → 1 is one step back, not nine forward) */
78
+ shortest: boolean
79
+ }
80
+
81
+ const DATE_DIGITS = new Set(['hour', 'minute', 'second', 'day', 'month', 'year', 'fractionalSecond', 'relatedYear'])
82
+
83
+ // Number digits are keyed by their place (ones, tens, tenths...), time digits by their field and place within it, so
84
+ // each keeps its column, and its spring, as the value changes; everything else by its type and where it sits.
85
+ const cells = computed<Cell[]>(() => {
86
+ const out: Cell[] = []
87
+ const push = (key: string, ch: string, base = 10, shortest = false) => {
88
+ const digit = Number(ch)
89
+ out.push(ch.trim() && !Number.isNaN(digit) ? { key, char: ch, digit, base, shortest } : { key: `${key}-${ch}`, char: ch, base, shortest })
90
+ }
91
+ if (kind.value === 'number') {
92
+ let place = parts.value.filter((p) => p.type === 'integer').reduce((n, p) => n + p.value.length, 0)
93
+ let fraction = 0
94
+ for (const part of parts.value) {
95
+ if (part.type === 'integer' || part.type === 'fraction') {
96
+ for (const ch of part.value) push(part.type === 'integer' ? `i${--place}` : `f${++fraction}`, ch)
97
+ } else {
98
+ const at = part.type === 'group' ? place : part.type === 'decimal' ? 'd' : out.length
99
+ out.push({ key: `${part.type}-${at}`, char: part.value, base: 10, shortest: false })
100
+ }
101
+ }
102
+ return out
103
+ }
104
+ parts.value.forEach((part, index) => {
105
+ if (!DATE_DIGITS.has(part.type)) {
106
+ out.push({ key: `${part.type}-${index}`, char: part.value, base: 10, shortest: false })
107
+ return
108
+ }
109
+ const chars = [...part.value]
110
+ chars.forEach((ch, i) => {
111
+ const fromRight = chars.length - 1 - i
112
+ const sixty = (part.type === 'minute' || part.type === 'second') && fromRight === 1
113
+ push(`${part.type}-${fromRight}`, ch, sixty ? 6 : 10, part.type === 'hour')
114
+ })
115
+ })
116
+ return out
117
+ })
118
+
119
+ // ── Rolling: one spring per digit column, stepped in a rAF loop and written to its strip's transform ─────────
120
+ interface Column { pos: number; vel: number; target: number; base: number; el?: HTMLElement }
121
+ const columns = new Map<string, Column>()
122
+ let mounted = false
123
+ let raf = 0
124
+ let last = 0
125
+ let direction = 1
126
+ const reduceMotion = () => typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches
127
+
128
+ const mod = (n: number, base: number) => ((n % base) + base) % base
129
+ const write = (c: Column) => {
130
+ if (!c.el) return
131
+ c.el.style.transform = `translateY(${-mod(c.pos, c.base)}lh)`
132
+ // Unmasked a little before landing, so the mask eases out with the last of the roll
133
+ c.el.parentElement?.toggleAttribute('data-rolling', Math.abs(c.pos - c.target) > 0.15)
134
+ }
135
+
136
+ // The strip's starting transform, set once per column, so the server renders the right digits. Vue may write it
137
+ // again when it patches the list (a digit added before it), so onUpdated puts every column back where it is.
138
+ const initialStyles = new Map<string, Record<string, string>>()
139
+ function initialStyle(cell: Cell) {
140
+ let style = initialStyles.get(cell.key)
141
+ if (!style) {
142
+ // A column that appears after mount rolls in from 0; the first render shows the digits as they are
143
+ const start = mounted && props.animate ? 0 : cell.digit!
144
+ columns.set(cell.key, { pos: start, vel: 0, target: cell.digit!, base: cell.base })
145
+ style = { transform: `translateY(${-start}lh)` }
146
+ initialStyles.set(cell.key, style)
147
+ }
148
+ return style
149
+ }
150
+ const setStrip = (key: string) => (el: unknown) => {
151
+ const c = columns.get(key)
152
+ if (c) c.el = (el as HTMLElement | null) ?? undefined
153
+ }
154
+ // Two runs of the column's digits, so a digit rolling past the last shows the first coming in below it seamlessly
155
+ const strip = (base: number) => Array.from({ length: base * 2 }, (_, i) => i % base)
156
+
157
+ function frame(now: number) {
158
+ let dt = Math.min((now - last) / 1000, 1 / 30)
159
+ last = now
160
+ const { stiffness: k, dampingRatio } = props.spring ?? motionSprings.standard.slowSpatial
161
+ const c = 2 * dampingRatio * Math.sqrt(k)
162
+ let moving = false
163
+ while (dt > 0) {
164
+ const h = Math.min(dt, 0.004)
165
+ dt -= h
166
+ for (const col of columns.values()) {
167
+ col.vel += (-k * (col.pos - col.target) - c * col.vel) * h
168
+ col.pos += col.vel * h
169
+ }
170
+ }
171
+ for (const col of columns.values()) {
172
+ if (Math.abs(col.pos - col.target) < 0.002 && Math.abs(col.vel) < 0.01) {
173
+ col.pos = col.target
174
+ col.vel = 0
175
+ } else moving = true
176
+ write(col)
177
+ }
178
+ raf = moving ? requestAnimationFrame(frame) : 0
179
+ }
180
+
181
+ watch(numeric, (next, prev) => (direction = next >= (prev ?? next) ? 1 : -1))
182
+
183
+ watch(cells, (next) => {
184
+ const keys = new Set(next.map((c) => c.key))
185
+ for (const key of [...columns.keys()]) {
186
+ if (!keys.has(key)) {
187
+ columns.delete(key)
188
+ initialStyles.delete(key)
189
+ }
190
+ }
191
+ const instant = !props.animate || reduceMotion()
192
+ for (const cell of next) {
193
+ const col = cell.digit === undefined ? undefined : columns.get(cell.key)
194
+ if (!col) continue
195
+ const base = col.base
196
+ const from = mod(Math.round(col.target), base)
197
+ const forward = mod(cell.digit! - from, base)
198
+ const backward = mod(from - cell.digit!, base)
199
+ // Forward through the last digit → 0 when the value grows, backward when it shrinks; hours the short way
200
+ col.target += cell.shortest ? (forward <= backward ? forward : -backward) : direction > 0 ? forward : -backward
201
+ if (instant) {
202
+ col.pos = col.target
203
+ col.vel = 0
204
+ write(col)
205
+ }
206
+ }
207
+ if (!instant && !raf && mounted) {
208
+ last = performance.now()
209
+ raf = requestAnimationFrame(frame)
210
+ }
211
+ }, { flush: 'post' })
212
+
213
+ onMounted(() => {
214
+ mounted = true
215
+ for (const col of columns.values()) write(col)
216
+ })
217
+ onUpdated(() => {
218
+ for (const col of columns.values()) write(col)
219
+ })
220
+ onUnmounted(() => cancelAnimationFrame(raf))
221
+ </script>
222
+
223
+ <template>
224
+ <span class="m3-animated-number">
225
+ <span class="m3-anum-sr">{{ text }}</span>
226
+ <TransitionGroup name="m3-anum" tag="span" class="m3-anum-cells" aria-hidden="true">
227
+ <span v-for="cell in cells" :key="cell.key" class="m3-anum-cell" :class="cell.digit !== undefined && 'm3-anum-digit'">
228
+ <span v-if="cell.digit !== undefined" :ref="setStrip(cell.key)" class="m3-anum-strip" :style="initialStyle(cell)">
229
+ <span v-for="(d, i) in strip(cell.base)" :key="i">{{ d }}</span>
230
+ </span>
231
+ <template v-else>{{ cell.char }}</template>
232
+ </span>
233
+ </TransitionGroup>
234
+ </span>
235
+ </template>
236
+
237
+ <style>
238
+ /* Defaults in the base layer so the consumer's classes on the root win (see MShape). */
239
+ @layer base {
240
+ .m3-animated-number {
241
+ display: inline-flex;
242
+ position: relative;
243
+ font-variant-numeric: tabular-nums;
244
+ white-space: nowrap;
245
+ }
246
+ }
247
+ .m3-anum-sr {
248
+ position: absolute;
249
+ width: 1px;
250
+ height: 1px;
251
+ overflow: hidden;
252
+ clip-path: inset(50%);
253
+ white-space: nowrap;
254
+ }
255
+ .m3-anum-cells {
256
+ display: inline-flex;
257
+ }
258
+ .m3-anum-cell {
259
+ display: inline-block;
260
+ white-space: pre;
261
+ }
262
+ .m3-anum-digit {
263
+ height: 1lh;
264
+ width: 1ch;
265
+ overflow: hidden;
266
+ /* Rolling digits fade at the column's edges. At rest the mask is stretched so its fades fall outside the
267
+ column; it eases in and out instead of switching, which read as an abrupt stop. */
268
+ mask-image: linear-gradient(transparent, #000 20%, #000 80%, transparent);
269
+ mask-size: 100% 180%;
270
+ mask-position: center;
271
+ mask-repeat: no-repeat;
272
+ transition: mask-size 350ms cubic-bezier(0.2, 0, 0, 1);
273
+ }
274
+ .m3-anum-digit[data-rolling] {
275
+ mask-size: 100% 100%;
276
+ transition-duration: 120ms;
277
+ }
278
+ .m3-anum-strip {
279
+ display: flex;
280
+ flex-direction: column;
281
+ align-items: center;
282
+ }
283
+ .m3-anum-strip > span {
284
+ height: 1lh;
285
+ }
286
+ .m3-anum-enter-active,
287
+ .m3-anum-leave-active {
288
+ transition: width 300ms cubic-bezier(0.2, 0, 0, 1), opacity 200ms ease;
289
+ }
290
+ .m3-anum-enter-from,
291
+ .m3-anum-leave-to {
292
+ width: 0;
293
+ opacity: 0;
294
+ }
295
+ @media (prefers-reduced-motion: reduce) {
296
+ .m3-anum-enter-active,
297
+ .m3-anum-leave-active {
298
+ transition: none;
299
+ }
300
+ }
301
+ </style>