@m3ui-vue/m3ui-vue 1.4.0 → 1.4.2

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 (95) hide show
  1. package/dist/API.md +295 -11
  2. package/dist/{MButton-DQMTIlaV.js → MButton-D7M324r9.js} +2 -2
  3. package/dist/{MButton-DQMTIlaV.js.map → MButton-D7M324r9.js.map} +1 -1
  4. package/dist/{MDialog-cdgapGfZ.js → MDialog-DuOnNF9s.js} +2 -2
  5. package/dist/{MDialog-cdgapGfZ.js.map → MDialog-DuOnNF9s.js.map} +1 -1
  6. package/dist/{MListItem-ZkSGIIrb.js → MListItem-Bb84X6ex.js} +144 -120
  7. package/dist/{MListItem-ZkSGIIrb.js.map → MListItem-Bb84X6ex.js.map} +1 -1
  8. package/dist/{MLoadingIndicator-U6_oGx8z.js → MLoadingIndicator-BUGRo2Tu.js} +2 -2
  9. package/dist/{MLoadingIndicator-U6_oGx8z.js.map → MLoadingIndicator-BUGRo2Tu.js.map} +1 -1
  10. package/dist/{MSeekBar-DTZVizZg.js → MSeekBar-BQUvUqb9.js} +2 -2
  11. package/dist/{MSeekBar-DTZVizZg.js.map → MSeekBar-BQUvUqb9.js.map} +1 -1
  12. package/dist/{MSlider-CqJkEYRZ.js → MSlider-SFdjE1Hy.js} +2 -2
  13. package/dist/{MSlider-CqJkEYRZ.js.map → MSlider-SFdjE1Hy.js.map} +1 -1
  14. package/dist/{MSpinner-Btgc-0nb.js → MSpinner-DKGNN64_.js} +2 -2
  15. package/dist/{MSpinner-Btgc-0nb.js.map → MSpinner-DKGNN64_.js.map} +1 -1
  16. package/dist/{MTextField-B6M0gJEO.js → MTextField-Utsef6Kk.js} +2 -2
  17. package/dist/{MTextField-B6M0gJEO.js.map → MTextField-Utsef6Kk.js.map} +1 -1
  18. package/dist/{MTooltip-Dspji4XG.js → MTooltip-BhTFQ9Z2.js} +4 -4
  19. package/dist/{MTooltip-Dspji4XG.js.map → MTooltip-BhTFQ9Z2.js.map} +1 -1
  20. package/dist/api.json +1 -1
  21. package/dist/code-editor.js +1 -1
  22. package/dist/components/MAvailabilityCalendar.vue.d.ts +1 -1
  23. package/dist/components/MCalendarHeatmap.vue.d.ts +120 -0
  24. package/dist/components/MCountdown.vue.d.ts +80 -0
  25. package/dist/components/MDatePicker.vue.d.ts +5 -0
  26. package/dist/components/MDatePickerModal.vue.d.ts +5 -0
  27. package/dist/components/MDateRangePicker.vue.d.ts +5 -0
  28. package/dist/components/MDateRangePickerModal.vue.d.ts +5 -0
  29. package/dist/components/MLightbox.vue.d.ts +1 -1
  30. package/dist/components/MListItem.vue.d.ts +10 -6
  31. package/dist/components/MMeterGroup.vue.d.ts +98 -0
  32. package/dist/components/MPhoneInput.vue.d.ts +72 -0
  33. package/dist/components/MSeekBar.vue.d.ts +1 -1
  34. package/dist/components/MTreeTable.vue.d.ts +1 -1
  35. package/dist/components/MTypewriter.vue.d.ts +57 -0
  36. package/dist/components/MVideoPlayer.vue.d.ts +1 -1
  37. package/dist/components/_MMonthYearButton.vue.d.ts +16 -0
  38. package/dist/components/_MYearGrid.vue.d.ts +19 -0
  39. package/dist/composables/_useCalendarMonth.d.ts +7 -0
  40. package/dist/composables/phoneNumber.d.ts +39 -0
  41. package/dist/composables/useLocale.d.ts +18 -0
  42. package/dist/data/phone-countries.d.ts +2 -0
  43. package/dist/draw.js +2 -2
  44. package/dist/flow.js +1 -1
  45. package/dist/gantt.js +1 -1
  46. package/dist/index.d.ts +10 -0
  47. package/dist/locales/index.js +63 -0
  48. package/dist/locales/index.js.map +1 -1
  49. package/dist/m3ui-vue.css +1 -1
  50. package/dist/m3ui.js +5133 -3366
  51. package/dist/m3ui.js.map +1 -1
  52. package/dist/map.js +5 -5
  53. package/dist/media.js +4 -4
  54. package/dist/pdf.js +4 -4
  55. package/dist/rich-text-editor.js +4 -4
  56. package/dist/styles.css +1 -1
  57. package/dist/{useLocale-DLKJIRFi.js → useLocale-B8YKWg-H.js} +10 -1
  58. package/dist/useLocale-B8YKWg-H.js.map +1 -0
  59. package/package.json +1 -1
  60. package/src/__tests__/MCalendarHeatmap.test.ts +79 -0
  61. package/src/__tests__/MCountdown.test.ts +75 -0
  62. package/src/__tests__/MListItemNestedControl.test.ts +88 -0
  63. package/src/__tests__/MMeterGroup.test.ts +43 -0
  64. package/src/__tests__/MPhoneInput.test.ts +97 -0
  65. package/src/__tests__/MTypewriter.test.ts +50 -0
  66. package/src/__tests__/calendarMonth.test.ts +104 -0
  67. package/src/__tests__/clearToNull.test.ts +30 -0
  68. package/src/__tests__/ssr.test.ts +4 -0
  69. package/src/components/MAutocomplete.vue +2 -2
  70. package/src/components/MCalendarHeatmap.vue +349 -0
  71. package/src/components/MCountdown.vue +200 -0
  72. package/src/components/MDatePicker.vue +74 -34
  73. package/src/components/MDatePickerModal.vue +79 -36
  74. package/src/components/MDateRangePicker.vue +73 -33
  75. package/src/components/MDateRangePickerModal.vue +75 -35
  76. package/src/components/MListItem.vue +54 -8
  77. package/src/components/MMeterGroup.vue +196 -0
  78. package/src/components/MPhoneInput.vue +480 -0
  79. package/src/components/MSelect.vue +2 -2
  80. package/src/components/MTypewriter.vue +195 -0
  81. package/src/components/_MMonthYearButton.vue +36 -0
  82. package/src/components/_MYearGrid.vue +106 -0
  83. package/src/composables/_useCalendarMonth.ts +32 -2
  84. package/src/composables/phoneNumber.ts +137 -0
  85. package/src/composables/useLocale.ts +27 -0
  86. package/src/data/phone-countries.ts +62 -0
  87. package/src/index.ts +10 -0
  88. package/src/locales/de.ts +9 -0
  89. package/src/locales/es.ts +9 -0
  90. package/src/locales/fr.ts +9 -0
  91. package/src/locales/ja.ts +9 -0
  92. package/src/locales/ko.ts +9 -0
  93. package/src/locales/pt.ts +9 -0
  94. package/src/locales/zh.ts +9 -0
  95. package/dist/useLocale-DLKJIRFi.js.map +0 -1
@@ -0,0 +1,349 @@
1
+ <script lang="ts">
2
+ /** One day of `data` when given as an array */
3
+ export interface HeatmapDay {
4
+ /** YYYY-MM-DD */
5
+ date: string
6
+ value: number
7
+ }
8
+
9
+ /** A cell, as the tooltip slot and the select event get it */
10
+ export interface HeatmapCell {
11
+ /** YYYY-MM-DD */
12
+ date: string
13
+ value: number
14
+ /** 0 (nothing) to levels - 1 (the most) */
15
+ level: number
16
+ }
17
+ </script>
18
+
19
+ <script setup lang="ts">
20
+ /**
21
+ * MCalendarHeatmap — activity per day as a grid of weeks (a column per week, a row per weekday), each day tinted by
22
+ * how much happened: commits, workouts, sales, habits. Month and weekday names come from `Intl` in the app's
23
+ * language. Hover or focus a day for its value; arrow keys move by day (up/down) and by week (left/right), and
24
+ * Enter/Space or a click select it (v-model). Scrolls sideways when it doesn't fit, starting at the latest week.
25
+ *
26
+ * @slot tooltip Replaces the tooltip's text; receives the `HeatmapCell` (`date`, `value`, `level`)
27
+ * @event update:modelValue Emitted with the date (YYYY-MM-DD) of the day picked — powers v-model
28
+ * @event select Emitted with the `HeatmapCell` of the day picked
29
+ */
30
+ import { computed, nextTick, onMounted, ref, watch } from 'vue'
31
+ import { useLocale } from '../composables/useLocale'
32
+ import { isoDate } from '../composables/_useCalendarMonth'
33
+
34
+ const props = withDefaults(
35
+ defineProps<{
36
+ /** Values per day: `{ '2026-11-20': 4 }` or `[{ date: '2026-11-20', value: 4 }]`. Missing days are 0 */
37
+ data: Record<string, number> | HeatmapDay[]
38
+ /** Last day shown (YYYY-MM-DD or a Date); defaults to today */
39
+ end?: string | Date
40
+ /** First day shown; defaults to `weeks` weeks before `end` */
41
+ start?: string | Date
42
+ /** How many weeks to show when there's no `start` */
43
+ weeks?: number
44
+ /** First day of the week: 1 Monday (default, like the date pickers), 0 Sunday */
45
+ weekStart?: 0 | 1
46
+ /** Number of tints, the empty one included */
47
+ levels?: number
48
+ /** The value that gets the darkest tint; defaults to the largest value shown */
49
+ max?: number
50
+ /** An M3 color role (`primary`, `tertiary`, `success`...) or any CSS color */
51
+ color?: string
52
+ /** Side of a day's square, in px */
53
+ cellSize?: number
54
+ /** Space between days, in px */
55
+ gap?: number
56
+ /** Month names above the weeks */
57
+ monthLabels?: boolean
58
+ /** Weekday names (Mon, Wed, Fri) beside the rows */
59
+ dayLabels?: boolean
60
+ /** The "Less ▢▢▢ More" scale below */
61
+ legend?: boolean
62
+ /** Show the day's value on hover and focus */
63
+ tooltip?: boolean
64
+ /** The tooltip's text (and each day's accessible name); defaults to "value · date" */
65
+ formatTooltip?: (cell: HeatmapCell) => string
66
+ /** BCP-47 language for month/weekday names and numbers; defaults to the app's locale */
67
+ locale?: string
68
+ /** Selected day, YYYY-MM-DD (v-model); outlined */
69
+ modelValue?: string | null
70
+ /** Accessible name of the grid */
71
+ label?: string
72
+ }>(),
73
+ {
74
+ weeks: 53,
75
+ weekStart: 1,
76
+ levels: 5,
77
+ color: 'primary',
78
+ cellSize: 12,
79
+ gap: 3,
80
+ monthLabels: true,
81
+ dayLabels: true,
82
+ legend: true,
83
+ tooltip: true,
84
+ modelValue: null,
85
+ },
86
+ )
87
+
88
+ const emit = defineEmits<{ 'update:modelValue': [string]; select: [HeatmapCell] }>()
89
+
90
+ const t = useLocale()
91
+ const lang = computed(() => props.locale ?? t.lang)
92
+
93
+ const ROLES = new Set(['primary', 'secondary', 'tertiary', 'error', 'success', 'on-surface', 'on-surface-variant', 'outline', 'inverse-primary'])
94
+ const baseColor = computed(() => (ROLES.has(props.color) ? `var(--color-${props.color})` : props.color))
95
+
96
+ const toDate = (v: string | Date) => (v instanceof Date ? new Date(v.getFullYear(), v.getMonth(), v.getDate()) : new Date(v + 'T00:00:00'))
97
+ const iso = (d: Date) => isoDate(d.getFullYear(), d.getMonth(), d.getDate())
98
+
99
+ const values = computed(() => {
100
+ const d = props.data ?? {}
101
+ if (!Array.isArray(d)) return d
102
+ const out: Record<string, number> = {}
103
+ for (const { date, value } of d) out[date] = (out[date] ?? 0) + value
104
+ return out
105
+ })
106
+
107
+ const range = computed(() => {
108
+ const end = toDate(props.end ?? new Date())
109
+ const start = props.start ? toDate(props.start) : new Date(end.getFullYear(), end.getMonth(), end.getDate() - (props.weeks * 7 - 1))
110
+ return { start: iso(start), end: iso(end), startDate: start, endDate: end }
111
+ })
112
+
113
+ const maxValue = computed(() => {
114
+ if (props.max != null) return props.max
115
+ let m = 0
116
+ for (const [date, v] of Object.entries(values.value)) if (date >= range.value.start && date <= range.value.end && v > m) m = v
117
+ return m
118
+ })
119
+
120
+ function levelOf(value: number) {
121
+ if (value <= 0 || maxValue.value <= 0) return 0
122
+ return Math.min(props.levels - 1, Math.max(1, Math.ceil((value / maxValue.value) * (props.levels - 1))))
123
+ }
124
+
125
+ // Level 0 is the empty container; the rest mix the color into it, evenly up to the full color
126
+ function levelColor(level: number) {
127
+ if (level === 0) return 'var(--color-surface-container-highest)'
128
+ const steps = props.levels - 1
129
+ const pct = steps <= 1 ? 100 : Math.round(25 + (75 * (level - 1)) / (steps - 1))
130
+ return `color-mix(in srgb, ${baseColor.value} ${pct}%, var(--color-surface-container-highest))`
131
+ }
132
+
133
+ interface Cell extends HeatmapCell { inRange: boolean }
134
+
135
+ // Rows are weekdays, columns weeks, from the week holding `start` to the one holding `end`
136
+ const grid = computed(() => {
137
+ const { startDate, endDate, start, end } = range.value
138
+ const lead = (startDate.getDay() - props.weekStart + 7) % 7
139
+ const first = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate() - lead)
140
+ const span = Math.round((endDate.getTime() - first.getTime()) / 86_400_000) + 1
141
+ const cols = Math.ceil(span / 7)
142
+ const rows: Cell[][] = Array.from({ length: 7 }, () => [])
143
+ const firstOfCol: string[] = []
144
+ for (let c = 0; c < cols; c++) {
145
+ for (let r = 0; r < 7; r++) {
146
+ const date = isoDate(first.getFullYear(), first.getMonth(), first.getDate() + c * 7 + r)
147
+ const inRange = date >= start && date <= end
148
+ const value = inRange ? (values.value[date] ?? 0) : 0
149
+ rows[r]!.push({ date, value, level: inRange ? levelOf(value) : 0, inRange })
150
+ if (inRange && firstOfCol[c] === undefined) firstOfCol[c] = date
151
+ }
152
+ }
153
+ return { rows, cols, firstOfCol }
154
+ })
155
+
156
+ // A month's name over the first week that starts in it, unless too close to the previous one (or the edge) to fit
157
+ const months = computed(() => {
158
+ const f = new Intl.DateTimeFormat(lang.value, { month: 'short' })
159
+ const out: { col: number; label: string }[] = []
160
+ let prev = ''
161
+ grid.value.firstOfCol.forEach((date, col) => {
162
+ if (!date) return
163
+ const ym = date.slice(0, 7)
164
+ if (ym === prev) return
165
+ prev = ym
166
+ const last = out[out.length - 1]
167
+ if (last && col - last.col < 3) return
168
+ if (!last && grid.value.cols - col < 2) return
169
+ out.push({ col, label: f.format(new Date(date + 'T00:00:00')) })
170
+ })
171
+ // The first label is dropped when the next month starts too soon after it
172
+ if (out.length > 1 && out[1]!.col - out[0]!.col < 3) out.shift()
173
+ return out
174
+ })
175
+
176
+ // Monday, Wednesday and Friday, whatever the week starts on
177
+ const weekdayLabels = computed(() => {
178
+ const f = new Intl.DateTimeFormat(lang.value, { weekday: 'short' })
179
+ return Array.from({ length: 7 }, (_, r) => {
180
+ const day = (props.weekStart + r) % 7
181
+ return day === 1 || day === 3 || day === 5 ? f.format(new Date(2024, 0, 7 + day)) : ''
182
+ })
183
+ })
184
+
185
+ const numberFormat = computed(() => new Intl.NumberFormat(lang.value))
186
+ const dateFormat = computed(() => new Intl.DateTimeFormat(lang.value, { weekday: 'short', day: 'numeric', month: 'short', year: 'numeric' }))
187
+ function describe(cell: HeatmapCell) {
188
+ if (props.formatTooltip) return props.formatTooltip(cell)
189
+ return `${numberFormat.value.format(cell.value)} · ${dateFormat.value.format(new Date(cell.date + 'T00:00:00'))}`
190
+ }
191
+
192
+ const legendLevels = computed(() => Array.from({ length: props.levels }, (_, i) => i))
193
+
194
+ // ── Focus, selection, tooltip ─────────────────────────────────────
195
+ const root = ref<HTMLElement>()
196
+ const scroller = ref<HTMLElement>()
197
+ const focusDate = ref<string>(props.modelValue ?? range.value.end)
198
+ watch(() => props.modelValue, (v) => { if (v) focusDate.value = v })
199
+ // Keeps the Tab stop inside the range when the range changes
200
+ const tabStop = computed(() => {
201
+ const { start, end } = range.value
202
+ return focusDate.value < start ? start : focusDate.value > end ? end : focusDate.value
203
+ })
204
+
205
+ const tip = ref<{ cell: HeatmapCell; x: number; y: number } | null>(null)
206
+
207
+ function showTip(cell: Cell, e: Event) {
208
+ if (!props.tooltip || !cell.inRange || !root.value) return
209
+ const r = (e.currentTarget as HTMLElement).getBoundingClientRect()
210
+ const o = root.value.getBoundingClientRect()
211
+ tip.value = { cell, x: r.left - o.left + r.width / 2, y: r.top - o.top }
212
+ }
213
+
214
+ function pick(cell: Cell) {
215
+ if (!cell.inRange) return
216
+ focusDate.value = cell.date
217
+ emit('update:modelValue', cell.date)
218
+ emit('select', { date: cell.date, value: cell.value, level: cell.level })
219
+ }
220
+
221
+ function cellAt(date: string) {
222
+ for (const row of grid.value.rows) for (const c of row) if (c.date === date) return c
223
+ return undefined
224
+ }
225
+
226
+ async function onKey(e: KeyboardEvent) {
227
+ const by: Record<string, number> = { ArrowUp: -1, ArrowDown: 1, ArrowLeft: -7, ArrowRight: 7 }
228
+ const { start, end } = range.value
229
+ let next: string | undefined
230
+ if (e.key in by) {
231
+ const d = new Date(tabStop.value + 'T00:00:00')
232
+ next = isoDate(d.getFullYear(), d.getMonth(), d.getDate() + by[e.key]!)
233
+ if (next < start || next > end) return e.preventDefault()
234
+ } else if (e.key === 'Home') next = start
235
+ else if (e.key === 'End') next = end
236
+ else if (e.key === 'Enter' || e.key === ' ') {
237
+ e.preventDefault()
238
+ const c = cellAt(tabStop.value)
239
+ if (c) pick(c)
240
+ return
241
+ } else return
242
+ e.preventDefault()
243
+ focusDate.value = next
244
+ await nextTick()
245
+ const el = root.value?.querySelector<HTMLElement>(`[data-date="${next}"]`)
246
+ el?.focus()
247
+ if (el) showTip(cellAt(next)!, { currentTarget: el } as unknown as Event)
248
+ }
249
+
250
+ // Starts on the latest weeks
251
+ onMounted(() => {
252
+ if (scroller.value) scroller.value.scrollLeft = scroller.value.scrollWidth
253
+ })
254
+
255
+ const step = computed(() => props.cellSize + props.gap)
256
+ </script>
257
+
258
+ <template>
259
+ <div ref="root" class="m3-heatmap relative inline-flex max-w-full flex-col gap-2 text-on-surface-variant">
260
+ <div class="flex min-w-0">
261
+ <!-- Weekday names -->
262
+ <div
263
+ v-if="dayLabels"
264
+ class="grid shrink-0 pr-2 text-label-small"
265
+ :style="{ gridTemplateRows: `repeat(7, ${cellSize}px)`, rowGap: `${gap}px`, marginTop: monthLabels ? '20px' : undefined }"
266
+ aria-hidden="true"
267
+ >
268
+ <span v-for="(d, i) in weekdayLabels" :key="i" class="flex items-center leading-none">{{ d }}</span>
269
+ </div>
270
+
271
+ <div ref="scroller" class="min-w-0 overflow-x-auto" @scroll="tip = null">
272
+ <!-- Month names -->
273
+ <div v-if="monthLabels" class="relative h-5 text-label-small" aria-hidden="true" :style="{ width: `${grid.cols * step - gap}px` }">
274
+ <span v-for="m in months" :key="m.col" class="absolute top-0 capitalize whitespace-nowrap" :style="{ left: `${m.col * step}px` }">{{ m.label }}</span>
275
+ </div>
276
+
277
+ <div
278
+ role="grid"
279
+ :aria-label="label"
280
+ class="grid"
281
+ :style="{ gridTemplateColumns: `repeat(${grid.cols}, ${cellSize}px)`, gridAutoRows: `${cellSize}px`, gap: `${gap}px` }"
282
+ @keydown="onKey"
283
+ @mouseleave="tip = null"
284
+ >
285
+ <div v-for="(row, r) in grid.rows" :key="r" role="row" class="contents">
286
+ <div
287
+ v-for="cell in row"
288
+ :key="cell.date"
289
+ :role="cell.inRange ? 'gridcell' : 'presentation'"
290
+ :data-date="cell.inRange ? cell.date : undefined"
291
+ :data-level="cell.inRange ? cell.level : undefined"
292
+ :tabindex="cell.inRange ? (cell.date === tabStop ? 0 : -1) : undefined"
293
+ :aria-label="cell.inRange ? describe(cell) : undefined"
294
+ :aria-selected="cell.inRange ? cell.date === modelValue : undefined"
295
+ class="m3-heatmap-cell rounded-[3px] outline-none"
296
+ :class="[
297
+ cell.inRange ? 'cursor-pointer' : 'invisible',
298
+ cell.date === modelValue && 'm3-heatmap-selected',
299
+ ]"
300
+ :style="{ backgroundColor: levelColor(cell.level) }"
301
+ @mouseenter="showTip(cell, $event)"
302
+ @focus="showTip(cell, $event)"
303
+ @blur="tip = null"
304
+ @click="pick(cell)"
305
+ />
306
+ </div>
307
+ </div>
308
+ </div>
309
+ </div>
310
+
311
+ <!-- Legend -->
312
+ <div v-if="legend" class="flex items-center justify-end gap-1 text-label-small" aria-hidden="true">
313
+ <span class="mr-1">{{ t.heatmapLess }}</span>
314
+ <span
315
+ v-for="l in legendLevels"
316
+ :key="l"
317
+ class="rounded-[3px]"
318
+ :style="{ width: `${cellSize}px`, height: `${cellSize}px`, backgroundColor: levelColor(l) }"
319
+ />
320
+ <span class="ml-1">{{ t.heatmapMore }}</span>
321
+ </div>
322
+
323
+ <!-- Tooltip: M3 plain tooltip (inverse surface, extra-small corners) -->
324
+ <div
325
+ v-if="tip"
326
+ class="pointer-events-none absolute z-10 -translate-x-1/2 -translate-y-full whitespace-nowrap rounded-xs bg-inverse-surface px-2 py-1 text-body-small text-inverse-on-surface shadow-elevation-1"
327
+ :style="{ left: `${tip.x}px`, top: `${tip.y - 4}px` }"
328
+ aria-hidden="true"
329
+ >
330
+ <slot name="tooltip" v-bind="tip.cell">{{ describe(tip.cell) }}</slot>
331
+ </div>
332
+ </div>
333
+ </template>
334
+
335
+ <style>
336
+ .m3-heatmap-cell {
337
+ transition: box-shadow 100ms;
338
+ }
339
+ .m3-heatmap-cell:hover {
340
+ box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--color-on-surface) 38%, transparent);
341
+ }
342
+ .m3-heatmap-cell:focus-visible {
343
+ box-shadow: 0 0 0 2px var(--color-secondary);
344
+ }
345
+ .m3-heatmap-selected,
346
+ .m3-heatmap-selected:hover {
347
+ box-shadow: 0 0 0 2px var(--color-on-surface);
348
+ }
349
+ </style>
@@ -0,0 +1,200 @@
1
+ <script lang="ts">
2
+ export type CountdownUnit = 'days' | 'hours' | 'minutes' | 'seconds'
3
+
4
+ /** What the default slot receives: the time left, split into the units shown */
5
+ export interface CountdownParts {
6
+ days: number
7
+ hours: number
8
+ minutes: number
9
+ seconds: number
10
+ /** Milliseconds left (0 once finished) */
11
+ total: number
12
+ finished: boolean
13
+ }
14
+ </script>
15
+
16
+ <script setup lang="ts">
17
+ /**
18
+ * MCountdown — a countdown to a date: days, hours, minutes and seconds with rolling digits, in boxes or inline.
19
+ * Unit names come from `Intl` in the app's language. Units left out of `units` fold into the next larger one shown
20
+ * (no `days` → 50 hours). Ticks on the second boundary; every tick costs one timer, not one per digit.
21
+ *
22
+ * @slot default Replaces the whole rendering; receives `CountdownParts` (`days`, `hours`, `minutes`, `seconds`, `total`, `finished`)
23
+ * @slot finished Shown instead of the countdown once it reaches zero
24
+ * @event finished Emitted once when the countdown reaches zero (not on mount if `to` is already past)
25
+ * @event tick Emitted every second with the `CountdownParts`
26
+ */
27
+ import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
28
+ import MAnimatedNumber from './MAnimatedNumber.vue'
29
+ import { useLocale } from '../composables/useLocale'
30
+
31
+ const props = withDefaults(
32
+ defineProps<{
33
+ /** The moment it counts down to: a `Date`, a timestamp in ms, or a date string */
34
+ to: Date | number | string
35
+ /** Units shown, largest first; leaving one out folds it into the next larger one */
36
+ units?: CountdownUnit[]
37
+ /** `boxes`: each unit in its own container with its name below; `inline`: one line of text (3d 04h 12m) */
38
+ variant?: 'boxes' | 'inline'
39
+ /** Digit size */
40
+ size?: 'sm' | 'md' | 'lg'
41
+ /** Show unit names */
42
+ labels?: boolean
43
+ /** Hide leading units while they're zero (no "0 days" a few hours before) */
44
+ hideEmpty?: boolean
45
+ /** Roll the digits; false (or the system's reduced motion) swaps them */
46
+ animate?: boolean
47
+ /** BCP-47 language for the unit names; defaults to the app's locale */
48
+ locale?: string
49
+ }>(),
50
+ {
51
+ units: () => ['days', 'hours', 'minutes', 'seconds'],
52
+ variant: 'boxes',
53
+ size: 'md',
54
+ labels: true,
55
+ hideEmpty: false,
56
+ animate: true,
57
+ },
58
+ )
59
+
60
+ const emit = defineEmits<{ finished: []; tick: [CountdownParts] }>()
61
+
62
+ const t = useLocale()
63
+ const lang = computed(() => props.locale ?? t.lang)
64
+
65
+ const target = computed(() => {
66
+ const v = props.to
67
+ return v instanceof Date ? v.getTime() : typeof v === 'number' ? v : new Date(v).getTime()
68
+ })
69
+
70
+ const now = ref(Date.now())
71
+ const total = computed(() => (Number.isNaN(target.value) ? 0 : Math.max(0, target.value - now.value)))
72
+
73
+ const ORDER: CountdownUnit[] = ['days', 'hours', 'minutes', 'seconds']
74
+ const MS: Record<CountdownUnit, number> = { days: 86_400_000, hours: 3_600_000, minutes: 60_000, seconds: 1000 }
75
+
76
+ const shown = computed(() => ORDER.filter((u) => props.units.includes(u)))
77
+
78
+ const parts = computed<CountdownParts>(() => {
79
+ // Round up to the smallest unit shown: 0.4s left reads 1s (30s left reads 1 min without seconds), and 0 only
80
+ // appears when it's really over.
81
+ const step = MS[shown.value[shown.value.length - 1] ?? 'seconds']
82
+ let rest = Math.ceil(total.value / step) * step
83
+ const out: CountdownParts = { days: 0, hours: 0, minutes: 0, seconds: 0, total: total.value, finished: total.value <= 0 }
84
+ for (const u of shown.value) {
85
+ out[u] = Math.floor(rest / MS[u])
86
+ rest -= out[u] * MS[u]
87
+ }
88
+ return out
89
+ })
90
+
91
+ const visible = computed(() => {
92
+ if (!props.hideEmpty) return shown.value
93
+ const first = shown.value.findIndex((u) => parts.value[u] > 0)
94
+ // Always keep the smallest unit, so the finished state still reads 00.
95
+ return shown.value.slice(first === -1 ? shown.value.length - 1 : Math.min(first, shown.value.length - 1))
96
+ })
97
+
98
+ const INTL_UNIT: Record<CountdownUnit, string> = { days: 'day', hours: 'hour', minutes: 'minute', seconds: 'second' }
99
+
100
+ /** The language's own word for the unit, plural-aware ("1 día", "3 días"), or its narrow form for inline */
101
+ function unitLabel(u: CountdownUnit, n: number, display: 'long' | 'narrow') {
102
+ try {
103
+ const fmt = new Intl.NumberFormat(lang.value, { style: 'unit', unit: INTL_UNIT[u], unitDisplay: display })
104
+ return fmt.formatToParts(n).filter((p) => p.type === 'unit' || (display === 'narrow' && p.type === 'literal'))
105
+ .map((p) => p.value).join('').trim()
106
+ } catch {
107
+ return u
108
+ }
109
+ }
110
+
111
+ const accessibleText = computed(() =>
112
+ shown.value
113
+ .map((u) => {
114
+ try {
115
+ return new Intl.NumberFormat(lang.value, { style: 'unit', unit: INTL_UNIT[u], unitDisplay: 'long' }).format(parts.value[u])
116
+ } catch {
117
+ return `${parts.value[u]} ${u}`
118
+ }
119
+ })
120
+ .join(', '),
121
+ )
122
+
123
+ // Leading unit unpadded (3 days, 120 hours), the rest always two digits (04:09).
124
+ const digitFormat = (i: number) => ({ minimumIntegerDigits: i === 0 ? 1 : 2, useGrouping: false })
125
+
126
+ let timer: ReturnType<typeof setTimeout> | undefined
127
+ let done = false
128
+
129
+ function schedule() {
130
+ clearTimeout(timer)
131
+ if (total.value <= 0) return
132
+ // Wake when the remaining time crosses the next whole second, so displayed seconds flip on time
133
+ // (a late timer is harmless, it just reschedules from the new remainder).
134
+ const delay = total.value % 1000 || 1000
135
+ timer = setTimeout(step, delay)
136
+ }
137
+
138
+ function step() {
139
+ now.value = Date.now()
140
+ emit('tick', parts.value)
141
+ if (total.value <= 0 && !done) {
142
+ done = true
143
+ emit('finished')
144
+ }
145
+ schedule()
146
+ }
147
+
148
+ watch(target, () => {
149
+ now.value = Date.now()
150
+ done = total.value <= 0
151
+ schedule()
152
+ })
153
+
154
+ onMounted(() => {
155
+ now.value = Date.now()
156
+ done = total.value <= 0
157
+ schedule()
158
+ })
159
+ onBeforeUnmount(() => clearTimeout(timer))
160
+
161
+ const sizeClass = computed(
162
+ () => ({ sm: 'text-title-large', md: 'text-display-small', lg: 'text-display-medium' })[props.size],
163
+ )
164
+
165
+ defineExpose({ parts })
166
+ </script>
167
+
168
+ <template>
169
+ <div class="m3-countdown" :data-variant="variant" role="timer" :aria-label="accessibleText">
170
+ <slot v-if="parts.finished && $slots.finished" name="finished" />
171
+ <slot v-else-if="$slots.default" v-bind="parts" />
172
+ <div v-else-if="variant === 'boxes'" class="flex items-start gap-2" aria-hidden="true">
173
+ <div v-for="(u, i) in visible" :key="u" class="flex flex-col items-center gap-1">
174
+ <div
175
+ class="flex min-w-[2ch] items-center justify-center rounded-md bg-surface-container-high px-3 py-2 tabular-nums text-on-surface"
176
+ :class="sizeClass"
177
+ >
178
+ <MAnimatedNumber :value="parts[u]" :format="digitFormat(i)" :animate="animate" />
179
+ </div>
180
+ <span v-if="labels" class="text-label-medium text-on-surface-variant">{{ unitLabel(u, parts[u], 'long') }}</span>
181
+ </div>
182
+ </div>
183
+ <span v-else class="inline-flex items-baseline gap-1.5 tabular-nums text-on-surface" :class="sizeClass" aria-hidden="true">
184
+ <span v-for="(u, i) in visible" :key="u" class="inline-flex items-baseline">
185
+ <MAnimatedNumber :value="parts[u]" :format="digitFormat(i)" :animate="animate" />
186
+ <span v-if="labels" class="text-on-surface-variant">{{ unitLabel(u, parts[u], 'narrow') }}</span>
187
+ <span v-else-if="i < visible.length - 1" class="text-on-surface-variant">:</span>
188
+ </span>
189
+ </span>
190
+ </div>
191
+ </template>
192
+
193
+ <style>
194
+ /* Defaults in the base layer so the consumer's classes on the root win (see MShape). */
195
+ @layer base {
196
+ .m3-countdown {
197
+ display: inline-block;
198
+ }
199
+ }
200
+ </style>