@m3ui-vue/m3ui-vue 0.5.10 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +26 -1
  2. package/dist/{MMenuItem-DyY4zhRA.js → MMenuItem-DbbrJhFE.js} +2 -2
  3. package/dist/{MMenuItem-DyY4zhRA.js.map → MMenuItem-DbbrJhFE.js.map} +1 -1
  4. package/dist/barcode.d.ts +1 -0
  5. package/dist/barcode.js +51 -0
  6. package/dist/barcode.js.map +1 -0
  7. package/dist/code-editor.js +1 -1
  8. package/dist/components/MAutocomplete.vue.d.ts +1 -1
  9. package/dist/components/MBarcode.vue.d.ts +35 -0
  10. package/dist/components/MButton.vue.d.ts +1 -1
  11. package/dist/components/MButtonGroup.vue.d.ts +1 -1
  12. package/dist/components/MChatBubble.vue.d.ts +1 -1
  13. package/dist/components/MCircleProgressBar.vue.d.ts +1 -1
  14. package/dist/components/MCopyButton.vue.d.ts +31 -0
  15. package/dist/components/MExportButton.vue.d.ts +43 -0
  16. package/dist/components/MFab.vue.d.ts +1 -1
  17. package/dist/components/MKbd.vue.d.ts +12 -0
  18. package/dist/components/MMultiAutocomplete.vue.d.ts +1 -1
  19. package/dist/components/MMultiSelect.vue.d.ts +1 -1
  20. package/dist/components/MPasswordMeter.vue.d.ts +17 -0
  21. package/dist/components/MPinInput.vue.d.ts +35 -0
  22. package/dist/components/MQRCode.vue.d.ts +35 -0
  23. package/dist/components/MRating.vue.d.ts +1 -1
  24. package/dist/components/MRelativeTime.vue.d.ts +8 -0
  25. package/dist/components/MSelect.vue.d.ts +1 -1
  26. package/dist/components/MShader.vue.d.ts +2 -2
  27. package/dist/components/MSignaturePad.vue.d.ts +37 -0
  28. package/dist/components/MSlider.vue.d.ts +1 -1
  29. package/dist/components/MSplitButton.vue.d.ts +1 -1
  30. package/dist/components/MSubtitle.vue.d.ts +1 -1
  31. package/dist/components/MTerminal.vue.d.ts +2 -2
  32. package/dist/components/MTitle.vue.d.ts +1 -1
  33. package/dist/components/MWindow.vue.d.ts +1 -1
  34. package/dist/composables/useLocale.d.ts +2 -0
  35. package/dist/index.d.ts +7 -0
  36. package/dist/locales/index.js +7 -0
  37. package/dist/locales/index.js.map +1 -1
  38. package/dist/m3ui.js +1192 -721
  39. package/dist/m3ui.js.map +1 -1
  40. package/dist/qrcode.d.ts +1 -0
  41. package/dist/qrcode.js +117 -0
  42. package/dist/qrcode.js.map +1 -0
  43. package/dist/rich-text-editor.js +2 -2
  44. package/dist/{useLocale-QCIVDYWx.js → useLocale-BKsIWNix.js} +2 -1
  45. package/dist/useLocale-BKsIWNix.js.map +1 -0
  46. package/package.json +21 -1
  47. package/src/__tests__/MBarcode.test.ts +40 -0
  48. package/src/__tests__/MCopyButton.test.ts +49 -0
  49. package/src/__tests__/MExportButton.test.ts +64 -0
  50. package/src/__tests__/MKbd.test.ts +33 -0
  51. package/src/__tests__/MPasswordMeter.test.ts +43 -0
  52. package/src/__tests__/MPinInput.test.ts +138 -0
  53. package/src/__tests__/MQRCode.test.ts +58 -0
  54. package/src/__tests__/MRelativeTime.test.ts +43 -0
  55. package/src/__tests__/MSignaturePad.test.ts +62 -0
  56. package/src/barcode.ts +1 -0
  57. package/src/components/MBarcode.vue +61 -0
  58. package/src/components/MCopyButton.vue +62 -0
  59. package/src/components/MExportButton.vue +73 -0
  60. package/src/components/MKbd.vue +36 -0
  61. package/src/components/MPasswordMeter.vue +56 -0
  62. package/src/components/MPinInput.vue +202 -0
  63. package/src/components/MQRCode.vue +131 -0
  64. package/src/components/MRelativeTime.vue +68 -0
  65. package/src/components/MSignaturePad.vue +138 -0
  66. package/src/composables/useLocale.ts +5 -0
  67. package/src/index.ts +7 -0
  68. package/src/locales/de.ts +2 -0
  69. package/src/locales/es.ts +2 -0
  70. package/src/locales/fr.ts +2 -0
  71. package/src/locales/ja.ts +2 -0
  72. package/src/locales/ko.ts +2 -0
  73. package/src/locales/pt.ts +2 -0
  74. package/src/locales/zh.ts +2 -0
  75. package/src/qrcode.ts +1 -0
  76. package/dist/useLocale-QCIVDYWx.js.map +0 -1
@@ -0,0 +1,58 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import { mount } from '@vue/test-utils'
3
+ import MQRCode from '../components/MQRCode.vue'
4
+
5
+ describe('MQRCode', () => {
6
+ it('renders an svg with the given size', () => {
7
+ const wrapper = mount(MQRCode, { props: { value: 'https://example.com', size: 150 } })
8
+ const svg = wrapper.find('svg')
9
+ expect(svg.exists()).toBe(true)
10
+ expect(svg.attributes('width')).toBe('150')
11
+ expect(svg.attributes('height')).toBe('150')
12
+ })
13
+
14
+ it('defaults the aria-label to the encoded value', () => {
15
+ const wrapper = mount(MQRCode, { props: { value: 'https://example.com' } })
16
+ expect(wrapper.find('svg').attributes('aria-label')).toBe('https://example.com')
17
+ })
18
+
19
+ it('uses a custom label when provided', () => {
20
+ const wrapper = mount(MQRCode, { props: { value: 'https://example.com', label: 'Table 5 menu' } })
21
+ expect(wrapper.find('svg').attributes('aria-label')).toBe('Table 5 menu')
22
+ })
23
+
24
+ it('defaults to plain square modules (rects, no arcs)', () => {
25
+ const wrapper = mount(MQRCode, { props: { value: 'hi', color: '#ff0000', background: '#eeeeee' } })
26
+ const rects = wrapper.findAll('rect')
27
+ expect(rects[0].attributes('fill')).toBe('#eeeeee')
28
+ const moduleRects = rects.slice(1)
29
+ expect(moduleRects.length).toBeGreaterThan(1)
30
+ expect(moduleRects.every((r) => r.attributes('fill') === '#ff0000')).toBe(true)
31
+ expect(wrapper.findAll('path')).toHaveLength(0)
32
+ })
33
+
34
+ it('rounds only the outer container when rounded is true', () => {
35
+ const rounded = mount(MQRCode, { props: { value: 'hi', rounded: true } })
36
+ const square = mount(MQRCode, { props: { value: 'hi', rounded: false } })
37
+ expect(Number(rounded.find('rect').attributes('rx'))).toBeGreaterThan(0)
38
+ expect(Number(square.find('rect').attributes('rx'))).toBe(0)
39
+ // modules are always plain rects with no rx, regardless of `rounded`
40
+ expect(rounded.findAll('rect').slice(1).every((r) => !r.attributes('rx'))).toBe(true)
41
+ })
42
+
43
+ it('renders dot-style modules as paths when moduleStyle is "dots"', () => {
44
+ const wrapper = mount(MQRCode, { props: { value: 'hi', moduleStyle: 'dots', color: '#ff0000' } })
45
+ const paths = wrapper.findAll('path')
46
+ expect(paths.length).toBeGreaterThan(1)
47
+ expect(paths.every((p) => p.attributes('fill') === '#ff0000')).toBe(true)
48
+ // isolated modules should have rounded/circular corners (arc commands)
49
+ expect(paths.some((p) => p.attributes('d')!.includes('A'))).toBe(true)
50
+ })
51
+
52
+ it('falls back to an error message when the data is too large to encode', () => {
53
+ const tooLong = 'x'.repeat(5000)
54
+ const wrapper = mount(MQRCode, { props: { value: tooLong } })
55
+ expect(wrapper.find('svg').exists()).toBe(false)
56
+ expect(wrapper.text().length).toBeGreaterThan(0)
57
+ })
58
+ })
@@ -0,0 +1,43 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import { mount } from '@vue/test-utils'
3
+ import MRelativeTime from '../components/MRelativeTime.vue'
4
+
5
+ describe('MRelativeTime', () => {
6
+ it('renders a past time as "ago"', () => {
7
+ const fiveMinAgo = new Date(Date.now() - 5 * 60 * 1000)
8
+ const wrapper = mount(MRelativeTime, { props: { value: fiveMinAgo, locale: 'en' } })
9
+ expect(wrapper.text()).toContain('ago')
10
+ })
11
+
12
+ it('renders a future time as "in"', () => {
13
+ const inTwoHours = new Date(Date.now() + 2 * 60 * 60 * 1000)
14
+ const wrapper = mount(MRelativeTime, { props: { value: inTwoHours, locale: 'en' } })
15
+ expect(wrapper.text()).toContain('in')
16
+ })
17
+
18
+ it('renders "now" for the current instant', () => {
19
+ const wrapper = mount(MRelativeTime, { props: { value: new Date(), locale: 'en' } })
20
+ expect(wrapper.text().toLowerCase()).toContain('now')
21
+ })
22
+
23
+ it('sets datetime and title attributes', () => {
24
+ const date = new Date('2026-01-01T00:00:00.000Z')
25
+ const wrapper = mount(MRelativeTime, { props: { value: date, locale: 'en' } })
26
+ const time = wrapper.find('time')
27
+ expect(time.attributes('datetime')).toBe(date.toISOString())
28
+ expect(time.attributes('title')).toBeTruthy()
29
+ })
30
+
31
+ it('accepts a timestamp number and an ISO string', () => {
32
+ const wrapper1 = mount(MRelativeTime, { props: { value: Date.now(), locale: 'en' } })
33
+ const wrapper2 = mount(MRelativeTime, { props: { value: new Date().toISOString(), locale: 'en' } })
34
+ expect(wrapper1.find('time').exists()).toBe(true)
35
+ expect(wrapper2.find('time').exists()).toBe(true)
36
+ })
37
+
38
+ it('respects the locale prop', () => {
39
+ const fiveMinAgo = new Date(Date.now() - 5 * 60 * 1000)
40
+ const wrapper = mount(MRelativeTime, { props: { value: fiveMinAgo, locale: 'es' } })
41
+ expect(wrapper.text()).toMatch(/hace/i)
42
+ })
43
+ })
@@ -0,0 +1,62 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import { mount } from '@vue/test-utils'
3
+ import MSignaturePad from '../components/MSignaturePad.vue'
4
+
5
+ function draw(wrapper: ReturnType<typeof mount>) {
6
+ const canvas = wrapper.find('canvas')
7
+ return canvas
8
+ .trigger('pointerdown', { clientX: 10, clientY: 10, pointerId: 1 })
9
+ .then(() => canvas.trigger('pointermove', { clientX: 20, clientY: 20, pointerId: 1 }))
10
+ .then(() => canvas.trigger('pointerup', { pointerId: 1 }))
11
+ }
12
+
13
+ describe('MSignaturePad', () => {
14
+ it('starts empty', () => {
15
+ const wrapper = mount(MSignaturePad)
16
+ expect((wrapper.vm as any).isEmpty()).toBe(true)
17
+ })
18
+
19
+ it('is no longer empty after drawing a stroke', async () => {
20
+ const wrapper = mount(MSignaturePad)
21
+ await draw(wrapper)
22
+ expect((wrapper.vm as any).isEmpty()).toBe(false)
23
+ })
24
+
25
+ it('emits begin, end and change with a data URL', async () => {
26
+ const wrapper = mount(MSignaturePad)
27
+ await draw(wrapper)
28
+ expect(wrapper.emitted('begin')).toHaveLength(1)
29
+ expect(wrapper.emitted('end')).toHaveLength(1)
30
+ expect(wrapper.emitted('end')![0]![0]).toMatch(/^data:/)
31
+ expect(wrapper.emitted('change')).toHaveLength(1)
32
+ })
33
+
34
+ it('clear() empties the pad', async () => {
35
+ const wrapper = mount(MSignaturePad)
36
+ await draw(wrapper)
37
+ ;(wrapper.vm as any).clear()
38
+ expect((wrapper.vm as any).isEmpty()).toBe(true)
39
+ })
40
+
41
+ it('undo() removes only the last stroke', async () => {
42
+ const wrapper = mount(MSignaturePad)
43
+ await draw(wrapper)
44
+ await draw(wrapper)
45
+ ;(wrapper.vm as any).undo()
46
+ expect((wrapper.vm as any).isEmpty()).toBe(false)
47
+ ;(wrapper.vm as any).undo()
48
+ expect((wrapper.vm as any).isEmpty()).toBe(true)
49
+ })
50
+
51
+ it('does not draw when disabled', async () => {
52
+ const wrapper = mount(MSignaturePad, { props: { disabled: true } })
53
+ await draw(wrapper)
54
+ expect((wrapper.vm as any).isEmpty()).toBe(true)
55
+ expect(wrapper.emitted('begin')).toBeUndefined()
56
+ })
57
+
58
+ it('exposes toDataURL()', () => {
59
+ const wrapper = mount(MSignaturePad)
60
+ expect((wrapper.vm as any).toDataURL()).toMatch(/^data:/)
61
+ })
62
+ })
package/src/barcode.ts ADDED
@@ -0,0 +1 @@
1
+ export { default as MBarcode } from './components/MBarcode.vue'
@@ -0,0 +1,61 @@
1
+ <script setup lang="ts">
2
+ import { ref, watchEffect } from 'vue'
3
+ import JsBarcode from 'jsbarcode'
4
+
5
+ const props = withDefaults(
6
+ defineProps<{
7
+ value: string
8
+ /** Barcode symbology. Common values: 'CODE128', 'EAN13', 'EAN8', 'UPC', 'CODE39', 'ITF14', 'MSI', 'pharmacode', 'codabar'. */
9
+ format?: string
10
+ width?: number
11
+ height?: number
12
+ displayValue?: boolean
13
+ color?: string
14
+ background?: string
15
+ margin?: number
16
+ fontSize?: number
17
+ label?: string
18
+ }>(),
19
+ {
20
+ format: 'CODE128',
21
+ width: 2,
22
+ height: 80,
23
+ displayValue: true,
24
+ color: '#000000',
25
+ background: '#ffffff',
26
+ margin: 10,
27
+ fontSize: 20,
28
+ },
29
+ )
30
+
31
+ const svgEl = ref<SVGSVGElement | null>(null)
32
+ const error = ref<string | null>(null)
33
+
34
+ // flush: 'post' runs synchronously right after (re-)render, once the ref is
35
+ // attached — the default 'pre' flush defers the first run to a microtask
36
+ // after the ref is set, which is later than callers expect a mount to settle.
37
+ watchEffect(() => {
38
+ if (!svgEl.value) return
39
+ error.value = null
40
+ JsBarcode(svgEl.value, props.value, {
41
+ format: props.format,
42
+ width: props.width,
43
+ height: props.height,
44
+ displayValue: props.displayValue,
45
+ lineColor: props.color,
46
+ background: props.background,
47
+ margin: props.margin,
48
+ fontSize: props.fontSize,
49
+ valid: (ok) => {
50
+ if (!ok) error.value = `Invalid value "${props.value}" for format "${props.format}"`
51
+ },
52
+ })
53
+ }, { flush: 'post' })
54
+ </script>
55
+
56
+ <template>
57
+ <div v-if="error" class="flex items-center justify-center text-body-small text-error">
58
+ <slot name="error">{{ error }}</slot>
59
+ </div>
60
+ <svg v-show="!error" ref="svgEl" role="img" :aria-label="label ?? value"></svg>
61
+ </template>
@@ -0,0 +1,62 @@
1
+ <script setup lang="ts">
2
+ import { onUnmounted, ref } from 'vue'
3
+ import MIconButton from './MIconButton.vue'
4
+
5
+ const props = withDefaults(
6
+ defineProps<{
7
+ value: string
8
+ icon?: string
9
+ copiedIcon?: string
10
+ label?: string
11
+ copiedLabel?: string
12
+ variant?: 'standard' | 'filled' | 'tonal' | 'outlined'
13
+ shape?: 'rounded' | 'squared'
14
+ size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl' | number
15
+ disabled?: boolean
16
+ resetDelay?: number
17
+ }>(),
18
+ {
19
+ icon: 'content_copy',
20
+ copiedIcon: 'check',
21
+ label: 'Copy',
22
+ copiedLabel: 'Copied',
23
+ variant: 'standard',
24
+ shape: 'rounded',
25
+ size: 'sm',
26
+ disabled: false,
27
+ resetDelay: 2000,
28
+ },
29
+ )
30
+
31
+ const emit = defineEmits<{ copied: [string]; error: [unknown] }>()
32
+
33
+ const copied = ref(false)
34
+ let resetTimer: ReturnType<typeof setTimeout> | undefined
35
+
36
+ async function onClick() {
37
+ if (props.disabled) return
38
+ try {
39
+ await navigator.clipboard.writeText(props.value)
40
+ copied.value = true
41
+ emit('copied', props.value)
42
+ clearTimeout(resetTimer)
43
+ resetTimer = setTimeout(() => { copied.value = false }, props.resetDelay)
44
+ } catch (err) {
45
+ emit('error', err)
46
+ }
47
+ }
48
+
49
+ onUnmounted(() => clearTimeout(resetTimer))
50
+ </script>
51
+
52
+ <template>
53
+ <MIconButton
54
+ :icon="copied ? copiedIcon : icon"
55
+ :label="copied ? copiedLabel : label"
56
+ :variant="variant"
57
+ :shape="shape"
58
+ :size="size"
59
+ :disabled="disabled"
60
+ @click="onClick"
61
+ />
62
+ </template>
@@ -0,0 +1,73 @@
1
+ <script setup lang="ts">
2
+ import MButton from './MButton.vue'
3
+
4
+ const props = withDefaults(
5
+ defineProps<{
6
+ data: Record<string, unknown>[]
7
+ format?: 'csv' | 'json'
8
+ filename?: string
9
+ label?: string
10
+ icon?: string
11
+ variant?: 'filled' | 'tonal' | 'outlined' | 'text' | 'elevated'
12
+ size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl'
13
+ disabled?: boolean
14
+ }>(),
15
+ {
16
+ format: 'csv',
17
+ filename: 'export',
18
+ label: 'Export',
19
+ icon: 'download',
20
+ variant: 'outlined',
21
+ size: 'sm',
22
+ disabled: false,
23
+ },
24
+ )
25
+
26
+ const emit = defineEmits<{ exported: [{ format: string; filename: string }]; error: [unknown] }>()
27
+
28
+ function escapeCsvField(value: unknown): string {
29
+ const s = value == null ? '' : String(value)
30
+ return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s
31
+ }
32
+
33
+ function toCsv(rows: Record<string, unknown>[]): string {
34
+ if (rows.length === 0) return ''
35
+ const headers = Object.keys(rows[0]!)
36
+ const lines = [
37
+ headers.map(escapeCsvField).join(','),
38
+ ...rows.map((row) => headers.map((h) => escapeCsvField(row[h])).join(',')),
39
+ ]
40
+ return lines.join('\n')
41
+ }
42
+
43
+ function download(content: string, filename: string, mime: string) {
44
+ const blob = new Blob([content], { type: mime })
45
+ const url = URL.createObjectURL(blob)
46
+ const a = document.createElement('a')
47
+ a.href = url
48
+ a.download = filename
49
+ a.click()
50
+ URL.revokeObjectURL(url)
51
+ }
52
+
53
+ function onClick() {
54
+ if (props.disabled) return
55
+ try {
56
+ const filename = `${props.filename}.${props.format}`
57
+ if (props.format === 'json') {
58
+ download(JSON.stringify(props.data, null, 2), filename, 'application/json')
59
+ } else {
60
+ download(toCsv(props.data), filename, 'text/csv')
61
+ }
62
+ emit('exported', { format: props.format, filename })
63
+ } catch (err) {
64
+ emit('error', err)
65
+ }
66
+ }
67
+ </script>
68
+
69
+ <template>
70
+ <MButton :variant="variant" :size="size" :icon="icon" :disabled="disabled" @click="onClick">
71
+ <slot>{{ label }}</slot>
72
+ </MButton>
73
+ </template>
@@ -0,0 +1,36 @@
1
+ <script setup lang="ts">
2
+ import { computed } from 'vue'
3
+
4
+ const props = withDefaults(
5
+ defineProps<{
6
+ /** A '+'-delimited string ("Ctrl+Shift+K") or an array of keys (['Ctrl', 'Shift', 'K']). */
7
+ keys: string | string[]
8
+ size?: 'sm' | 'md' | 'lg'
9
+ separator?: string
10
+ }>(),
11
+ {
12
+ size: 'md',
13
+ separator: '+',
14
+ },
15
+ )
16
+
17
+ const keyList = computed(() => (Array.isArray(props.keys) ? props.keys : props.keys.split('+')))
18
+
19
+ const sizeClasses = {
20
+ sm: 'h-5 min-w-5 px-1 text-[10px]',
21
+ md: 'h-6 min-w-6 px-1.5 text-label-small',
22
+ lg: 'h-7 min-w-7 px-2 text-label-medium',
23
+ }
24
+ </script>
25
+
26
+ <template>
27
+ <span class="inline-flex items-center gap-1">
28
+ <template v-for="(key, i) in keyList" :key="i">
29
+ <kbd
30
+ class="inline-flex items-center justify-center rounded-sm border border-b-2 border-outline-variant bg-surface-container-high font-sans font-medium text-on-surface-variant"
31
+ :class="sizeClasses[size]"
32
+ >{{ key }}</kbd>
33
+ <span v-if="i < keyList.length - 1" class="text-on-surface-variant" aria-hidden="true">{{ separator }}</span>
34
+ </template>
35
+ </span>
36
+ </template>
@@ -0,0 +1,56 @@
1
+ <script setup lang="ts">
2
+ import { computed, watch } from 'vue'
3
+
4
+ const props = withDefaults(
5
+ defineProps<{
6
+ value: string
7
+ /** 5 labels, weakest to strongest. */
8
+ labels?: string[]
9
+ /** Length considered "long enough" — also used (+4) as the "very long" bonus threshold. */
10
+ minLength?: number
11
+ }>(),
12
+ {
13
+ labels: () => ['Very weak', 'Weak', 'Fair', 'Good', 'Strong'],
14
+ minLength: 8,
15
+ },
16
+ )
17
+
18
+ const emit = defineEmits<{ score: [number] }>()
19
+
20
+ function scorePassword(pw: string, minLength: number): number {
21
+ let score = 0
22
+ if (pw.length >= minLength) score++
23
+ if (pw.length >= minLength + 4) score++
24
+ if (/[a-z]/.test(pw) && /[A-Z]/.test(pw)) score++
25
+ if (/\d/.test(pw)) score++
26
+ if (/[^a-zA-Z0-9]/.test(pw)) score++
27
+ return Math.min(score, 4)
28
+ }
29
+
30
+ const hasValue = computed(() => props.value.length > 0)
31
+ const score = computed(() => scorePassword(props.value, props.minLength))
32
+ const filledCount = computed(() => (hasValue.value ? score.value + 1 : 0))
33
+
34
+ const COLORS = ['bg-error', 'bg-error', 'bg-tertiary', 'bg-primary', 'bg-success']
35
+ const TEXT_COLORS = ['text-error', 'text-error', 'text-tertiary', 'text-primary', 'text-success']
36
+
37
+ const barColor = computed(() => COLORS[score.value])
38
+ const textColor = computed(() => TEXT_COLORS[score.value])
39
+ const label = computed(() => props.labels[score.value] ?? '')
40
+
41
+ watch([() => props.value, score], () => emit('score', hasValue.value ? score.value : -1), { immediate: true })
42
+ </script>
43
+
44
+ <template>
45
+ <div class="flex flex-col gap-1">
46
+ <div class="flex gap-1">
47
+ <div
48
+ v-for="i in 5"
49
+ :key="i"
50
+ class="h-1 flex-1 rounded-full transition-colors duration-200"
51
+ :class="i <= filledCount ? barColor : 'bg-surface-container-highest'"
52
+ />
53
+ </div>
54
+ <p v-if="hasValue" class="text-body-small" :class="textColor">{{ label }}</p>
55
+ </div>
56
+ </template>
@@ -0,0 +1,202 @@
1
+ <script setup lang="ts">
2
+ import { computed, nextTick, ref, watch } from 'vue'
3
+
4
+ const props = withDefaults(
5
+ defineProps<{
6
+ modelValue: string
7
+ length?: number
8
+ /** Segment sizes for a grouped layout, e.g. [2, 4, 2, 3, 1, 3] renders `__ ____ __ ___ _ ___`. Overrides `length` (derived as the sum). */
9
+ groups?: number[]
10
+ /** Visual separator rendered between groups (only used when `groups` is set). */
11
+ separator?: string
12
+ type?: 'numeric' | 'alphanumeric'
13
+ masked?: boolean
14
+ variant?: 'filled' | 'outlined'
15
+ error?: boolean
16
+ errorLabel?: string
17
+ hint?: string
18
+ disabled?: boolean
19
+ autoFocus?: boolean
20
+ label?: string
21
+ }>(),
22
+ {
23
+ modelValue: '',
24
+ length: 6,
25
+ separator: '-',
26
+ type: 'numeric',
27
+ masked: false,
28
+ variant: 'filled',
29
+ disabled: false,
30
+ autoFocus: false,
31
+ },
32
+ )
33
+
34
+ const totalLength = computed(() => (props.groups?.length ? props.groups.reduce((a, b) => a + b, 0) : props.length))
35
+
36
+ // Index (0-based) of the last box in each group except the last — a
37
+ // separator is rendered right after each of these boxes.
38
+ const groupBoundaries = computed(() => {
39
+ const boundaries = new Set<number>()
40
+ if (!props.groups?.length) return boundaries
41
+ let sum = 0
42
+ for (const size of props.groups.slice(0, -1)) {
43
+ sum += size
44
+ boundaries.add(sum - 1)
45
+ }
46
+ return boundaries
47
+ })
48
+
49
+ const emit = defineEmits<{ 'update:modelValue': [string]; complete: [string] }>()
50
+
51
+ const inputEls = ref<(HTMLInputElement | null)[]>([])
52
+
53
+ function setInputEl(el: any, i: number) {
54
+ inputEls.value[i] = el as HTMLInputElement | null
55
+ }
56
+
57
+ const allowedPattern = computed(() => (props.type === 'numeric' ? /[0-9]/ : /[a-zA-Z0-9]/))
58
+
59
+ // A gap can appear in the middle of the value if the user clicks past an
60
+ // empty box (e.g. fills 0 and 1, then clicks box 3 directly). '\0' preserves
61
+ // that empty slot's position; trailing empties are just dropped.
62
+ const EMPTY = '\0'
63
+
64
+ const digits = computed(() => Array.from({ length: totalLength.value }, (_, i) => {
65
+ const c = props.modelValue[i]
66
+ return c === undefined || c === EMPTY ? '' : c
67
+ }))
68
+
69
+ function charsToValue(chars: string[]): string {
70
+ let end = chars.length
71
+ while (end > 0 && !chars[end - 1]) end--
72
+ return chars.slice(0, end).map((c) => c || EMPTY).join('')
73
+ }
74
+
75
+ function setValue(chars: string[]) {
76
+ const next = charsToValue(chars)
77
+ emit('update:modelValue', next)
78
+ if (next.length === totalLength.value && !next.includes(EMPTY)) {
79
+ emit('complete', next)
80
+ }
81
+ }
82
+
83
+ function focusInput(i: number) {
84
+ nextTick(() => inputEls.value[i]?.focus())
85
+ }
86
+
87
+ function onFocus(i: number) {
88
+ inputEls.value[i]?.select()
89
+ }
90
+
91
+ function onInput(i: number, e: Event) {
92
+ const input = e.target as HTMLInputElement
93
+ const char = input.value.slice(-1)
94
+
95
+ if (char && !allowedPattern.value.test(char)) {
96
+ input.value = digits.value[i] ?? ''
97
+ return
98
+ }
99
+
100
+ const chars = [...digits.value]
101
+ chars[i] = char
102
+ setValue(chars)
103
+
104
+ if (char && i < totalLength.value - 1) {
105
+ focusInput(i + 1)
106
+ }
107
+ }
108
+
109
+ function onKeydown(i: number, e: KeyboardEvent) {
110
+ if (e.key === 'Backspace' && !digits.value[i] && i > 0) {
111
+ e.preventDefault()
112
+ const chars = [...digits.value]
113
+ chars[i - 1] = ''
114
+ setValue(chars)
115
+ focusInput(i - 1)
116
+ } else if (e.key === 'ArrowLeft' && i > 0) {
117
+ e.preventDefault()
118
+ focusInput(i - 1)
119
+ } else if (e.key === 'ArrowRight' && i < totalLength.value - 1) {
120
+ e.preventDefault()
121
+ focusInput(i + 1)
122
+ }
123
+ }
124
+
125
+ function onPaste(i: number, e: ClipboardEvent) {
126
+ e.preventDefault()
127
+ const pasted = (e.clipboardData?.getData('text') ?? '').split('').filter((c) => allowedPattern.value.test(c))
128
+ if (pasted.length === 0) return
129
+
130
+ const chars = [...digits.value]
131
+ let last = i
132
+ for (const c of pasted) {
133
+ if (last >= totalLength.value) break
134
+ chars[last] = c
135
+ last++
136
+ }
137
+ setValue(chars)
138
+ focusInput(Math.min(last, totalLength.value - 1))
139
+ }
140
+
141
+ watch(
142
+ () => props.autoFocus,
143
+ (v) => {
144
+ if (v) focusInput(0)
145
+ },
146
+ { immediate: true },
147
+ )
148
+
149
+ const boxClasses = computed(() => {
150
+ const base = [
151
+ 'h-14 w-12 text-center text-title-large text-on-surface outline-none',
152
+ 'transition-[border-color,border-width] duration-150',
153
+ 'disabled:cursor-not-allowed disabled:opacity-[0.38]',
154
+ ]
155
+ if (props.variant === 'outlined') {
156
+ return [...base,
157
+ 'rounded-sm border bg-transparent',
158
+ props.error
159
+ ? 'border-error focus:border-2 focus:border-error'
160
+ : 'border-outline hover:border-on-surface focus:border-2 focus:border-primary',
161
+ ].join(' ')
162
+ }
163
+ return [...base,
164
+ 'rounded-t-sm bg-surface-container-highest border-b',
165
+ props.error
166
+ ? 'border-error focus:border-b-2 focus:border-error'
167
+ : 'border-on-surface-variant hover:border-on-surface focus:border-b-2 focus:border-primary',
168
+ ].join(' ')
169
+ })
170
+ </script>
171
+
172
+ <template>
173
+ <div class="flex flex-col gap-1">
174
+ <div role="group" :aria-label="label" class="flex items-center gap-2">
175
+ <template v-for="(digit, i) in digits" :key="i">
176
+ <input
177
+ :ref="(el) => setInputEl(el, i)"
178
+ :value="digit"
179
+ :type="masked ? 'password' : 'text'"
180
+ :inputmode="type === 'numeric' ? 'numeric' : 'text'"
181
+ autocomplete="one-time-code"
182
+ maxlength="1"
183
+ :disabled="disabled"
184
+ :aria-label="`Digit ${i + 1} of ${totalLength}`"
185
+ :class="boxClasses"
186
+ @input="onInput(i, $event)"
187
+ @keydown="onKeydown(i, $event)"
188
+ @paste="onPaste(i, $event)"
189
+ @focus="onFocus(i)"
190
+ />
191
+ <span
192
+ v-if="groupBoundaries.has(i)"
193
+ aria-hidden="true"
194
+ class="select-none text-title-large text-on-surface-variant"
195
+ >{{ separator }}</span>
196
+ </template>
197
+ </div>
198
+
199
+ <p v-if="error && errorLabel" class="px-1 text-body-small text-error">{{ errorLabel }}</p>
200
+ <p v-else-if="hint" class="px-1 text-body-small text-on-surface-variant">{{ hint }}</p>
201
+ </div>
202
+ </template>