@m3ui-vue/m3ui-vue 1.4.3 → 1.4.4

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@m3ui-vue/m3ui-vue",
3
- "version": "1.4.3",
3
+ "version": "1.4.4",
4
4
  "description": "Material 3 component library for Vue 3 + Tailwind CSS v4",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -46,16 +46,20 @@ describe('MTabs', () => {
46
46
  (k) => [k, Object.getOwnPropertyDescriptor(proto, k)] as const,
47
47
  )
48
48
  const isTab = (el: HTMLElement) => el.tagName === 'BUTTON'
49
- function mockLayout() {
49
+ // Per-tab widths, editable mid-test to simulate a tab resizing after mount.
50
+ let widths: number[] = []
51
+ const tabIndex = (el: HTMLElement) => [...el.parentElement!.querySelectorAll(':scope > button')].indexOf(el)
52
+ function mockLayout(w: number[] = Array(8).fill(120)) {
53
+ widths = w
50
54
  Object.defineProperty(proto, 'offsetLeft', {
51
55
  configurable: true,
52
- get(this: HTMLElement) { return isTab(this) ? [...this.parentElement!.children].indexOf(this) * 120 : 0 },
56
+ get(this: HTMLElement) { return isTab(this) ? widths.slice(0, tabIndex(this)).reduce((a, b) => a + b, 0) : 0 },
53
57
  })
54
- Object.defineProperty(proto, 'offsetWidth', { configurable: true, get(this: HTMLElement) { return isTab(this) ? 120 : 390 } })
58
+ Object.defineProperty(proto, 'offsetWidth', { configurable: true, get(this: HTMLElement) { return isTab(this) ? widths[tabIndex(this)]! : 390 } })
55
59
  Object.defineProperty(proto, 'clientWidth', { configurable: true, get() { return 390 } })
56
60
  Object.defineProperty(proto, 'scrollWidth', {
57
61
  configurable: true,
58
- get(this: HTMLElement) { return this.querySelector(':scope > button') ? this.querySelectorAll(':scope > button').length * 120 : 390 },
62
+ get(this: HTMLElement) { return this.querySelector('button') ? Math.max(390, widths.reduce((a, b) => a + b, 0)) : 390 },
59
63
  })
60
64
  }
61
65
  function spyScroll() {
@@ -133,5 +137,109 @@ describe('MTabs', () => {
133
137
  await flushPromises()
134
138
  expect(calls).toEqual([])
135
139
  })
140
+
141
+ // A fake ResizeObserver the test can fire by hand (happy-dom's never reports).
142
+ class FakeRO {
143
+ static instances: FakeRO[] = []
144
+ targets = new Set<Element>()
145
+ disconnected = false
146
+ constructor(public cb: ResizeObserverCallback) { FakeRO.instances.push(this) }
147
+ observe(el: Element) { this.targets.add(el); this.fire([el]) }
148
+ unobserve(el: Element) { this.targets.delete(el) }
149
+ disconnect() { this.targets.clear(); this.disconnected = true }
150
+ fire(els: Element[] = [...this.targets]) {
151
+ const entries = els.map((target) => {
152
+ const el = target as HTMLElement
153
+ return { target, contentRect: { width: el.offsetWidth, height: 48 } } as unknown as ResizeObserverEntry
154
+ })
155
+ this.cb(entries, this as unknown as ResizeObserver)
156
+ }
157
+ }
158
+ function stubRO() { FakeRO.instances = []; vi.stubGlobal('ResizeObserver', FakeRO) }
159
+ const indicator = (w: ReturnType<typeof mount>) => {
160
+ const el = w.find('button').element.parentElement!.querySelector(':scope > div') as HTMLElement
161
+ return { left: parseFloat(el.style.left), width: parseFloat(el.style.width) }
162
+ }
163
+ // Icons drawn as their ligature names before the font loads: 300px tabs
164
+ const wide = () => [300, 300, 300, 300]
165
+ const iconTabs = Array.from({ length: 4 }, (_, i) => ({ value: i, label: `Tab ${i}`, icon: 'fact_check' }))
166
+
167
+ it('moves the indicator and re-centers, without animation, when the tabs resize after mount', async () => {
168
+ mockLayout(wide()); mockReducedMotion(false); stubRO()
169
+ const calls = spyScroll()
170
+ const w = mount(MTabs, { props: { modelValue: 3, tabs: iconTabs, scrollable: true } })
171
+ await flushPromises()
172
+ // tab 3 at 900–1200 (inset 16): indicator 916–1184; row scrolled to its end
173
+ expect(indicator(w)).toEqual({ left: 916, width: 268 })
174
+ expect(calls).toEqual([{ left: 1200 - 390, behavior: 'auto' }])
175
+
176
+ widths = [108, 108, 108, 108] // the font loaded: tabs shrink
177
+ FakeRO.instances[0]!.fire()
178
+ await flushPromises()
179
+ // tab 3 now at 324–432: indicator 340–416, row clamped to 432 - 390
180
+ expect(indicator(w)).toEqual({ left: 340, width: 76 })
181
+ expect(calls[1]).toEqual({ left: 42, behavior: 'auto' })
182
+ })
183
+
184
+ it('keeps the row where the user scrolled it by hand, but still moves the indicator', async () => {
185
+ mockLayout(wide()); mockReducedMotion(false); stubRO()
186
+ const calls = spyScroll()
187
+ const w = mount(MTabs, { props: { modelValue: 3, tabs: iconTabs, scrollable: true } })
188
+ await flushPromises()
189
+ const row = w.find('button').element.parentElement!.parentElement!
190
+ row.dispatchEvent(new Event('wheel'))
191
+ widths = [108, 108, 108, 108]
192
+ FakeRO.instances[0]!.fire()
193
+ await flushPromises()
194
+ expect(indicator(w)).toEqual({ left: 340, width: 76 })
195
+ expect(calls).toHaveLength(1)
196
+ })
197
+
198
+ it('ignores the first report of a newly observed element (no snap of a running animation)', async () => {
199
+ mockLayout(); mockReducedMotion(false); stubRO()
200
+ const w = mount(MTabs, { props: { modelValue: 0, tabs: many, scrollable: true } })
201
+ await flushPromises()
202
+ const ro = FakeRO.instances[0]!
203
+ widths = widths.map(() => 200)
204
+ const report = (el: Element) => ro.cb([{ target: el, contentRect: { width: 200, height: 48 } } as unknown as ResizeObserverEntry], ro as unknown as ResizeObserver)
205
+ report(document.createElement('button')) // first sight of an element
206
+ await flushPromises()
207
+ expect(indicator(w)).toEqual({ left: 16, width: 88 })
208
+ report(w.find('button').element) // a known tab that changed size
209
+ await flushPromises()
210
+ expect(indicator(w)).toEqual({ left: 16, width: 168 })
211
+ })
212
+
213
+ it('re-measures once fonts are ready', async () => {
214
+ mockLayout(wide()); mockReducedMotion(false)
215
+ let resolveFonts!: () => void
216
+ const ready = new Promise<void>((r) => { resolveFonts = r })
217
+ Object.defineProperty(document, 'fonts', { configurable: true, value: { ready } })
218
+ try {
219
+ const w = mount(MTabs, { props: { modelValue: 1, tabs: iconTabs, scrollable: true } })
220
+ await flushPromises()
221
+ expect(indicator(w)).toEqual({ left: 316, width: 268 })
222
+ widths = [108, 108, 108, 108]
223
+ resolveFonts()
224
+ await flushPromises()
225
+ expect(indicator(w)).toEqual({ left: 124, width: 76 })
226
+ } finally {
227
+ delete (document as unknown as Record<string, unknown>).fonts
228
+ }
229
+ })
230
+
231
+ it('keeps the indicator inside a clipping box the width of the tabs, and disconnects on unmount', async () => {
232
+ mockLayout(); mockReducedMotion(false); stubRO()
233
+ const w = mount(MTabs, { props: { modelValue: 0, tabs: many, scrollable: true } })
234
+ await flushPromises()
235
+ const box = w.find('button').element.parentElement!
236
+ expect(box.querySelector(':scope > div.absolute')).not.toBeNull()
237
+ expect(box.classList).toContain('overflow-hidden')
238
+ expect(box.classList).toContain('w-max')
239
+ const ro = FakeRO.instances[0]!
240
+ expect(ro.targets.size).toBe(9) // the row + 8 tabs
241
+ w.unmount()
242
+ expect(ro.disconnected).toBe(true)
243
+ })
136
244
  })
137
245
  })
@@ -5,7 +5,7 @@
5
5
  *
6
6
  * @event update:modelValue Emitted with the value of the tab you picked.
7
7
  */
8
- import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
8
+ import { computed, nextTick, onMounted, onUnmounted, onUpdated, ref, watch } from 'vue'
9
9
  import MIcon from './MIcon.vue'
10
10
 
11
11
  interface Tab {
@@ -41,6 +41,7 @@ const emit = defineEmits<{ 'update:modelValue': [string | number] }>()
41
41
 
42
42
  const tabEls = ref<HTMLElement[]>([])
43
43
  const rowEl = ref<HTMLElement | null>(null)
44
+ const contentEl = ref<HTMLElement | null>(null)
44
45
  const indicatorLeft = ref(0)
45
46
  const indicatorWidth = ref(0)
46
47
 
@@ -121,38 +122,117 @@ function scrollToTab(rect: { left: number; width: number }, smooth: boolean) {
121
122
  // re-render pulling the row back from wherever the user scrolled it.
122
123
  let shownValue: unknown = Symbol('none')
123
124
 
125
+ function measureTarget() {
126
+ const idx = props.tabs.findIndex((t) => t.value === props.modelValue)
127
+ const rect = getTabRect(idx)
128
+ if (!rect) return null
129
+ if (props.variant === 'primary') {
130
+ const inset = Math.min(rect.width * 0.2, 16)
131
+ return { rect, offset: rect.left + inset, width: rect.width - inset * 2 }
132
+ }
133
+ return { rect, offset: rect.left, width: rect.width }
134
+ }
135
+
136
+ function snapIndicator() {
137
+ offsetPos = offsetTarget; offsetVel = 0
138
+ widthPos = widthTarget; widthVel = 0
139
+ indicatorLeft.value = offsetPos
140
+ indicatorWidth.value = widthPos
141
+ }
142
+
124
143
  function updateIndicator(animate = true, scroll: 'none' | 'instant' | 'smooth' = 'none') {
125
144
  nextTick(() => {
126
- const idx = props.tabs.findIndex((t) => t.value === props.modelValue)
127
- const rect = getTabRect(idx)
128
- if (!rect) return
145
+ const m = measureTarget()
146
+ if (!m) return
129
147
  if (scroll !== 'none') {
130
148
  shownValue = props.modelValue
131
- scrollToTab(rect, scroll === 'smooth')
149
+ if (scroll === 'smooth') manualScroll = false
150
+ scrollToTab(m.rect, scroll === 'smooth')
132
151
  }
152
+ offsetTarget = m.offset
153
+ widthTarget = m.width
154
+ if (animate) ensureRaf()
155
+ else snapIndicator()
156
+ })
157
+ }
133
158
 
134
- if (props.variant === 'primary') {
135
- const inset = Math.min(rect.width * 0.2, 16)
136
- offsetTarget = rect.left + inset
137
- widthTarget = rect.width - inset * 2
138
- } else {
139
- offsetTarget = rect.left
140
- widthTarget = rect.width
141
- }
159
+ // Tabs can change size after mount: a Material Symbols icon is drawn as its
160
+ // ligature name ("fact_check") until the font loads, so the tab is far wider
161
+ // at first. Re-measure without animation whenever the row or a tab resizes,
162
+ // and re-center the active tab unless the user has scrolled the row by hand
163
+ // since it was last centered for them.
164
+ let manualScroll = false
165
+ function markManualScroll() { manualScroll = true }
166
+ const SCROLL_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown'])
167
+ function onRowKeydown(e: KeyboardEvent) { if (SCROLL_KEYS.has(e.key)) manualScroll = true }
142
168
 
143
- if (animate) {
144
- ensureRaf()
145
- } else {
146
- offsetPos = offsetTarget; offsetVel = 0
147
- widthPos = widthTarget; widthVel = 0
148
- indicatorLeft.value = offsetPos
149
- indicatorWidth.value = widthPos
150
- }
151
- })
169
+ function relayout() {
170
+ const m = measureTarget()
171
+ if (!m) return
172
+ if (Math.abs(m.offset - offsetTarget) >= 0.5 || Math.abs(m.width - widthTarget) >= 0.5) {
173
+ offsetTarget = m.offset
174
+ widthTarget = m.width
175
+ snapIndicator()
176
+ }
177
+ if (!manualScroll) scrollToTab(m.rect, false)
178
+ }
179
+
180
+ let ro: ResizeObserver | null = null
181
+ const observed = new Set<Element>()
182
+ const lastSize = new WeakMap<Element, string>()
183
+ let listenedRow: HTMLElement | null = null
184
+
185
+ function onResize(entries: ResizeObserverEntry[]) {
186
+ let changed = false
187
+ for (const e of entries) {
188
+ const key = `${e.contentRect.width}x${e.contentRect.height}`
189
+ // The first notification of every newly observed element only reports
190
+ // its current size: ignore it, so it can't cut short a running animation.
191
+ if (lastSize.has(e.target) && lastSize.get(e.target) !== key) changed = true
192
+ lastSize.set(e.target, key)
193
+ }
194
+ if (changed) relayout()
195
+ }
196
+
197
+ function syncObserved() {
198
+ const row = rowEl.value
199
+ if (row !== listenedRow) {
200
+ listenedRow?.removeEventListener('wheel', markManualScroll)
201
+ listenedRow?.removeEventListener('touchmove', markManualScroll)
202
+ listenedRow?.removeEventListener('keydown', onRowKeydown)
203
+ row?.addEventListener('wheel', markManualScroll, { passive: true })
204
+ row?.addEventListener('touchmove', markManualScroll, { passive: true })
205
+ row?.addEventListener('keydown', onRowKeydown)
206
+ listenedRow = row
207
+ }
208
+ if (!ro) return
209
+ const want = new Set<Element>()
210
+ if (row) want.add(row)
211
+ if (contentEl.value) for (const el of contentEl.value.querySelectorAll(':scope > button')) want.add(el)
212
+ for (const el of observed) if (!want.has(el)) { ro.unobserve(el); observed.delete(el) }
213
+ for (const el of want) if (!observed.has(el)) { ro.observe(el); observed.add(el) }
152
214
  }
153
215
 
154
- onMounted(() => updateIndicator(false, 'instant'))
155
- onUnmounted(() => { if (rafId) cancelAnimationFrame(rafId) })
216
+ let mounted = false
217
+ onMounted(() => {
218
+ mounted = true
219
+ updateIndicator(false, 'instant')
220
+ if (typeof ResizeObserver !== 'undefined') ro = new ResizeObserver(onResize)
221
+ syncObserved()
222
+ // Fallback for browsers or layouts where the font swap doesn't resize an
223
+ // observed box (and for the first paint before the observer reports).
224
+ document.fonts?.ready.then(() => { if (mounted) relayout() })
225
+ })
226
+ onUpdated(syncObserved)
227
+ onUnmounted(() => {
228
+ mounted = false
229
+ if (rafId) cancelAnimationFrame(rafId)
230
+ ro?.disconnect(); ro = null; observed.clear()
231
+ listenedRow?.removeEventListener('wheel', markManualScroll)
232
+ listenedRow?.removeEventListener('touchmove', markManualScroll)
233
+ listenedRow?.removeEventListener('keydown', onRowKeydown)
234
+ listenedRow = null
235
+ })
156
236
  watch(() => props.modelValue, () => updateIndicator(true, 'smooth'))
157
237
  // Animated (not a hard snap) here too: a consumer passing an inline `:tabs="[...]"`
158
238
  // literal gets a brand-new array reference on every unrelated parent re-render,
@@ -170,64 +250,70 @@ function select(tab: Tab) {
170
250
  <template>
171
251
  <!-- ── Primary: sliding short indicator with stretch ──────────────── -->
172
252
  <div v-if="variant === 'primary'" class="border-b border-outline-variant">
173
- <div ref="rowEl" class="relative flex" :class="scrollable ? 'overflow-x-auto' : 'overflow-x-hidden'" style="scrollbar-width: none">
174
- <button
175
- v-for="tab in tabs"
176
- :key="tab.value"
177
- :ref="(el) => { if (el) tabEls[tabs.indexOf(tab)] = el as HTMLElement }"
178
- type="button"
179
- class="relative flex items-center justify-center pb-1.5 text-title-small transition-colors duration-150 focus-visible:outline-none"
180
- :class="[
181
- scrollable ? 'shrink-0' : 'flex-1 min-w-0',
182
- // LeadingIconTab: 48dp row, 16dp side padding, 8dp from the icon to the label
183
- leading ? 'h-12 flex-row gap-2 px-4' : ['flex-col gap-1 px-6', tab.icon ? 'h-16' : 'h-12'],
184
- tab.value === modelValue
185
- ? 'text-primary'
186
- : tab.disabled
187
- ? 'cursor-not-allowed text-on-surface/38'
188
- : 'cursor-pointer text-on-surface-variant hover:text-on-surface',
189
- ]"
190
- :disabled="tab.disabled"
191
- @click="select(tab)"
192
- >
193
- <MIcon v-if="tab.icon" :name="tab.icon" :size="24" />
194
- <span>{{ tab.label }}</span>
195
- </button>
196
- <div
197
- class="absolute bottom-0 h-[3px] rounded-t-full bg-primary"
198
- :style="{ left: `${indicatorLeft}px`, width: `${indicatorWidth}px` }"
199
- />
253
+ <div ref="rowEl" :class="scrollable ? 'overflow-x-auto' : 'overflow-x-hidden'" style="scrollbar-width: none">
254
+ <!-- Content-width box: clips the indicator so it never widens the scroll area -->
255
+ <div ref="contentEl" class="relative flex overflow-hidden" :class="scrollable ? 'w-max min-w-full' : 'w-full'">
256
+ <button
257
+ v-for="tab in tabs"
258
+ :key="tab.value"
259
+ :ref="(el) => { if (el) tabEls[tabs.indexOf(tab)] = el as HTMLElement }"
260
+ type="button"
261
+ class="relative flex items-center justify-center pb-1.5 text-title-small transition-colors duration-150 focus-visible:outline-none"
262
+ :class="[
263
+ scrollable ? 'shrink-0' : 'flex-1 min-w-0',
264
+ // LeadingIconTab: 48dp row, 16dp side padding, 8dp from the icon to the label
265
+ leading ? 'h-12 flex-row gap-2 px-4' : ['flex-col gap-1 px-6', tab.icon ? 'h-16' : 'h-12'],
266
+ tab.value === modelValue
267
+ ? 'text-primary'
268
+ : tab.disabled
269
+ ? 'cursor-not-allowed text-on-surface/38'
270
+ : 'cursor-pointer text-on-surface-variant hover:text-on-surface',
271
+ ]"
272
+ :disabled="tab.disabled"
273
+ @click="select(tab)"
274
+ >
275
+ <MIcon v-if="tab.icon" :name="tab.icon" :size="24" />
276
+ <span>{{ tab.label }}</span>
277
+ </button>
278
+ <div
279
+ class="absolute bottom-0 h-[3px] rounded-t-full bg-primary"
280
+ :style="{ left: `${indicatorLeft}px`, width: `${indicatorWidth}px` }"
281
+ />
282
+ </div>
200
283
  </div>
201
284
  </div>
202
285
 
203
286
  <!-- ── Secondary: full-width underline indicator ─────────────────── -->
204
287
  <div v-else class="border-b border-outline-variant">
205
- <div ref="rowEl" class="relative flex" :class="scrollable ? 'overflow-x-auto' : 'overflow-x-hidden'" style="scrollbar-width: none">
206
- <button
207
- v-for="tab in tabs"
208
- :key="tab.value"
209
- :ref="(el) => { if (el) tabEls[tabs.indexOf(tab)] = el as HTMLElement }"
210
- type="button"
211
- class="relative flex items-center justify-center text-title-small transition-colors duration-150 focus-visible:outline-none"
212
- :class="[
213
- scrollable ? 'shrink-0' : 'flex-1 min-w-0',
214
- leading ? 'h-12 flex-row gap-2 px-4' : ['flex-col gap-1 px-6', tab.icon ? 'h-16' : 'h-12'],
215
- tab.value === modelValue
216
- ? 'text-on-surface'
217
- : tab.disabled
218
- ? 'cursor-not-allowed text-on-surface/38'
219
- : 'cursor-pointer text-on-surface-variant hover:text-on-surface',
220
- ]"
221
- :disabled="tab.disabled"
222
- @click="select(tab)"
223
- >
224
- <MIcon v-if="tab.icon" :name="tab.icon" :size="24" />
225
- <span>{{ tab.label }}</span>
226
- </button>
227
- <div
228
- class="absolute bottom-0 h-[3px] bg-primary"
229
- :style="{ left: `${indicatorLeft}px`, width: `${indicatorWidth}px` }"
230
- />
288
+ <div ref="rowEl" :class="scrollable ? 'overflow-x-auto' : 'overflow-x-hidden'" style="scrollbar-width: none">
289
+ <!-- Content-width box: clips the indicator so it never widens the scroll area -->
290
+ <div ref="contentEl" class="relative flex overflow-hidden" :class="scrollable ? 'w-max min-w-full' : 'w-full'">
291
+ <button
292
+ v-for="tab in tabs"
293
+ :key="tab.value"
294
+ :ref="(el) => { if (el) tabEls[tabs.indexOf(tab)] = el as HTMLElement }"
295
+ type="button"
296
+ class="relative flex items-center justify-center text-title-small transition-colors duration-150 focus-visible:outline-none"
297
+ :class="[
298
+ scrollable ? 'shrink-0' : 'flex-1 min-w-0',
299
+ leading ? 'h-12 flex-row gap-2 px-4' : ['flex-col gap-1 px-6', tab.icon ? 'h-16' : 'h-12'],
300
+ tab.value === modelValue
301
+ ? 'text-on-surface'
302
+ : tab.disabled
303
+ ? 'cursor-not-allowed text-on-surface/38'
304
+ : 'cursor-pointer text-on-surface-variant hover:text-on-surface',
305
+ ]"
306
+ :disabled="tab.disabled"
307
+ @click="select(tab)"
308
+ >
309
+ <MIcon v-if="tab.icon" :name="tab.icon" :size="24" />
310
+ <span>{{ tab.label }}</span>
311
+ </button>
312
+ <div
313
+ class="absolute bottom-0 h-[3px] bg-primary"
314
+ :style="{ left: `${indicatorLeft}px`, width: `${indicatorWidth}px` }"
315
+ />
316
+ </div>
231
317
  </div>
232
318
  </div>
233
319
  </template>