@m3ui-vue/m3ui-vue 1.6.2 → 1.8.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.
- package/dist/API.md +1224 -28
- package/dist/{MColorPickerModal-NtkihoK6.js → MColorPickerModal-H8nuX0Wu.js} +3 -4
- package/dist/{MColorPickerModal-NtkihoK6.js.map → MColorPickerModal-H8nuX0Wu.js.map} +1 -1
- package/dist/MDialog-B42Mhn8W.js +331 -0
- package/dist/MDialog-B42Mhn8W.js.map +1 -0
- package/dist/{MListItem-D2cNUyzP.js → MListItem-DiOAxaN7.js} +431 -325
- package/dist/MListItem-DiOAxaN7.js.map +1 -0
- package/dist/{MLoadingIndicator-DWUj0BAB.js → MLoadingIndicator-CuTZYFFj.js} +2 -2
- package/dist/{MLoadingIndicator-DWUj0BAB.js.map → MLoadingIndicator-CuTZYFFj.js.map} +1 -1
- package/dist/{MSeekBar-C4cn9RIF.js → MSeekBar-BCDQTx2t.js} +2 -2
- package/dist/{MSeekBar-C4cn9RIF.js.map → MSeekBar-BCDQTx2t.js.map} +1 -1
- package/dist/MSegmentedButton-BXzRsg1S.js +105 -0
- package/dist/MSegmentedButton-BXzRsg1S.js.map +1 -0
- package/dist/MSignaturePad-BTqGaPXA.js +313 -0
- package/dist/MSignaturePad-BTqGaPXA.js.map +1 -0
- package/dist/MSlider-D_O8J9YH.js +739 -0
- package/dist/MSlider-D_O8J9YH.js.map +1 -0
- package/dist/{MSpinner-DZkXZJpc.js → MSpinner-UCdtSOHP.js} +2 -2
- package/dist/{MSpinner-DZkXZJpc.js.map → MSpinner-UCdtSOHP.js.map} +1 -1
- package/dist/{MTextField-CNH-byir.js → MTextField-CYk9yFvi.js} +162 -115
- package/dist/MTextField-CYk9yFvi.js.map +1 -0
- package/dist/_useFieldValidation-B0B44M_t.js +191 -0
- package/dist/_useFieldValidation-B0B44M_t.js.map +1 -0
- package/dist/api.json +1 -1
- package/dist/code-editor.js +184 -103
- package/dist/code-editor.js.map +1 -1
- package/dist/components/MAddressField.vue.d.ts +18 -3
- package/dist/components/MAppBarWithSearch.vue.d.ts +1 -1
- package/dist/components/MAudioRecorder.vue.d.ts +2 -2
- package/dist/components/MAutocomplete.vue.d.ts +22 -3
- package/dist/components/MCheckbox.vue.d.ts +23 -1
- package/dist/components/MCodeEditor.vue.d.ts +23 -1
- package/dist/components/MColorPicker.vue.d.ts +24 -3
- package/dist/components/MConfirmDialog.vue.d.ts +2 -2
- package/dist/components/MCountrySelect.vue.d.ts +13 -2
- package/dist/components/MCreditCardInput.vue.d.ts +33 -0
- package/dist/components/MCronField.vue.d.ts +23 -1
- package/dist/components/MDataTable.vue.d.ts +1 -1
- package/dist/components/MDatePicker.vue.d.ts +24 -3
- package/dist/components/MDateRangePicker.vue.d.ts +24 -3
- package/dist/components/MFileUpload.vue.d.ts +23 -2
- package/dist/components/MForm.vue.d.ts +61 -0
- package/dist/components/MFormBuilder.vue.d.ts +22 -0
- package/dist/components/MFormRenderer.vue.d.ts +151 -0
- package/dist/components/MJsonEditor.vue.d.ts +23 -1
- package/dist/components/MMapRoute.vue.d.ts +176 -0
- package/dist/components/MMaskField.vue.d.ts +20 -2
- package/dist/components/MMentionField.vue.d.ts +13 -2
- package/dist/components/MMultiAutocomplete.vue.d.ts +22 -3
- package/dist/components/MMultiSelect.vue.d.ts +22 -3
- package/dist/components/MNavigationRail.vue.d.ts +1 -1
- package/dist/components/MNotificationCenter.vue.d.ts +2 -2
- package/dist/components/MNumberField.vue.d.ts +20 -2
- package/dist/components/MPdfSigner.vue.d.ts +499 -0
- package/dist/components/MPdfViewer.vue.d.ts +12 -0
- package/dist/components/MPhoneInput.vue.d.ts +19 -4
- package/dist/components/MPinInput.vue.d.ts +24 -3
- package/dist/components/MPosKeypad.vue.d.ts +3 -3
- package/dist/components/MRadioGroup.vue.d.ts +23 -1
- package/dist/components/MRating.vue.d.ts +23 -1
- package/dist/components/MRichTextEditor.vue.d.ts +23 -1
- package/dist/components/MSearchBar.vue.d.ts +1 -1
- package/dist/components/MSegmentedButton.vue.d.ts +23 -2
- package/dist/components/MSelect.vue.d.ts +22 -3
- package/dist/components/MSignaturePad.vue.d.ts +19 -0
- package/dist/components/MSlider.vue.d.ts +23 -1
- package/dist/components/MSpreadsheet.vue.d.ts +137 -0
- package/dist/components/MStack.vue.d.ts +1 -1
- package/dist/components/MSwitch.vue.d.ts +23 -1
- package/dist/components/MTable.vue.d.ts +1 -1
- package/dist/components/MTagInput.vue.d.ts +20 -2
- package/dist/components/MText.vue.d.ts +1 -1
- package/dist/components/MTextField.vue.d.ts +26 -3
- package/dist/components/MTimePicker.vue.d.ts +24 -3
- package/dist/components/MTimezoneSelect.vue.d.ts +13 -2
- package/dist/components/MTour.vue.d.ts +2 -2
- package/dist/components/MTrackingTimeline.vue.d.ts +75 -0
- package/dist/components/MWindow.vue.d.ts +2 -2
- package/dist/composables/_routeGeometry.d.ts +26 -0
- package/dist/composables/_useFieldValidation.d.ts +91 -0
- package/dist/composables/mapRouting.d.ts +35 -0
- package/dist/composables/pdfSign.d.ts +52 -0
- package/dist/composables/spreadsheetFormula.d.ts +55 -0
- package/dist/composables/useLocale.d.ts +177 -0
- package/dist/composables/validation.d.ts +82 -0
- package/dist/draw.js +2 -2
- package/dist/flow.js +1 -1
- package/dist/gantt.js +2 -2
- package/dist/index.d.ts +12 -0
- package/dist/locales/index.js +693 -7
- package/dist/locales/index.js.map +1 -1
- package/dist/m3ui-vue.css +1 -1
- package/dist/m3ui.js +15507 -12417
- package/dist/m3ui.js.map +1 -1
- package/dist/map.d.ts +4 -0
- package/dist/map.js +1207 -745
- package/dist/map.js.map +1 -1
- package/dist/media.js +4 -4
- package/dist/pdf.d.ts +3 -0
- package/dist/pdf.js +1228 -687
- package/dist/pdf.js.map +1 -1
- package/dist/rich-text-editor.js +188 -146
- package/dist/rich-text-editor.js.map +1 -1
- package/dist/styles.css +1 -1
- package/dist/{useLocale-DaVSTdm0.js → useLocale-DL96OFgr.js} +99 -1
- package/dist/useLocale-DL96OFgr.js.map +1 -0
- package/package.json +5 -1
- package/src/__tests__/MForm.test.ts +325 -0
- package/src/__tests__/MFormRenderer.test.ts +157 -0
- package/src/__tests__/MMapRoute.test.ts +418 -0
- package/src/__tests__/MPdfSigner.test.ts +175 -0
- package/src/__tests__/MPhoneInput.test.ts +5 -2
- package/src/__tests__/MRichTextEditor.test.ts +2 -1
- package/src/__tests__/MSpreadsheet.test.ts +223 -0
- package/src/__tests__/MTrackingTimeline.test.ts +66 -0
- package/src/__tests__/_fakeMaplibre.ts +4 -1
- package/src/__tests__/_osrmRoutes.ts +10 -0
- package/src/__tests__/attrsFallthrough.test.ts +11 -0
- package/src/__tests__/fieldsValidation.test.ts +229 -0
- package/src/__tests__/spreadsheetFormula.test.ts +77 -0
- package/src/__tests__/ssr.test.ts +4 -0
- package/src/__tests__/validation.test.ts +77 -0
- package/src/components/MAddressField.vue +45 -8
- package/src/components/MAutocomplete.vue +69 -23
- package/src/components/MCheckbox.vue +80 -17
- package/src/components/MCodeEditor.vue +59 -2
- package/src/components/MColorPicker.vue +65 -16
- package/src/components/MCountrySelect.vue +17 -3
- package/src/components/MCreditCardInput.vue +76 -7
- package/src/components/MCronField.vue +60 -10
- package/src/components/MDatePicker.vue +65 -16
- package/src/components/MDateRangePicker.vue +66 -16
- package/src/components/MFileUpload.vue +71 -8
- package/src/components/MForm.vue +208 -0
- package/src/components/MFormBuilder.vue +417 -0
- package/src/components/MFormRenderer.vue +324 -0
- package/src/components/MJsonEditor.vue +57 -3
- package/src/components/MMapRoute.vue +523 -0
- package/src/components/MMaskField.vue +55 -13
- package/src/components/MMentionField.vue +17 -2
- package/src/components/MMultiAutocomplete.vue +70 -23
- package/src/components/MMultiSelect.vue +70 -23
- package/src/components/MNumberField.vue +58 -16
- package/src/components/MPdfSigner.vue +433 -0
- package/src/components/MPdfViewer.vue +12 -0
- package/src/components/MPhoneInput.vue +60 -18
- package/src/components/MPinInput.vue +58 -10
- package/src/components/MRadioGroup.vue +65 -4
- package/src/components/MRating.vue +62 -6
- package/src/components/MRichTextEditor.vue +64 -4
- package/src/components/MSegmentedButton.vue +59 -2
- package/src/components/MSelect.vue +72 -26
- package/src/components/MSignaturePad.vue +71 -6
- package/src/components/MSlider.vue +61 -10
- package/src/components/MSpreadsheet.vue +992 -0
- package/src/components/MSwitch.vue +63 -8
- package/src/components/MTagInput.vue +67 -25
- package/src/components/MTextField.vue +68 -14
- package/src/components/MTimePicker.vue +65 -16
- package/src/components/MTimezoneSelect.vue +17 -3
- package/src/components/MTrackingTimeline.vue +257 -0
- package/src/composables/_routeGeometry.ts +140 -0
- package/src/composables/_useFieldValidation.ts +287 -0
- package/src/composables/mapRouting.ts +55 -0
- package/src/composables/pdfSign.ts +141 -0
- package/src/composables/spreadsheetFormula.ts +459 -0
- package/src/composables/useLocale.ts +277 -0
- package/src/composables/validation.ts +178 -0
- package/src/index.ts +12 -0
- package/src/locales/de.ts +98 -0
- package/src/locales/es.ts +105 -7
- package/src/locales/fr.ts +98 -0
- package/src/locales/ja.ts +98 -0
- package/src/locales/ko.ts +98 -0
- package/src/locales/pt.ts +98 -0
- package/src/locales/zh.ts +98 -0
- package/src/map.ts +4 -0
- package/src/pdf.ts +3 -0
- package/dist/MButton-OQ4wIERQ.js +0 -171
- package/dist/MButton-OQ4wIERQ.js.map +0 -1
- package/dist/MDialog-DYMnaBlt.js +0 -167
- package/dist/MDialog-DYMnaBlt.js.map +0 -1
- package/dist/MListItem-D2cNUyzP.js.map +0 -1
- package/dist/MProgressBar-BWly1UKN.js +0 -179
- package/dist/MProgressBar-BWly1UKN.js.map +0 -1
- package/dist/MSegmentedButton-BEB4gXLA.js +0 -64
- package/dist/MSegmentedButton-BEB4gXLA.js.map +0 -1
- package/dist/MSlider-BIkA6DiE.js +0 -690
- package/dist/MSlider-BIkA6DiE.js.map +0 -1
- package/dist/MTextField-CNH-byir.js.map +0 -1
- package/dist/useLocale-DaVSTdm0.js.map +0 -1
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
<script setup lang="ts">
|
|
2
|
+
/**
|
|
3
|
+
* Sign and fill a PDF: fields placed on its pages (signature, initials, name, date, text, checkbox) that the signer
|
|
4
|
+
* fills in order, a signature drawn with a finger or mouse or typed, adopted once and reused for every signature
|
|
5
|
+
* field, and `save()` to get the PDF with everything written into it. In `prepare` mode the sender places the
|
|
6
|
+
* fields instead: add, drag, resize, mark required. Fields are plain JSON (`v-model:fields`, positions as fractions
|
|
7
|
+
* of the page), so a backend can store them and send them to each signer (`signer` picks whose fields are active).
|
|
8
|
+
* Built on MPdfViewer (zoom, search, thumbnails) and MSignaturePad. Writing the PDF needs `pdf-lib`. A visual
|
|
9
|
+
* signature, as e-signature flows show and print; for a certificate-based digital signature (PAdES), sign the
|
|
10
|
+
* saved file on your server. Available from the `/pdf` entry point. Not an M3 spec component.
|
|
11
|
+
*
|
|
12
|
+
* @event update:fields The fields changed (placed, moved, filled)
|
|
13
|
+
* @event complete Every required field is filled (after the last one is)
|
|
14
|
+
* @event finish The signer pressed Finish (every required field is filled): call `save()` here
|
|
15
|
+
* @event loaded The document loaded (MPdfViewer's)
|
|
16
|
+
*/
|
|
17
|
+
import { computed, nextTick, ref, useId, watch } from 'vue'
|
|
18
|
+
import MPdfViewer from './MPdfViewer.vue'
|
|
19
|
+
import MSignaturePad from './MSignaturePad.vue'
|
|
20
|
+
import MDialog from './MDialog.vue'
|
|
21
|
+
import MButton from './MButton.vue'
|
|
22
|
+
import MIcon from './MIcon.vue'
|
|
23
|
+
import MIconButton from './MIconButton.vue'
|
|
24
|
+
import MSegmentedButton from './MSegmentedButton.vue'
|
|
25
|
+
import MTextField from './MTextField.vue'
|
|
26
|
+
import { fieldMissing, signPdf, type PdfSignField, type SignPdfOptions } from '../composables/pdfSign'
|
|
27
|
+
import type { PdfSource } from '../composables/usePdf'
|
|
28
|
+
import { useLocale, type M3Locale } from '../composables/useLocale'
|
|
29
|
+
|
|
30
|
+
defineOptions({ inheritAttrs: false })
|
|
31
|
+
|
|
32
|
+
const props = withDefaults(
|
|
33
|
+
defineProps<{
|
|
34
|
+
/** The PDF: a URL, its bytes, or a `File`/`Blob` */
|
|
35
|
+
src?: PdfSource | null
|
|
36
|
+
/** The fields on its pages (v-model:fields) */
|
|
37
|
+
fields?: PdfSignField[]
|
|
38
|
+
/** `sign`: fill the fields. `prepare`: place them (add, move, resize, delete) */
|
|
39
|
+
mode?: 'sign' | 'prepare'
|
|
40
|
+
/** Whose turn it is: only fields with this `signer` (or none) can be filled; the rest show dimmed */
|
|
41
|
+
signer?: string
|
|
42
|
+
/** Fills name fields, and starts a typed signature with it */
|
|
43
|
+
signerName?: string
|
|
44
|
+
/** How date fields write today's date */
|
|
45
|
+
dateFormat?: Intl.DateTimeFormatOptions
|
|
46
|
+
/** The field types offered in prepare mode */
|
|
47
|
+
types?: PdfSignField['type'][]
|
|
48
|
+
/** The pdf.js worker URL (MPdfViewer's) */
|
|
49
|
+
workerSrc?: string
|
|
50
|
+
}>(),
|
|
51
|
+
{ src: null, fields: () => [], mode: 'sign', dateFormat: () => ({ dateStyle: 'medium' }), types: () => ['signature', 'initials', 'name', 'date', 'text', 'checkbox'] },
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
const emit = defineEmits<{
|
|
55
|
+
'update:fields': [fields: PdfSignField[]]
|
|
56
|
+
complete: []
|
|
57
|
+
finish: []
|
|
58
|
+
loaded: [doc: unknown]
|
|
59
|
+
}>()
|
|
60
|
+
|
|
61
|
+
const locale = useLocale()
|
|
62
|
+
const uid = useId()
|
|
63
|
+
const viewer = ref<InstanceType<typeof MPdfViewer>>()
|
|
64
|
+
|
|
65
|
+
const TYPE: Record<PdfSignField['type'], { icon: string; key: keyof M3Locale; w: number; h: number }> = {
|
|
66
|
+
signature: { icon: 'signature', key: 'pdfSignSignature', w: 0.3, h: 0.06 },
|
|
67
|
+
initials: { icon: 'draw', key: 'pdfSignInitials', w: 0.1, h: 0.05 },
|
|
68
|
+
name: { icon: 'badge', key: 'pdfSignName', w: 0.3, h: 0.035 },
|
|
69
|
+
date: { icon: 'calendar_today', key: 'pdfSignDate', w: 0.2, h: 0.035 },
|
|
70
|
+
text: { icon: 'text_fields', key: 'pdfSignText', w: 0.3, h: 0.035 },
|
|
71
|
+
checkbox: { icon: 'check_box', key: 'pdfSignCheckbox', w: 0.03, h: 0.022 },
|
|
72
|
+
}
|
|
73
|
+
const typeName = (t: PdfSignField['type']) => locale[TYPE[t].key] as string
|
|
74
|
+
|
|
75
|
+
const mine = (f: PdfSignField) => !props.signer || !f.signer || f.signer === props.signer
|
|
76
|
+
const byPage = computed(() => {
|
|
77
|
+
const map = new Map<number, PdfSignField[]>()
|
|
78
|
+
for (const f of props.fields) map.set(f.page, [...(map.get(f.page) ?? []), f])
|
|
79
|
+
return map
|
|
80
|
+
})
|
|
81
|
+
const todo = computed(() => props.fields.filter((f) => mine(f) && (f.required ?? (f.type === 'signature' || f.type === 'initials'))))
|
|
82
|
+
const done = computed(() => todo.value.filter((f) => !fieldMissing(f)).length)
|
|
83
|
+
const complete = computed(() => done.value === todo.value.length)
|
|
84
|
+
watch(complete, (c, was) => { if (c && !was && props.mode === 'sign') emit('complete') })
|
|
85
|
+
const progress = computed(() => locale.pdfSignProgress.replace('{done}', String(done.value)).replace('{total}', String(todo.value.length)))
|
|
86
|
+
|
|
87
|
+
function patch(id: string, change: Partial<PdfSignField>) {
|
|
88
|
+
emit('update:fields', props.fields.map((f) => (f.id === id ? { ...f, ...change } : f)))
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// ── signing ──
|
|
92
|
+
/** The signature (and initials) adopted once, reused by every other such field */
|
|
93
|
+
const adopted = ref<{ signature?: string; initials?: string }>({})
|
|
94
|
+
const dialog = ref<{ field: PdfSignField; tab: 'draw' | 'type'; text: string } | null>(null)
|
|
95
|
+
const pad = ref<InstanceType<typeof MSignaturePad>>()
|
|
96
|
+
const padEmpty = ref(true)
|
|
97
|
+
// The pad's canvas has a fixed size: as wide as the dialog's body
|
|
98
|
+
const padBox = ref<HTMLElement>()
|
|
99
|
+
const padWidth = ref(400)
|
|
100
|
+
watch(() => dialog.value?.tab, () => nextTick(() => { if (padBox.value?.clientWidth) padWidth.value = padBox.value.clientWidth - 2 }))
|
|
101
|
+
|
|
102
|
+
function today() {
|
|
103
|
+
return new Intl.DateTimeFormat(undefined, props.dateFormat).format(new Date())
|
|
104
|
+
}
|
|
105
|
+
function fill(f: PdfSignField, force = false) {
|
|
106
|
+
if (props.mode !== 'sign' || !mine(f)) return
|
|
107
|
+
if (f.type === 'checkbox') return patch(f.id, { value: f.value === 'true' ? undefined : 'true' })
|
|
108
|
+
if (f.type === 'date' && !f.value) return patch(f.id, { value: today() })
|
|
109
|
+
if (f.type === 'name' && !f.value && props.signerName) return patch(f.id, { value: props.signerName })
|
|
110
|
+
if ((f.type === 'signature' || f.type === 'initials') && !force) {
|
|
111
|
+
const saved = adopted.value[f.type]
|
|
112
|
+
if (saved && !f.value) return patch(f.id, { value: saved })
|
|
113
|
+
}
|
|
114
|
+
const initial = f.type === 'initials' ? initialsOf(props.signerName ?? '') : props.signerName ?? ''
|
|
115
|
+
dialog.value = {
|
|
116
|
+
field: f,
|
|
117
|
+
tab: f.type === 'signature' || f.type === 'initials' ? 'draw' : 'type',
|
|
118
|
+
text: f.type === 'signature' || f.type === 'initials' ? initial : f.value ?? (f.type === 'name' ? initial : ''),
|
|
119
|
+
}
|
|
120
|
+
padEmpty.value = true
|
|
121
|
+
}
|
|
122
|
+
const initialsOf = (name: string) => name.split(/\s+/).filter(Boolean).map((w) => w[0]!.toUpperCase()).join('')
|
|
123
|
+
|
|
124
|
+
const SCRIPT_FONT = '"Segoe Script", "Brush Script MT", "Snell Roundhand", "URW Chancery L", cursive'
|
|
125
|
+
/** A typed signature, drawn as an image in a handwriting font */
|
|
126
|
+
function typedSignature(text: string): string {
|
|
127
|
+
const canvas = document.createElement('canvas')
|
|
128
|
+
const ctx = canvas.getContext('2d')
|
|
129
|
+
if (!ctx) return ''
|
|
130
|
+
const size = 96
|
|
131
|
+
ctx.font = `${size}px ${SCRIPT_FONT}`
|
|
132
|
+
const w = Math.ceil(ctx.measureText(text).width) + 40
|
|
133
|
+
canvas.width = w
|
|
134
|
+
canvas.height = size * 1.6
|
|
135
|
+
ctx.font = `${size}px ${SCRIPT_FONT}`
|
|
136
|
+
ctx.fillStyle = '#1a237e'
|
|
137
|
+
ctx.textBaseline = 'middle'
|
|
138
|
+
ctx.fillText(text, 20, canvas.height / 2)
|
|
139
|
+
return canvas.toDataURL('image/png')
|
|
140
|
+
}
|
|
141
|
+
const isSignature = computed(() => dialog.value?.field.type === 'signature' || dialog.value?.field.type === 'initials')
|
|
142
|
+
const canApply = computed(() => {
|
|
143
|
+
const d = dialog.value
|
|
144
|
+
if (!d) return false
|
|
145
|
+
if (isSignature.value && d.tab === 'draw') return !padEmpty.value
|
|
146
|
+
return d.text.trim() !== ''
|
|
147
|
+
})
|
|
148
|
+
async function apply() {
|
|
149
|
+
const d = dialog.value
|
|
150
|
+
if (!d || !canApply.value) return
|
|
151
|
+
let value: string
|
|
152
|
+
if (isSignature.value) {
|
|
153
|
+
value = d.tab === 'draw' ? await cropped(pad.value?.toDataURL() ?? '') : typedSignature(d.text.trim())
|
|
154
|
+
adopted.value = { ...adopted.value, [d.field.type]: value }
|
|
155
|
+
} else value = d.text.trim()
|
|
156
|
+
patch(d.field.id, { value })
|
|
157
|
+
dialog.value = null
|
|
158
|
+
}
|
|
159
|
+
/** The drawn signature without the empty pad around it */
|
|
160
|
+
async function cropped(url: string): Promise<string> {
|
|
161
|
+
if (!url || typeof document === 'undefined') return url
|
|
162
|
+
const img = new Image()
|
|
163
|
+
img.src = url
|
|
164
|
+
try { await img.decode() } catch { return url }
|
|
165
|
+
if (!img.width) return url
|
|
166
|
+
const c = document.createElement('canvas')
|
|
167
|
+
c.width = img.width
|
|
168
|
+
c.height = img.height
|
|
169
|
+
const ctx = c.getContext('2d')
|
|
170
|
+
if (!ctx) return url
|
|
171
|
+
ctx.drawImage(img, 0, 0)
|
|
172
|
+
const { data, width, height } = ctx.getImageData(0, 0, c.width, c.height)
|
|
173
|
+
let x1 = width, y1 = height, x2 = -1, y2 = -1
|
|
174
|
+
for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
|
|
175
|
+
if (data[(y * width + x) * 4 + 3]! > 8) { x1 = Math.min(x1, x); x2 = Math.max(x2, x); y1 = Math.min(y1, y); y2 = Math.max(y2, y) }
|
|
176
|
+
}
|
|
177
|
+
if (x2 < 0) return url
|
|
178
|
+
const pad = 8
|
|
179
|
+
x1 = Math.max(0, x1 - pad); y1 = Math.max(0, y1 - pad); x2 = Math.min(width - 1, x2 + pad); y2 = Math.min(height - 1, y2 + pad)
|
|
180
|
+
const out = document.createElement('canvas')
|
|
181
|
+
out.width = x2 - x1 + 1
|
|
182
|
+
out.height = y2 - y1 + 1
|
|
183
|
+
out.getContext('2d')?.drawImage(c, x1, y1, out.width, out.height, 0, 0, out.width, out.height)
|
|
184
|
+
return out.toDataURL('image/png')
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function next() {
|
|
188
|
+
const list = todo.value
|
|
189
|
+
const target = list.find((f) => fieldMissing(f)) ?? list[0]
|
|
190
|
+
if (!target) return
|
|
191
|
+
const el = document.getElementById(fieldId(target))
|
|
192
|
+
el?.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
|
193
|
+
el?.focus({ preventScroll: true })
|
|
194
|
+
}
|
|
195
|
+
const fieldId = (f: PdfSignField) => `${uid}-f-${f.id}`
|
|
196
|
+
|
|
197
|
+
// ── preparing ──
|
|
198
|
+
const selectedId = ref<string | null>(null)
|
|
199
|
+
let seq = 0
|
|
200
|
+
function addField(type: PdfSignField['type']) {
|
|
201
|
+
const t = TYPE[type]
|
|
202
|
+
const page = currentPage.value
|
|
203
|
+
const id = `${type}-${Date.now().toString(36)}-${++seq}`
|
|
204
|
+
const field: PdfSignField = { id, type, page, x: 0.5 - t.w / 2, y: 0.45, width: t.w, height: t.h, label: typeName(type) }
|
|
205
|
+
if (type === 'signature' || type === 'initials') field.required = true
|
|
206
|
+
emit('update:fields', [...props.fields, field])
|
|
207
|
+
selectedId.value = id
|
|
208
|
+
}
|
|
209
|
+
function removeField(id: string) {
|
|
210
|
+
emit('update:fields', props.fields.filter((f) => f.id !== id))
|
|
211
|
+
if (selectedId.value === id) selectedId.value = null
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Dragging a field (or its corner) in prepare mode: the change in fractions of its page */
|
|
215
|
+
let drag: { id: string; kind: 'move' | 'resize'; x: number; y: number; start: PdfSignField; w: number; h: number } | null = null
|
|
216
|
+
function onFieldDown(e: PointerEvent, f: PdfSignField, kind: 'move' | 'resize', page: { width: number; height: number }) {
|
|
217
|
+
if (props.mode !== 'prepare' || e.button !== 0) return
|
|
218
|
+
e.preventDefault()
|
|
219
|
+
e.stopPropagation()
|
|
220
|
+
selectedId.value = f.id
|
|
221
|
+
drag = { id: f.id, kind, x: e.clientX, y: e.clientY, start: { ...f }, w: page.width, h: page.height }
|
|
222
|
+
;(e.currentTarget as HTMLElement).setPointerCapture?.(e.pointerId)
|
|
223
|
+
}
|
|
224
|
+
function onFieldMove(e: PointerEvent) {
|
|
225
|
+
if (!drag) return
|
|
226
|
+
const dx = (e.clientX - drag.x) / drag.w
|
|
227
|
+
const dy = (e.clientY - drag.y) / drag.h
|
|
228
|
+
const s = drag.start
|
|
229
|
+
if (drag.kind === 'move') {
|
|
230
|
+
patch(drag.id, { x: clamp(s.x + dx, 0, 1 - s.width), y: clamp(s.y + dy, 0, 1 - s.height) })
|
|
231
|
+
} else {
|
|
232
|
+
patch(drag.id, { width: clamp(s.width + dx, 0.02, 1 - s.x), height: clamp(s.height + dy, 0.015, 1 - s.y) })
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
function onFieldUp() { drag = null }
|
|
236
|
+
const clamp = (v: number, a: number, b: number) => Math.min(Math.max(v, a), b)
|
|
237
|
+
|
|
238
|
+
function onFieldKey(e: KeyboardEvent, f: PdfSignField) {
|
|
239
|
+
if (props.mode === 'sign') {
|
|
240
|
+
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); fill(f) }
|
|
241
|
+
return
|
|
242
|
+
}
|
|
243
|
+
const step = e.shiftKey ? 0.02 : 0.005
|
|
244
|
+
const moves: Record<string, [number, number]> = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }
|
|
245
|
+
if (moves[e.key]) {
|
|
246
|
+
e.preventDefault()
|
|
247
|
+
const [dx, dy] = moves[e.key]!
|
|
248
|
+
patch(f.id, { x: clamp(f.x + dx, 0, 1 - f.width), y: clamp(f.y + dy, 0, 1 - f.height) })
|
|
249
|
+
} else if (e.key === 'Delete' || e.key === 'Backspace') {
|
|
250
|
+
e.preventDefault()
|
|
251
|
+
removeField(f.id)
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const currentPage = ref(1)
|
|
256
|
+
|
|
257
|
+
/** The overlay of a page shown rotated by the viewer: laid out on the page as it is, then turned with it */
|
|
258
|
+
function frameStyle(slot: { width: number; height: number; rotation: number }) {
|
|
259
|
+
const r = slot.rotation
|
|
260
|
+
const swap = r % 180 !== 0
|
|
261
|
+
const w = swap ? slot.height : slot.width
|
|
262
|
+
const h = swap ? slot.width : slot.height
|
|
263
|
+
const t = r === 90 ? 'rotate(90deg) translateY(-100%)' : r === 180 ? 'rotate(180deg) translate(-100%, -100%)' : r === 270 ? 'rotate(270deg) translateX(-100%)' : undefined
|
|
264
|
+
return { width: `${w}px`, height: `${h}px`, transform: t, transformOrigin: 'top left' }
|
|
265
|
+
}
|
|
266
|
+
const fieldStyle = (f: PdfSignField) => ({ left: `${f.x * 100}%`, top: `${f.y * 100}%`, width: `${f.width * 100}%`, height: `${f.height * 100}%` })
|
|
267
|
+
|
|
268
|
+
// ── saving ──
|
|
269
|
+
async function sourceBytes(src: PdfSource): Promise<ArrayBuffer | Uint8Array> {
|
|
270
|
+
if (src instanceof Uint8Array || src instanceof ArrayBuffer) return src
|
|
271
|
+
if (typeof Blob !== 'undefined' && src instanceof Blob) return src.arrayBuffer()
|
|
272
|
+
const res = await fetch(String(src))
|
|
273
|
+
if (!res.ok) throw new Error(`PDF ${res.status}`)
|
|
274
|
+
return res.arrayBuffer()
|
|
275
|
+
}
|
|
276
|
+
/** The PDF with the filled fields written into it */
|
|
277
|
+
async function save(options?: SignPdfOptions): Promise<Uint8Array> {
|
|
278
|
+
if (!props.src) throw new Error('No PDF')
|
|
279
|
+
return signPdf(await sourceBytes(props.src), props.fields, options)
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
defineExpose({
|
|
283
|
+
/** The PDF with the filled fields written in (needs `pdf-lib`) */
|
|
284
|
+
save,
|
|
285
|
+
/** Scrolls to the next field to fill */
|
|
286
|
+
next,
|
|
287
|
+
/** Whether every required field of this signer is filled */
|
|
288
|
+
complete,
|
|
289
|
+
/** The viewer underneath (zoom, pages, search) */
|
|
290
|
+
viewer,
|
|
291
|
+
})
|
|
292
|
+
</script>
|
|
293
|
+
|
|
294
|
+
<template>
|
|
295
|
+
<div class="m3-pdf-signer" v-bind="$attrs">
|
|
296
|
+
<div class="flex shrink-0 flex-wrap items-center gap-2 border-b border-outline-variant bg-surface-container px-3 py-2">
|
|
297
|
+
<template v-if="mode === 'sign'">
|
|
298
|
+
<MIcon :name="complete ? 'task_alt' : 'edit_document'" :size="20" :class="complete ? 'text-primary' : 'text-on-surface-variant'" />
|
|
299
|
+
<span class="text-body-medium text-on-surface" aria-live="polite">{{ complete ? locale.pdfSignComplete : progress }}</span>
|
|
300
|
+
<span class="flex-1" />
|
|
301
|
+
<MButton v-if="!complete" variant="tonal" icon="arrow_downward" @click="next">{{ locale.pdfSignNext }}</MButton>
|
|
302
|
+
<MButton :disabled="!complete" icon="check" @click="emit('finish')">{{ locale.pdfSignFinish }}</MButton>
|
|
303
|
+
</template>
|
|
304
|
+
<template v-else>
|
|
305
|
+
<span class="mr-1 text-label-large text-on-surface-variant">{{ locale.pdfSignAddField }}</span>
|
|
306
|
+
<MButton v-for="t in types" :key="t" variant="tonal" size="sm" :icon="TYPE[t].icon" :data-add="t" @click="addField(t)">{{ typeName(t) }}</MButton>
|
|
307
|
+
</template>
|
|
308
|
+
</div>
|
|
309
|
+
|
|
310
|
+
<MPdfViewer
|
|
311
|
+
ref="viewer"
|
|
312
|
+
:src="src"
|
|
313
|
+
:worker-src="workerSrc"
|
|
314
|
+
class="min-h-0 flex-1"
|
|
315
|
+
@update:page="currentPage = $event"
|
|
316
|
+
@loaded="emit('loaded', $event)"
|
|
317
|
+
>
|
|
318
|
+
<template #page="slot">
|
|
319
|
+
<div class="pointer-events-none absolute inset-0">
|
|
320
|
+
<div class="absolute left-0 top-0" :style="frameStyle(slot)">
|
|
321
|
+
<div
|
|
322
|
+
v-for="f in byPage.get(slot.page) ?? []"
|
|
323
|
+
:id="fieldId(f)"
|
|
324
|
+
:key="f.id"
|
|
325
|
+
class="m3-pdf-sign-field pointer-events-auto absolute flex items-center justify-center rounded-xs outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
|
|
326
|
+
:class="[
|
|
327
|
+
mode === 'prepare' ? 'cursor-move' : mine(f) ? 'cursor-pointer' : 'cursor-default opacity-40',
|
|
328
|
+
f.value ? 'm3-pdf-sign-filled' : 'm3-pdf-sign-empty',
|
|
329
|
+
mode === 'sign' && mine(f) && fieldMissing(f) ? 'm3-pdf-sign-todo' : '',
|
|
330
|
+
selectedId === f.id && mode === 'prepare' ? 'm3-pdf-sign-selected' : '',
|
|
331
|
+
]"
|
|
332
|
+
:style="fieldStyle(f)"
|
|
333
|
+
:data-field="f.id"
|
|
334
|
+
:data-type="f.type"
|
|
335
|
+
role="button"
|
|
336
|
+
:tabindex="mode === 'prepare' || mine(f) ? 0 : -1"
|
|
337
|
+
:aria-label="`${f.label ?? typeName(f.type)}${f.value ? '' : (f.required ?? (f.type === 'signature' || f.type === 'initials')) ? ` (${locale.pdfSignRequired})` : ''}`"
|
|
338
|
+
@click="mode === 'sign' ? fill(f, !!f.value) : (selectedId = f.id)"
|
|
339
|
+
@pointerdown="onFieldDown($event, f, 'move', { width: slot.rotation % 180 ? slot.height : slot.width, height: slot.rotation % 180 ? slot.width : slot.height })"
|
|
340
|
+
@pointermove="onFieldMove"
|
|
341
|
+
@pointerup="onFieldUp"
|
|
342
|
+
@pointercancel="onFieldUp"
|
|
343
|
+
@keydown="onFieldKey($event, f)"
|
|
344
|
+
>
|
|
345
|
+
<img v-if="f.value && (f.type === 'signature' || f.type === 'initials')" :src="f.value" alt="" class="h-full w-full object-contain" draggable="false" />
|
|
346
|
+
<MIcon v-else-if="f.type === 'checkbox' && f.value === 'true'" name="check" class="text-on-surface" :size="Math.max(12, slot.height * f.height * 0.9)" />
|
|
347
|
+
<span v-else-if="f.value" class="m3-pdf-sign-text w-full truncate px-1 text-left" :style="{ fontSize: `${Math.max(8, slot.height * f.height * 0.6)}px` }">{{ f.value }}</span>
|
|
348
|
+
<span v-else-if="f.type !== 'checkbox'" class="flex min-w-0 items-center gap-1 truncate px-1 text-label-medium">
|
|
349
|
+
<MIcon :name="TYPE[f.type].icon" :size="16" />
|
|
350
|
+
<span class="truncate">{{ f.type === 'signature' && mode === 'sign' ? locale.pdfSignHere : f.label ?? typeName(f.type) }}</span>
|
|
351
|
+
</span>
|
|
352
|
+
<template v-if="mode === 'prepare' && selectedId === f.id">
|
|
353
|
+
<span
|
|
354
|
+
class="absolute -right-1.5 -bottom-1.5 h-3 w-3 cursor-nwse-resize rounded-full border-2 border-surface bg-primary touch-none"
|
|
355
|
+
aria-hidden="true"
|
|
356
|
+
@pointerdown="onFieldDown($event, f, 'resize', { width: slot.rotation % 180 ? slot.height : slot.width, height: slot.rotation % 180 ? slot.width : slot.height })"
|
|
357
|
+
/>
|
|
358
|
+
<div class="absolute -top-11 left-0 flex items-center gap-1 rounded-full bg-surface-container-high px-1 shadow-elevation-2" @pointerdown.stop>
|
|
359
|
+
<MButton
|
|
360
|
+
:variant="f.required ?? (f.type === 'signature' || f.type === 'initials') ? 'filled' : 'text'"
|
|
361
|
+
size="xs"
|
|
362
|
+
@click.stop="patch(f.id, { required: !(f.required ?? (f.type === 'signature' || f.type === 'initials')) })"
|
|
363
|
+
>{{ locale.pdfSignRequired }}</MButton>
|
|
364
|
+
<MIconButton icon="delete" size="xs" :label="locale.pdfSignDelete" @click.stop="removeField(f.id)" />
|
|
365
|
+
</div>
|
|
366
|
+
</template>
|
|
367
|
+
</div>
|
|
368
|
+
</div>
|
|
369
|
+
</div>
|
|
370
|
+
</template>
|
|
371
|
+
</MPdfViewer>
|
|
372
|
+
|
|
373
|
+
<MDialog :model-value="!!dialog" :title="dialog ? (dialog.field.label ?? typeName(dialog.field.type)) : ''" max-width="560px" @update:model-value="(v: boolean) => { if (!v) dialog = null }">
|
|
374
|
+
<div v-if="dialog" class="flex flex-col gap-4">
|
|
375
|
+
<template v-if="isSignature">
|
|
376
|
+
<MSegmentedButton
|
|
377
|
+
v-model="dialog.tab"
|
|
378
|
+
:options="[{ value: 'draw', label: locale.pdfSignDraw, icon: 'draw' }, { value: 'type', label: locale.pdfSignTypeIt, icon: 'keyboard' }]"
|
|
379
|
+
density="compact"
|
|
380
|
+
/>
|
|
381
|
+
<div v-if="dialog.tab === 'draw'" ref="padBox" class="flex flex-col gap-2">
|
|
382
|
+
<MSignaturePad ref="pad" :key="padWidth" :width="padWidth" :height="180" @end="padEmpty = false" @change="padEmpty = !!pad?.isEmpty()" />
|
|
383
|
+
<MButton variant="text" icon="ink_eraser" class="self-start" @click="pad?.clear(); padEmpty = true">{{ locale.clear }}</MButton>
|
|
384
|
+
</div>
|
|
385
|
+
<template v-else>
|
|
386
|
+
<MTextField v-model="dialog.text" :label="typeName(dialog.field.type)" autocomplete="name" />
|
|
387
|
+
<div class="flex h-24 items-center overflow-hidden rounded-lg bg-surface-container-highest px-4 text-[2.5rem] text-[#1a237e] dark:text-[#c5cae9]" :style="{ fontFamily: SCRIPT_FONT }">{{ dialog.text }}</div>
|
|
388
|
+
</template>
|
|
389
|
+
</template>
|
|
390
|
+
<MTextField v-else v-model="dialog.text" :label="dialog.field.label ?? typeName(dialog.field.type)" @keydown.enter="apply" />
|
|
391
|
+
</div>
|
|
392
|
+
<template #actions>
|
|
393
|
+
<MButton variant="text" @click="dialog = null">{{ locale.cancel }}</MButton>
|
|
394
|
+
<MButton :disabled="!canApply" @click="apply">{{ isSignature ? locale.pdfSignAdopt : locale.ok }}</MButton>
|
|
395
|
+
</template>
|
|
396
|
+
</MDialog>
|
|
397
|
+
</div>
|
|
398
|
+
</template>
|
|
399
|
+
|
|
400
|
+
<style>
|
|
401
|
+
@layer base {
|
|
402
|
+
.m3-pdf-signer {
|
|
403
|
+
display: flex;
|
|
404
|
+
flex-direction: column;
|
|
405
|
+
overflow: hidden;
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
.m3-pdf-sign-empty {
|
|
409
|
+
border: 1.5px dashed var(--color-primary);
|
|
410
|
+
background: color-mix(in srgb, var(--color-primary) 10%, transparent);
|
|
411
|
+
color: var(--color-primary);
|
|
412
|
+
}
|
|
413
|
+
.m3-pdf-sign-todo {
|
|
414
|
+
background: color-mix(in srgb, var(--color-tertiary-container) 70%, transparent);
|
|
415
|
+
border-color: var(--color-tertiary);
|
|
416
|
+
color: var(--color-on-tertiary-container);
|
|
417
|
+
}
|
|
418
|
+
.m3-pdf-sign-filled {
|
|
419
|
+
border: 1px solid transparent;
|
|
420
|
+
}
|
|
421
|
+
.m3-pdf-sign-filled:hover,
|
|
422
|
+
.m3-pdf-sign-filled:focus-visible {
|
|
423
|
+
border-color: color-mix(in srgb, var(--color-primary) 50%, transparent);
|
|
424
|
+
}
|
|
425
|
+
.m3-pdf-sign-text {
|
|
426
|
+
color: #111;
|
|
427
|
+
font-family: system-ui, sans-serif;
|
|
428
|
+
line-height: 1;
|
|
429
|
+
}
|
|
430
|
+
.m3-pdf-sign-selected {
|
|
431
|
+
box-shadow: 0 0 0 2px var(--color-primary);
|
|
432
|
+
}
|
|
433
|
+
</style>
|
|
@@ -88,6 +88,9 @@ export type PdfZoom = number | 'fit-width' | 'fit-page'
|
|
|
88
88
|
*
|
|
89
89
|
* @slot actions Extra buttons at the end of the top bar. Props: `{ pdf }`
|
|
90
90
|
* @slot empty Shown without a `src`
|
|
91
|
+
* @slot page Drawn over each page (fields, stamps, your own marks), positioned in its box. Props: `{ page, width,
|
|
92
|
+
* height, scale, rotation, size }`: the page's box in px, px per PDF point, the view's rotation, and the page's
|
|
93
|
+
* own size in points (before that rotation)
|
|
91
94
|
* @event loaded The document loaded, with its pdf.js proxy
|
|
92
95
|
* @event error The document failed to load
|
|
93
96
|
* @event link A link was followed: `{ url }` (opens in a new tab) or `{ page }` (scrolled to)
|
|
@@ -1026,6 +1029,15 @@ const TOOLS = computed(() => [
|
|
|
1026
1029
|
@select="onSelect"
|
|
1027
1030
|
@text-selection="onTextSelection"
|
|
1028
1031
|
/>
|
|
1032
|
+
<slot
|
|
1033
|
+
name="page"
|
|
1034
|
+
:page="i + 1"
|
|
1035
|
+
:width="box.width"
|
|
1036
|
+
:height="box.height"
|
|
1037
|
+
:scale="scale"
|
|
1038
|
+
:rotation="rotation"
|
|
1039
|
+
:size="pdf.pageSizes.value[i]"
|
|
1040
|
+
/>
|
|
1029
1041
|
</div>
|
|
1030
1042
|
</div>
|
|
1031
1043
|
|
|
@@ -11,8 +11,11 @@
|
|
|
11
11
|
* @event update:modelValue Emitted with the number in E.164, or null when empty — powers v-model
|
|
12
12
|
* @event update:country Emitted with the ISO code when the country changes — powers v-model:country
|
|
13
13
|
* @event update:valid Emitted when the number becomes (in)valid for its country — powers v-model:valid
|
|
14
|
+
* @event blur Focus left the field and its country list
|
|
14
15
|
*/
|
|
15
|
-
import { computed, nextTick, onBeforeUnmount, ref, useId, watch } from 'vue'
|
|
16
|
+
import { computed, inject, nextTick, onBeforeUnmount, ref, useId, watch } from 'vue'
|
|
17
|
+
import { FORM_KEY, useFieldValidation, useFocusLeave } from '../composables/_useFieldValidation'
|
|
18
|
+
import type { ValidateOn, ValidationRule } from '../composables/validation'
|
|
16
19
|
import MIcon from './MIcon.vue'
|
|
17
20
|
import { useFieldBg } from '../composables/useFieldBg'
|
|
18
21
|
import { useLocale } from '../composables/useLocale'
|
|
@@ -47,17 +50,25 @@ const props = withDefaults(
|
|
|
47
50
|
preferred?: string[]
|
|
48
51
|
/** Visual style */
|
|
49
52
|
variant?: 'filled' | 'outlined'
|
|
50
|
-
/** Puts the field in error state */
|
|
51
|
-
error?: boolean
|
|
53
|
+
/** Puts the field in error state. A string is also the message */
|
|
54
|
+
error?: boolean | string
|
|
52
55
|
/** Error message below the field (when `error`, or when `validate` finds the number incomplete) */
|
|
53
56
|
errorLabel?: string
|
|
57
|
+
/** More validation rules (functions or a Standard Schema), run on the E.164 value; see `MForm` */
|
|
58
|
+
rules?: ValidationRule | ValidationRule[]
|
|
59
|
+
/** When the rules are checked and shown: on leaving the field (default), while typing, or only on submit */
|
|
60
|
+
validateOn?: ValidateOn
|
|
61
|
+
/** Wait this long (ms) after the value stops changing before re-checking (one request for an async rule, not one per key). Defaults to its `MForm`'s */
|
|
62
|
+
validateDebounce?: number
|
|
63
|
+
/** The key of this field in its `MForm` */
|
|
64
|
+
name?: string
|
|
54
65
|
/** Hint text below the field */
|
|
55
66
|
hint?: string
|
|
56
67
|
/** Disables the field */
|
|
57
68
|
disabled?: boolean
|
|
58
69
|
/** Marks as required — adds a red asterisk after the label */
|
|
59
70
|
required?: boolean
|
|
60
|
-
/** After leaving the field, show an error when the number doesn't fit its country's length */
|
|
71
|
+
/** After leaving the field, show an error when the number doesn't fit its country's length (and block an `MForm`'s submit) */
|
|
61
72
|
validate?: boolean
|
|
62
73
|
/** Placeholder; defaults to an example in the country's format */
|
|
63
74
|
placeholder?: string
|
|
@@ -75,6 +86,7 @@ const emit = defineEmits<{
|
|
|
75
86
|
'update:modelValue': [string | null]
|
|
76
87
|
'update:country': [string]
|
|
77
88
|
'update:valid': [boolean]
|
|
89
|
+
blur: []
|
|
78
90
|
}>()
|
|
79
91
|
|
|
80
92
|
const t = useLocale()
|
|
@@ -132,7 +144,6 @@ const examplePlaceholder = computed(() => {
|
|
|
132
144
|
|
|
133
145
|
// ── Typing ────────────────────────────────────────────────────────
|
|
134
146
|
const inputEl = ref<HTMLInputElement>()
|
|
135
|
-
const touched = ref(false)
|
|
136
147
|
|
|
137
148
|
// Puts the caret after the n-th digit of the formatted text, so reformatting doesn't throw it to the end
|
|
138
149
|
function caretAfterDigits(text: string, n: number) {
|
|
@@ -188,9 +199,30 @@ function onKeydown(e: KeyboardEvent) {
|
|
|
188
199
|
commit(digits.slice(0, digitsBefore - 1) + digits.slice(digitsBefore), digitsBefore - 1)
|
|
189
200
|
}
|
|
190
201
|
|
|
191
|
-
|
|
192
|
-
const
|
|
193
|
-
const
|
|
202
|
+
// The number's own check (`validate`) is one more rule, after the consumer's
|
|
203
|
+
const phoneRule: ValidationRule = () => !props.validate || !national.value || valid.value || props.errorLabel || t.phoneInvalid
|
|
204
|
+
const inForm = !!inject(FORM_KEY, null)
|
|
205
|
+
const rootEl = ref<HTMLElement | null>(null)
|
|
206
|
+
const validation = useFieldValidation({
|
|
207
|
+
value: () => props.modelValue,
|
|
208
|
+
rules: () => [...(props.rules ? (Array.isArray(props.rules) ? props.rules : [props.rules]) : []), phoneRule],
|
|
209
|
+
// phoneRule is always there: `required` alone (no MForm, no rules) still only shows the asterisk
|
|
210
|
+
required: () => props.required && (inForm || !!props.rules),
|
|
211
|
+
error: () => props.error,
|
|
212
|
+
errorLabel: () => props.errorLabel,
|
|
213
|
+
name: () => props.name,
|
|
214
|
+
validateOn: () => props.validateOn,
|
|
215
|
+
validateDebounce: () => props.validateDebounce,
|
|
216
|
+
disabled: () => props.disabled,
|
|
217
|
+
focus: () => inputEl.value?.focus(),
|
|
218
|
+
el: () => inputEl.value,
|
|
219
|
+
setValue: (v) => emit('update:modelValue', (v as string | null) ?? null),
|
|
220
|
+
})
|
|
221
|
+
/** Its own `disabled` or its MForm's */
|
|
222
|
+
const isDisabled = validation.disabled
|
|
223
|
+
const isError = validation.hasError
|
|
224
|
+
const errorText = validation.message
|
|
225
|
+
const messageId = validation.messageId
|
|
194
226
|
|
|
195
227
|
// ── Country list ──────────────────────────────────────────────────
|
|
196
228
|
const open = ref(false)
|
|
@@ -258,7 +290,7 @@ function place() {
|
|
|
258
290
|
}
|
|
259
291
|
|
|
260
292
|
async function openList() {
|
|
261
|
-
if (
|
|
293
|
+
if (isDisabled.value) return
|
|
262
294
|
open.value = true
|
|
263
295
|
search.value = ''
|
|
264
296
|
await nextTick()
|
|
@@ -320,15 +352,25 @@ onBeforeUnmount(() => {
|
|
|
320
352
|
document.removeEventListener('mousedown', onDocDown)
|
|
321
353
|
})
|
|
322
354
|
|
|
355
|
+
// Last: it watches `open`, declared above
|
|
356
|
+
const onFocusOut = useFocusLeave(() => rootEl.value, () => {
|
|
357
|
+
validation.onBlur()
|
|
358
|
+
emit('blur')
|
|
359
|
+
}, () => open.value)
|
|
360
|
+
|
|
323
361
|
defineExpose({
|
|
324
362
|
focus: (options?: FocusOptions) => inputEl.value?.focus(options),
|
|
363
|
+
/** Checks its rules (and the number's length) and shows the result; resolves to whether they pass */
|
|
364
|
+
validate: validation.validate,
|
|
365
|
+
/** Hides its validation error (until the next check) */
|
|
366
|
+
resetValidation: validation.resetValidation,
|
|
325
367
|
/** Whether the number fits its country's length */
|
|
326
368
|
valid,
|
|
327
369
|
})
|
|
328
370
|
</script>
|
|
329
371
|
|
|
330
372
|
<template>
|
|
331
|
-
<div class="m3-phone-input flex flex-col gap-1">
|
|
373
|
+
<div ref="rootEl" class="m3-phone-input flex flex-col gap-1" @focusout="onFocusOut">
|
|
332
374
|
<div
|
|
333
375
|
ref="fieldEl"
|
|
334
376
|
class="group relative flex h-14 transition-[border-color,border-width] duration-150"
|
|
@@ -336,7 +378,7 @@ defineExpose({
|
|
|
336
378
|
variant === 'outlined'
|
|
337
379
|
? [
|
|
338
380
|
'mt-2 items-center rounded-xs border',
|
|
339
|
-
|
|
381
|
+
isDisabled
|
|
340
382
|
? 'border-on-surface/12'
|
|
341
383
|
: isError
|
|
342
384
|
? 'border-error focus-within:border-2 focus-within:border-error'
|
|
@@ -344,7 +386,7 @@ defineExpose({
|
|
|
344
386
|
]
|
|
345
387
|
: [
|
|
346
388
|
'items-end rounded-t-xs border-b bg-surface-container-highest pb-2',
|
|
347
|
-
|
|
389
|
+
isDisabled
|
|
348
390
|
? 'border-b-on-surface/38 bg-[color-mix(in_srgb,var(--color-on-surface)_4%,var(--color-surface-container-highest))]'
|
|
349
391
|
: isError
|
|
350
392
|
? 'border-b-error focus-within:border-b-2 focus-within:border-b-error'
|
|
@@ -359,7 +401,7 @@ defineExpose({
|
|
|
359
401
|
class="pointer-events-none absolute truncate text-label-small"
|
|
360
402
|
:class="[
|
|
361
403
|
variant === 'outlined' ? 'left-3 -top-2.5 max-w-[calc(100%-1.5rem)] bg-[var(--field-bg)] px-1' : 'left-4 top-2 right-4',
|
|
362
|
-
|
|
404
|
+
isDisabled ? 'text-on-surface/38' : isError ? 'text-error' : 'text-on-surface-variant group-focus-within:text-primary',
|
|
363
405
|
]"
|
|
364
406
|
>
|
|
365
407
|
{{ label }}<span v-if="required" class="text-error"> *</span>
|
|
@@ -371,7 +413,7 @@ defineExpose({
|
|
|
371
413
|
type="button"
|
|
372
414
|
class="m3-phone-country ml-1 flex h-8 shrink-0 cursor-pointer items-center gap-1 rounded-full pr-1 pl-3 text-body-large text-on-surface outline-none transition-colors hover:bg-on-surface/8 focus-visible:ring-2 focus-visible:ring-secondary disabled:cursor-not-allowed disabled:text-on-surface/38"
|
|
373
415
|
:class="variant === 'filled' && '-mb-1'"
|
|
374
|
-
:disabled="
|
|
416
|
+
:disabled="isDisabled"
|
|
375
417
|
:aria-label="`${t.phoneCountry}: ${nameOf(country.iso2)} +${country.dial}`"
|
|
376
418
|
aria-haspopup="listbox"
|
|
377
419
|
:aria-expanded="open"
|
|
@@ -392,20 +434,20 @@ defineExpose({
|
|
|
392
434
|
inputmode="tel"
|
|
393
435
|
autocomplete="tel"
|
|
394
436
|
:value="display"
|
|
395
|
-
:disabled="
|
|
437
|
+
:disabled="isDisabled"
|
|
396
438
|
:required="required"
|
|
397
439
|
:placeholder="placeholder ?? examplePlaceholder"
|
|
398
440
|
:aria-invalid="isError || undefined"
|
|
441
|
+
:aria-describedby="errorText || hint ? messageId : undefined"
|
|
399
442
|
class="min-w-0 flex-1 bg-transparent pr-4 pl-1 text-body-large text-on-surface outline-none placeholder:text-on-surface-variant/60 disabled:cursor-not-allowed disabled:text-on-surface/38"
|
|
400
443
|
:class="isError ? 'caret-error' : 'caret-primary'"
|
|
401
444
|
@input="onInput"
|
|
402
445
|
@keydown="onKeydown"
|
|
403
|
-
@blur="touched = true"
|
|
404
446
|
/>
|
|
405
447
|
</div>
|
|
406
448
|
|
|
407
|
-
<p v-if="
|
|
408
|
-
<p v-else-if="hint" class="px-4 text-body-small text-on-surface-variant">{{ hint }}</p>
|
|
449
|
+
<p v-if="errorText" :id="messageId" role="alert" class="px-4 text-body-small text-error">{{ errorText }}</p>
|
|
450
|
+
<p v-else-if="hint" :id="messageId" class="px-4 text-body-small text-on-surface-variant">{{ hint }}</p>
|
|
409
451
|
|
|
410
452
|
<!-- Country list: a menu surface (surface-container, elevation 2) with a search field on top -->
|
|
411
453
|
<Teleport to="body">
|