@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
@@ -66,6 +66,96 @@ function onTipLeave() {
66
66
  visible.value = false
67
67
  }
68
68
 
69
+ // Input as Compose's BasicTooltip: a mouse shows it on hover; touch and pen on a long press, which also swallows
70
+ // the click it would end in (a long-pressed button doesn't fire) and hides it TOUCH_DURATION after the finger
71
+ // lifts (BasicTooltipDefaults.TooltipDuration); focus only from the keyboard. Before, the mouse events a browser
72
+ // emulates for a tap (and the focus a tap gives a button) showed it on every tap, and it stuck around.
73
+ const LONG_PRESS = 500
74
+ const TOUCH_DURATION = 1500
75
+ let press: { id: number; x: number; y: number; timer: ReturnType<typeof setTimeout> } | null = null
76
+ let longPressed = false
77
+
78
+ function onPointerEnter(e: PointerEvent) {
79
+ if (e.pointerType === 'mouse') show()
80
+ }
81
+ function onPointerLeave(e: PointerEvent) {
82
+ if (e.pointerType === 'mouse') hide()
83
+ }
84
+
85
+ function endPress() {
86
+ if (press) clearTimeout(press.timer)
87
+ press = null
88
+ window.removeEventListener('pointermove', onPressMove)
89
+ window.removeEventListener('pointerup', onPressUp)
90
+ window.removeEventListener('pointercancel', onPressCancel)
91
+ }
92
+ function onPointerDown(e: PointerEvent) {
93
+ if (e.pointerType === 'mouse') return
94
+ endPress()
95
+ longPressed = false
96
+ press = {
97
+ id: e.pointerId,
98
+ x: e.clientX,
99
+ y: e.clientY,
100
+ timer: setTimeout(async () => {
101
+ longPressed = true
102
+ cancelTimers()
103
+ visible.value = true
104
+ await nextTick()
105
+ reposition()
106
+ }, LONG_PRESS),
107
+ }
108
+ window.addEventListener('pointermove', onPressMove)
109
+ window.addEventListener('pointerup', onPressUp)
110
+ window.addEventListener('pointercancel', onPressCancel)
111
+ }
112
+ function onPressMove(e: PointerEvent) {
113
+ if (press && e.pointerId === press.id && Math.hypot(e.clientX - press.x, e.clientY - press.y) > 10) endPress()
114
+ }
115
+ function onPressUp(e: PointerEvent) {
116
+ if (!press || e.pointerId !== press.id) return
117
+ endPress()
118
+ if (!longPressed) return
119
+ cancelTimers()
120
+ // A rich tooltip may hold actions to tap: it stays until a touch outside it (Compose's persistent tooltips)
121
+ if (props.rich) document.addEventListener('pointerdown', onOutsideTouch, true)
122
+ else hideTimer = setTimeout(() => { visible.value = false }, TOUCH_DURATION)
123
+ }
124
+ function onOutsideTouch(e: PointerEvent) {
125
+ const t = e.target as Node
126
+ if (tipEl.value?.contains(t) || triggerEl.value?.contains(t)) return
127
+ document.removeEventListener('pointerdown', onOutsideTouch, true)
128
+ visible.value = false
129
+ }
130
+ // The browser took the touch (a scroll)
131
+ function onPressCancel(e: PointerEvent) {
132
+ if (!press || e.pointerId !== press.id) return
133
+ endPress()
134
+ if (longPressed) hide()
135
+ }
136
+ // The click a long press ends in, and the context menu it may open, belong to the tooltip
137
+ function onClickCapture(e: MouseEvent) {
138
+ if (!longPressed) return
139
+ longPressed = false
140
+ e.preventDefault()
141
+ e.stopPropagation()
142
+ }
143
+ function onContextMenu(e: Event) {
144
+ if (press || longPressed) e.preventDefault()
145
+ }
146
+
147
+ function onFocusIn(e: FocusEvent) {
148
+ let keyboard = true
149
+ try { keyboard = (e.target as Element).matches(':focus-visible') } catch { /* no :focus-visible: show */ }
150
+ if (keyboard) show()
151
+ }
152
+ function onKeyDown(e: KeyboardEvent) {
153
+ if (e.key === 'Escape' && visible.value) {
154
+ cancelTimers()
155
+ visible.value = false
156
+ }
157
+ }
158
+
69
159
  function onScroll() {
70
160
  if (visible.value) {
71
161
  cancelTimers()
@@ -96,6 +186,8 @@ onMounted(() => window.addEventListener('scroll', onScroll, true))
96
186
  onUnmounted(() => {
97
187
  window.removeEventListener('scroll', onScroll, true)
98
188
  cancelTimers()
189
+ endPress()
190
+ document.removeEventListener('pointerdown', onOutsideTouch, true)
99
191
  })
100
192
  </script>
101
193
 
@@ -104,10 +196,14 @@ onUnmounted(() => {
104
196
  ref="triggerEl"
105
197
  v-bind="$attrs"
106
198
  class="inline-flex"
107
- @mouseenter="show"
108
- @mouseleave="hide"
109
- @focusin="show"
199
+ @pointerenter="onPointerEnter"
200
+ @pointerleave="onPointerLeave"
201
+ @pointerdown="onPointerDown"
202
+ @click.capture="onClickCapture"
203
+ @contextmenu="onContextMenu"
204
+ @focusin="onFocusIn"
110
205
  @focusout="hide"
206
+ @keydown="onKeyDown"
111
207
  >
112
208
  <slot />
113
209
  </span>
@@ -0,0 +1,81 @@
1
+ <script setup lang="ts">
2
+ /*
3
+ * Internal (not exported): MMap's attribution, instead of MapLibre's AttributionControl. A round M3 icon button in a
4
+ * corner (surface, elevation 2) that opens into a pill with the credits of the style's sources, its size springing
5
+ * open and closed through MMapControl. The credits are collected like MapLibre's control does: the attribution of
6
+ * every source a layer uses (from its TileJSON once loaded, else the style), without repeats or ones contained in
7
+ * another. They're HTML from the style (links), as MapLibre renders them.
8
+ */
9
+ import { computed, ref } from 'vue'
10
+ import type * as Maplibre from 'maplibre-gl'
11
+ import MIcon from './MIcon.vue'
12
+ import MMapControl from './MMapControl.vue'
13
+ import { useMap } from '../composables/useMap'
14
+ import { useLocale } from '../composables/useLocale'
15
+ import type { MapControlPosition } from './MMap.vue'
16
+
17
+ const props = defineProps<{ position: MapControlPosition }>()
18
+
19
+ const t = useLocale()
20
+ const { on, onReady } = useMap()
21
+
22
+ const credits = ref<string[]>([])
23
+ const open = ref(true)
24
+ // The text wraps against the map's width, not the control's while its size springs (it would reflow every frame)
25
+ const maxWidth = ref(0)
26
+ let map: Maplibre.Map | undefined
27
+
28
+ function collect() {
29
+ if (!map) return
30
+ const style = map.getStyle?.()
31
+ if (!style?.sources) return
32
+ const used = new Set(style.layers?.map((l) => (l as { source?: string }).source).filter(Boolean))
33
+ const found: string[] = []
34
+ for (const [id, spec] of Object.entries(style.sources)) {
35
+ if (used.size && !used.has(id)) continue
36
+ const text = (map.getSource(id) as { attribution?: string } | undefined)?.attribution ?? (spec as { attribution?: string }).attribution
37
+ if (text && !found.includes(text)) found.push(text)
38
+ }
39
+ const next = found.filter((a) => !found.some((b) => b !== a && b.includes(a)))
40
+ if (next.join('\n') !== credits.value.join('\n')) credits.value = next
41
+ maxWidth.value = Math.max(0, map.getContainer().clientWidth - 20)
42
+ }
43
+
44
+ onReady((m) => {
45
+ map = m
46
+ collect()
47
+ })
48
+ on('styledata', collect)
49
+ on('sourcedata', collect)
50
+ on('resize', collect)
51
+ // Open when the map loads, folded away once it's dragged, as MapLibre's compact attribution
52
+ on('dragstart', () => { open.value = false })
53
+
54
+ const html = computed(() => credits.value.join(' '))
55
+ // The button sits at the corner's outer edge, the text inward
56
+ const end = computed(() => props.position.endsWith('right'))
57
+ </script>
58
+
59
+ <template>
60
+ <MMapControl
61
+ v-if="html"
62
+ :position="position"
63
+ :group="false"
64
+ class="m3-map-attrib"
65
+ :class="open ? 'm3-map-attrib-open' : ''"
66
+ >
67
+ <div class="m3-map-attrib-row" :class="end ? 'flex-row-reverse' : ''" :style="maxWidth ? { maxWidth: `${maxWidth}px` } : undefined">
68
+ <button
69
+ type="button"
70
+ class="m3-map-attrib-button"
71
+ :title="t.mapToggleAttribution"
72
+ :aria-label="t.mapToggleAttribution"
73
+ :aria-expanded="open"
74
+ @click="open = !open"
75
+ >
76
+ <MIcon name="info" :size="20" />
77
+ </button>
78
+ <div v-if="open" class="m3-map-attrib-text" :class="end ? 'pl-3.5' : 'pr-3.5'" v-html="html" />
79
+ </div>
80
+ </MMapControl>
81
+ </template>
@@ -0,0 +1,77 @@
1
+ <script setup lang="ts">
2
+ // Internal: one layer of MMapLayers (visibility, title, and expanded: description, opacity, legend, download)
3
+ import MIcon from './MIcon.vue'
4
+ import MSlider from './MSlider.vue'
5
+ import { useLocale } from '../composables/useLocale'
6
+ import { useMapLayers } from '../composables/useMapLayers'
7
+ import type { MapLayerInfo } from '../composables/mapAdapters'
8
+
9
+ defineProps<{ layer: MapLayerInfo; expanded: boolean }>()
10
+ const emit = defineEmits<{ 'toggle-expanded': [] }>()
11
+
12
+ const t = useLocale()
13
+ const { isVisible, toggle, opacityOf, setOpacity } = useMapLayers()
14
+ </script>
15
+
16
+ <template>
17
+ <div class="flex overflow-hidden rounded-2xl bg-surface-container" :class="isVisible(layer.id) ? '' : 'opacity-75'">
18
+ <div class="w-1 shrink-0 transition-colors duration-200" :class="isVisible(layer.id) ? 'bg-primary' : 'bg-outline-variant'" />
19
+ <div class="flex min-w-0 flex-1 flex-col">
20
+ <div class="flex cursor-pointer items-center gap-2 px-3 py-2" @click="emit('toggle-expanded')">
21
+ <button
22
+ type="button"
23
+ class="grid size-8 shrink-0 cursor-pointer place-items-center rounded-full transition-colors duration-200"
24
+ :class="isVisible(layer.id) ? 'bg-primary/12 text-primary' : 'bg-on-surface/5 text-on-surface-variant'"
25
+ :aria-label="isVisible(layer.id) ? t.mapHideLayer : t.mapShowLayer"
26
+ :aria-pressed="isVisible(layer.id)"
27
+ @click.stop="toggle(layer.id)"
28
+ >
29
+ <MIcon :name="isVisible(layer.id) ? 'visibility' : 'visibility_off'" :size="18" />
30
+ </button>
31
+ <div class="flex min-w-0 flex-1 flex-col">
32
+ <span class="truncate text-body-medium" :class="isVisible(layer.id) ? 'text-on-surface' : 'text-on-surface-variant'">{{ layer.title }}</span>
33
+ <span v-if="layer.description && !expanded" class="truncate text-label-small text-on-surface-variant">{{ layer.description }}</span>
34
+ </div>
35
+ <span v-if="isVisible(layer.id) && opacityOf(layer.id) < 1" class="rounded-full bg-primary/8 px-2 py-0.5 text-label-small tabular-nums text-primary">
36
+ {{ Math.round(opacityOf(layer.id) * 100) }}%
37
+ </span>
38
+ <MIcon name="expand_more" :size="18" class="shrink-0 text-on-surface-variant transition-transform duration-300" :class="expanded ? 'rotate-180' : ''" />
39
+ </div>
40
+ <!-- Expands with grid rows 0fr → 1fr, so the height animates without measuring it -->
41
+ <div class="grid transition-[grid-template-rows] duration-300 ease-[cubic-bezier(0.2,0,0,1)]" :style="{ gridTemplateRows: expanded ? '1fr' : '0fr' }">
42
+ <div class="min-h-0 overflow-hidden">
43
+ <div class="flex flex-col gap-3 px-3 pb-3">
44
+ <p v-if="layer.description" class="text-body-small text-on-surface-variant">{{ layer.description }}</p>
45
+ <div class="flex items-center gap-2 rounded-2xl bg-surface-container-highest/60 px-3 py-1">
46
+ <MIcon name="opacity" :size="16" class="shrink-0 text-on-surface-variant" />
47
+ <MSlider
48
+ :model-value="opacityOf(layer.id)"
49
+ :min="0"
50
+ :max="1"
51
+ :step="0.01"
52
+ :label="t.mapOpacity"
53
+ class="flex-1"
54
+ @update:model-value="setOpacity(layer.id, Number($event))"
55
+ />
56
+ </div>
57
+ <img v-if="layer.legend" :src="layer.legend" alt="" class="max-w-full self-start" loading="lazy">
58
+ <div v-if="layer.download || $slots.actions" class="flex flex-wrap items-center gap-2">
59
+ <a
60
+ v-if="layer.download"
61
+ :href="layer.download"
62
+ target="_blank"
63
+ rel="noopener"
64
+ download
65
+ class="inline-flex items-center gap-1 rounded-full px-3 py-1.5 text-label-large text-primary hover:bg-primary/8"
66
+ >
67
+ <MIcon name="download" :size="18" />
68
+ {{ t.mapDownload }}
69
+ </a>
70
+ <slot name="actions" :layer="layer" :visible="isVisible(layer.id)" />
71
+ </div>
72
+ </div>
73
+ </div>
74
+ </div>
75
+ </div>
76
+ </div>
77
+ </template>
@@ -0,0 +1,75 @@
1
+ // Internal: the geodesy MMapMeasure needs, on a sphere of the Earth's mean radius (as @turf/length and @turf/area do,
2
+ // so the numbers match what the Orvian viewers measured with turf)
3
+
4
+ export type LngLat = [number, number]
5
+
6
+ const R = 6371008.8 // meters
7
+ const RAD = Math.PI / 180
8
+
9
+ /** Great-circle distance between two points, in meters (haversine). */
10
+ export function distance(a: LngLat, b: LngLat): number {
11
+ const dLat = (b[1] - a[1]) * RAD
12
+ const dLng = (b[0] - a[0]) * RAD
13
+ const h = Math.sin(dLat / 2) ** 2 + Math.cos(a[1] * RAD) * Math.cos(b[1] * RAD) * Math.sin(dLng / 2) ** 2
14
+ return 2 * R * Math.asin(Math.min(1, Math.sqrt(h)))
15
+ }
16
+
17
+ /** The length of a path, in meters. */
18
+ export function pathLength(points: LngLat[]): number {
19
+ let total = 0
20
+ for (let i = 1; i < points.length; i++) total += distance(points[i - 1]!, points[i]!)
21
+ return total
22
+ }
23
+
24
+ /** The point halfway along the great circle between two points. */
25
+ export function midpoint(a: LngLat, b: LngLat): LngLat {
26
+ const [l1, p1, l2, p2] = [a[0] * RAD, a[1] * RAD, b[0] * RAD, b[1] * RAD]
27
+ const bx = Math.cos(p2) * Math.cos(l2 - l1)
28
+ const by = Math.cos(p2) * Math.sin(l2 - l1)
29
+ const lat = Math.atan2(Math.sin(p1) + Math.sin(p2), Math.sqrt((Math.cos(p1) + bx) ** 2 + by ** 2))
30
+ const lng = l1 + Math.atan2(by, Math.cos(p1) + bx)
31
+ return [lng / RAD, lat / RAD]
32
+ }
33
+
34
+ /** The area of a ring (closed or not), in square meters, on the sphere (@turf/area's formula). */
35
+ export function ringArea(points: LngLat[]): number {
36
+ const ring = closeRing(points)
37
+ const n = ring.length - 1
38
+ if (n <= 2) return 0
39
+ let total = 0
40
+ for (let i = 0; i < n; i++) {
41
+ const lower = ring[i]!
42
+ const middle = ring[i + 1 === n ? 0 : i + 1]!
43
+ const upper = ring[i + 2 >= n ? (i + 2) % n : i + 2]!
44
+ total += (upper[0] - lower[0]) * RAD * Math.sin(middle[1] * RAD)
45
+ }
46
+ return Math.abs((total * R * R) / 2)
47
+ }
48
+
49
+ /** The ring with its first point repeated at the end. */
50
+ export function closeRing(points: LngLat[]): LngLat[] {
51
+ const first = points[0]
52
+ const last = points[points.length - 1]
53
+ return first && last && (first[0] !== last[0] || first[1] !== last[1]) ? [...points, first] : points
54
+ }
55
+
56
+ /** Where to label a polygon: its area centroid (in degrees, fine at a measuring scale), or the vertices' mean. */
57
+ export function centroid(points: LngLat[]): LngLat {
58
+ const ring = closeRing(points)
59
+ let a = 0
60
+ let x = 0
61
+ let y = 0
62
+ for (let i = 0; i < ring.length - 1; i++) {
63
+ const [x0, y0] = ring[i]!
64
+ const [x1, y1] = ring[i + 1]!
65
+ const f = x0 * y1 - x1 * y0
66
+ a += f
67
+ x += (x0 + x1) * f
68
+ y += (y0 + y1) * f
69
+ }
70
+ if (Math.abs(a) < 1e-12) {
71
+ const pts = ring.slice(0, -1)
72
+ return [pts.reduce((s, p) => s + p[0], 0) / pts.length, pts.reduce((s, p) => s + p[1], 0) / pts.length]
73
+ }
74
+ return [x / (3 * a), y / (3 * a)]
75
+ }
@@ -0,0 +1,25 @@
1
+ // Internal (not exported): MapLibre's default marker pin. Its SVG is 41px tall with the tip at the center of the
2
+ // shadow ellipse below it (y ≈ 34.8), so MapLibre places it by its center, offset [0, -14], and gives a popup it
3
+ // opens an offset per side (Marker.setPopup) so the popup meets the pin wherever it opens. Passing the pin an
4
+ // anchor of 'bottom' (plus that default offset) put the tip about 20px above its point.
5
+ import type * as Maplibre from 'maplibre-gl'
6
+
7
+ const HEIGHT = 41 - 5.8 / 2
8
+ const RADIUS = 13.5
9
+ const LINEAR = RADIUS / Math.SQRT2
10
+
11
+ /** The default pin's offset with its default (center) anchor */
12
+ export const PIN_OFFSET: [number, number] = [0, -14]
13
+
14
+ /** Offsets for a popup at a pin's point, per side, as MapLibre's Marker.setPopup gives them */
15
+ export const PIN_POPUP_OFFSET: Record<Maplibre.PositionAnchor, [number, number]> = {
16
+ center: [0, 0],
17
+ top: [0, 0],
18
+ 'top-left': [0, 0],
19
+ 'top-right': [0, 0],
20
+ bottom: [0, -HEIGHT],
21
+ 'bottom-left': [LINEAR, (HEIGHT - RADIUS + LINEAR) * -1],
22
+ 'bottom-right': [-LINEAR, (HEIGHT - RADIUS + LINEAR) * -1],
23
+ left: [RADIUS, (HEIGHT - RADIUS) * -1],
24
+ right: [-RADIUS, (HEIGHT - RADIUS) * -1],
25
+ }
@@ -0,0 +1,39 @@
1
+ /*
2
+ * Internal (not exported from index.ts): keeps a popup on screen along one axis, after Compose's
3
+ * DropdownMenuPositionProvider (material3/internal/MenuPosition.kt). The candidates are tried in order and the
4
+ * first that fits inside the window, MARGIN in from its edges (MenuHorizontalMargin), wins; when none does, a
5
+ * popup wider than the window minus the margins is centered, anything else is clamped inside them.
6
+ *
7
+ * Measure the popup with nothing constraining its width (no `right`, no narrow `left`) before calling this:
8
+ * a fixed element anchored on its right shrinks to the space on its left, which is the very overflow to avoid.
9
+ */
10
+
11
+ /** Compose's MenuHorizontalMargin (8dp). */
12
+ export const POPUP_MARGIN = 8
13
+
14
+ /** The first candidate start position that keeps `size` inside `viewport`, else centered or clamped. */
15
+ export function fitPopup(candidates: number[], size: number, viewport: number, margin = POPUP_MARGIN): number {
16
+ for (const x of candidates) {
17
+ if (x >= margin && x + size <= viewport - margin) return x
18
+ }
19
+ if (size >= viewport - 2 * margin) return (viewport - size) / 2
20
+ const last = candidates[candidates.length - 1] ?? margin
21
+ return Math.min(viewport - margin - size, Math.max(margin, last))
22
+ }
23
+
24
+ /**
25
+ * A dropdown's left edge: aligned with the anchor's start or end edge (`align` picks which is tried first), else
26
+ * against the window edge on the anchor's side (MenuAnchorPosition.Below's xCandidates).
27
+ */
28
+ export function dropdownX(
29
+ anchor: { left: number; right: number },
30
+ width: number,
31
+ viewport: number,
32
+ align: 'start' | 'end',
33
+ margin = POPUP_MARGIN,
34
+ ): number {
35
+ const start = anchor.left
36
+ const end = anchor.right - width
37
+ const windowSide = (anchor.left + anchor.right) / 2 < viewport / 2 ? margin : viewport - margin - width
38
+ return fitPopup(align === 'start' ? [start, end, windowSide] : [end, start, windowSide], width, viewport, margin)
39
+ }
@@ -0,0 +1,80 @@
1
+ import { computed, hasInjectionContext, inject, onMounted, ref, type InjectionKey, type Ref } from 'vue'
2
+ import { isHydrating } from './_hydration'
3
+ import { VIEWPORT_KEY } from './_storageKeys'
4
+ import type { Theme } from './useTheme'
5
+ import type { ContrastLevel } from './useColorPalette'
6
+
7
+ /** The user's theme choices as a server knows them (from cookies), for server-side rendering. */
8
+ export interface M3InitialState {
9
+ theme?: Theme
10
+ palette?: string
11
+ contrast?: ContrastLevel
12
+ /** The browser window's size: the adaptive layouts and `useWindowSizeClass()` render for it instead of compact. */
13
+ viewport?: { width: number; height: number }
14
+ }
15
+
16
+ /** `initialState` with the plugin's defaults filled in (the viewport stays optional: there's no default for it). */
17
+ export type ResolvedInitialState = Required<Omit<M3InitialState, 'viewport'>> & Pick<M3InitialState, 'viewport'>
18
+
19
+ // Internal: `createM3UI({ initialState })`, resolved against the plugin's defaults
20
+ export const M3_INITIAL_STATE_KEY: InjectionKey<ResolvedInitialState> = Symbol('m3-initial-state')
21
+
22
+ export function initialState(): ResolvedInitialState | null {
23
+ return hasInjectionContext() ? inject(M3_INITIAL_STATE_KEY, null) : null
24
+ }
25
+
26
+ /**
27
+ * What a composable reports for a stored choice. On the server: the initial state (the module-level refs are shared
28
+ * by every request and hold nothing there). On the client while hydrating: the initial state too, so the first
29
+ * render matches the server's HTML, then the live value once mounted. Otherwise the live ref itself.
30
+ */
31
+ export function ssrValue<T>(live: Ref<T>, initial: T | undefined): Ref<T> {
32
+ if (initial === undefined) return live
33
+ if (typeof window === 'undefined') return ref(initial) as Ref<T>
34
+ if (!isHydrating()) return live
35
+ const mounted = ref(false)
36
+ onMounted(() => { mounted.value = true })
37
+ return computed({
38
+ get: () => (mounted.value ? live.value : initial),
39
+ set: (value) => { live.value = value },
40
+ }) as Ref<T>
41
+ }
42
+
43
+ // ── Cookies ─────────────────────────────────────────────────────────────────────────────────────
44
+ // `createM3UI({ cookies: true })`: the choices are also kept in cookies, which a server can read.
45
+
46
+ let cookiesEnabled = false
47
+
48
+ export function enableCookies() {
49
+ cookiesEnabled = true
50
+ }
51
+
52
+ let trackingViewport = false
53
+
54
+ /** Keeps the window's size in a cookie, for the server to render the adaptive layouts at it. */
55
+ export function trackViewport() {
56
+ if (!cookiesEnabled || trackingViewport || typeof window === 'undefined') return
57
+ trackingViewport = true
58
+ const write = () => writeCookie(VIEWPORT_KEY, `${window.innerWidth}x${window.innerHeight}`)
59
+ let timer: ReturnType<typeof setTimeout> | undefined
60
+ write()
61
+ window.addEventListener('resize', () => {
62
+ clearTimeout(timer)
63
+ timer = setTimeout(write, 300)
64
+ })
65
+ }
66
+
67
+ /** A cookie's value: the stored choice when localStorage has none (cleared storage, or a server that set it). */
68
+ export function readCookie(key: string): string | null {
69
+ if (typeof document === 'undefined') return null
70
+ const match = document.cookie.match(new RegExp(`(?:^|; )${key}=([^;]*)`))
71
+ if (!match) return null
72
+ try { return decodeURIComponent(match[1]!) } catch { return null }
73
+ }
74
+
75
+ export function writeCookie(key: string, value: string | null) {
76
+ if (!cookiesEnabled || typeof document === 'undefined') return
77
+ document.cookie = value == null
78
+ ? `${key}=; Max-Age=0; Path=/; SameSite=Lax`
79
+ : `${key}=${encodeURIComponent(value)}; Max-Age=31536000; Path=/; SameSite=Lax`
80
+ }
@@ -0,0 +1,6 @@
1
+ // Storage keys shared with modules that must not load useTheme (it applies the theme to <html> when it loads)
2
+ export const THEME_KEY = 'm3-theme'
3
+ // The <style> useColorPalette writes a generated palette's CSS into
4
+ export const STYLE_ID = 'm3-dynamic-palette'
5
+ // The window's size, a cookie only (createM3UI({ cookies: true })): `<width>x<height>`
6
+ export const VIEWPORT_KEY = 'm3-viewport'
@@ -0,0 +1,74 @@
1
+ import { computed, type Ref } from 'vue'
2
+
3
+ /*
4
+ * Internal (not exported from index.ts): the month grid MDatePicker, MDatePickerModal, MDateRangePicker and
5
+ * MDateRangePickerModal each built by hand, line for line the same. Six weeks starting on Monday, the days of the
6
+ * months around it included, as ISO dates (YYYY-MM-DD) with whether min/max leave them out.
7
+ */
8
+
9
+ export interface CalendarDay {
10
+ /** Day of the month */
11
+ date: number
12
+ /** In the month shown (not the neighbors' days filling its first and last week) */
13
+ current: boolean
14
+ iso: string
15
+ disabled: boolean
16
+ }
17
+
18
+ /** YYYY-MM-DD for a year, a 0-based month and a day; months and days past their range roll over, as Date does */
19
+ export function isoDate(y: number, m: number, d: number) {
20
+ const dt = new Date(y, m, d)
21
+ return `${dt.getFullYear()}-${String(dt.getMonth() + 1).padStart(2, '0')}-${String(dt.getDate()).padStart(2, '0')}`
22
+ }
23
+
24
+ export function useCalendarMonth(
25
+ viewDate: Ref<Date>,
26
+ opts: { locale: () => string; min: () => string | undefined; max: () => string | undefined },
27
+ ) {
28
+ // Narrow weekday names, Monday first (1 Jan 2024 was a Monday)
29
+ const weekdays = computed(() => {
30
+ const f = new Intl.DateTimeFormat(opts.locale(), { weekday: 'narrow' })
31
+ return Array.from({ length: 7 }, (_, i) => f.format(new Date(2024, 0, i + 1)))
32
+ })
33
+
34
+ const monthLabel = computed(() =>
35
+ new Intl.DateTimeFormat(opts.locale(), { month: 'long', year: 'numeric' }).format(viewDate.value),
36
+ )
37
+
38
+ function isOutOfRange(iso: string) {
39
+ const min = opts.min()
40
+ const max = opts.max()
41
+ return (!!min && iso < min) || (!!max && iso > max)
42
+ }
43
+
44
+ const days = computed(() => {
45
+ const y = viewDate.value.getFullYear()
46
+ const m = viewDate.value.getMonth()
47
+ const startDay = (new Date(y, m, 1).getDay() + 6) % 7
48
+ const daysInMonth = new Date(y, m + 1, 0).getDate()
49
+ const out: CalendarDay[] = []
50
+ const day = (yy: number, mm: number, d: number, current: boolean) => {
51
+ const iso = isoDate(yy, mm, d)
52
+ out.push({ date: d, current, iso, disabled: isOutOfRange(iso) })
53
+ }
54
+ const prevDays = new Date(y, m, 0).getDate()
55
+ for (let i = startDay - 1; i >= 0; i--) day(y, m - 1, prevDays - i, false)
56
+ for (let d = 1; d <= daysInMonth; d++) day(y, m, d, true)
57
+ for (let d = 1; out.length < 42; d++) day(y, m + 1, d, false)
58
+ return out
59
+ })
60
+
61
+ const isToday = (iso: string) => {
62
+ const now = new Date()
63
+ return iso === isoDate(now.getFullYear(), now.getMonth(), now.getDate())
64
+ }
65
+
66
+ // Through the 1st: setMonth(month ± 1) on the 31st rolled over (31 March + 1 month = 1 May, skipping April)
67
+ function shiftMonth(by: number) {
68
+ viewDate.value = new Date(viewDate.value.getFullYear(), viewDate.value.getMonth() + by, 1)
69
+ }
70
+ const prevMonth = () => shiftMonth(-1)
71
+ const nextMonth = () => shiftMonth(1)
72
+
73
+ return { weekdays, monthLabel, days, isOutOfRange, isToday, prevMonth, nextMonth }
74
+ }
@@ -0,0 +1,33 @@
1
+ import { getCurrentInstance, onBeforeUnmount, watch, type WatchSource } from 'vue'
2
+
3
+ /*
4
+ * Internal (not exported from index.ts): Escape for stacked modal surfaces. Each MDialog used to listen on document
5
+ * itself, so with a dialog opened over another (a date picker over a form) one Escape closed them all. Open
6
+ * surfaces go on a stack, and one listener hands Escape to the top one only. A persistent dialog on top takes it and
7
+ * does nothing, so the one under it stays.
8
+ */
9
+
10
+ const stack: (() => void)[] = []
11
+
12
+ function onKeydown(e: KeyboardEvent) {
13
+ if (e.key !== 'Escape' || !stack.length) return
14
+ stack[stack.length - 1]!()
15
+ }
16
+
17
+ /** Calls `onEscape` on Escape while `active`, unless something opened later is on top of it. */
18
+ export function useEscapeStack(active: WatchSource<boolean>, onEscape: () => void) {
19
+ const entry = () => onEscape()
20
+ function set(on: boolean) {
21
+ if (typeof document === 'undefined') return
22
+ const i = stack.indexOf(entry)
23
+ if (on && i < 0) {
24
+ stack.push(entry)
25
+ if (stack.length === 1) document.addEventListener('keydown', onKeydown)
26
+ } else if (!on && i >= 0) {
27
+ stack.splice(i, 1)
28
+ if (!stack.length) document.removeEventListener('keydown', onKeydown)
29
+ }
30
+ }
31
+ watch(active, (on) => set(!!on), { immediate: true })
32
+ if (getCurrentInstance()) onBeforeUnmount(() => set(false))
33
+ }
@@ -0,0 +1,41 @@
1
+ import { getCurrentInstance, onBeforeUnmount, watch, type WatchSource } from 'vue'
2
+
3
+ /*
4
+ * Internal (not exported from index.ts): locks the page's scroll (body overflow hidden) while a modal surface is
5
+ * open, shared by every component that does it. Counted, so overlays stacked on each other (a select's modal or a
6
+ * date picker inside an MDialog) release it only when the last one closes: each component used to write
7
+ * `overflow = ''` on its own, so closing the inner one let the page under the outer one scroll again. Each
8
+ * instance also releases what it holds when it unmounts (a dialog removed while open left the page locked for good)
9
+ * and nothing when it holds nothing (a select unmounting inside an open dialog used to unlock it).
10
+ */
11
+
12
+ let count = 0
13
+ let previous = ''
14
+
15
+ function lock() {
16
+ if (count++ === 0) {
17
+ previous = document.body.style.overflow
18
+ document.body.style.overflow = 'hidden'
19
+ }
20
+ }
21
+
22
+ function unlock() {
23
+ if (count > 0 && --count === 0) document.body.style.overflow = previous
24
+ }
25
+
26
+ /**
27
+ * Locks the page's scroll while `active` is true (from the start too: a dialog mounted open locks it), and releases
28
+ * it when it turns false or the component unmounts. Without `active`, drive it with the returned `set`.
29
+ */
30
+ export function useScrollLock(active?: WatchSource<boolean>) {
31
+ let held = false
32
+ function set(on: boolean) {
33
+ if (typeof document === 'undefined' || on === held) return
34
+ held = on
35
+ if (on) lock()
36
+ else unlock()
37
+ }
38
+ if (active) watch(active, (on) => set(!!on), { immediate: true })
39
+ if (getCurrentInstance()) onBeforeUnmount(() => set(false))
40
+ return { set }
41
+ }