@m3ui-vue/m3ui-vue 1.0.2 → 1.1.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 (157) hide show
  1. package/dist/API.md +666 -12
  2. package/dist/MMenuItem-BOkcVtEe.js +809 -0
  3. package/dist/MMenuItem-BOkcVtEe.js.map +1 -0
  4. package/dist/MSlider-BXsBv0ox.js +1402 -0
  5. package/dist/MSlider-BXsBv0ox.js.map +1 -0
  6. package/dist/MTextField-rML9jnXs.js +671 -0
  7. package/dist/MTextField-rML9jnXs.js.map +1 -0
  8. package/dist/api.json +1 -1
  9. package/dist/code-editor.js +1 -1
  10. package/dist/components/MBottomSheet.vue.d.ts +20 -1
  11. package/dist/components/MDialog.vue.d.ts +17 -8
  12. package/dist/components/MDragDropList.vue.d.ts +1 -1
  13. package/dist/components/MIconButton.vue.d.ts +1 -1
  14. package/dist/components/MMap.vue.d.ts +74 -0
  15. package/dist/components/MMapBaseLayers.vue.d.ts +15 -0
  16. package/dist/components/MMapControl.vue.d.ts +40 -0
  17. package/dist/components/MMapFeatureInfo.vue.d.ts +25 -0
  18. package/dist/components/MMapFilter.vue.d.ts +19 -0
  19. package/dist/components/MMapGeoJson.vue.d.ts +34 -0
  20. package/dist/components/MMapHover.vue.d.ts +17 -0
  21. package/dist/components/MMapIdentify.vue.d.ts +37 -0
  22. package/dist/components/MMapLayers.vue.d.ts +31 -0
  23. package/dist/components/MMapMarker.vue.d.ts +45 -0
  24. package/dist/components/MMapMeasure.vue.d.ts +43 -0
  25. package/dist/components/MMapPopup.vue.d.ts +45 -0
  26. package/dist/components/MMapSearch.vue.d.ts +28 -0
  27. package/dist/components/MMenuItem.vue.d.ts +2 -2
  28. package/dist/components/MSeekBar.vue.d.ts +122 -0
  29. package/dist/components/MSplitButton.vue.d.ts +2 -2
  30. package/dist/components/_MMapAttribution.vue.d.ts +7 -0
  31. package/dist/components/_MMapLayerItem.vue.d.ts +25 -0
  32. package/dist/composables/_mapGeometry.d.ts +13 -0
  33. package/dist/composables/_mapPin.d.ts +5 -0
  34. package/dist/composables/_popupPosition.d.ts +12 -0
  35. package/dist/composables/_ssrState.d.ts +30 -0
  36. package/dist/composables/_storageKeys.d.ts +3 -0
  37. package/dist/composables/_useCalendarMonth.d.ts +24 -0
  38. package/dist/composables/_useEscapeStack.d.ts +3 -0
  39. package/dist/composables/_useScrollLock.d.ts +8 -0
  40. package/dist/composables/_useSheetMotion.d.ts +16 -1
  41. package/dist/composables/_useThemeTokens.d.ts +7 -0
  42. package/dist/composables/mapAdapters.d.ts +111 -0
  43. package/dist/composables/mapSearch.d.ts +31 -0
  44. package/dist/composables/themeInitScript.d.ts +4 -3
  45. package/dist/composables/useColorPalette.d.ts +173 -7
  46. package/dist/composables/useLocale.d.ts +38 -0
  47. package/dist/composables/useMap.d.ts +47 -0
  48. package/dist/composables/useMapFilter.d.ts +10 -0
  49. package/dist/composables/useMapLayers.d.ts +30 -0
  50. package/dist/composables/useTheme.d.ts +2 -1
  51. package/dist/index.d.ts +4 -1
  52. package/dist/locales/index.js +273 -7
  53. package/dist/locales/index.js.map +1 -1
  54. package/dist/m3ui-vue.css +1 -1
  55. package/dist/m3ui.js +7913 -8625
  56. package/dist/m3ui.js.map +1 -1
  57. package/dist/map.d.ts +24 -0
  58. package/dist/map.js +2067 -0
  59. package/dist/map.js.map +1 -0
  60. package/dist/plugin.d.ts +18 -2
  61. package/dist/rich-text-editor.js +26 -25
  62. package/dist/rich-text-editor.js.map +1 -1
  63. package/dist/styles.css +1 -1
  64. package/dist/{useLocale-CuvWRZ1h.js → useLocale-CqQrhWFl.js} +40 -2
  65. package/dist/useLocale-CqQrhWFl.js.map +1 -0
  66. package/package.json +11 -2
  67. package/src/__tests__/MDialog.test.ts +30 -0
  68. package/src/__tests__/MFab.test.ts +52 -6
  69. package/src/__tests__/MMap.test.ts +422 -0
  70. package/src/__tests__/MMapLayers.test.ts +257 -0
  71. package/src/__tests__/MMapTools.test.ts +233 -0
  72. package/src/__tests__/MSeekBar.test.ts +170 -0
  73. package/src/__tests__/MTooltip.test.ts +110 -0
  74. package/src/__tests__/_fakeMaplibre.ts +161 -0
  75. package/src/__tests__/calendarMonth.test.ts +59 -0
  76. package/src/__tests__/hydration.test.ts +33 -0
  77. package/src/__tests__/pickerModals.test.ts +128 -0
  78. package/src/__tests__/popupPosition.test.ts +224 -0
  79. package/src/__tests__/scrollLock.test.ts +110 -0
  80. package/src/__tests__/sheets.test.ts +158 -0
  81. package/src/__tests__/ssr.test.ts +63 -1
  82. package/src/__tests__/ssrState.test.ts +155 -0
  83. package/src/__tests__/themeInitScript.test.ts +18 -0
  84. package/src/components/MAutocomplete.vue +2 -4
  85. package/src/components/MBottomSheet.vue +211 -13
  86. package/src/components/MCommandPalette.vue +4 -6
  87. package/src/components/MContextMenu.vue +19 -5
  88. package/src/components/MDatePicker.vue +29 -70
  89. package/src/components/MDatePickerModal.vue +116 -172
  90. package/src/components/MDateRangePicker.vue +29 -51
  91. package/src/components/MDateRangePickerModal.vue +84 -162
  92. package/src/components/MDialog.vue +87 -63
  93. package/src/components/MFab.vue +29 -7
  94. package/src/components/MIconButton.vue +1 -1
  95. package/src/components/MLightbox.vue +12 -5
  96. package/src/components/MMap.vue +568 -0
  97. package/src/components/MMapBaseLayers.vue +67 -0
  98. package/src/components/MMapControl.vue +175 -0
  99. package/src/components/MMapFeatureInfo.vue +41 -0
  100. package/src/components/MMapFilter.vue +80 -0
  101. package/src/components/MMapGeoJson.vue +136 -0
  102. package/src/components/MMapHover.vue +131 -0
  103. package/src/components/MMapIdentify.vue +104 -0
  104. package/src/components/MMapLayers.vue +111 -0
  105. package/src/components/MMapMarker.vue +109 -0
  106. package/src/components/MMapMeasure.vue +452 -0
  107. package/src/components/MMapPopup.vue +103 -0
  108. package/src/components/MMapSearch.vue +162 -0
  109. package/src/components/MMenu.vue +31 -12
  110. package/src/components/MMenuItem.vue +21 -4
  111. package/src/components/MMultiAutocomplete.vue +2 -4
  112. package/src/components/MMultiSelect.vue +2 -4
  113. package/src/components/MNavigationDrawer.vue +2 -8
  114. package/src/components/MNavigationRail.vue +2 -3
  115. package/src/components/MSearchBar.vue +2 -5
  116. package/src/components/MSeekBar.vue +593 -0
  117. package/src/components/MSelect.vue +2 -8
  118. package/src/components/MSplitButton.vue +23 -7
  119. package/src/components/MSpotlightSearch.vue +4 -6
  120. package/src/components/MTimePicker.vue +23 -6
  121. package/src/components/MTimePickerModal.vue +213 -226
  122. package/src/components/MTooltip.vue +99 -3
  123. package/src/components/_MMapAttribution.vue +81 -0
  124. package/src/components/_MMapLayerItem.vue +77 -0
  125. package/src/composables/_mapGeometry.ts +75 -0
  126. package/src/composables/_mapPin.ts +25 -0
  127. package/src/composables/_popupPosition.ts +39 -0
  128. package/src/composables/_ssrState.ts +80 -0
  129. package/src/composables/_storageKeys.ts +6 -0
  130. package/src/composables/_useCalendarMonth.ts +74 -0
  131. package/src/composables/_useEscapeStack.ts +33 -0
  132. package/src/composables/_useScrollLock.ts +41 -0
  133. package/src/composables/_useSheetMotion.ts +82 -20
  134. package/src/composables/_useThemeTokens.ts +42 -0
  135. package/src/composables/mapAdapters.ts +208 -0
  136. package/src/composables/mapSearch.ts +56 -0
  137. package/src/composables/themeInitScript.ts +6 -4
  138. package/src/composables/useColorPalette.ts +23 -9
  139. package/src/composables/useLocale.ts +78 -0
  140. package/src/composables/useMap.ts +98 -0
  141. package/src/composables/useMapFilter.ts +45 -0
  142. package/src/composables/useMapLayers.ts +124 -0
  143. package/src/composables/useTheme.ts +8 -3
  144. package/src/composables/useWindowSizeClass.ts +14 -5
  145. package/src/index.ts +4 -1
  146. package/src/locales/de.ts +39 -1
  147. package/src/locales/es.ts +39 -1
  148. package/src/locales/fr.ts +39 -1
  149. package/src/locales/ja.ts +39 -1
  150. package/src/locales/ko.ts +39 -1
  151. package/src/locales/pt.ts +39 -1
  152. package/src/locales/zh.ts +39 -1
  153. package/src/map.ts +32 -0
  154. package/src/plugin.ts +54 -3
  155. package/dist/MTextField-BPbFeI9M.js +0 -1368
  156. package/dist/MTextField-BPbFeI9M.js.map +0 -1
  157. package/dist/useLocale-CuvWRZ1h.js.map +0 -1
@@ -0,0 +1,452 @@
1
+ <script setup lang="ts">
2
+ /**
3
+ * Distance and area measuring on an `MMap`, with its own control (distance, area, clear). Click to add points (a
4
+ * preview follows the pointer), double-click, Enter or Escape to finish, click the first point to close the shape, or
5
+ * press the active button again (in fullscreen, Escape finishes it too where the browser allows: Chromium). Finished
6
+ * measurements stay editable: drag a vertex, or a midpoint to add one; the ✕ on a total or area deletes that one.
7
+ * Labels show each segment, the total and the area; everything follows the theme. While measuring it owns the map's clicks
8
+ * (`MMapIdentify` waits). Geodesic numbers, the same as turf's. Available from the `/map` entry point.
9
+ *
10
+ * @event update:modelValue The measuring mode changed (`'distance'`, `'area'`, or null when it finished)
11
+ * @event change The measurements changed (added, edited, cleared): each one's points, length in meters and area in m²
12
+ */
13
+ import { computed, onBeforeUnmount, ref, shallowRef, useId, watch } from 'vue'
14
+ import type * as Maplibre from 'maplibre-gl'
15
+ import MIcon from './MIcon.vue'
16
+ import MMapControl from './MMapControl.vue'
17
+ import MMapMarker from './MMapMarker.vue'
18
+ import { useLocale } from '../composables/useLocale'
19
+ import { useMap } from '../composables/useMap'
20
+ import { useThemeTokens } from '../composables/_useThemeTokens'
21
+ import { centroid, closeRing, distance, midpoint, pathLength, ringArea, type LngLat } from '../composables/_mapGeometry'
22
+ import type { MapControlPosition } from './MMap.vue'
23
+
24
+ type Mode = 'distance' | 'area'
25
+
26
+ const props = withDefaults(
27
+ defineProps<{
28
+ /** The measuring mode (v-model): `'distance'`, `'area'`, or null. Set it to start measuring from outside */
29
+ modelValue?: Mode | null
30
+ /** Its buttons: `false` (drive it with v-model), or a corner (`true` is top-right) */
31
+ control?: boolean | MapControlPosition
32
+ }>(),
33
+ { modelValue: null, control: true },
34
+ )
35
+
36
+ const emit = defineEmits<{
37
+ 'update:modelValue': [mode: Mode | null]
38
+ change: [measurements: { mode: Mode; points: LngLat[]; closed: boolean; length: number; area?: number }[]]
39
+ }>()
40
+
41
+ const t = useLocale()
42
+ const { onReady, styleVersion, activeTool } = useMap()
43
+ const theme = useThemeTokens(['primary', 'surface'] as const)
44
+
45
+ const id = `m3-measure-${useId()}`
46
+ const SRC = { done: `${id}-done`, draft: `${id}-draft`, handles: `${id}-handles` }
47
+ const VERTEX = `${SRC.handles}-vertex`
48
+ const MIDPOINT = `${SRC.handles}-midpoint`
49
+
50
+ interface Measurement { mode: Mode; points: LngLat[]; closed: boolean }
51
+ // Plain state, stepped on every pointer move: only the labels and the buttons are reactive
52
+ const measurements: Measurement[] = []
53
+ let draft: LngLat[] = []
54
+ let cursor: LngLat | null = null
55
+ let closingByFirst = false
56
+ let drag: { m: number; v: number } | null = null
57
+ let raf = 0
58
+ let map: Maplibre.Map | undefined
59
+
60
+ const mode = ref<Mode | null>(null)
61
+ const count = ref(0)
62
+ // `m`: the finished measurement a total or area label belongs to (it carries that one's delete button)
63
+ const labels = shallowRef<{ key: string; at: LngLat; text: string; kind: 'segment' | 'total' | 'area'; m?: number }[]>([])
64
+
65
+ // ── Text ───────────────────────────────────────────────────────────────────────────────────────
66
+
67
+ const lang = () => (typeof document !== 'undefined' ? document.documentElement.lang || undefined : undefined)
68
+ const num = (n: number, digits: number) => new Intl.NumberFormat(lang(), { minimumFractionDigits: digits, maximumFractionDigits: digits }).format(n)
69
+ const fmtDistance = (m: number) => (m === 0 ? '' : m < 1000 ? `${num(Math.round(m), 0)} m` : `${num(m / 1000, 2)} km`)
70
+ const fmtArea = (m2: number) => (m2 >= 1e6 ? `${num(m2 / 1e6, 2)} km²` : m2 >= 1e4 ? `${num(m2 / 1e4, 2)} ha` : `${num(Math.round(m2), 0)} m²`)
71
+
72
+ // ── GeoJSON ────────────────────────────────────────────────────────────────────────────────────
73
+
74
+ // Just the GeoJSON this draws (the global GeoJSON namespace isn't always typed)
75
+ type Geometry = { type: 'Point'; coordinates: LngLat } | { type: 'LineString'; coordinates: LngLat[] } | { type: 'Polygon'; coordinates: LngLat[][] }
76
+ type Feature = { type: 'Feature'; geometry: Geometry; properties: Record<string, unknown> }
77
+ type Label = (typeof labels.value)[number]
78
+ const point = (p: LngLat, properties: Record<string, unknown> = {}): Feature => ({ type: 'Feature', geometry: { type: 'Point', coordinates: p }, properties })
79
+
80
+ /** A measurement's shapes, and its labels. */
81
+ function build(points: LngLat[], m: Mode, key: string, index?: number): { features: Feature[]; labels: Label[] } {
82
+ const features: Feature[] = points.map((p) => point(p))
83
+ const out: Label[] = []
84
+ if (points.length < 2) return { features, labels: out }
85
+ features.push({ type: 'Feature', geometry: { type: 'LineString', coordinates: points }, properties: {} })
86
+ const segments = (path: LngLat[]) => {
87
+ for (let i = 0; i < path.length - 1; i++) {
88
+ const text = fmtDistance(distance(path[i]!, path[i + 1]!))
89
+ if (text) out.push({ key: `${key}-s${i}`, at: midpoint(path[i]!, path[i + 1]!), text, kind: 'segment' })
90
+ }
91
+ }
92
+ if (m === 'distance') {
93
+ segments(points)
94
+ out.push({ key: `${key}-t`, at: points[points.length - 1]!, text: `${t.mapTotal}: ${fmtDistance(pathLength(points))}`, kind: 'total', m: index })
95
+ } else if (points.length >= 3) {
96
+ const ring = closeRing(points)
97
+ features.push({ type: 'Feature', geometry: { type: 'Polygon', coordinates: [ring] }, properties: {} })
98
+ segments(ring)
99
+ out.push({ key: `${key}-a`, at: centroid(ring), text: fmtArea(ringArea(ring)), kind: 'area', m: index })
100
+ } else {
101
+ out.push({ key: `${key}-t`, at: points[points.length - 1]!, text: fmtDistance(pathLength(points)), kind: 'total', m: index })
102
+ }
103
+ return { features, labels: out }
104
+ }
105
+
106
+ const collection = (features: Feature[]) => ({ type: 'FeatureCollection' as const, features })
107
+ const setData = (source: string, features: Feature[]) => (map?.getSource(source) as Maplibre.GeoJSONSource | undefined)?.setData(collection(features))
108
+
109
+ function render() {
110
+ if (!map) return
111
+ const done = measurements.map((m, i) => build(m.points, m.mode, `m${i}`, i))
112
+ const preview = mode.value && draft.length ? build(cursor ? [...draft, cursor] : draft, mode.value, 'draft') : { features: [], labels: [] }
113
+ setData(SRC.done, done.flatMap((d) => d.features))
114
+ setData(SRC.draft, preview.features)
115
+ // Edit handles while not drawing: every vertex, and every segment's midpoint
116
+ const handles: Feature[] = []
117
+ if (!mode.value) {
118
+ measurements.forEach((m, mi) => {
119
+ const vertices = m.closed ? m.points.slice(0, -1) : m.points
120
+ vertices.forEach((p, vi) => handles.push(point(p, { handle: 'vertex', m: mi, v: vi })))
121
+ for (let i = 0; i < m.points.length - 1; i++) handles.push(point(midpoint(m.points[i]!, m.points[i + 1]!), { handle: 'midpoint', m: mi, after: i }))
122
+ })
123
+ }
124
+ setData(SRC.handles, handles)
125
+ labels.value = [...done.flatMap((d) => d.labels), ...preview.labels]
126
+ }
127
+
128
+ function report() {
129
+ count.value = measurements.length
130
+ emit('change', measurements.map((m) => ({
131
+ mode: m.mode,
132
+ points: m.points.map((p) => [...p] as LngLat),
133
+ closed: m.closed,
134
+ length: pathLength(m.points),
135
+ ...(m.mode === 'area' || m.closed ? { area: ringArea(m.points) } : {}),
136
+ })))
137
+ }
138
+
139
+ // ── Layers ─────────────────────────────────────────────────────────────────────────────────────
140
+
141
+ const is = (type: string): Maplibre.FilterSpecification => ['==', ['geometry-type'], type]
142
+
143
+ function paints() {
144
+ const { primary, surface } = theme.value
145
+ return {
146
+ fill: { 'fill-color': primary },
147
+ line: { 'line-color': primary },
148
+ vertices: { 'circle-color': surface, 'circle-stroke-color': primary },
149
+ }
150
+ }
151
+
152
+ function ensureLayers() {
153
+ if (!map) return
154
+ for (const source of Object.values(SRC)) {
155
+ if (!map.getSource(source)) map.addSource(source, { type: 'geojson', data: collection([]) })
156
+ }
157
+ const p = paints()
158
+ const add = (layer: Maplibre.LayerSpecification) => { if (!map!.getLayer(layer.id)) map!.addLayer(layer) }
159
+ for (const [source, draftStyle] of [[SRC.done, false], [SRC.draft, true]] as const) {
160
+ add({ id: `${source}-fill`, type: 'fill', source, filter: is('Polygon'), paint: { ...p.fill, 'fill-opacity': draftStyle ? 0.15 : 0.2 } })
161
+ add({ id: `${source}-line`, type: 'line', source, filter: ['!=', ['geometry-type'], 'Point'], paint: { ...p.line, 'line-width': 3, ...(draftStyle ? { 'line-dasharray': [2, 2] } : {}) } })
162
+ add({ id: `${source}-points`, type: 'circle', source, filter: is('Point'), paint: { ...p.vertices, 'circle-radius': 5, 'circle-stroke-width': 2 } })
163
+ }
164
+ add({ id: MIDPOINT, type: 'circle', source: SRC.handles, filter: ['==', ['get', 'handle'], 'midpoint'], paint: { ...p.vertices, 'circle-radius': 4, 'circle-stroke-width': 1.5, 'circle-opacity': 0.7 } })
165
+ add({ id: VERTEX, type: 'circle', source: SRC.handles, filter: ['==', ['get', 'handle'], 'vertex'], paint: { ...p.vertices, 'circle-radius': 7, 'circle-stroke-width': 2.5 } })
166
+ }
167
+
168
+ watch(theme, () => {
169
+ if (!map) return
170
+ const p = paints()
171
+ const set = (layer: string, paint: Record<string, unknown>) => {
172
+ if (map!.getLayer(layer)) for (const [k, v] of Object.entries(paint)) map!.setPaintProperty(layer, k, v)
173
+ }
174
+ for (const source of [SRC.done, SRC.draft]) {
175
+ set(`${source}-fill`, p.fill)
176
+ set(`${source}-line`, p.line)
177
+ set(`${source}-points`, p.vertices)
178
+ }
179
+ set(MIDPOINT, p.vertices)
180
+ set(VERTEX, p.vertices)
181
+ })
182
+
183
+ // ── Measuring ──────────────────────────────────────────────────────────────────────────────────
184
+
185
+ const lngLatOf = (e: { lngLat: { lng: number; lat: number } }): LngLat => [e.lngLat.lng, e.lngLat.lat]
186
+
187
+ function onClick(e: Maplibre.MapMouseEvent) {
188
+ if (draft.length >= 2) {
189
+ const first = map!.project(draft[0]!)
190
+ if (Math.hypot(first.x - e.point.x, first.y - e.point.y) < 20) {
191
+ closingByFirst = true
192
+ finish()
193
+ return
194
+ }
195
+ }
196
+ draft.push(lngLatOf(e))
197
+ render()
198
+ }
199
+
200
+ function onMove(e: Maplibre.MapMouseEvent) {
201
+ cursor = lngLatOf(e)
202
+ if (raf) return
203
+ raf = requestAnimationFrame(() => {
204
+ raf = 0
205
+ render()
206
+ })
207
+ }
208
+
209
+ function onDblClick(e: Maplibre.MapMouseEvent) {
210
+ e.preventDefault()
211
+ if (draft.length < 2) return
212
+ // The double click's first click added a point on top of the last one
213
+ const a = map!.project(draft[draft.length - 1]!)
214
+ const b = map!.project(draft[draft.length - 2]!)
215
+ if (Math.hypot(a.x - b.x, a.y - b.y) < 10) draft.pop()
216
+ finish()
217
+ }
218
+
219
+ function onKey(e: KeyboardEvent) {
220
+ if (e.key === 'Escape' || e.key === 'Enter') finish(e.key === 'Escape')
221
+ }
222
+
223
+ // In fullscreen the browser keeps Escape to leave it, and the page never sees it. Keyboard Lock (Chromium) lets the
224
+ // page have it while measuring, so Escape finishes the measurement (holding Escape still leaves fullscreen)
225
+ type KeyboardLock = { lock?: (keys: string[]) => Promise<void>; unlock?: () => void }
226
+ const keyboard = () => (typeof navigator !== 'undefined' ? (navigator as Navigator & { keyboard?: KeyboardLock }).keyboard : undefined)
227
+ let locked = false
228
+ function lockEscape() {
229
+ if (!mode.value || !document.fullscreenElement || !keyboard()?.lock) return
230
+ keyboard()!.lock!(['Escape']).then(() => { locked = true }, () => {})
231
+ }
232
+ function unlockEscape() {
233
+ // Measuring again by then: that measurement holds the lock now
234
+ if (mode.value) return
235
+ if (locked) keyboard()?.unlock?.()
236
+ locked = false
237
+ }
238
+ // Released once the Escape that finished the measurement is let go: unlocking during its keydown hands the rest of
239
+ // that press back to the browser, which then leaves fullscreen anyway
240
+ function unlockAfterEscape() {
241
+ let fallback: ReturnType<typeof setTimeout> | undefined
242
+ const done = () => {
243
+ document.removeEventListener('keyup', onUp, true)
244
+ clearTimeout(fallback)
245
+ setTimeout(unlockEscape)
246
+ }
247
+ const onUp = (e: KeyboardEvent) => { if (e.key === 'Escape') done() }
248
+ document.addEventListener('keyup', onUp, true)
249
+ fallback = setTimeout(done, 1500)
250
+ }
251
+
252
+ function start(next: Mode) {
253
+ if (!map) return
254
+ if (mode.value === next) return finish()
255
+ if (mode.value) finish()
256
+ mode.value = next
257
+ activeTool.value = 'measure'
258
+ draft = []
259
+ cursor = null
260
+ map.getCanvas().style.cursor = 'crosshair'
261
+ map.doubleClickZoom.disable()
262
+ map.on('click', onClick)
263
+ map.on('mousemove', onMove)
264
+ map.on('dblclick', onDblClick)
265
+ document.addEventListener('keydown', onKey)
266
+ document.addEventListener('fullscreenchange', lockEscape)
267
+ lockEscape()
268
+ render()
269
+ if (props.modelValue !== next) emit('update:modelValue', next)
270
+ }
271
+
272
+ function finish(byEscape = false) {
273
+ if (!map || !mode.value) return
274
+ cancelAnimationFrame(raf)
275
+ raf = 0
276
+ const closed = draft.length >= 3 && (closingByFirst || mode.value === 'area')
277
+ if (draft.length >= 2) {
278
+ measurements.push({ mode: mode.value, points: closed ? [...draft, [...draft[0]!] as LngLat] : draft, closed })
279
+ }
280
+ draft = []
281
+ cursor = null
282
+ closingByFirst = false
283
+ mode.value = null
284
+ if (activeTool.value === 'measure') activeTool.value = null
285
+ map.getCanvas().style.cursor = ''
286
+ map.doubleClickZoom.enable()
287
+ map.off('click', onClick)
288
+ map.off('mousemove', onMove)
289
+ map.off('dblclick', onDblClick)
290
+ document.removeEventListener('keydown', onKey)
291
+ document.removeEventListener('fullscreenchange', lockEscape)
292
+ if (byEscape && locked) unlockAfterEscape()
293
+ else unlockEscape()
294
+ render()
295
+ report()
296
+ if (props.modelValue !== null) emit('update:modelValue', null)
297
+ }
298
+
299
+ /** Deletes one finished measurement. */
300
+ function remove(index: number) {
301
+ if (!measurements[index]) return
302
+ measurements.splice(index, 1)
303
+ render()
304
+ report()
305
+ }
306
+
307
+ function clear() {
308
+ if (mode.value) finish()
309
+ measurements.length = 0
310
+ render()
311
+ report()
312
+ }
313
+
314
+ // ── Editing ────────────────────────────────────────────────────────────────────────────────────
315
+
316
+ type HandleEvent = (Maplibre.MapMouseEvent | Maplibre.MapTouchEvent) & { features?: Maplibre.MapGeoJSONFeature[] }
317
+
318
+ function onHandleDown(e: HandleEvent) {
319
+ const f = e.features?.[0]
320
+ if (!f || mode.value || !map) return
321
+ e.preventDefault()
322
+ const mi = f.properties.m as number
323
+ const m = measurements[mi]
324
+ if (!m) return
325
+ let vi = f.properties.v as number
326
+ if (f.properties.handle === 'midpoint') {
327
+ vi = (f.properties.after as number) + 1
328
+ m.points.splice(vi, 0, lngLatOf(e))
329
+ }
330
+ drag = { m: mi, v: vi }
331
+ activeTool.value = 'measure'
332
+ map.getCanvas().style.cursor = 'grabbing'
333
+ const touch = e.type === 'touchstart'
334
+ if (touch) map.dragPan.disable()
335
+ map.on(touch ? 'touchmove' : 'mousemove', onDragMove)
336
+ map.once(touch ? 'touchend' : 'mouseup', onDragEnd)
337
+ render()
338
+ }
339
+
340
+ function onDragMove(e: Maplibre.MapMouseEvent | Maplibre.MapTouchEvent) {
341
+ if (!drag) return
342
+ const m = measurements[drag.m]
343
+ if (!m) return
344
+ const p = lngLatOf(e)
345
+ m.points[drag.v] = p
346
+ if (m.closed && drag.v === 0) m.points[m.points.length - 1] = p
347
+ render()
348
+ }
349
+
350
+ function onDragEnd() {
351
+ if (!map) return
352
+ drag = null
353
+ map.off('mousemove', onDragMove)
354
+ map.off('touchmove', onDragMove)
355
+ map.dragPan.enable()
356
+ map.getCanvas().style.cursor = ''
357
+ report()
358
+ // The click that ends a press comes after mouseup: keep it from MMapIdentify
359
+ setTimeout(() => { if (activeTool.value === 'measure' && !mode.value) activeTool.value = null })
360
+ }
361
+
362
+ const onHandleEnter = () => { if (map && !drag && !mode.value) map.getCanvas().style.cursor = 'grab' }
363
+ const onHandleLeave = () => { if (map && !drag && !mode.value) map.getCanvas().style.cursor = '' }
364
+
365
+ onReady((m) => {
366
+ map = m
367
+ ensureLayers()
368
+ for (const layer of [VERTEX, MIDPOINT]) {
369
+ m.on('mousedown', layer, onHandleDown)
370
+ m.on('touchstart', layer, onHandleDown)
371
+ m.on('mouseenter', layer, onHandleEnter)
372
+ m.on('mouseleave', layer, onHandleLeave)
373
+ }
374
+ if (props.modelValue) start(props.modelValue)
375
+ })
376
+ watch(styleVersion, () => {
377
+ ensureLayers()
378
+ render()
379
+ })
380
+ watch(() => props.modelValue, (next) => {
381
+ if (next && next !== mode.value) start(next)
382
+ else if (!next && mode.value) finish()
383
+ })
384
+
385
+ onBeforeUnmount(() => {
386
+ if (!map) return
387
+ if (mode.value) finish()
388
+ for (const layer of [VERTEX, MIDPOINT]) {
389
+ map.off('mousedown', layer, onHandleDown)
390
+ map.off('touchstart', layer, onHandleDown)
391
+ map.off('mouseenter', layer, onHandleEnter)
392
+ map.off('mouseleave', layer, onHandleLeave)
393
+ }
394
+ const layers = [VERTEX, MIDPOINT, ...[SRC.done, SRC.draft].flatMap((s) => [`${s}-points`, `${s}-line`, `${s}-fill`])]
395
+ for (const layer of layers) if (map.getLayer(layer)) map.removeLayer(layer)
396
+ for (const source of Object.values(SRC)) if (map.getSource(source)) map.removeSource(source)
397
+ })
398
+
399
+ const corner = computed(() => (props.control === true ? 'top-right' : props.control || 'top-right'))
400
+
401
+ defineExpose({ start, finish, clear, remove })
402
+ </script>
403
+
404
+ <template>
405
+ <div class="hidden">
406
+ <MMapControl v-if="control" :position="corner">
407
+ <button type="button" class="grid place-items-center" :title="t.mapMeasureDistance" :aria-pressed="mode === 'distance'" @click="start('distance')">
408
+ <MIcon name="straighten" :size="20" />
409
+ </button>
410
+ <button type="button" class="grid place-items-center" :title="t.mapMeasureArea" :aria-pressed="mode === 'area'" @click="start('area')">
411
+ <MIcon name="pentagon" :size="20" />
412
+ </button>
413
+ <button type="button" class="grid place-items-center" :title="t.mapClearMeasurements" :disabled="!count && !mode" @click="clear">
414
+ <MIcon name="delete" :size="20" />
415
+ </button>
416
+ </MMapControl>
417
+ <!-- Labels: M3 chips that let the pointer through to the map -->
418
+ <MMapMarker
419
+ v-for="label in labels"
420
+ :key="label.key"
421
+ :lng-lat="label.at"
422
+ :anchor="label.kind === 'area' ? 'center' : 'top'"
423
+ :offset="label.kind === 'area' ? [0, 0] : [0, 8]"
424
+ class="pointer-events-none"
425
+ >
426
+ <span
427
+ class="flex items-center gap-1 whitespace-nowrap rounded-full py-0.5 shadow-elevation-1"
428
+ :class="[
429
+ label.kind === 'segment' ? 'bg-surface-container-highest text-label-small text-on-surface' : 'bg-primary text-label-medium text-on-primary',
430
+ label.m !== undefined ? 'pr-0.5 pl-2' : 'px-2',
431
+ ]"
432
+ >
433
+ {{ label.text }}
434
+ <!-- Deletes this measurement; it catches its own pointer, so the map neither pans nor gets a click -->
435
+ <button
436
+ v-if="label.m !== undefined"
437
+ type="button"
438
+ class="pointer-events-auto grid size-5 cursor-pointer place-items-center rounded-full hover:bg-on-primary/12 focus-visible:outline-2 focus-visible:outline-on-primary"
439
+ :aria-label="t.mapDeleteMeasurement"
440
+ :title="t.mapDeleteMeasurement"
441
+ @click.stop="remove(label.m)"
442
+ @pointerdown.stop
443
+ @mousedown.stop
444
+ @touchstart.stop
445
+ @dblclick.stop
446
+ >
447
+ <MIcon name="close" :size="14" />
448
+ </button>
449
+ </span>
450
+ </MMapMarker>
451
+ </div>
452
+ </template>
@@ -0,0 +1,103 @@
1
+ <script setup lang="ts">
2
+ /**
3
+ * A popup on an `MMap` at `lngLat`, shown while `open` (v-model): e.g. what the user clicked on. Its content is the
4
+ * default slot, styled as an M3 surface. For a popup that opens from a marker, use `MMapMarker`'s `#popup` slot.
5
+ * Available from the `/map` entry point.
6
+ *
7
+ * @slot default The popup's content
8
+ * @event update:open Closed by its close button or a click on the map (`closeOnClick`)
9
+ */
10
+ import { onBeforeUnmount, ref, watch } from 'vue'
11
+ import type * as Maplibre from 'maplibre-gl'
12
+ import { useMap } from '../composables/useMap'
13
+
14
+ // Attributes (class, style…) go on what's shown on the map, not on the hidden wrapper it's rendered in
15
+ defineOptions({ inheritAttrs: false })
16
+
17
+ const props = withDefaults(
18
+ defineProps<{
19
+ /** Position, `[lng, lat]` */
20
+ lngLat: [number, number]
21
+ /** Shown (v-model) */
22
+ open?: boolean
23
+ /** Show a close button */
24
+ closeButton?: boolean
25
+ /** Close it when the map is clicked */
26
+ closeOnClick?: boolean
27
+ /** Where the popup sits relative to `lngLat`. By default MapLibre picks the side with room */
28
+ anchor?: Maplibre.PositionAnchor
29
+ /**
30
+ * Offset from `lngLat`: pixels, `[x, y]`, or one per side (`{ bottom: [0, -38], … }`, MapLibre's `Offset`).
31
+ * By default none: its tip touches the point
32
+ */
33
+ offset?: Maplibre.Offset
34
+ /** Maximum width (CSS) */
35
+ maxWidth?: string
36
+ }>(),
37
+ { open: true, closeButton: true, closeOnClick: true, maxWidth: '320px' },
38
+ )
39
+
40
+ const emit = defineEmits<{ 'update:open': [open: boolean] }>()
41
+
42
+ const content = ref<HTMLElement>()
43
+ const { onReady } = useMap()
44
+
45
+ let popup: Maplibre.Popup | undefined
46
+ let map: Maplibre.Map | undefined
47
+ // Closing it from `open` (rather than by the user) mustn't echo back as update:open
48
+ let closingFromProp = false
49
+
50
+ function show() {
51
+ if (!popup || !map || popup.isOpen()) return
52
+ popup.setLngLat(props.lngLat).addTo(map)
53
+ }
54
+
55
+ onReady((m, ml) => {
56
+ map = m
57
+ popup = new ml.Popup({
58
+ closeButton: props.closeButton,
59
+ closeOnClick: props.closeOnClick,
60
+ closeOnMove: false,
61
+ anchor: props.anchor,
62
+ ...(props.offset !== undefined ? { offset: props.offset } : {}),
63
+ maxWidth: props.maxWidth,
64
+ focusAfterOpen: false,
65
+ })
66
+ if (content.value) popup.setDOMContent(content.value)
67
+ popup.on('close', () => {
68
+ if (!closingFromProp) emit('update:open', false)
69
+ })
70
+ if (props.open) show()
71
+ })
72
+
73
+ watch(() => props.open, (open) => {
74
+ if (open) show()
75
+ else if (popup?.isOpen()) {
76
+ closingFromProp = true
77
+ popup.remove()
78
+ closingFromProp = false
79
+ }
80
+ })
81
+ watch(() => props.lngLat.join(','), () => popup?.setLngLat(props.lngLat))
82
+ watch(() => props.maxWidth, (w) => popup?.setMaxWidth(w))
83
+ watch(() => props.offset, (offset) => popup?.setOffset(offset ?? 0))
84
+
85
+ onBeforeUnmount(() => {
86
+ closingFromProp = true
87
+ popup?.remove()
88
+ })
89
+
90
+ defineExpose({
91
+ /** The MapLibre popup */
92
+ popup: () => popup,
93
+ })
94
+ </script>
95
+
96
+ <template>
97
+ <!-- Moved into the popup by MapLibre -->
98
+ <div class="hidden">
99
+ <div ref="content" v-bind="$attrs">
100
+ <slot />
101
+ </div>
102
+ </div>
103
+ </template>