@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.
Files changed (191) hide show
  1. package/dist/API.md +1224 -28
  2. package/dist/{MColorPickerModal-NtkihoK6.js → MColorPickerModal-H8nuX0Wu.js} +3 -4
  3. package/dist/{MColorPickerModal-NtkihoK6.js.map → MColorPickerModal-H8nuX0Wu.js.map} +1 -1
  4. package/dist/MDialog-B42Mhn8W.js +331 -0
  5. package/dist/MDialog-B42Mhn8W.js.map +1 -0
  6. package/dist/{MListItem-D2cNUyzP.js → MListItem-DiOAxaN7.js} +431 -325
  7. package/dist/MListItem-DiOAxaN7.js.map +1 -0
  8. package/dist/{MLoadingIndicator-DWUj0BAB.js → MLoadingIndicator-CuTZYFFj.js} +2 -2
  9. package/dist/{MLoadingIndicator-DWUj0BAB.js.map → MLoadingIndicator-CuTZYFFj.js.map} +1 -1
  10. package/dist/{MSeekBar-C4cn9RIF.js → MSeekBar-BCDQTx2t.js} +2 -2
  11. package/dist/{MSeekBar-C4cn9RIF.js.map → MSeekBar-BCDQTx2t.js.map} +1 -1
  12. package/dist/MSegmentedButton-BXzRsg1S.js +105 -0
  13. package/dist/MSegmentedButton-BXzRsg1S.js.map +1 -0
  14. package/dist/MSignaturePad-BTqGaPXA.js +313 -0
  15. package/dist/MSignaturePad-BTqGaPXA.js.map +1 -0
  16. package/dist/MSlider-D_O8J9YH.js +739 -0
  17. package/dist/MSlider-D_O8J9YH.js.map +1 -0
  18. package/dist/{MSpinner-DZkXZJpc.js → MSpinner-UCdtSOHP.js} +2 -2
  19. package/dist/{MSpinner-DZkXZJpc.js.map → MSpinner-UCdtSOHP.js.map} +1 -1
  20. package/dist/{MTextField-CNH-byir.js → MTextField-CYk9yFvi.js} +162 -115
  21. package/dist/MTextField-CYk9yFvi.js.map +1 -0
  22. package/dist/_useFieldValidation-B0B44M_t.js +191 -0
  23. package/dist/_useFieldValidation-B0B44M_t.js.map +1 -0
  24. package/dist/api.json +1 -1
  25. package/dist/code-editor.js +184 -103
  26. package/dist/code-editor.js.map +1 -1
  27. package/dist/components/MAddressField.vue.d.ts +18 -3
  28. package/dist/components/MAppBarWithSearch.vue.d.ts +1 -1
  29. package/dist/components/MAudioRecorder.vue.d.ts +2 -2
  30. package/dist/components/MAutocomplete.vue.d.ts +22 -3
  31. package/dist/components/MCheckbox.vue.d.ts +23 -1
  32. package/dist/components/MCodeEditor.vue.d.ts +23 -1
  33. package/dist/components/MColorPicker.vue.d.ts +24 -3
  34. package/dist/components/MConfirmDialog.vue.d.ts +2 -2
  35. package/dist/components/MCountrySelect.vue.d.ts +13 -2
  36. package/dist/components/MCreditCardInput.vue.d.ts +33 -0
  37. package/dist/components/MCronField.vue.d.ts +23 -1
  38. package/dist/components/MDataTable.vue.d.ts +1 -1
  39. package/dist/components/MDatePicker.vue.d.ts +24 -3
  40. package/dist/components/MDateRangePicker.vue.d.ts +24 -3
  41. package/dist/components/MFileUpload.vue.d.ts +23 -2
  42. package/dist/components/MForm.vue.d.ts +61 -0
  43. package/dist/components/MFormBuilder.vue.d.ts +22 -0
  44. package/dist/components/MFormRenderer.vue.d.ts +151 -0
  45. package/dist/components/MJsonEditor.vue.d.ts +23 -1
  46. package/dist/components/MMapRoute.vue.d.ts +176 -0
  47. package/dist/components/MMaskField.vue.d.ts +20 -2
  48. package/dist/components/MMentionField.vue.d.ts +13 -2
  49. package/dist/components/MMultiAutocomplete.vue.d.ts +22 -3
  50. package/dist/components/MMultiSelect.vue.d.ts +22 -3
  51. package/dist/components/MNavigationRail.vue.d.ts +1 -1
  52. package/dist/components/MNotificationCenter.vue.d.ts +2 -2
  53. package/dist/components/MNumberField.vue.d.ts +20 -2
  54. package/dist/components/MPdfSigner.vue.d.ts +499 -0
  55. package/dist/components/MPdfViewer.vue.d.ts +12 -0
  56. package/dist/components/MPhoneInput.vue.d.ts +19 -4
  57. package/dist/components/MPinInput.vue.d.ts +24 -3
  58. package/dist/components/MPosKeypad.vue.d.ts +3 -3
  59. package/dist/components/MRadioGroup.vue.d.ts +23 -1
  60. package/dist/components/MRating.vue.d.ts +23 -1
  61. package/dist/components/MRichTextEditor.vue.d.ts +23 -1
  62. package/dist/components/MSearchBar.vue.d.ts +1 -1
  63. package/dist/components/MSegmentedButton.vue.d.ts +23 -2
  64. package/dist/components/MSelect.vue.d.ts +22 -3
  65. package/dist/components/MSignaturePad.vue.d.ts +19 -0
  66. package/dist/components/MSlider.vue.d.ts +23 -1
  67. package/dist/components/MSpreadsheet.vue.d.ts +137 -0
  68. package/dist/components/MStack.vue.d.ts +1 -1
  69. package/dist/components/MSwitch.vue.d.ts +23 -1
  70. package/dist/components/MTable.vue.d.ts +1 -1
  71. package/dist/components/MTagInput.vue.d.ts +20 -2
  72. package/dist/components/MText.vue.d.ts +1 -1
  73. package/dist/components/MTextField.vue.d.ts +26 -3
  74. package/dist/components/MTimePicker.vue.d.ts +24 -3
  75. package/dist/components/MTimezoneSelect.vue.d.ts +13 -2
  76. package/dist/components/MTour.vue.d.ts +2 -2
  77. package/dist/components/MTrackingTimeline.vue.d.ts +75 -0
  78. package/dist/components/MWindow.vue.d.ts +2 -2
  79. package/dist/composables/_routeGeometry.d.ts +26 -0
  80. package/dist/composables/_useFieldValidation.d.ts +91 -0
  81. package/dist/composables/mapRouting.d.ts +35 -0
  82. package/dist/composables/pdfSign.d.ts +52 -0
  83. package/dist/composables/spreadsheetFormula.d.ts +55 -0
  84. package/dist/composables/useLocale.d.ts +177 -0
  85. package/dist/composables/validation.d.ts +82 -0
  86. package/dist/draw.js +2 -2
  87. package/dist/flow.js +1 -1
  88. package/dist/gantt.js +2 -2
  89. package/dist/index.d.ts +12 -0
  90. package/dist/locales/index.js +693 -7
  91. package/dist/locales/index.js.map +1 -1
  92. package/dist/m3ui-vue.css +1 -1
  93. package/dist/m3ui.js +15507 -12417
  94. package/dist/m3ui.js.map +1 -1
  95. package/dist/map.d.ts +4 -0
  96. package/dist/map.js +1207 -745
  97. package/dist/map.js.map +1 -1
  98. package/dist/media.js +4 -4
  99. package/dist/pdf.d.ts +3 -0
  100. package/dist/pdf.js +1228 -687
  101. package/dist/pdf.js.map +1 -1
  102. package/dist/rich-text-editor.js +188 -146
  103. package/dist/rich-text-editor.js.map +1 -1
  104. package/dist/styles.css +1 -1
  105. package/dist/{useLocale-DaVSTdm0.js → useLocale-DL96OFgr.js} +99 -1
  106. package/dist/useLocale-DL96OFgr.js.map +1 -0
  107. package/package.json +5 -1
  108. package/src/__tests__/MForm.test.ts +325 -0
  109. package/src/__tests__/MFormRenderer.test.ts +157 -0
  110. package/src/__tests__/MMapRoute.test.ts +418 -0
  111. package/src/__tests__/MPdfSigner.test.ts +175 -0
  112. package/src/__tests__/MPhoneInput.test.ts +5 -2
  113. package/src/__tests__/MRichTextEditor.test.ts +2 -1
  114. package/src/__tests__/MSpreadsheet.test.ts +223 -0
  115. package/src/__tests__/MTrackingTimeline.test.ts +66 -0
  116. package/src/__tests__/_fakeMaplibre.ts +4 -1
  117. package/src/__tests__/_osrmRoutes.ts +10 -0
  118. package/src/__tests__/attrsFallthrough.test.ts +11 -0
  119. package/src/__tests__/fieldsValidation.test.ts +229 -0
  120. package/src/__tests__/spreadsheetFormula.test.ts +77 -0
  121. package/src/__tests__/ssr.test.ts +4 -0
  122. package/src/__tests__/validation.test.ts +77 -0
  123. package/src/components/MAddressField.vue +45 -8
  124. package/src/components/MAutocomplete.vue +69 -23
  125. package/src/components/MCheckbox.vue +80 -17
  126. package/src/components/MCodeEditor.vue +59 -2
  127. package/src/components/MColorPicker.vue +65 -16
  128. package/src/components/MCountrySelect.vue +17 -3
  129. package/src/components/MCreditCardInput.vue +76 -7
  130. package/src/components/MCronField.vue +60 -10
  131. package/src/components/MDatePicker.vue +65 -16
  132. package/src/components/MDateRangePicker.vue +66 -16
  133. package/src/components/MFileUpload.vue +71 -8
  134. package/src/components/MForm.vue +208 -0
  135. package/src/components/MFormBuilder.vue +417 -0
  136. package/src/components/MFormRenderer.vue +324 -0
  137. package/src/components/MJsonEditor.vue +57 -3
  138. package/src/components/MMapRoute.vue +523 -0
  139. package/src/components/MMaskField.vue +55 -13
  140. package/src/components/MMentionField.vue +17 -2
  141. package/src/components/MMultiAutocomplete.vue +70 -23
  142. package/src/components/MMultiSelect.vue +70 -23
  143. package/src/components/MNumberField.vue +58 -16
  144. package/src/components/MPdfSigner.vue +433 -0
  145. package/src/components/MPdfViewer.vue +12 -0
  146. package/src/components/MPhoneInput.vue +60 -18
  147. package/src/components/MPinInput.vue +58 -10
  148. package/src/components/MRadioGroup.vue +65 -4
  149. package/src/components/MRating.vue +62 -6
  150. package/src/components/MRichTextEditor.vue +64 -4
  151. package/src/components/MSegmentedButton.vue +59 -2
  152. package/src/components/MSelect.vue +72 -26
  153. package/src/components/MSignaturePad.vue +71 -6
  154. package/src/components/MSlider.vue +61 -10
  155. package/src/components/MSpreadsheet.vue +992 -0
  156. package/src/components/MSwitch.vue +63 -8
  157. package/src/components/MTagInput.vue +67 -25
  158. package/src/components/MTextField.vue +68 -14
  159. package/src/components/MTimePicker.vue +65 -16
  160. package/src/components/MTimezoneSelect.vue +17 -3
  161. package/src/components/MTrackingTimeline.vue +257 -0
  162. package/src/composables/_routeGeometry.ts +140 -0
  163. package/src/composables/_useFieldValidation.ts +287 -0
  164. package/src/composables/mapRouting.ts +55 -0
  165. package/src/composables/pdfSign.ts +141 -0
  166. package/src/composables/spreadsheetFormula.ts +459 -0
  167. package/src/composables/useLocale.ts +277 -0
  168. package/src/composables/validation.ts +178 -0
  169. package/src/index.ts +12 -0
  170. package/src/locales/de.ts +98 -0
  171. package/src/locales/es.ts +105 -7
  172. package/src/locales/fr.ts +98 -0
  173. package/src/locales/ja.ts +98 -0
  174. package/src/locales/ko.ts +98 -0
  175. package/src/locales/pt.ts +98 -0
  176. package/src/locales/zh.ts +98 -0
  177. package/src/map.ts +4 -0
  178. package/src/pdf.ts +3 -0
  179. package/dist/MButton-OQ4wIERQ.js +0 -171
  180. package/dist/MButton-OQ4wIERQ.js.map +0 -1
  181. package/dist/MDialog-DYMnaBlt.js +0 -167
  182. package/dist/MDialog-DYMnaBlt.js.map +0 -1
  183. package/dist/MListItem-D2cNUyzP.js.map +0 -1
  184. package/dist/MProgressBar-BWly1UKN.js +0 -179
  185. package/dist/MProgressBar-BWly1UKN.js.map +0 -1
  186. package/dist/MSegmentedButton-BEB4gXLA.js +0 -64
  187. package/dist/MSegmentedButton-BEB4gXLA.js.map +0 -1
  188. package/dist/MSlider-BIkA6DiE.js +0 -690
  189. package/dist/MSlider-BIkA6DiE.js.map +0 -1
  190. package/dist/MTextField-CNH-byir.js.map +0 -1
  191. package/dist/useLocale-DaVSTdm0.js.map +0 -1
@@ -0,0 +1,418 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2
+ import { flushPromises, mount } from '@vue/test-utils'
3
+ import { h, nextTick, ref } from 'vue'
4
+ import { created, type FakeMap } from './_fakeMaplibre'
5
+ import { bearing, bounds, cumulative, pointAlong, project, projectForward, slicePath } from '../composables/_routeGeometry'
6
+ import { roundabout, roundTrip, costanera, roundaboutMeta } from './_osrmRoutes'
7
+ import { pathLength } from '../composables/_mapGeometry'
8
+ import type { LngLat } from '../composables/_mapGeometry'
9
+
10
+ vi.mock('maplibre-gl', async () => (await import('./_fakeMaplibre')).fakeModule)
11
+
12
+ const { MMap, MMapRoute, osrmRouteProvider } = await import('../map')
13
+
14
+ beforeEach(() => {
15
+ created.maps = []
16
+ created.markers = []
17
+ created.popups = []
18
+ document.documentElement.style.setProperty('--color-primary', '#6750a4')
19
+ document.documentElement.style.setProperty('--color-outline', '#79747e')
20
+ document.documentElement.style.setProperty('--color-surface', '#fef7ff')
21
+ // Reduced motion: moves jump, so tests don't wait for frames
22
+ vi.stubGlobal('matchMedia', (q: string) => ({ matches: q.includes('reduce'), addEventListener() {}, removeEventListener() {} }))
23
+ })
24
+ afterEach(() => {
25
+ document.body.innerHTML = ''
26
+ vi.unstubAllGlobals()
27
+ })
28
+
29
+ // An L: 1 km-ish east, then north
30
+ const path: LngLat[] = [[-64.19, -31.42], [-64.18, -31.42], [-64.18, -31.41]]
31
+
32
+ describe('route geometry', () => {
33
+ const cum = cumulative(path)
34
+
35
+ it('accumulates distances and matches the path length', () => {
36
+ expect(cum[0]).toBe(0)
37
+ expect(cum[2]).toBeCloseTo(pathLength(path), 6)
38
+ })
39
+
40
+ it('walks along the path, with the heading of each leg', () => {
41
+ const half = pointAlong(path, cum, cum[1]! / 2)
42
+ expect(half.lngLat[0]).toBeCloseTo(-64.185, 6)
43
+ expect(half.bearing).toBeCloseTo(90, 0) // east
44
+ expect(pointAlong(path, cum, cum[1]! + 1).bearing).toBeCloseTo(0, 0) // north
45
+ expect(pointAlong(path, cum, 1e9).lngLat).toEqual(path[2]) // clamped
46
+ })
47
+
48
+ it('slices the path between two distances, through its corners', () => {
49
+ const part = slicePath(path, cum, cum[1]! / 2, cum[1]! + (cum[2]! - cum[1]!) / 2)
50
+ expect(part).toHaveLength(3)
51
+ expect(part[1]).toEqual(path[1])
52
+ })
53
+
54
+ it('projects an off-road point onto the route', () => {
55
+ // A GPS fix a little north of the first leg's middle lands on it
56
+ expect(project(path, cum, [-64.185, -31.4195])).toBeCloseTo(cum[1]! / 2, -1)
57
+ })
58
+
59
+ it('bearing and bounds', () => {
60
+ expect(bearing([0, 0], [0, 1])).toBeCloseTo(0, 6)
61
+ expect(bearing([0, 0], [-1, 0])).toBeCloseTo(270, 6)
62
+ expect(bounds(path)).toEqual([[-64.19, -31.42], [-64.18, -31.41]])
63
+ })
64
+ })
65
+
66
+ async function mountRoute(props: Record<string, unknown>) {
67
+ const p = ref(props)
68
+ const wrapper = mount(() => h(MMap, { mapStyle: 's' }, () => h(MMapRoute, p.value)), { attachTo: document.body })
69
+ await flushPromises()
70
+ const map = created.maps.at(-1)! as FakeMap
71
+ map.load()
72
+ await nextTick()
73
+ await nextTick()
74
+ return { wrapper, map, p }
75
+ }
76
+
77
+ const routeData = (map: FakeMap) => {
78
+ const source = [...map.sources.entries()].find(([id]) => id.startsWith('m3-route'))![1]
79
+ return source.data as { features: { properties: { part: string }; geometry: { coordinates: LngLat[] } }[] }
80
+ }
81
+
82
+ describe('MMapRoute', () => {
83
+ const stops = [{ lngLat: path[0]!, label: 'Restaurant' }, { lngLat: path[2]!, label: 'Home' }]
84
+
85
+ it('draws the route, split into done and ahead, and fits the map to it', async () => {
86
+ const { map } = await mountRoute({ stops, path, progress: 0.5 })
87
+ expect(map.layers.map((l) => l.id).filter((id) => id.startsWith('m3-route'))).toHaveLength(3)
88
+ const [rest, done] = routeData(map).features
89
+ expect(rest!.properties.part).toBe('rest')
90
+ expect(done!.geometry.coordinates[0]).toEqual(path[0])
91
+ expect(rest!.geometry.coordinates.at(-1)).toEqual(path[2])
92
+ expect(map.flights.some(([kind]) => kind === 'fitBounds')).toBe(true)
93
+ // Ahead is the whole route, unchanging (its dots don't crawl); the exact shape, no simplification
94
+ expect(rest!.geometry.coordinates).toEqual(path)
95
+ expect((map.sources.get([...map.sources.keys()].find((id) => id.startsWith('m3-route'))!)!.spec as { tolerance?: number }).tolerance).toBe(0)
96
+ })
97
+
98
+ it('places the vehicle along the road, and a GPS position on the nearest point', async () => {
99
+ const { map, p } = await mountRoute({ stops, path, progress: 0 })
100
+ const vehicle = created.markers.find((m) => (m.getElement() as HTMLElement).classList?.contains('m3-map-route-vehicle'))!
101
+ expect(vehicle.getLngLat()).toEqual({ lng: path[0]![0], lat: path[0]![1] })
102
+ p.value = { stops, path, vehicle: [-64.18, -31.4152] } // off the road, near the second leg
103
+ await nextTick()
104
+ await flushPromises()
105
+ expect(vehicle.getLngLat().lng).toBeCloseTo(-64.18, 6)
106
+ expect(routeData(map).features[1]!.geometry.coordinates).toContainEqual(path[1])
107
+ })
108
+
109
+ it('marks the stops reached and emits arrive at the end', async () => {
110
+ const onArrive = vi.fn()
111
+ const { p, wrapper } = await mountRoute({ stops, path, progress: 0, onArrive })
112
+ const stopEls = () => [...document.querySelectorAll('.m3-map-route-stop')]
113
+ expect(stopEls()[0]!.classList.contains('bg-primary')).toBe(true) // the start is reached at 0
114
+ expect(stopEls()[1]!.classList.contains('bg-primary')).toBe(false)
115
+ p.value = { stops, path, progress: 1, onArrive }
116
+ await nextTick()
117
+ await flushPromises()
118
+ expect(stopEls()[1]!.classList.contains('bg-primary')).toBe(true)
119
+ expect(onArrive).toHaveBeenCalledTimes(1)
120
+ expect(stopEls()[1]!.getAttribute('aria-label')).toBe('Home')
121
+ wrapper.unmount()
122
+ })
123
+
124
+ it('without progress or vehicle there is no vehicle; straight lines when there is no path', async () => {
125
+ const { map } = await mountRoute({ stops })
126
+ expect(created.markers.find((m) => (m.getElement() as HTMLElement).classList?.contains('m3-map-route-vehicle'))?.map).toBeUndefined()
127
+ expect(routeData(map).features[0]!.geometry.coordinates).toEqual([path[0], path[2]])
128
+ })
129
+
130
+ it('removes its layers and source on unmount', async () => {
131
+ const { map, wrapper } = await mountRoute({ stops, path, progress: 0.3 })
132
+ wrapper.unmount()
133
+ expect(map.layers.some((l) => l.id.startsWith('m3-route'))).toBe(false)
134
+ expect([...map.sources.keys()].some((id) => id.startsWith('m3-route'))).toBe(false)
135
+ })
136
+ })
137
+
138
+ // ── Real streets (OSRM routes in Córdoba) ─────────────────────────────
139
+ const M = 111_320
140
+ const offRoad = (path: LngLat[], p: LngLat) => {
141
+ // Distance (m) from p to the polyline, flat approximation
142
+ const k = Math.cos((p[1] * Math.PI) / 180)
143
+ let best = Infinity
144
+ for (let i = 0; i < path.length - 1; i++) {
145
+ const [ax, ay] = [path[i]![0] * k, path[i]![1]], [bx, by] = [path[i + 1]![0] * k, path[i + 1]![1]]
146
+ const [dx, dy] = [bx - ax, by - ay]
147
+ const l2 = dx * dx + dy * dy
148
+ const t = l2 ? Math.max(0, Math.min(1, ((p[0] * k - ax) * dx + (p[1] - ay) * dy) / l2)) : 0
149
+ best = Math.min(best, Math.hypot(ax + dx * t - p[0] * k, ay + dy * t - p[1]) * M)
150
+ }
151
+ return best
152
+ }
153
+ /** A point of the return half that lies on the outbound half too (the stretch both ways share) */
154
+ function sharedPoint(path: LngLat[], cum: number[]) {
155
+ const half = cum.at(-1)! / 2
156
+ const outbound = slicePath(path, cum, 0, half * 0.9)
157
+ for (let i = path.length - 1; i >= 0; i--) {
158
+ if (cum[i]! > half * 1.1 && offRoad(outbound, path[i]!) < 3) return { point: path[i]!, at: cum[i]! }
159
+ }
160
+ throw new Error('no shared stretch')
161
+ }
162
+
163
+ describe('route geometry on real streets', () => {
164
+ it('follows curves and roundabouts: every point along it is on the road, heading every way it turns', () => {
165
+ const cum = cumulative(roundabout)
166
+ expect(cum.at(-1)!).toBeCloseTo(roundaboutMeta.distance, -2) // our length ≈ OSRM's
167
+ const headings: number[] = []
168
+ for (let d = 0; d <= cum.at(-1)!; d += 15) {
169
+ const { lngLat, bearing: b } = pointAlong(roundabout, cum, d)
170
+ expect(offRoad(roundabout, lngLat)).toBeLessThan(0.5)
171
+ headings.push(b)
172
+ }
173
+ // Diagonals and the roundabout: headings well away from the four grid directions
174
+ expect(headings.some((b) => Math.min(...[0, 90, 180, 270, 360].map((g) => Math.abs(b - g))) > 25)).toBe(true)
175
+ // Turning through the roundabout and the boulevard's curves: headings in at least 5 of the 8 compass sectors
176
+ expect(new Set(headings.map((b) => Math.floor(b / 45) % 8)).size).toBeGreaterThanOrEqual(5)
177
+ const curvy = cumulative(costanera)
178
+ expect(slicePath(costanera, curvy, 0, curvy.at(-1)!)).toHaveLength(costanera.length)
179
+ })
180
+
181
+ it('keeps a heading over repeated points (routing output has them)', () => {
182
+ const p: LngLat[] = [[0, 0], [0.001, 0], [0.001, 0], [0.002, 0]]
183
+ const cum = cumulative(p)
184
+ expect(pointAlong(p, cum, cum[1]!).bearing).toBeCloseTo(90, 3)
185
+ })
186
+
187
+ it('forward snapping: on the way back, a fix on the shared stretch stays on the way back', () => {
188
+ const cum = cumulative(roundTrip)
189
+ const { point, at } = sharedPoint(roundTrip, cum)
190
+ expect(project(roundTrip, cum, point)).toBeLessThan(cum.at(-1)! / 2) // the plain nearest point is on the way out
191
+ expect(projectForward(roundTrip, cum, point, at - 80)).toBeCloseTo(at, -1)
192
+ // Never backwards, even with jitter behind it
193
+ expect(projectForward(roundTrip, cum, roundTrip[0]!, at)).toBe(at)
194
+ })
195
+ })
196
+
197
+ describe('MMapRoute on real streets', () => {
198
+ const depot = roundTrip[0]!
199
+ const drop = roundTrip[Math.floor(roundTrip.length / 2)]!
200
+ const trip = [{ lngLat: depot, label: 'Depot' }, { lngLat: drop, label: 'Drop' }, { lngLat: depot, label: 'Back' }]
201
+ const route = (w: ReturnType<typeof mount>) => w.findComponent(MMapRoute as never).vm as unknown as { travelled: number; length: number }
202
+ const stopDone = (i: number) => document.querySelectorAll('.m3-map-route-stop')[i]!.classList.contains('bg-primary')
203
+
204
+ it('a round trip: the last stop (where the first is) is reached at the end, not at the start', async () => {
205
+ const { p } = await mountRoute({ stops: trip, path: roundTrip, progress: 0.1 })
206
+ expect(stopDone(0)).toBe(true)
207
+ expect(stopDone(2)).toBe(false)
208
+ p.value = { stops: trip, path: roundTrip, progress: 1 }
209
+ await nextTick()
210
+ await flushPromises()
211
+ expect(stopDone(2)).toBe(true)
212
+ })
213
+
214
+ it('a GPS fix on the shared stretch, on the way back, keeps the van on the way back (snap: forward)', async () => {
215
+ const cum = cumulative(roundTrip)
216
+ const { point, at } = sharedPoint(roundTrip, cum)
217
+ const before = pointAlong(roundTrip, cum, at - 60).lngLat
218
+ const { wrapper, p } = await mountRoute({ stops: trip, path: roundTrip, vehicle: before })
219
+ p.value = { stops: trip, path: roundTrip, vehicle: [point[0] + 0.00005, point[1] + 0.00005] } // ~7 m off, as GPS is
220
+ await nextTick()
221
+ await flushPromises()
222
+ expect(route(wrapper).travelled).toBeGreaterThan(cum.at(-1)! / 2)
223
+ })
224
+
225
+ it("snap: 'nearest' takes the closest point of the whole route", async () => {
226
+ const cum = cumulative(roundTrip)
227
+ const { point, at } = sharedPoint(roundTrip, cum)
228
+ const { wrapper, p } = await mountRoute({ stops: trip, path: roundTrip, vehicle: pointAlong(roundTrip, cum, at - 60).lngLat, snap: 'nearest' })
229
+ p.value = { stops: trip, path: roundTrip, vehicle: point, snap: 'nearest' }
230
+ await nextTick()
231
+ await flushPromises()
232
+ expect(route(wrapper).travelled).toBeLessThan(cum.at(-1)! / 2)
233
+ })
234
+
235
+ it('provider: fetches the road between the stops, emits route, and redraws on it', async () => {
236
+ const provider = vi.fn(async () => ({ path: roundabout, ...roundaboutMeta }))
237
+ const onRoute = vi.fn()
238
+ const stops = [{ lngLat: roundabout[0]! }, { lngLat: roundabout.at(-1)! }]
239
+ const { map } = await mountRoute({ stops, provider, onRoute, progress: 0 })
240
+ await flushPromises()
241
+ expect(provider).toHaveBeenCalledWith([roundabout[0], roundabout.at(-1)], expect.objectContaining({ signal: expect.any(AbortSignal) }))
242
+ expect(onRoute).toHaveBeenCalledWith(expect.objectContaining({ distance: roundaboutMeta.distance }))
243
+ expect(routeData(map).features[0]!.geometry.coordinates.length).toBeGreaterThan(100) // the streets, not a straight line
244
+ })
245
+
246
+ it('provider: a failure emits error and keeps straight lines; a newer request aborts the older one', async () => {
247
+ const signals: AbortSignal[] = []
248
+ const provider = vi.fn((_: LngLat[], { signal }: { signal?: AbortSignal }) => {
249
+ signals.push(signal!)
250
+ return Promise.reject(new Error('down'))
251
+ })
252
+ const onError = vi.fn()
253
+ const stops = [{ lngLat: path[0]! }, { lngLat: path[2]! }]
254
+ const { map, p } = await mountRoute({ stops, provider, onError })
255
+ await flushPromises()
256
+ expect(onError).toHaveBeenCalled()
257
+ expect(routeData(map).features[0]!.geometry.coordinates).toEqual([path[0], path[2]])
258
+ p.value = { stops: [stops[0]!, { lngLat: path[1]! }], provider, onError }
259
+ await nextTick()
260
+ expect(signals[0]!.aborted).toBe(true)
261
+ })
262
+ })
263
+
264
+ describe('osrmRouteProvider', () => {
265
+ it('asks OSRM for the full GeoJSON geometry and returns path, distance, duration', async () => {
266
+ const fetchMock = vi.fn(async () => ({ ok: true, json: async () => ({ code: 'Ok', routes: [{ geometry: { coordinates: roundabout }, ...roundaboutMeta }] }) }))
267
+ vi.stubGlobal('fetch', fetchMock)
268
+ const result = await osrmRouteProvider({ url: 'https://osrm.test/', params: { exclude: 'toll' } })([[-64.189, -31.4199], [-64.1752, -31.433]], {})
269
+ const url = String((fetchMock.mock.calls[0] as unknown[])[0])
270
+ expect(url).toBe('https://osrm.test/route/v1/driving/-64.189,-31.4199;-64.1752,-31.433?overview=full&geometries=geojson&exclude=toll')
271
+ expect(result).toEqual({ path: roundabout, ...roundaboutMeta })
272
+ })
273
+
274
+ it('throws on an OSRM error (NoRoute…) or a bad status', async () => {
275
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({ code: 'NoRoute', message: 'Impossible route' }) })))
276
+ await expect(osrmRouteProvider()([[0, 0], [1, 1]], {})).rejects.toThrow('Impossible route')
277
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 429 })))
278
+ await expect(osrmRouteProvider()([[0, 0], [1, 1]], {})).rejects.toThrow('429')
279
+ })
280
+ })
281
+
282
+ describe('MMapRoute vehicle steadiness', () => {
283
+ it("an icon heading south on a wobbly road doesn't flip back and forth; it turns around when clearly heading west", async () => {
284
+ // South, wobbling a hair east and west (bearings around 180°, as a real road's short segments)
285
+ const wobbly: LngLat[] = Array.from({ length: 12 }, (_, i) => [-64.18 + (i % 2 ? 0.000004 : -0.000004), -31.41 - i * 0.0005])
286
+ const westward: LngLat[] = [...wobbly, [-64.19, -31.4155]]
287
+ const stops = [{ lngLat: wobbly[0]! }, { lngLat: westward.at(-1)! }]
288
+ const { p } = await mountRoute({ stops, path: westward, progress: 0, vehicleIcon: 'two_wheeler' })
289
+ const icon = () => [...document.querySelectorAll('.m3-map-route-vehicle *')].find((e) => e.textContent?.trim() === 'two_wheeler' && !e.children.length) as HTMLElement
290
+ const states: boolean[] = []
291
+ const total = cumulative(westward).at(-1)!
292
+ const southEnd = cumulative(wobbly).at(-1)! / total
293
+ for (let k = 1; k <= 20; k++) {
294
+ p.value = { stops, path: westward, progress: (k / 20) * southEnd * 0.95, vehicleIcon: 'two_wheeler' }
295
+ await nextTick()
296
+ await flushPromises()
297
+ states.push(!!icon().style.transform)
298
+ }
299
+ expect(new Set(states).size).toBe(1) // never flipped on the way south
300
+ p.value = { stops, path: westward, progress: 0.99, vehicleIcon: 'two_wheeler' }
301
+ await nextTick()
302
+ await flushPromises()
303
+ expect(icon().style.transform).toBe('scaleX(-1)') // heading west at the end
304
+ })
305
+
306
+ it('positions the vehicle with subpixel precision', async () => {
307
+ await mountRoute({ stops: [{ lngLat: path[0]! }, { lngLat: path[2]! }], path, progress: 0.3 })
308
+ const vehicle = created.markers.find((m) => (m.getElement() as HTMLElement).classList?.contains('m3-map-route-vehicle'))!
309
+ expect((vehicle as unknown as { options: Record<string, unknown> }).options.subpixelPositioning).toBe(true)
310
+ })
311
+ })
312
+
313
+ describe('MMapRoute smooth motion', () => {
314
+ it("duration 'auto' moves for as long as the time between positions: no stop before the next one comes", async () => {
315
+ vi.stubGlobal('matchMedia', () => ({ matches: false, addEventListener() {}, removeEventListener() {} }))
316
+ let t = 0
317
+ const frames: FrameRequestCallback[] = []
318
+ vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => frames.push(cb))
319
+ vi.stubGlobal('cancelAnimationFrame', () => {})
320
+ vi.spyOn(performance, 'now').mockImplementation(() => t)
321
+ const run = (until: number) => { while (t < until) { t = Math.min(t + 16, until); frames.splice(0).forEach((cb) => cb(t)) } }
322
+ const stops = [{ lngLat: path[0]! }, { lngLat: path[2]! }]
323
+ const { p } = await mountRoute({ stops, path, progress: 0, flow: false })
324
+ const vehicle = () => created.markers.find((m) => (m.getElement() as HTMLElement).classList?.contains('m3-map-route-vehicle'))!.getLngLat().lng
325
+ const set = async (progress: number) => { p.value = { stops, path, progress, flow: false }; await nextTick() }
326
+ run(1000)
327
+ await set(0.1) // first move: a second
328
+ run(2500)
329
+ await set(0.2) // came 1.5 s after the last one: this move takes 1.5 s
330
+ run(2500 + 1400)
331
+ const before = vehicle()
332
+ run(2500 + 1480)
333
+ expect(vehicle()).toBeGreaterThan(before) // still on its way (a fixed 1 s would have stopped at 3.5 s)
334
+ run(2500 + 1600)
335
+ const settled = vehicle()
336
+ run(2500 + 2000)
337
+ expect(vehicle()).toBe(settled)
338
+ })
339
+
340
+ it('the vehicle is drawn under a hint of rotation (Firefox draws a translate-only element at whole pixels)', async () => {
341
+ await mountRoute({ stops: [{ lngLat: path[0]! }, { lngLat: path[2]! }], path, progress: 0.3, vehicleIcon: 'two_wheeler' })
342
+ const inner = document.querySelector('.m3-map-route-vehicle > div') as HTMLElement
343
+ expect(inner.style.transform).toBe('rotate(0.01deg)')
344
+ })
345
+ })
346
+
347
+ describe('MMapRoute custom vehicle', () => {
348
+ it('#vehicle gets { bearing, west }; rotateVehicle makes the marker turn it with the road', async () => {
349
+ const scopes: { bearing: number; west: boolean }[] = []
350
+ const p = ref<Record<string, unknown>>({ stops: [{ lngLat: path[0]! }, { lngLat: path[2]! }], path, progress: 0.25, rotateVehicle: true })
351
+ mount(() => h(MMap, { mapStyle: 's' }, () => h(MMapRoute, p.value, {
352
+ vehicle: (scope: { bearing: number; west: boolean }) => { scopes.push(scope); return h('img', { class: 'my-car', src: 'car.svg' }) },
353
+ })), { attachTo: document.body })
354
+ await flushPromises()
355
+ const map = created.maps.at(-1)! as FakeMap
356
+ map.load()
357
+ await nextTick()
358
+ await nextTick()
359
+ expect(document.querySelector('.m3-map-route-vehicle .my-car')).not.toBeNull()
360
+ const vehicle = created.markers.find((m) => (m.getElement() as HTMLElement).classList?.contains('m3-map-route-vehicle'))! as unknown as { options: Record<string, unknown>; rotation: number }
361
+ expect(vehicle.options.rotationAlignment).toBe('map')
362
+ expect(vehicle.rotation).toBeCloseTo(90, 0) // the first leg heads east
363
+ expect(scopes.at(-1)).toEqual(expect.objectContaining({ west: false }))
364
+ })
365
+ })
366
+
367
+ describe('MMapRoute flow', () => {
368
+ it('the dots ahead stream toward the destination by shifting the dash pattern; the geometry stays put', async () => {
369
+ vi.stubGlobal('matchMedia', () => ({ matches: false, addEventListener() {}, removeEventListener() {} }))
370
+ let t = 0
371
+ const frames: FrameRequestCallback[] = []
372
+ vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => frames.push(cb))
373
+ vi.stubGlobal('cancelAnimationFrame', () => {})
374
+ vi.spyOn(performance, 'now').mockImplementation(() => t)
375
+ // Runs every callback queued (other parts of the map may ask for frames too)
376
+ const tick = (ms: number) => { t += ms; frames.splice(0).forEach((cb) => cb(t)) }
377
+ const { map, p } = await mountRoute({ stops: [{ lngLat: path[0]! }, { lngLat: path[2]! }], path, progress: 0 })
378
+ const paint = vi.spyOn(map, 'setPaintProperty')
379
+ const data = routeData(map)
380
+ const dashes = () => paint.mock.calls.filter(([id, prop]) => String(id).endsWith('-rest') && prop === 'line-dasharray').map((c) => c[2] as number[])
381
+ tick(16)
382
+ tick(60)
383
+ tick(60)
384
+ const seen = dashes()
385
+ expect(seen.length).toBeGreaterThanOrEqual(2)
386
+ // Each pattern covers one period (dot + gap), the dot a little further along each time
387
+ for (const d of seen) expect(d.reduce((a, b) => a + b, 0)).toBeCloseTo(2.6, 6)
388
+ expect(seen[1]![1]!).toBeGreaterThan(seen[0]![1]!)
389
+ expect(routeData(map)).toBe(data) // no geometry re-sent for the flow
390
+ // flow: false stops it, back to the unshifted pattern
391
+ p.value = { stops: [{ lngLat: path[0]! }, { lngLat: path[2]! }], path, progress: 0, flow: false }
392
+ await nextTick()
393
+ expect(dashes().at(-1)).toEqual([0, 0, 1, 1.6])
394
+ })
395
+
396
+ it('pauses while the map is off screen', async () => {
397
+ vi.stubGlobal('matchMedia', () => ({ matches: false, addEventListener() {}, removeEventListener() {} }))
398
+ let report: (entries: { isIntersecting: boolean }[]) => void = () => {}
399
+ vi.stubGlobal('IntersectionObserver', class { constructor(cb: typeof report) { report = cb } observe() {} disconnect() {} })
400
+ let t = 0
401
+ const frames: FrameRequestCallback[] = []
402
+ vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => frames.push(cb))
403
+ vi.stubGlobal('cancelAnimationFrame', () => { frames.length = 0 })
404
+ vi.spyOn(performance, 'now').mockImplementation(() => t)
405
+ const tick = (ms: number) => { t += ms; frames.splice(0).forEach((cb) => cb(t)) }
406
+ const { map } = await mountRoute({ stops: [{ lngLat: path[0]! }, { lngLat: path[2]! }], path, progress: 0 })
407
+ const paint = vi.spyOn(map, 'setPaintProperty')
408
+ report([{ isIntersecting: false }])
409
+ paint.mockClear()
410
+ tick(100)
411
+ tick(100)
412
+ expect(paint).not.toHaveBeenCalled()
413
+ report([{ isIntersecting: true }])
414
+ tick(16)
415
+ tick(100)
416
+ expect(paint).toHaveBeenCalled()
417
+ })
418
+ })
@@ -0,0 +1,175 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2
+ import { flushPromises, mount } from '@vue/test-utils'
3
+ import { h, nextTick, ref } from 'vue'
4
+ import { PDFDocument, PDFName, PDFDict, degrees } from 'pdf-lib'
5
+ import { shownToUser, signPdf, fieldMissing, type PdfSignField } from '../composables/pdfSign'
6
+
7
+ vi.mock('pdfjs-dist', () => import('./pdfMock'))
8
+ const { fakeDoc } = await import('./pdfMock')
9
+ const { default: MPdfSigner } = await import('../components/MPdfSigner.vue')
10
+
11
+ // A 2×1 PNG (red, transparent)
12
+ const PNG = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAYAAAD0In+KAAAAD0lEQVR4nGP4z8AARAwMAAz8Af9c/RSVAAAAAElFTkSuQmCC'
13
+
14
+ describe('shownToUser', () => {
15
+ const box = { x: 0, y: 0, width: 600, height: 800 }
16
+ const r = { x: 100, y: 50, width: 200, height: 40 }
17
+ it('no rotation: y flips (bottom-left origin)', () => {
18
+ expect(shownToUser(r, box, 0)).toEqual({ x: 100, y: 800 - 90, rotate: 0 })
19
+ })
20
+ it('a crop box offsets it', () => {
21
+ expect(shownToUser(r, { ...box, x: 10, y: 20 }, 0)).toEqual({ x: 110, y: 730, rotate: 0 })
22
+ })
23
+ it('a page shown turned 90°, 180°, 270°: anchored at the shown bottom-left corner, drawn turned with it', () => {
24
+ expect(shownToUser(r, box, 90)).toEqual({ x: 90, y: 100, rotate: 90 })
25
+ expect(shownToUser(r, box, 180)).toEqual({ x: 500, y: 90, rotate: 180 })
26
+ expect(shownToUser(r, box, 270)).toEqual({ x: 510, y: 700, rotate: 270 })
27
+ })
28
+ })
29
+
30
+ describe('signPdf', () => {
31
+ it('draws the filled fields into a copy of the PDF, on their page; empty ones are skipped', async () => {
32
+ const doc = await PDFDocument.create()
33
+ doc.addPage([600, 800])
34
+ doc.addPage([600, 800])
35
+ const bytes = await doc.save()
36
+ const fields: PdfSignField[] = [
37
+ { id: 's', type: 'signature', page: 2, x: 0.1, y: 0.8, width: 0.3, height: 0.06, value: PNG },
38
+ { id: 'e', type: 'signature', page: 1, x: 0.1, y: 0.8, width: 0.3, height: 0.06 },
39
+ ]
40
+ const out = await signPdf(bytes, fields)
41
+ const signed = await PDFDocument.load(out)
42
+ const xobjects = (n: number) => {
43
+ const res = signed.getPages()[n]!.node.Resources()
44
+ const xo = res?.lookupMaybe(PDFName.of('XObject'), PDFDict)
45
+ return xo ? xo.keys().length : 0
46
+ }
47
+ expect(xobjects(0)).toBe(0)
48
+ expect(xobjects(1)).toBe(1)
49
+ expect(signed.getPageCount()).toBe(2)
50
+ })
51
+
52
+ it('works on a page with its own rotation', async () => {
53
+ const doc = await PDFDocument.create()
54
+ doc.addPage([600, 800]).setRotation(degrees(90))
55
+ const out = await signPdf(await doc.save(), [{ id: 's', type: 'initials', page: 1, x: 0.5, y: 0.5, width: 0.1, height: 0.05, value: PNG }])
56
+ expect((await PDFDocument.load(out)).getPage(0).getRotation().angle).toBe(90)
57
+ })
58
+
59
+ it('fieldMissing: signatures are required unless said otherwise', () => {
60
+ expect(fieldMissing({ id: 'a', type: 'signature', page: 1, x: 0, y: 0, width: 0.1, height: 0.1 })).toBe(true)
61
+ expect(fieldMissing({ id: 'a', type: 'text', page: 1, x: 0, y: 0, width: 0.1, height: 0.1 })).toBe(false)
62
+ expect(fieldMissing({ id: 'a', type: 'text', page: 1, x: 0, y: 0, width: 0.1, height: 0.1, required: true, value: 'x' })).toBe(false)
63
+ })
64
+ })
65
+
66
+ describe('MPdfSigner', () => {
67
+ beforeEach(() => {
68
+ vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(640)
69
+ vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(480)
70
+ fakeDoc.password = ''
71
+ fakeDoc.outline = []
72
+ fakeDoc.pages = Array.from({ length: 2 }, () => ({ width: 612, height: 792, text: [] }))
73
+ })
74
+ afterEach(() => {
75
+ vi.restoreAllMocks()
76
+ document.body.innerHTML = ''
77
+ })
78
+ const settle = async () => { for (let i = 0; i < 8; i++) await flushPromises() }
79
+
80
+ function setup(initial: PdfSignField[], props: Record<string, unknown> = {}) {
81
+ const fields = ref(initial)
82
+ const events: string[] = []
83
+ const w = mount(() => h(MPdfSigner, {
84
+ src: '/contract.pdf',
85
+ fields: fields.value,
86
+ 'onUpdate:fields': (f: PdfSignField[]) => (fields.value = f),
87
+ onComplete: () => events.push('complete'),
88
+ onFinish: () => events.push('finish'),
89
+ ...props,
90
+ }), { attachTo: document.body })
91
+ return { w, fields, events }
92
+ }
93
+
94
+ const contract: PdfSignField[] = [
95
+ { id: 'date', type: 'date', page: 1, x: 0.6, y: 0.85, width: 0.2, height: 0.03, required: true },
96
+ { id: 'ok', type: 'checkbox', page: 1, x: 0.1, y: 0.7, width: 0.03, height: 0.02 },
97
+ { id: 'sig', type: 'signature', page: 2, x: 0.1, y: 0.8, width: 0.3, height: 0.06 },
98
+ { id: 'theirs', type: 'signature', page: 2, x: 0.5, y: 0.8, width: 0.3, height: 0.06, signer: 'landlord' },
99
+ ]
100
+
101
+ it('places the fields on their pages, as fractions of the page', async () => {
102
+ const { w } = setup(contract)
103
+ await settle()
104
+ const date = w.find('[data-field="date"]')
105
+ expect(date.exists()).toBe(true)
106
+ expect((date.element as HTMLElement).style.left).toBe('60%')
107
+ expect(w.findAll('.m3-pdf-page')[1]!.element.parentElement!.querySelector('[data-field="sig"]')).not.toBeNull()
108
+ })
109
+
110
+ it('signing: a date fills with today, a checkbox ticks, progress counts the required ones; other signers\' fields are off', async () => {
111
+ const { w, fields, events } = setup(contract, { signer: 'tenant' })
112
+ await settle()
113
+ expect(w.text()).toContain('0 of 2 fields')
114
+ await w.find('[data-field="date"]').trigger('click')
115
+ expect(fields.value.find((f) => f.id === 'date')!.value).toBeTruthy()
116
+ await w.find('[data-field="ok"]').trigger('click')
117
+ expect(fields.value.find((f) => f.id === 'ok')!.value).toBe('true')
118
+ await nextTick()
119
+ expect(w.text()).toContain('1 of 2 fields')
120
+ expect(w.find('[data-field="theirs"]').classes()).toContain('opacity-40')
121
+ await w.find('[data-field="theirs"]').trigger('click')
122
+ expect(document.querySelector('[role="dialog"]')).toBeNull()
123
+
124
+ // The signature: typed, adopted
125
+ await w.find('[data-field="sig"]').trigger('click')
126
+ await nextTick()
127
+ expect(document.querySelector('[role="dialog"]')).not.toBeNull()
128
+ expect(events).not.toContain('complete')
129
+ const finish = w.findAll('button').find((b) => b.text().includes('Finish'))!
130
+ expect(finish.attributes('disabled')).toBeDefined()
131
+ })
132
+
133
+ it('a signature adopted once fills the next signature field with one click', async () => {
134
+ const twice: PdfSignField[] = [
135
+ { id: 'a', type: 'signature', page: 1, x: 0.1, y: 0.1, width: 0.3, height: 0.06 },
136
+ { id: 'b', type: 'signature', page: 2, x: 0.1, y: 0.1, width: 0.3, height: 0.06 },
137
+ ]
138
+ // happy-dom has no canvas: the typed signature is stubbed
139
+ const ctx = new Proxy({} as Record<string | symbol, unknown>, {
140
+ get: (t, k) => (k in t ? t[k] : k === 'measureText' ? () => ({ width: 100 }) : () => {}),
141
+ set: (t, k, v) => { t[k] = v; return true },
142
+ })
143
+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(ctx as never)
144
+ vi.spyOn(HTMLCanvasElement.prototype, 'toDataURL').mockReturnValue(PNG)
145
+ const { w, fields, events } = setup(twice, { signerName: 'Ana Pérez' })
146
+ await settle()
147
+ await w.find('[data-field="a"]').trigger('click')
148
+ await nextTick()
149
+ const dialog = document.querySelector('[role="dialog"]')!
150
+ ;[...dialog.querySelectorAll('button')].find((b) => b.textContent?.includes('Type'))!.click()
151
+ await nextTick()
152
+ expect((dialog.querySelector('input') as HTMLInputElement).value).toBe('Ana Pérez')
153
+ ;[...dialog.querySelectorAll('button')].find((b) => b.textContent?.trim() === 'Sign')!.click()
154
+ await settle()
155
+ expect(fields.value[0]!.value).toBe(PNG)
156
+ await w.find('[data-field="b"]').trigger('click')
157
+ expect(fields.value[1]!.value).toBe(PNG)
158
+ await nextTick()
159
+ expect(events).toContain('complete')
160
+ })
161
+
162
+ it('prepare mode: adds a field on the current page, moves it with the keyboard, deletes it', async () => {
163
+ const { w, fields } = setup([], { mode: 'prepare' })
164
+ await settle()
165
+ await w.find('[data-add="signature"]').trigger('click')
166
+ expect(fields.value).toHaveLength(1)
167
+ const f = fields.value[0]!
168
+ expect(f).toMatchObject({ type: 'signature', page: 1, required: true })
169
+ await nextTick()
170
+ await w.find(`[data-field="${f.id}"]`).trigger('keydown', { key: 'ArrowRight' })
171
+ expect(fields.value[0]!.x).toBeCloseTo(f.x + 0.005, 6)
172
+ await w.find(`[data-field="${f.id}"]`).trigger('keydown', { key: 'Delete' })
173
+ expect(fields.value).toHaveLength(0)
174
+ })
175
+ })
@@ -1,6 +1,6 @@
1
1
  import { describe, it, expect, afterEach } from 'vitest'
2
2
  import { nextTick } from 'vue'
3
- import { mount } from '@vue/test-utils'
3
+ import { mount, flushPromises } from '@vue/test-utils'
4
4
  import MPhoneInput from '../components/MPhoneInput.vue'
5
5
  import { formatPhone, isValidPhone, parsePhone } from '../composables/phoneNumber'
6
6
 
@@ -69,7 +69,10 @@ describe('MPhoneInput', () => {
69
69
  it('flags an incomplete number after leaving the field', async () => {
70
70
  const w = mount(MPhoneInput, { props: { label: 'Phone', country: 'AR', modelValue: '+54112', locale: 'en' } })
71
71
  expect(w.text()).not.toContain('Incomplete')
72
- await input(w).trigger('blur')
72
+ // Leaving the field (focusout, which a real blur always brings) shows it once focus has settled elsewhere
73
+ await input(w).trigger('focusout')
74
+ await new Promise((r) => setTimeout(r))
75
+ await flushPromises()
73
76
  expect(w.text()).toContain('Incomplete phone number')
74
77
  })
75
78
 
@@ -13,7 +13,8 @@ describe('MRichTextEditor fill', () => {
13
13
 
14
14
  it('fills its height and scrolls the text inside with fill', () => {
15
15
  const w = mount(MRichTextEditor, { props: { modelValue: '', fill: true } })
16
- expect(w.classes()).toContain('flex-col')
16
+ // The editor box (the root is the box plus its validation message)
17
+ expect(w.find('div.rounded-lg').classes()).toContain('flex-col')
17
18
  const content = w.find('.rte-content')
18
19
  expect(content.classes()).toEqual(expect.arrayContaining(['flex-1', 'min-h-0', 'overflow-y-auto']))
19
20
  expect((content.element as HTMLElement).style.minHeight).toBe('')