@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,287 @@
|
|
|
1
|
+
import { computed, inject, nextTick, onBeforeUnmount, onMounted, ref, useId, watch, type InjectionKey } from 'vue'
|
|
2
|
+
import { useLocale } from './useLocale'
|
|
3
|
+
import { REQUIRED_RULE, isEmpty, runRules, type ValidateOn, type ValidationRule } from './validation'
|
|
4
|
+
|
|
5
|
+
/** @internal What a field registers with its `MForm` */
|
|
6
|
+
export interface FormField {
|
|
7
|
+
name: () => string | undefined
|
|
8
|
+
value: () => unknown
|
|
9
|
+
/** Checks the rules, shows the result, resolves to whether its own rules pass */
|
|
10
|
+
validate: () => Promise<boolean>
|
|
11
|
+
resetValidation: () => void
|
|
12
|
+
reset: () => Promise<void>
|
|
13
|
+
focus: () => void
|
|
14
|
+
el: () => Element | null | undefined
|
|
15
|
+
/** The message on display, if any */
|
|
16
|
+
error: () => string | null
|
|
17
|
+
/** Whether its rules pass right now (checked silently, whether or not it's shown yet) */
|
|
18
|
+
valid: () => boolean
|
|
19
|
+
pending: () => boolean
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** @internal Provided by `MForm` */
|
|
23
|
+
export interface FormContext {
|
|
24
|
+
register: (field: FormField) => () => void
|
|
25
|
+
/** Every named field's value, by name */
|
|
26
|
+
values: () => Record<string, unknown>
|
|
27
|
+
/** An error given from outside (`MForm`'s `errors` prop) */
|
|
28
|
+
externalError: (name: string) => string | null
|
|
29
|
+
hasSchema: () => boolean
|
|
30
|
+
/** The form schema's first issue for this field */
|
|
31
|
+
schemaError: (name: string) => Promise<string | null>
|
|
32
|
+
validateOn: () => ValidateOn | undefined
|
|
33
|
+
/** Default debounce (ms) for re-checks while the value changes */
|
|
34
|
+
validateDebounce: () => number | undefined
|
|
35
|
+
/** The `errors` object itself: a new one (a new server response) shows its errors again */
|
|
36
|
+
externalErrorsKey: () => unknown
|
|
37
|
+
/** Keep an outside error after its field changes, instead of hiding it */
|
|
38
|
+
keepErrors: () => boolean
|
|
39
|
+
disabled: () => boolean
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** @internal */
|
|
43
|
+
export const FORM_KEY: InjectionKey<FormContext> = Symbol('m3-form')
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* @internal "Blur" for a field made of several focusable parts (stepper buttons, chips, a popup panel): calls
|
|
47
|
+
* `onLeave` once focus has left `root` for good, not while it moves between its parts or while `open` (its
|
|
48
|
+
* teleported panel, which sits outside `root` in the DOM) is showing. Closing the panel with focus outside
|
|
49
|
+
* counts as leaving. Bind the returned handler to the root's `@focusout`.
|
|
50
|
+
*/
|
|
51
|
+
export function useFocusLeave(root: () => Element | null | undefined, onLeave: () => void, open?: () => boolean) {
|
|
52
|
+
function check() {
|
|
53
|
+
if (open?.()) return
|
|
54
|
+
const r = root()
|
|
55
|
+
const active = document.activeElement
|
|
56
|
+
if (r && active && r.contains(active)) return
|
|
57
|
+
onLeave()
|
|
58
|
+
}
|
|
59
|
+
if (open) watch(open, (now, was) => { if (!now && was) setTimeout(check) })
|
|
60
|
+
// Focus lands on its next element after focusout: look once it has
|
|
61
|
+
return () => { setTimeout(check) }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface FieldValidationOptions {
|
|
65
|
+
value: () => unknown
|
|
66
|
+
rules: () => ValidationRule | ValidationRule[] | undefined
|
|
67
|
+
required: () => boolean | undefined
|
|
68
|
+
error: () => boolean | string | undefined
|
|
69
|
+
errorLabel: () => string | undefined
|
|
70
|
+
name: () => string | undefined
|
|
71
|
+
validateOn: () => ValidateOn | undefined
|
|
72
|
+
/** Wait this long (ms) after the value stops changing before re-checking (async rules: one request, not one per key) */
|
|
73
|
+
validateDebounce?: () => number | undefined
|
|
74
|
+
disabled: () => boolean | undefined
|
|
75
|
+
focus: () => void
|
|
76
|
+
el: () => Element | null | undefined
|
|
77
|
+
/** Writes a value back through v-model (used by `MForm`'s `reset()`) */
|
|
78
|
+
setValue?: (value: unknown) => void
|
|
79
|
+
/** What "not filled in" means for `required`, when `isEmpty` isn't it (a date range needs both ends) */
|
|
80
|
+
isEmpty?: (value: unknown) => boolean
|
|
81
|
+
/** Called when the field is validated on demand (`validate()`, an `MForm` submit), to reveal sub-parts' own errors */
|
|
82
|
+
onValidate?: () => void
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* @internal The validation every form field shares: its own `rules` (plus `required` inside an `MForm` or
|
|
87
|
+
* next to other rules), errors from outside (the `error` prop, `MForm`'s `errors`, its `schema`), when to show
|
|
88
|
+
* them (`validateOn`), and registration with the surrounding `MForm`.
|
|
89
|
+
*
|
|
90
|
+
* Priority of what's shown: a string `error` → `error: true` with `errorLabel` → `MForm`'s `errors[name]`
|
|
91
|
+
* → the field's own rules.
|
|
92
|
+
*/
|
|
93
|
+
export function useFieldValidation(opts: FieldValidationOptions) {
|
|
94
|
+
const form = inject(FORM_KEY, null)
|
|
95
|
+
const locale = useLocale()
|
|
96
|
+
const messageId = useId()
|
|
97
|
+
|
|
98
|
+
const disabled = computed(() => !!opts.disabled() || !!form?.disabled())
|
|
99
|
+
|
|
100
|
+
const ruleList = computed<ValidationRule[]>(() => {
|
|
101
|
+
const r = opts.rules()
|
|
102
|
+
const list = r ? (Array.isArray(r) ? r : [r]) : []
|
|
103
|
+
// `required` only validates where validation is in use, so a plain field keeps today's behavior
|
|
104
|
+
// (just the asterisk and the native attribute)
|
|
105
|
+
const empty = opts.isEmpty ?? isEmpty
|
|
106
|
+
// A `required()` in the rules: use the field's own "empty" with its message, instead of a second check
|
|
107
|
+
const own = list.map((r) => {
|
|
108
|
+
const mark = (r as any)?.[REQUIRED_RULE]
|
|
109
|
+
if (mark === undefined || !opts.isEmpty) return r
|
|
110
|
+
const fieldRequired: ValidationRule = (value, { locale }) => !empty(value) || (typeof mark === 'string' ? mark : locale.validationRequired)
|
|
111
|
+
;(fieldRequired as any)[REQUIRED_RULE] = mark
|
|
112
|
+
return fieldRequired
|
|
113
|
+
})
|
|
114
|
+
if (!(opts.required() && (form || own.length))) return own
|
|
115
|
+
if (own.some((r) => (r as any)?.[REQUIRED_RULE] !== undefined)) return own
|
|
116
|
+
const required: ValidationRule = (value, { locale }) => !empty(value) || locale.validationRequired
|
|
117
|
+
return [required, ...own]
|
|
118
|
+
})
|
|
119
|
+
const active = computed(() => ruleList.value.length > 0 || (!!form && !!opts.name() && form.hasSchema()))
|
|
120
|
+
|
|
121
|
+
/** The rules' verdict, kept up to date silently; only displayed once `shown` */
|
|
122
|
+
const result = ref<string | null>(null)
|
|
123
|
+
const shown = ref(false)
|
|
124
|
+
const pending = ref(false)
|
|
125
|
+
/** Names of other fields the rules read through `ctx.values` (e.g. `sameAs('password')`) */
|
|
126
|
+
const deps = ref<string[]>([])
|
|
127
|
+
let token = 0
|
|
128
|
+
|
|
129
|
+
async function run(): Promise<string | null> {
|
|
130
|
+
const t = ++token
|
|
131
|
+
if (disabled.value || !active.value) {
|
|
132
|
+
result.value = null
|
|
133
|
+
pending.value = false
|
|
134
|
+
return null
|
|
135
|
+
}
|
|
136
|
+
pending.value = true
|
|
137
|
+
const read = new Set<string>()
|
|
138
|
+
const all = form?.values() ?? {}
|
|
139
|
+
const values = new Proxy(all, {
|
|
140
|
+
get(target, key) {
|
|
141
|
+
if (typeof key === 'string') read.add(key)
|
|
142
|
+
return Reflect.get(target, key)
|
|
143
|
+
},
|
|
144
|
+
})
|
|
145
|
+
let message: string | null = null
|
|
146
|
+
try {
|
|
147
|
+
message = await runRules(ruleList.value, opts.value(), { locale, values })
|
|
148
|
+
const name = opts.name()
|
|
149
|
+
if (!message && form && name && form.hasSchema()) message = await form.schemaError(name)
|
|
150
|
+
} catch (e) {
|
|
151
|
+
console.error('[m3ui] a validation rule threw:', e)
|
|
152
|
+
}
|
|
153
|
+
if (t === token) {
|
|
154
|
+
result.value = message
|
|
155
|
+
pending.value = false
|
|
156
|
+
const next = [...read]
|
|
157
|
+
// Only a real change: a new array every run would re-trigger the deps watcher below, forever
|
|
158
|
+
if (next.length !== deps.value.length || next.some((k, i) => k !== deps.value[i])) deps.value = next
|
|
159
|
+
}
|
|
160
|
+
return message
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const mode = () => opts.validateOn() ?? form?.validateOn() ?? 'blur'
|
|
164
|
+
let resetting = false
|
|
165
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
166
|
+
const debounceMs = () => opts.validateDebounce?.() ?? form?.validateDebounce() ?? 0
|
|
167
|
+
/** Re-checks now, or after the debounce while the value keeps changing (pending meanwhile) */
|
|
168
|
+
function schedule() {
|
|
169
|
+
clearTimeout(timer)
|
|
170
|
+
const ms = debounceMs()
|
|
171
|
+
if (ms <= 0 || !active.value || disabled.value) return run()
|
|
172
|
+
pending.value = true
|
|
173
|
+
token++ // a check already running is stale now
|
|
174
|
+
timer = setTimeout(run, ms)
|
|
175
|
+
}
|
|
176
|
+
onBeforeUnmount(() => clearTimeout(timer))
|
|
177
|
+
|
|
178
|
+
/** An outside error (MForm `errors`) hides once its field changes, until a new `errors` object comes */
|
|
179
|
+
const dismissed = ref(false)
|
|
180
|
+
if (form) watch(() => form.externalErrorsKey(), () => (dismissed.value = false))
|
|
181
|
+
|
|
182
|
+
watch(opts.value, () => {
|
|
183
|
+
if (mode() === 'input' && !resetting) shown.value = true
|
|
184
|
+
if (form && !form.keepErrors() && !resetting) dismissed.value = true
|
|
185
|
+
schedule()
|
|
186
|
+
}, { deep: true })
|
|
187
|
+
// Not the rules array itself: an inline `:rules="[...]"` is a new array on every render of the parent, and
|
|
188
|
+
// re-checking then would re-run every field's (async) rules on any keystroke anywhere. Its length changes when
|
|
189
|
+
// rules are really swapped (`:rules="company ? [required()] : []"`); `required` and `disabled` are watched too
|
|
190
|
+
watch([() => ruleList.value.length, () => !!opts.required(), disabled], () => run())
|
|
191
|
+
// Cross-field rules: re-check when a field they read changes, but only once this one is on display
|
|
192
|
+
// (compared value by value: the getter returns a new array whenever any field of the form changes)
|
|
193
|
+
watch(
|
|
194
|
+
() => (form ? deps.value.map((k) => form.values()[k]) : []),
|
|
195
|
+
(now, before) => {
|
|
196
|
+
const changed = now.length !== before.length || now.some((v, i) => !Object.is(v, before[i]))
|
|
197
|
+
if (changed && shown.value) run()
|
|
198
|
+
},
|
|
199
|
+
)
|
|
200
|
+
onMounted(run)
|
|
201
|
+
|
|
202
|
+
function onBlur() {
|
|
203
|
+
if (mode() !== 'submit') shown.value = true
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async function validate(): Promise<boolean> {
|
|
207
|
+
clearTimeout(timer)
|
|
208
|
+
shown.value = true
|
|
209
|
+
opts.onValidate?.()
|
|
210
|
+
return !(await run())
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function resetValidation() {
|
|
214
|
+
clearTimeout(timer)
|
|
215
|
+
token++
|
|
216
|
+
shown.value = false
|
|
217
|
+
pending.value = false
|
|
218
|
+
run()
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const initial = (() => {
|
|
222
|
+
const v = opts.value()
|
|
223
|
+
return Array.isArray(v) ? [...v] : v
|
|
224
|
+
})()
|
|
225
|
+
|
|
226
|
+
async function reset() {
|
|
227
|
+
if (opts.setValue) {
|
|
228
|
+
resetting = true
|
|
229
|
+
opts.setValue(Array.isArray(initial) ? [...initial] : initial)
|
|
230
|
+
await nextTick()
|
|
231
|
+
resetting = false
|
|
232
|
+
}
|
|
233
|
+
resetValidation()
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const external = computed(() => {
|
|
237
|
+
const name = opts.name()
|
|
238
|
+
return form && name && !dismissed.value ? form.externalError(name) : null
|
|
239
|
+
})
|
|
240
|
+
const own = computed(() => (shown.value ? result.value : null))
|
|
241
|
+
|
|
242
|
+
/** The message to show under the field (null = none) */
|
|
243
|
+
const message = computed<string | null>(() => {
|
|
244
|
+
const e = opts.error()
|
|
245
|
+
if (typeof e === 'string' && e) return e
|
|
246
|
+
if (e === true) return opts.errorLabel() || own.value || external.value
|
|
247
|
+
return external.value || own.value
|
|
248
|
+
})
|
|
249
|
+
const hasError = computed(() => !!opts.error() || !!external.value || !!own.value)
|
|
250
|
+
|
|
251
|
+
if (form) {
|
|
252
|
+
let unregister: (() => void) | undefined
|
|
253
|
+
onMounted(() => {
|
|
254
|
+
unregister = form.register({
|
|
255
|
+
name: opts.name,
|
|
256
|
+
value: opts.value,
|
|
257
|
+
validate,
|
|
258
|
+
resetValidation,
|
|
259
|
+
reset,
|
|
260
|
+
focus: opts.focus,
|
|
261
|
+
el: opts.el,
|
|
262
|
+
error: () => (hasError.value ? message.value ?? '' : null),
|
|
263
|
+
valid: () => !result.value && !pending.value,
|
|
264
|
+
pending: () => pending.value,
|
|
265
|
+
})
|
|
266
|
+
})
|
|
267
|
+
onBeforeUnmount(() => unregister?.())
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
return {
|
|
271
|
+
/** Error state (red border/label) */
|
|
272
|
+
hasError,
|
|
273
|
+
/** Message under the field, or null */
|
|
274
|
+
message,
|
|
275
|
+
/** id for the message element, to point `aria-describedby` at */
|
|
276
|
+
messageId,
|
|
277
|
+
/** Whether async rules are still running */
|
|
278
|
+
pending,
|
|
279
|
+
/** The field's own disabled state merged with its `MForm`'s */
|
|
280
|
+
disabled,
|
|
281
|
+
/** Call from the field's blur */
|
|
282
|
+
onBlur,
|
|
283
|
+
validate,
|
|
284
|
+
resetValidation,
|
|
285
|
+
reset,
|
|
286
|
+
}
|
|
287
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { LngLat } from './_mapGeometry'
|
|
2
|
+
|
|
3
|
+
/** A route between waypoints, as a routing service returns it. */
|
|
4
|
+
export interface MapRouteResult {
|
|
5
|
+
/** The road to follow, `[lng, lat][]`: the streets' real shape (curves, roundabouts), one-way streets respected */
|
|
6
|
+
path: LngLat[]
|
|
7
|
+
/** Length in meters */
|
|
8
|
+
distance: number
|
|
9
|
+
/** Expected travel time in seconds */
|
|
10
|
+
duration: number
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Where `MMapRoute` gets its road from when you give it `stops` but no `path`: any function from waypoints to a route.
|
|
15
|
+
* `osrmRouteProvider()` ships; GraphHopper, Valhalla, OpenRouteService, Mapbox Directions or your own backend fit
|
|
16
|
+
* the same shape. Gets an `AbortSignal`: a newer request cancels the older one.
|
|
17
|
+
*/
|
|
18
|
+
export type MapRouteProvider = (waypoints: LngLat[], options: { signal?: AbortSignal }) => Promise<MapRouteResult>
|
|
19
|
+
|
|
20
|
+
export interface OsrmRouteOptions {
|
|
21
|
+
/**
|
|
22
|
+
* The OSRM server. Defaults to the project's public demo server, which is meant for light use only (see its usage
|
|
23
|
+
* policy): run your own (`osrm-backend` in Docker) or use a hosted one in production
|
|
24
|
+
*/
|
|
25
|
+
url?: string
|
|
26
|
+
/** The routing profile in the URL: `driving` (the demo server has only this one), `cycling`, `walking`, or your server's own */
|
|
27
|
+
profile?: string
|
|
28
|
+
/** More query parameters for OSRM (`exclude=toll`, `alternatives`…) */
|
|
29
|
+
params?: Record<string, string>
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Routes through an OSRM server (Open Source Routing Machine, on OpenStreetMap data): the path follows the streets
|
|
34
|
+
* as they are, and the car profile respects one-way streets and turn restrictions. Available from the `/map` entry
|
|
35
|
+
* point.
|
|
36
|
+
*/
|
|
37
|
+
export function osrmRouteProvider(options: OsrmRouteOptions = {}): MapRouteProvider {
|
|
38
|
+
const url = (options.url ?? 'https://router.project-osrm.org').replace(/\/$/, '')
|
|
39
|
+
const profile = options.profile ?? 'driving'
|
|
40
|
+
return async (waypoints, { signal }) => {
|
|
41
|
+
if (waypoints.length < 2) return { path: [...waypoints], distance: 0, duration: 0 }
|
|
42
|
+
const coords = waypoints.map(([lng, lat]) => `${lng},${lat}`).join(';')
|
|
43
|
+
const query = new URLSearchParams({ overview: 'full', geometries: 'geojson', ...options.params })
|
|
44
|
+
const res = await fetch(`${url}/route/v1/${profile}/${coords}?${query}`, { signal })
|
|
45
|
+
if (!res.ok) throw new Error(`OSRM ${res.status}`)
|
|
46
|
+
const data = (await res.json()) as {
|
|
47
|
+
code: string
|
|
48
|
+
message?: string
|
|
49
|
+
routes?: { geometry: { coordinates: LngLat[] }; distance: number; duration: number }[]
|
|
50
|
+
}
|
|
51
|
+
const route = data.routes?.[0]
|
|
52
|
+
if (data.code !== 'Ok' || !route) throw new Error(`OSRM: ${data.message ?? data.code}`)
|
|
53
|
+
return { path: route.geometry.coordinates, distance: route.distance, duration: route.duration }
|
|
54
|
+
}
|
|
55
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// Writing filled signature fields into a PDF (MPdfSigner). Uses pdf-lib, an optional peer dependency loaded only
|
|
2
|
+
// when a document is saved
|
|
3
|
+
|
|
4
|
+
/** A field placed on a page to sign or fill */
|
|
5
|
+
export interface PdfSignField {
|
|
6
|
+
id: string
|
|
7
|
+
type: 'signature' | 'initials' | 'name' | 'date' | 'text' | 'checkbox'
|
|
8
|
+
/** 1-based page */
|
|
9
|
+
page: number
|
|
10
|
+
/** Where it is, as fractions (0–1) of the page as shown (its own rotation included): left, top, width, height */
|
|
11
|
+
x: number
|
|
12
|
+
y: number
|
|
13
|
+
width: number
|
|
14
|
+
height: number
|
|
15
|
+
/** What it asks for (shown in the empty field, and to screen readers) */
|
|
16
|
+
label?: string
|
|
17
|
+
/** Must be filled before the document is complete. Default true for signature fields */
|
|
18
|
+
required?: boolean
|
|
19
|
+
/** Who fills it, for documents several people sign; `signer` on MPdfSigner picks whose fields are active */
|
|
20
|
+
signer?: string
|
|
21
|
+
/** What it holds: a PNG data URL for a signature or initials, text otherwise, `'true'` for a ticked checkbox */
|
|
22
|
+
value?: string
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Whether a field needs filling and is empty */
|
|
26
|
+
export const fieldMissing = (f: PdfSignField) => (f.required ?? (f.type === 'signature' || f.type === 'initials')) && !f.value
|
|
27
|
+
|
|
28
|
+
type Rect = { x: number; y: number; width: number; height: number }
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* A rectangle on the page as shown (top-left origin, y down, in points) to PDF user space (bottom-left origin):
|
|
32
|
+
* where to anchor something drawn upright on screen, and the rotation to draw it with, for a page with its own
|
|
33
|
+
* `/Rotate` and a crop box. `box` is the crop box, `rotate` the page's rotation in degrees
|
|
34
|
+
*/
|
|
35
|
+
export function shownToUser(r: Rect, box: Rect, rotate: number): { x: number; y: number; rotate: number } {
|
|
36
|
+
const rot = ((rotate % 360) + 360) % 360
|
|
37
|
+
// The shown rectangle's bottom-left corner, mapped back into the unrotated page
|
|
38
|
+
const sx = r.x
|
|
39
|
+
const sy = r.y + r.height
|
|
40
|
+
let ux: number
|
|
41
|
+
let uy: number
|
|
42
|
+
if (rot === 90) { ux = sy; uy = sx }
|
|
43
|
+
else if (rot === 180) { ux = box.width - sx; uy = sy }
|
|
44
|
+
else if (rot === 270) { ux = box.width - sy; uy = box.height - sx }
|
|
45
|
+
else { ux = sx; uy = box.height - sy }
|
|
46
|
+
return { x: box.x + ux, y: box.y + uy, rotate: rot }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Draws a field's value into a PNG (text in the page's font stack; any script works, unlike PDF standard fonts) */
|
|
50
|
+
async function fieldImage(f: PdfSignField, wPt: number, hPt: number, font: string): Promise<Uint8Array | null> {
|
|
51
|
+
if (!f.value) return null
|
|
52
|
+
if ((f.type === 'signature' || f.type === 'initials') && f.value.startsWith('data:image/png')) return dataUrlBytes(f.value)
|
|
53
|
+
const ratio = 4 // px per point: sharp when printed
|
|
54
|
+
const canvas = document.createElement('canvas')
|
|
55
|
+
canvas.width = Math.max(1, Math.round(wPt * ratio))
|
|
56
|
+
canvas.height = Math.max(1, Math.round(hPt * ratio))
|
|
57
|
+
const ctx = canvas.getContext('2d')
|
|
58
|
+
if (!ctx) return null
|
|
59
|
+
ctx.fillStyle = '#111'
|
|
60
|
+
ctx.textBaseline = 'middle'
|
|
61
|
+
if (f.type === 'checkbox') {
|
|
62
|
+
if (f.value !== 'true') return null
|
|
63
|
+
const s = Math.min(canvas.width, canvas.height)
|
|
64
|
+
ctx.lineWidth = s * 0.12
|
|
65
|
+
ctx.lineCap = 'round'
|
|
66
|
+
ctx.lineJoin = 'round'
|
|
67
|
+
ctx.strokeStyle = '#111'
|
|
68
|
+
ctx.beginPath()
|
|
69
|
+
ctx.moveTo(s * 0.2, s * 0.55)
|
|
70
|
+
ctx.lineTo(s * 0.42, s * 0.76)
|
|
71
|
+
ctx.lineTo(s * 0.82, s * 0.26)
|
|
72
|
+
ctx.stroke()
|
|
73
|
+
} else {
|
|
74
|
+
let size = canvas.height * 0.62
|
|
75
|
+
ctx.font = `${size}px ${font}`
|
|
76
|
+
while (size > 6 && ctx.measureText(f.value).width > canvas.width * 0.96) {
|
|
77
|
+
size *= 0.92
|
|
78
|
+
ctx.font = `${size}px ${font}`
|
|
79
|
+
}
|
|
80
|
+
ctx.fillText(f.value, canvas.width * 0.02, canvas.height / 2)
|
|
81
|
+
}
|
|
82
|
+
const blob = await new Promise<Blob | null>((res) => canvas.toBlob(res, 'image/png'))
|
|
83
|
+
return blob ? new Uint8Array(await blob.arrayBuffer()) : null
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function dataUrlBytes(url: string): Uint8Array {
|
|
87
|
+
const b64 = url.slice(url.indexOf(',') + 1)
|
|
88
|
+
const bin = atob(b64)
|
|
89
|
+
const out = new Uint8Array(bin.length)
|
|
90
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
|
|
91
|
+
return out
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface SignPdfOptions {
|
|
95
|
+
/** The font for text fields (a CSS font list). Default the page's sans-serif */
|
|
96
|
+
font?: string
|
|
97
|
+
/** Written into the document's metadata */
|
|
98
|
+
producer?: string
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Writes the filled fields into a copy of the PDF and returns its bytes: signatures and initials as the images
|
|
103
|
+
* drawn, text, dates and ticks drawn the same way. A visual signature (what an e-signature flow shows and prints),
|
|
104
|
+
* not a cryptographic one: for a certificate-based digital signature (PAdES), sign the result on your server.
|
|
105
|
+
* Needs the `pdf-lib` package
|
|
106
|
+
*/
|
|
107
|
+
export async function signPdf(pdf: ArrayBuffer | Uint8Array, fields: PdfSignField[], options: SignPdfOptions = {}): Promise<Uint8Array> {
|
|
108
|
+
const { PDFDocument, degrees } = await import('pdf-lib')
|
|
109
|
+
const doc = await PDFDocument.load(pdf)
|
|
110
|
+
const pages = doc.getPages()
|
|
111
|
+
const font = options.font ?? 'system-ui, sans-serif'
|
|
112
|
+
for (const f of fields) {
|
|
113
|
+
const page = pages[f.page - 1]
|
|
114
|
+
if (!page || !f.value) continue
|
|
115
|
+
const box = page.getCropBox()
|
|
116
|
+
const rot = page.getRotation().angle
|
|
117
|
+
const swap = ((rot % 180) + 180) % 180 !== 0
|
|
118
|
+
const shownW = swap ? box.height : box.width
|
|
119
|
+
const shownH = swap ? box.width : box.height
|
|
120
|
+
const rect = { x: f.x * shownW, y: f.y * shownH, width: f.width * shownW, height: f.height * shownH }
|
|
121
|
+
const png = await fieldImage(f, rect.width, rect.height, font)
|
|
122
|
+
if (!png) continue
|
|
123
|
+
const image = await doc.embedPng(png)
|
|
124
|
+
// Signatures keep their shape, centered in the field
|
|
125
|
+
let { width, height } = rect
|
|
126
|
+
let dx = 0
|
|
127
|
+
let dy = 0
|
|
128
|
+
if (f.type === 'signature' || f.type === 'initials') {
|
|
129
|
+
const s = Math.min(rect.width / image.width, rect.height / image.height)
|
|
130
|
+
width = image.width * s
|
|
131
|
+
height = image.height * s
|
|
132
|
+
dx = (rect.width - width) / 2
|
|
133
|
+
dy = (rect.height - height) / 2
|
|
134
|
+
}
|
|
135
|
+
const at = shownToUser({ x: rect.x + dx, y: rect.y + dy, width, height }, { x: box.x, y: box.y, width: box.width, height: box.height }, rot)
|
|
136
|
+
page.drawImage(image, { x: at.x, y: at.y, width, height, rotate: degrees(at.rotate) })
|
|
137
|
+
}
|
|
138
|
+
if (options.producer) doc.setProducer(options.producer)
|
|
139
|
+
doc.setModificationDate(new Date())
|
|
140
|
+
return doc.save()
|
|
141
|
+
}
|