@m3ui-vue/m3ui-vue 1.0.1 → 1.0.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 (115) hide show
  1. package/dist/API.md +636 -20
  2. package/dist/MMenuItem-DFyXflk9.js +707 -0
  3. package/dist/MMenuItem-DFyXflk9.js.map +1 -0
  4. package/dist/MSlider-CdNIH7jc.js +1376 -0
  5. package/dist/MSlider-CdNIH7jc.js.map +1 -0
  6. package/dist/MTextField-B4X92vH_.js +671 -0
  7. package/dist/MTextField-B4X92vH_.js.map +1 -0
  8. package/dist/api.json +1 -1
  9. package/dist/chart.js +1 -1
  10. package/dist/chart.js.map +1 -1
  11. package/dist/code-editor.js +1 -1
  12. package/dist/components/MIconButton.vue.d.ts +1 -1
  13. package/dist/components/MMap.vue.d.ts +74 -0
  14. package/dist/components/MMapBaseLayers.vue.d.ts +15 -0
  15. package/dist/components/MMapControl.vue.d.ts +23 -0
  16. package/dist/components/MMapFeatureInfo.vue.d.ts +25 -0
  17. package/dist/components/MMapFilter.vue.d.ts +19 -0
  18. package/dist/components/MMapGeoJson.vue.d.ts +34 -0
  19. package/dist/components/MMapHover.vue.d.ts +17 -0
  20. package/dist/components/MMapIdentify.vue.d.ts +37 -0
  21. package/dist/components/MMapLayers.vue.d.ts +31 -0
  22. package/dist/components/MMapMarker.vue.d.ts +42 -0
  23. package/dist/components/MMapMeasure.vue.d.ts +43 -0
  24. package/dist/components/MMapPopup.vue.d.ts +43 -0
  25. package/dist/components/MMapSearch.vue.d.ts +28 -0
  26. package/dist/components/MShader.vue.d.ts +9 -3
  27. package/dist/components/_MMapLayerItem.vue.d.ts +25 -0
  28. package/dist/composables/_hydration.d.ts +4 -0
  29. package/dist/composables/_mapGeometry.d.ts +13 -0
  30. package/dist/composables/_ssrState.d.ts +30 -0
  31. package/dist/composables/_storageKeys.d.ts +3 -0
  32. package/dist/composables/_useThemeTokens.d.ts +7 -0
  33. package/dist/composables/mapAdapters.d.ts +111 -0
  34. package/dist/composables/mapSearch.d.ts +31 -0
  35. package/dist/composables/themeInitScript.d.ts +22 -0
  36. package/dist/composables/useColorPalette.d.ts +176 -6
  37. package/dist/composables/useLocale.d.ts +30 -0
  38. package/dist/composables/useMap.d.ts +47 -0
  39. package/dist/composables/useMapFilter.d.ts +10 -0
  40. package/dist/composables/useMapLayers.d.ts +30 -0
  41. package/dist/composables/useTheme.d.ts +2 -0
  42. package/dist/index.d.ts +4 -1
  43. package/dist/locales/index.js +217 -7
  44. package/dist/locales/index.js.map +1 -1
  45. package/dist/m3ui-vue.css +1 -1
  46. package/dist/m3ui.js +6742 -7961
  47. package/dist/m3ui.js.map +1 -1
  48. package/dist/map.d.ts +24 -0
  49. package/dist/map.js +1931 -0
  50. package/dist/map.js.map +1 -0
  51. package/dist/plugin.d.ts +25 -2
  52. package/dist/rich-text-editor.js +27 -26
  53. package/dist/rich-text-editor.js.map +1 -1
  54. package/dist/styles.css +1 -1
  55. package/dist/{useLocale-CuvWRZ1h.js → useLocale-b5-hzsL3.js} +32 -2
  56. package/dist/useLocale-b5-hzsL3.js.map +1 -0
  57. package/package.json +11 -2
  58. package/src/__tests__/MFab.test.ts +52 -6
  59. package/src/__tests__/MMap.test.ts +292 -0
  60. package/src/__tests__/MMapLayers.test.ts +257 -0
  61. package/src/__tests__/MMapTools.test.ts +233 -0
  62. package/src/__tests__/MShader.test.ts +16 -0
  63. package/src/__tests__/_fakeMaplibre.ts +158 -0
  64. package/src/__tests__/hydration.test.ts +119 -0
  65. package/src/__tests__/ssr.test.ts +171 -0
  66. package/src/__tests__/ssrState.test.ts +155 -0
  67. package/src/__tests__/themeInitScript.test.ts +122 -0
  68. package/src/components/MChart.vue +3 -2
  69. package/src/components/MFab.vue +29 -7
  70. package/src/components/MIconButton.vue +1 -1
  71. package/src/components/MLightbox.vue +10 -1
  72. package/src/components/MMap.vue +522 -0
  73. package/src/components/MMapBaseLayers.vue +67 -0
  74. package/src/components/MMapControl.vue +61 -0
  75. package/src/components/MMapFeatureInfo.vue +41 -0
  76. package/src/components/MMapFilter.vue +80 -0
  77. package/src/components/MMapGeoJson.vue +136 -0
  78. package/src/components/MMapHover.vue +131 -0
  79. package/src/components/MMapIdentify.vue +103 -0
  80. package/src/components/MMapLayers.vue +111 -0
  81. package/src/components/MMapMarker.vue +102 -0
  82. package/src/components/MMapMeasure.vue +452 -0
  83. package/src/components/MMapPopup.vue +99 -0
  84. package/src/components/MMapSearch.vue +162 -0
  85. package/src/components/MSearchBar.vue +4 -1
  86. package/src/components/MShader.vue +11 -3
  87. package/src/components/_MMapLayerItem.vue +77 -0
  88. package/src/composables/_hydration.ts +10 -0
  89. package/src/composables/_mapGeometry.ts +75 -0
  90. package/src/composables/_ssrState.ts +80 -0
  91. package/src/composables/_storageKeys.ts +6 -0
  92. package/src/composables/_useThemeTokens.ts +42 -0
  93. package/src/composables/mapAdapters.ts +208 -0
  94. package/src/composables/mapSearch.ts +56 -0
  95. package/src/composables/themeInitScript.ts +51 -0
  96. package/src/composables/useColorPalette.ts +32 -14
  97. package/src/composables/useLocale.ts +62 -0
  98. package/src/composables/useMap.ts +98 -0
  99. package/src/composables/useMapFilter.ts +45 -0
  100. package/src/composables/useMapLayers.ts +124 -0
  101. package/src/composables/useTheme.ts +18 -7
  102. package/src/composables/useWindowSizeClass.ts +23 -4
  103. package/src/index.ts +4 -1
  104. package/src/locales/de.ts +31 -1
  105. package/src/locales/es.ts +31 -1
  106. package/src/locales/fr.ts +31 -1
  107. package/src/locales/ja.ts +31 -1
  108. package/src/locales/ko.ts +31 -1
  109. package/src/locales/pt.ts +31 -1
  110. package/src/locales/zh.ts +31 -1
  111. package/src/map.ts +32 -0
  112. package/src/plugin.ts +77 -13
  113. package/dist/MTextField-BPbFeI9M.js +0 -1368
  114. package/dist/MTextField-BPbFeI9M.js.map +0 -1
  115. package/dist/useLocale-CuvWRZ1h.js.map +0 -1
@@ -0,0 +1,119 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest'
2
+ import { createSSRApp, h, nextTick, type Component } from 'vue'
3
+ import { renderToString } from 'vue/server-renderer'
4
+
5
+ // Each test imports the whole library afresh: a cold import can take seconds when the suite runs in parallel
6
+ vi.setConfig({ testTimeout: 30_000 })
7
+
8
+ /** A fresh copy of the library seeing a window of this width (the window size is read when its modules load). */
9
+ async function load(width: number) {
10
+ Object.defineProperty(window, 'innerWidth', { value: width, configurable: true })
11
+ vi.resetModules()
12
+ return {
13
+ createM3UI: (await import('../plugin')).createM3UI,
14
+ useWindowSizeClass: (await import('../composables/useWindowSizeClass')).useWindowSizeClass,
15
+ MNavigationSuite: (await import('../components/MNavigationSuite.vue')).default,
16
+ MListDetail: (await import('../components/MListDetail.vue')).default,
17
+ MSupportingPane: (await import('../components/MSupportingPane.vue')).default,
18
+ }
19
+ }
20
+ type Lib = Awaited<ReturnType<typeof load>>
21
+
22
+ const items = [
23
+ { value: 'a', label: 'A', icon: 'home' },
24
+ { value: 'b', label: 'B', icon: 'search' },
25
+ ]
26
+
27
+ const cases: [keyof Lib, Record<string, unknown>, Record<string, () => unknown>][] = [
28
+ ['MNavigationSuite', { modelValue: 'a', items }, { default: () => 'content' }],
29
+ ['MListDetail', {}, { list: () => 'list', detail: () => 'detail' }],
30
+ ['MSupportingPane', {}, { default: () => 'main', supporting: () => 'supporting' }],
31
+ ]
32
+
33
+ afterEach(() => {
34
+ vi.restoreAllMocks()
35
+ document.body.innerHTML = ''
36
+ })
37
+
38
+ /**
39
+ * The server has no window, so it renders the adaptive layouts compact. The client (a 1024px wide window here) has to
40
+ * hydrate that HTML without mismatches, then adapt to its real size.
41
+ */
42
+ async function hydrate(name: keyof Lib, props: Record<string, unknown>, slots: Record<string, () => unknown>) {
43
+ // What a server renders: no window to measure, so width 0
44
+ const server = await load(0)
45
+ const html = await renderToString(createSSRApp({ render: () => h(server[name] as Component, props, slots) }).use(server.createM3UI()))
46
+
47
+ const lib = await load(1024)
48
+
49
+ const container = document.createElement('div')
50
+ container.innerHTML = html
51
+ document.body.appendChild(container)
52
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
53
+ let hydrating = true
54
+ const client = createSSRApp({ render: () => h(lib[name] as Component, props, slots) }).use(lib.createM3UI({ isHydrating: () => hydrating }))
55
+ vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(1200)
56
+ vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(800)
57
+ client.mount(container)
58
+ hydrating = false
59
+ await nextTick()
60
+ return { container, mismatches: warn.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('Hydration')) }
61
+ }
62
+
63
+ describe('hydrating server-rendered adaptive layouts', () => {
64
+ it.each(cases)('%s matches the server HTML, then adapts', async (name, props, slots) => {
65
+ const { container, mismatches } = await hydrate(name, props, slots)
66
+ expect(mismatches).toEqual([])
67
+ expect(container.innerHTML).not.toBe('')
68
+ })
69
+
70
+ it('MNavigationSuite switches to the rail once mounted on a wide window', async () => {
71
+ const { container } = await hydrate('MNavigationSuite', { modelValue: 'a', items }, { default: () => 'content' })
72
+ // Compact (the server's) is a short navigation bar; at 1200px it's a rail, laid out in a row
73
+ expect(container.firstElementChild!.className).toContain('flex-row')
74
+ expect(container.textContent).toContain('content')
75
+ })
76
+
77
+ it('with a viewport (from a cookie), renders the right layout from the server on, without a jump', async () => {
78
+ const props = { modelValue: 'a', items }
79
+ const slots = { default: () => 'content' }
80
+ const viewport = { width: 1200, height: 800 }
81
+ const server = await load(0)
82
+ // Under happy-dom there is a window, so the flag stands in for the server's (ssr.test.ts renders it without one)
83
+ const html = await renderToString(createSSRApp({ render: () => h(server.MNavigationSuite, props, slots) }).use(server.createM3UI({ initialState: { viewport }, isHydrating: () => true })))
84
+ expect(html).toMatch(/^<div class="[^"]*flex-row/)
85
+
86
+ const lib = await load(1200)
87
+ const container = document.createElement('div')
88
+ container.innerHTML = html
89
+ document.body.appendChild(container)
90
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
91
+ const layouts: string[] = []
92
+ const app = createSSRApp({
93
+ render: () => h(lib.MNavigationSuite, { ...props, onVnodeUpdated: () => layouts.push(container.firstElementChild!.className) }, slots),
94
+ })
95
+ app.use(lib.createM3UI({ initialState: { viewport }, isHydrating: () => true }))
96
+ // happy-dom has no layout: what the browser measures once mounted
97
+ vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(1200)
98
+ vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(800)
99
+ app.mount(container)
100
+ await nextTick()
101
+ expect(warn.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('Hydration'))).toEqual([])
102
+ // Never compact on the client either
103
+ expect(container.firstElementChild!.className).toContain('flex-row')
104
+ expect(layouts.filter((c) => c.includes('flex-col'))).toEqual([])
105
+ })
106
+
107
+ it('without isHydrating, guesses from the window on the first render (client-only apps)', async () => {
108
+ const { useWindowSizeClass } = await load(1024)
109
+ let first = -1
110
+ const app = createSSRApp({
111
+ setup() {
112
+ first = useWindowSizeClass(() => null).width.value
113
+ return () => h('div')
114
+ },
115
+ })
116
+ app.mount(document.createElement('div'))
117
+ expect(first).toBe(1024)
118
+ })
119
+ })
@@ -0,0 +1,171 @@
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
+ // The empty container: MapLibre only loads in the browser
77
+ ['map', 'MMap', { mapStyle: 'https://tiles.test/style.json' }],
78
+ ] as const)('renders %s/%s', async (entry, name, componentProps) => {
79
+ const mod = await import(`../${entry}.ts`)
80
+ await expect(render(mod[name], componentProps)).resolves.toBeTypeOf('string')
81
+ })
82
+
83
+ it.each([
84
+ {},
85
+ { palette: 'red' },
86
+ { palette: 'red', persistPalette: false },
87
+ { seed: '#6750a4' },
88
+ { contrast: 'high' },
89
+ { themeColor: 'surface' },
90
+ { locale: { close: 'Cerrar' } },
91
+ { customPalettes: [{ id: 'mine', label: 'Mine', seed: '#ff0000' }] },
92
+ ])('installs createM3UI(%o)', async (options) => {
93
+ await expect(render(lib.MButton, {}, options)).resolves.toContain('button')
94
+ })
95
+
96
+ it('applies the app locale', async () => {
97
+ expect(await render(lib.MPagination, { modelValue: 1, total: 50 }, { locale: lib.defaultLocale })).toBeTruthy()
98
+ })
99
+
100
+ describe('initialState', () => {
101
+ // What a component renders from the composables, server-side
102
+ async function state(options: object) {
103
+ const app = createSSRApp({
104
+ setup() {
105
+ const { theme } = lib.useTheme()
106
+ const { palette, contrast, activeContrast } = lib.useColorPalette()
107
+ return () => h('p', `${theme.value} ${palette.value} ${contrast.value} ${activeContrast.value}`)
108
+ },
109
+ })
110
+ app.use(lib.createM3UI(options))
111
+ return (await renderToString(app)).replace(/<\/?p>/g, '')
112
+ }
113
+
114
+ it('reports the user\'s choice on the server', async () => {
115
+ expect(await state({ initialState: { theme: 'dark', palette: 'blue', contrast: 'high' } })).toBe('dark blue high high')
116
+ })
117
+
118
+ it('falls back to the plugin\'s defaults, like a first visit', async () => {
119
+ expect(await state({ palette: 'red', contrast: 'medium', initialState: {} })).toBe('system red medium medium')
120
+ expect(await state({ seed: '#6750a4', initialState: {} })).toBe('system seed standard standard')
121
+ })
122
+
123
+ it('resolves system contrast to standard (the server can\'t know the OS preference)', async () => {
124
+ expect(await state({ initialState: { contrast: 'system' } })).toBe('system purple system standard')
125
+ })
126
+
127
+ it('lets persistPalette: false win over the stored choice', async () => {
128
+ expect(await state({ palette: 'red', contrast: 'high', persistPalette: false, initialState: { palette: 'blue', contrast: 'medium' } }))
129
+ .toBe('system red high high')
130
+ })
131
+
132
+ it('ignores invalid values (cookies are user input)', async () => {
133
+ expect(await state({ initialState: { theme: 'pink', contrast: 'max' } as object })).toBe('system purple standard standard')
134
+ })
135
+
136
+ it('renders the adaptive layouts for the given viewport', async () => {
137
+ const suite = (options: object) => render(lib.MNavigationSuite, { modelValue: 'a', items: [{ value: 'a', label: 'A', icon: 'home' }] }, options)
138
+ // A desktop window: a rail beside the content (a row); none known: compact, a bar under it (a column)
139
+ expect(await suite({ initialState: { viewport: { width: 1280, height: 800 } } })).toMatch(/^<div class="[^"]*flex-row/)
140
+ expect(await suite({ initialState: {} })).toMatch(/^<div class="[^"]*flex-col/)
141
+ expect(await suite({ initialState: { viewport: { width: -1, height: 800 } } })).toMatch(/^<div class="[^"]*flex-col/)
142
+ })
143
+
144
+ it('reports the viewport through useWindowSizeClass()', async () => {
145
+ const app = createSSRApp({
146
+ setup() {
147
+ const { widthClass, heightClass } = lib.useWindowSizeClass()
148
+ return () => h('p', `${widthClass.value} ${heightClass.value}`)
149
+ },
150
+ })
151
+ app.use(lib.createM3UI({ initialState: { viewport: { width: 1280, height: 800 } } }))
152
+ expect(await renderToString(app)).toBe('<p>large medium</p>')
153
+ })
154
+
155
+ it('without it, keeps reporting the module defaults', async () => {
156
+ expect(await state({ palette: 'red' })).toBe('system purple standard standard')
157
+ })
158
+ })
159
+
160
+ it.each(['useTheme','useColorPalette', 'useDevice', 'useLocale', 'useWindowSizeClass', 'useToast', 'useNotification'] as const)(
161
+ '%s() works in setup', async (name) => {
162
+ const app = createSSRApp({
163
+ setup() {
164
+ ;(lib[name] as () => unknown)()
165
+ return () => h('div')
166
+ },
167
+ })
168
+ await expect(renderToString(app)).resolves.toBe('<div></div>')
169
+ },
170
+ )
171
+ })
@@ -0,0 +1,155 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2
+ import { createSSRApp, h, nextTick } from 'vue'
3
+
4
+ // Each test imports the whole library afresh: a cold import can take seconds when the suite runs in parallel
5
+ vi.setConfig({ testTimeout: 30_000 })
6
+
7
+ // Fresh modules per test: the theme, palette and cookie switch live at module level
8
+ async function load() {
9
+ vi.resetModules()
10
+ return await import('../index')
11
+ }
12
+
13
+ function cookie(name: string) {
14
+ return document.cookie.split('; ').find((c) => c.startsWith(`${name}=`))?.slice(name.length + 1)
15
+ }
16
+
17
+ beforeEach(() => {
18
+ localStorage.clear()
19
+ for (const name of ['m3-theme', 'm3-palette', 'm3-contrast', 'm3-viewport']) document.cookie = `${name}=; Max-Age=0; Path=/`
20
+ })
21
+
22
+ afterEach(() => {
23
+ vi.restoreAllMocks()
24
+ document.body.innerHTML = ''
25
+ })
26
+
27
+ describe('initialState while hydrating', () => {
28
+ it('renders the server\'s values first (no mismatch), then the stored ones', async () => {
29
+ // The browser holds other values than the cookies the server read (a user from before the cookies)
30
+ localStorage.setItem('m3-theme', 'light')
31
+ localStorage.setItem('m3-palette', 'green')
32
+ const lib = await load()
33
+ const container = document.createElement('div')
34
+ // What the server rendered from the cookies (see ssr.test.ts)
35
+ container.innerHTML = '<p>dark blue</p>'
36
+ document.body.appendChild(container)
37
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
38
+
39
+ let hydrating = true
40
+ const app = createSSRApp({
41
+ setup() {
42
+ const { theme } = lib.useTheme()
43
+ const { palette } = lib.useColorPalette()
44
+ return () => h('p', `${theme.value} ${palette.value}`)
45
+ },
46
+ })
47
+ app.use(lib.createM3UI({ initialState: { theme: 'dark', palette: 'blue' }, isHydrating: () => hydrating }))
48
+ app.mount(container)
49
+ hydrating = false
50
+ await nextTick()
51
+
52
+ expect(warn.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('Hydration'))).toEqual([])
53
+ expect(container.textContent).toBe('light green')
54
+ })
55
+
56
+ it('stays writable during hydration', async () => {
57
+ const lib = await load()
58
+ let theme!: ReturnType<typeof lib.useTheme>['theme']
59
+ const app = createSSRApp({
60
+ setup() {
61
+ theme = lib.useTheme().theme
62
+ return () => h('p', theme.value)
63
+ },
64
+ })
65
+ const container = document.createElement('div')
66
+ container.innerHTML = '<p>dark</p>'
67
+ app.use(lib.createM3UI({ initialState: { theme: 'dark' }, isHydrating: () => true })).mount(container)
68
+ theme.value = 'light'
69
+ await nextTick()
70
+ expect(localStorage.getItem('m3-theme')).toBe('light')
71
+ })
72
+ })
73
+
74
+ describe('cookies', () => {
75
+ it('copies what is already stored when the plugin installs', async () => {
76
+ localStorage.setItem('m3-theme', 'dark')
77
+ localStorage.setItem('m3-palette', 'teal')
78
+ const lib = await load()
79
+ createSSRApp({ render: () => null }).use(lib.createM3UI({ cookies: true }))
80
+ expect(cookie('m3-theme')).toBe('dark')
81
+ expect(cookie('m3-palette')).toBe('teal')
82
+ })
83
+
84
+ it('writes the first-visit default palette', async () => {
85
+ const lib = await load()
86
+ createSSRApp({ render: () => null }).use(lib.createM3UI({ cookies: true, palette: 'red' }))
87
+ expect(cookie('m3-palette')).toBe('red')
88
+ })
89
+
90
+ it('follows changes to the theme, the palette and the contrast', async () => {
91
+ const lib = await load()
92
+ let api!: { theme: ReturnType<typeof lib.useTheme>, palette: ReturnType<typeof lib.useColorPalette> }
93
+ const app = createSSRApp({
94
+ setup() {
95
+ api = { theme: lib.useTheme(), palette: lib.useColorPalette() }
96
+ return () => null
97
+ },
98
+ })
99
+ app.use(lib.createM3UI({ cookies: true })).mount(document.createElement('div'))
100
+ api.theme.theme.value = 'dark'
101
+ api.palette.set('blue')
102
+ api.palette.setContrast('high')
103
+ await nextTick()
104
+ await vi.waitFor(() => expect(cookie('m3-palette')).toBe('blue'))
105
+ expect(cookie('m3-theme')).toBe('dark')
106
+ expect(cookie('m3-contrast')).toBe('high')
107
+ })
108
+
109
+ it('keeps the window size, following resizes', async () => {
110
+ vi.useFakeTimers()
111
+ try {
112
+ Object.defineProperty(window, 'innerWidth', { value: 1280, configurable: true })
113
+ Object.defineProperty(window, 'innerHeight', { value: 800, configurable: true })
114
+ const lib = await load()
115
+ createSSRApp({ render: () => null }).use(lib.createM3UI({ cookies: true }))
116
+ expect(cookie('m3-viewport')).toBe('1280x800')
117
+ Object.defineProperty(window, 'innerWidth', { value: 390, configurable: true })
118
+ window.dispatchEvent(new Event('resize'))
119
+ // Debounced: not on every resize event
120
+ expect(cookie('m3-viewport')).toBe('1280x800')
121
+ vi.advanceTimersByTime(300)
122
+ expect(cookie('m3-viewport')).toBe('390x800')
123
+ } finally {
124
+ vi.useRealTimers()
125
+ }
126
+ })
127
+
128
+ it('falls back to the cookies when storage has nothing (cleared storage, or set by a server), and keeps them', async () => {
129
+ document.cookie = 'm3-theme=dark; Path=/'
130
+ document.cookie = 'm3-palette=blue; Path=/'
131
+ const lib = await load()
132
+ let state = ''
133
+ createSSRApp({
134
+ setup() {
135
+ const { theme } = lib.useTheme()
136
+ const { palette } = lib.useColorPalette()
137
+ state = `${theme.value} ${palette.value}`
138
+ return () => null
139
+ },
140
+ }).use(lib.createM3UI({ cookies: true, palette: 'red' })).mount(document.createElement('div'))
141
+ expect(state).toBe('dark blue')
142
+ expect(cookie('m3-theme')).toBe('dark')
143
+ expect(cookie('m3-palette')).toBe('blue')
144
+ expect(document.documentElement.classList.contains('dark')).toBe(true)
145
+ })
146
+
147
+ it('writes none without the option', async () => {
148
+ localStorage.setItem('m3-theme', 'dark')
149
+ const lib = await load()
150
+ createSSRApp({ render: () => null }).use(lib.createM3UI({ palette: 'red' }))
151
+ expect(cookie('m3-theme')).toBeUndefined()
152
+ expect(cookie('m3-palette')).toBeUndefined()
153
+ expect(cookie('m3-viewport')).toBeUndefined()
154
+ })
155
+ })
@@ -0,0 +1,122 @@
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('falls back to the cookies when storage has nothing', () => {
96
+ document.cookie = 'm3-theme=dark; Path=/'
97
+ document.cookie = 'm3-palette=blue; Path=/'
98
+ try {
99
+ matchMedia({})
100
+ run({ palette: 'red' })
101
+ expect(html.classList.contains('dark')).toBe(true)
102
+ expect(html.getAttribute('data-palette')).toBe('blue')
103
+ // Storage wins over a cookie
104
+ localStorage.setItem('m3-theme', 'light')
105
+ run()
106
+ expect(html.classList.contains('dark')).toBe(false)
107
+ } finally {
108
+ document.cookie = 'm3-theme=; Max-Age=0; Path=/'
109
+ document.cookie = 'm3-palette=; Max-Age=0; Path=/'
110
+ }
111
+ })
112
+
113
+ it('survives blocked storage', () => {
114
+ vi.stubGlobal('localStorage', { getItem: () => { throw new Error('blocked') } })
115
+ expect(() => run({ palette: 'red' })).not.toThrow()
116
+ expect(html.getAttribute('data-palette')).toBe('red')
117
+ })
118
+
119
+ it('escapes the options it inlines', () => {
120
+ expect(themeInitScript({ palette: '</script><script>alert(1)' })).not.toContain('</script>')
121
+ })
122
+ })
@@ -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'),
@@ -113,10 +113,11 @@ const colorMap: Record<string, string> = {
113
113
  // minimum width = height, MediumExtendedFabIconPadding/LargeExtendedFabIconPadding (12/16dp, the tokens'
114
114
  // IconLabelSpace is marked incorrect there).
115
115
  const EXTENDED = {
116
- regular: { px: 56, icon: 24, gap: 12, box: 'h-14 min-w-20 rounded-2xl pl-4 pr-5', text: 'text-label-large font-medium' },
117
- small: { px: 56, icon: 24, gap: 8, box: 'h-14 min-w-14 rounded-2xl px-4', text: 'text-title-medium font-medium' },
118
- medium: { px: 80, icon: 28, gap: 12, box: 'h-20 min-w-20 rounded-lg-increased px-[26px]', text: 'text-title-large' },
119
- large: { px: 96, icon: 32, gap: 16, box: 'h-24 min-w-24 rounded-xl px-7', text: 'text-headline-small' },
116
+ // lead: the box's start padding (its pl-/px- class)
117
+ regular: { px: 56, icon: 24, lead: 16, gap: 'pl-3', box: 'h-14 min-w-20 rounded-2xl pl-4 pr-5', text: 'text-label-large font-medium' },
118
+ small: { px: 56, icon: 24, lead: 16, gap: 'pl-2', box: 'h-14 min-w-14 rounded-2xl px-4', text: 'text-title-medium font-medium' },
119
+ medium: { px: 80, icon: 28, lead: 26, gap: 'pl-3', box: 'h-20 min-w-20 rounded-lg-increased px-[26px]', text: 'text-title-large' },
120
+ large: { px: 96, icon: 32, lead: 28, gap: 'pl-4', box: 'h-24 min-w-24 rounded-xl px-7', text: 'text-headline-small' },
120
121
  } as const
121
122
  const extended = computed(() => (props.label ? EXTENDED[props.size] : null))
122
123
 
@@ -152,7 +153,23 @@ const fabPx = computed(() => {
152
153
 
153
154
  // Collapsing an extended FAB: the width lerps from the square (the minimum width) to the full width on
154
155
  // FastSpatial, the label fades on FastEffects, and it leaves the layout once fully collapsed.
156
+ // Collapsed, the icon sits centered like a plain FAB's. Compose keeps the start padding instead, which only centers it
157
+ // where padding + icon + padding fills the square: the large size's 28 + 32 + 28 leaves it 4dp off center (a
158
+ // deliberate departure), so the start padding lerps to the centered one with the width.
159
+ const collapsedLead = (e: (typeof EXTENDED)[keyof typeof EXTENDED]) => (e.px - e.icon) / 2
155
160
  const fabButton = ref<HTMLElement | { $el: HTMLElement }>()
161
+ // An extended FAB that starts collapsed renders collapsed (server-side rendering: before the springs below run).
162
+ // Constant objects: Vue applies a binding again only when its value changes, so these never undo the springs'
163
+ // writes on a later render
164
+ const startCollapsed = !!extended.value && !props.expanded
165
+ const initialButtonStyle = startCollapsed
166
+ ? {
167
+ width: `${extended.value!.px}px`,
168
+ minWidth: '0',
169
+ ...(collapsedLead(extended.value!) !== extended.value!.lead && { paddingLeft: `${collapsedLead(extended.value!)}px` }),
170
+ }
171
+ : undefined
172
+ const initialLabelStyle = startCollapsed ? { display: 'none', opacity: '0' } : undefined
156
173
  const labelEl = ref<HTMLElement>()
157
174
  const buttonEl = () => (fabButton.value instanceof HTMLElement ? fabButton.value : fabButton.value?.$el)
158
175
 
@@ -164,11 +181,15 @@ useSpring(
164
181
  if (labelEl.value) labelEl.value.style.display = p <= 0 && !props.expanded ? 'none' : ''
165
182
  el.style.width = ''
166
183
  el.style.minWidth = ''
184
+ el.style.paddingLeft = ''
167
185
  if (p >= 1 && props.expanded) return
168
186
  const full = el.offsetWidth
169
- const min = extended.value.px
187
+ const { px: min, lead } = extended.value
188
+ const t = Math.min(1, Math.max(0, p))
170
189
  el.style.minWidth = '0'
171
190
  el.style.width = `${min + (full - min) * Math.max(0, p)}px`
191
+ const centered = collapsedLead(extended.value)
192
+ if (centered !== lead) el.style.paddingLeft = `${centered + (lead - centered) * t}px`
172
193
  },
173
194
  FAST_SPATIAL,
174
195
  )
@@ -348,6 +369,7 @@ onUnmounted(() => {
348
369
  :class="[colorMap[color], fabSizeClasses, extended ? 'justify-start' : 'justify-center', inBottomAppBar ? '' : 'shadow-elevation-3 hover:shadow-elevation-4 active:shadow-elevation-3']"
349
370
  :disabled="disabled"
350
371
  :aria-label="label && !expanded ? label : undefined"
372
+ :style="initialButtonStyle"
351
373
  v-ripple="{ disabled, color: rippleColor }"
352
374
  @click="handleFabClick"
353
375
  >
@@ -362,8 +384,8 @@ onUnmounted(() => {
362
384
  v-if="extended"
363
385
  ref="labelEl"
364
386
  class="shrink-0 whitespace-nowrap"
365
- :class="extended.text"
366
- :style="{ paddingLeft: `${extended.gap}px` }"
387
+ :class="[extended.text, extended.gap]"
388
+ :style="initialLabelStyle"
367
389
  >{{ label }}</span>
368
390
  </component>
369
391
  </div>
@@ -14,7 +14,7 @@ const props = withDefaults(
14
14
  defineProps<{
15
15
  /** Material Symbol icon name */
16
16
  icon: string
17
- /** Accessible label (aria-label and title) */
17
+ /** Accessible label (its aria-label; no visible tooltip: wrap it in MTooltip for one) */
18
18
  label?: string
19
19
  /** Visual style */
20
20
  variant?: 'standard' | 'filled' | 'tonal' | 'outlined'