@m3ui-vue/m3ui-vue 1.0.1 → 1.0.3

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 (115) hide show
  1. package/dist/API.md +636 -20
  2. package/dist/MMenuItem-DFyXflk9.js +707 -0
  3. package/dist/MMenuItem-DFyXflk9.js.map +1 -0
  4. package/dist/MSlider-CdNIH7jc.js +1376 -0
  5. package/dist/MSlider-CdNIH7jc.js.map +1 -0
  6. package/dist/MTextField-B4X92vH_.js +671 -0
  7. package/dist/MTextField-B4X92vH_.js.map +1 -0
  8. package/dist/api.json +1 -1
  9. package/dist/chart.js +1 -1
  10. package/dist/chart.js.map +1 -1
  11. package/dist/code-editor.js +1 -1
  12. package/dist/components/MIconButton.vue.d.ts +1 -1
  13. package/dist/components/MMap.vue.d.ts +74 -0
  14. package/dist/components/MMapBaseLayers.vue.d.ts +15 -0
  15. package/dist/components/MMapControl.vue.d.ts +23 -0
  16. package/dist/components/MMapFeatureInfo.vue.d.ts +25 -0
  17. package/dist/components/MMapFilter.vue.d.ts +19 -0
  18. package/dist/components/MMapGeoJson.vue.d.ts +34 -0
  19. package/dist/components/MMapHover.vue.d.ts +17 -0
  20. package/dist/components/MMapIdentify.vue.d.ts +37 -0
  21. package/dist/components/MMapLayers.vue.d.ts +31 -0
  22. package/dist/components/MMapMarker.vue.d.ts +42 -0
  23. package/dist/components/MMapMeasure.vue.d.ts +43 -0
  24. package/dist/components/MMapPopup.vue.d.ts +43 -0
  25. package/dist/components/MMapSearch.vue.d.ts +28 -0
  26. package/dist/components/MShader.vue.d.ts +9 -3
  27. package/dist/components/_MMapLayerItem.vue.d.ts +25 -0
  28. package/dist/composables/_hydration.d.ts +4 -0
  29. package/dist/composables/_mapGeometry.d.ts +13 -0
  30. package/dist/composables/_ssrState.d.ts +30 -0
  31. package/dist/composables/_storageKeys.d.ts +3 -0
  32. package/dist/composables/_useThemeTokens.d.ts +7 -0
  33. package/dist/composables/mapAdapters.d.ts +111 -0
  34. package/dist/composables/mapSearch.d.ts +31 -0
  35. package/dist/composables/themeInitScript.d.ts +22 -0
  36. package/dist/composables/useColorPalette.d.ts +176 -6
  37. package/dist/composables/useLocale.d.ts +30 -0
  38. package/dist/composables/useMap.d.ts +47 -0
  39. package/dist/composables/useMapFilter.d.ts +10 -0
  40. package/dist/composables/useMapLayers.d.ts +30 -0
  41. package/dist/composables/useTheme.d.ts +2 -0
  42. package/dist/index.d.ts +4 -1
  43. package/dist/locales/index.js +217 -7
  44. package/dist/locales/index.js.map +1 -1
  45. package/dist/m3ui-vue.css +1 -1
  46. package/dist/m3ui.js +6742 -7961
  47. package/dist/m3ui.js.map +1 -1
  48. package/dist/map.d.ts +24 -0
  49. package/dist/map.js +1931 -0
  50. package/dist/map.js.map +1 -0
  51. package/dist/plugin.d.ts +25 -2
  52. package/dist/rich-text-editor.js +27 -26
  53. package/dist/rich-text-editor.js.map +1 -1
  54. package/dist/styles.css +1 -1
  55. package/dist/{useLocale-CuvWRZ1h.js → useLocale-b5-hzsL3.js} +32 -2
  56. package/dist/useLocale-b5-hzsL3.js.map +1 -0
  57. package/package.json +11 -2
  58. package/src/__tests__/MFab.test.ts +52 -6
  59. package/src/__tests__/MMap.test.ts +292 -0
  60. package/src/__tests__/MMapLayers.test.ts +257 -0
  61. package/src/__tests__/MMapTools.test.ts +233 -0
  62. package/src/__tests__/MShader.test.ts +16 -0
  63. package/src/__tests__/_fakeMaplibre.ts +158 -0
  64. package/src/__tests__/hydration.test.ts +119 -0
  65. package/src/__tests__/ssr.test.ts +171 -0
  66. package/src/__tests__/ssrState.test.ts +155 -0
  67. package/src/__tests__/themeInitScript.test.ts +122 -0
  68. package/src/components/MChart.vue +3 -2
  69. package/src/components/MFab.vue +29 -7
  70. package/src/components/MIconButton.vue +1 -1
  71. package/src/components/MLightbox.vue +10 -1
  72. package/src/components/MMap.vue +522 -0
  73. package/src/components/MMapBaseLayers.vue +67 -0
  74. package/src/components/MMapControl.vue +61 -0
  75. package/src/components/MMapFeatureInfo.vue +41 -0
  76. package/src/components/MMapFilter.vue +80 -0
  77. package/src/components/MMapGeoJson.vue +136 -0
  78. package/src/components/MMapHover.vue +131 -0
  79. package/src/components/MMapIdentify.vue +103 -0
  80. package/src/components/MMapLayers.vue +111 -0
  81. package/src/components/MMapMarker.vue +102 -0
  82. package/src/components/MMapMeasure.vue +452 -0
  83. package/src/components/MMapPopup.vue +99 -0
  84. package/src/components/MMapSearch.vue +162 -0
  85. package/src/components/MSearchBar.vue +4 -1
  86. package/src/components/MShader.vue +11 -3
  87. package/src/components/_MMapLayerItem.vue +77 -0
  88. package/src/composables/_hydration.ts +10 -0
  89. package/src/composables/_mapGeometry.ts +75 -0
  90. package/src/composables/_ssrState.ts +80 -0
  91. package/src/composables/_storageKeys.ts +6 -0
  92. package/src/composables/_useThemeTokens.ts +42 -0
  93. package/src/composables/mapAdapters.ts +208 -0
  94. package/src/composables/mapSearch.ts +56 -0
  95. package/src/composables/themeInitScript.ts +51 -0
  96. package/src/composables/useColorPalette.ts +32 -14
  97. package/src/composables/useLocale.ts +62 -0
  98. package/src/composables/useMap.ts +98 -0
  99. package/src/composables/useMapFilter.ts +45 -0
  100. package/src/composables/useMapLayers.ts +124 -0
  101. package/src/composables/useTheme.ts +18 -7
  102. package/src/composables/useWindowSizeClass.ts +23 -4
  103. package/src/index.ts +4 -1
  104. package/src/locales/de.ts +31 -1
  105. package/src/locales/es.ts +31 -1
  106. package/src/locales/fr.ts +31 -1
  107. package/src/locales/ja.ts +31 -1
  108. package/src/locales/ko.ts +31 -1
  109. package/src/locales/pt.ts +31 -1
  110. package/src/locales/zh.ts +31 -1
  111. package/src/map.ts +32 -0
  112. package/src/plugin.ts +77 -13
  113. package/dist/MTextField-BPbFeI9M.js +0 -1368
  114. package/dist/MTextField-BPbFeI9M.js.map +0 -1
  115. package/dist/useLocale-CuvWRZ1h.js.map +0 -1
@@ -0,0 +1,162 @@
1
+ <script setup lang="ts">
2
+ /**
3
+ * A place search on an `MMap`: a search card in a corner. Enter searches through `provider` (OpenStreetMap's
4
+ * Nominatim by default, or any function returning places); picking a result flies there (or fits its extent) and
5
+ * marks it. Available from the `/map` entry point.
6
+ *
7
+ * @event select A result was picked
8
+ */
9
+ import { computed, onBeforeUnmount, ref, shallowRef } from 'vue'
10
+ import type * as Maplibre from 'maplibre-gl'
11
+ import MCard from './MCard.vue'
12
+ import MIcon from './MIcon.vue'
13
+ import MIconButton from './MIconButton.vue'
14
+ import MList from './MList.vue'
15
+ import MListItem from './MListItem.vue'
16
+ import MSpinner from './MSpinner.vue'
17
+ import MMapControl from './MMapControl.vue'
18
+ import MMapMarker from './MMapMarker.vue'
19
+ import { useLocale } from '../composables/useLocale'
20
+ import { useMap } from '../composables/useMap'
21
+ import { nominatimProvider, type MapSearchProvider, type MapSearchResult } from '../composables/mapSearch'
22
+ import type { MapControlPosition } from './MMap.vue'
23
+
24
+ const props = withDefaults(
25
+ defineProps<{
26
+ /** Where to search: `nominatimProvider(options)` by default, or your own function */
27
+ provider?: MapSearchProvider
28
+ /** The corner */
29
+ position?: MapControlPosition
30
+ /** The field's placeholder (the locale's "Search places" by default) */
31
+ placeholder?: string
32
+ /** The zoom to fly to for a result without an extent */
33
+ zoom?: number
34
+ /** Mark the picked result */
35
+ marker?: boolean
36
+ /** Search while typing (debounced), for providers that allow it; Nominatim's public server doesn't */
37
+ instant?: boolean
38
+ }>(),
39
+ { position: 'top-left', zoom: 17, marker: true, instant: false },
40
+ )
41
+
42
+ const emit = defineEmits<{ select: [result: MapSearchResult] }>()
43
+
44
+ const t = useLocale()
45
+ const { map } = useMap()
46
+ const provider = computed(() => props.provider ?? nominatimProvider())
47
+
48
+ const query = ref('')
49
+ const results = shallowRef<MapSearchResult[]>([])
50
+ const loading = ref(false)
51
+ const searched = ref(false)
52
+ const open = ref(false)
53
+ const picked = shallowRef<MapSearchResult | null>(null)
54
+ let controller: AbortController | undefined
55
+ let debounce: ReturnType<typeof setTimeout> | undefined
56
+
57
+ async function search() {
58
+ const q = query.value.trim()
59
+ if (!q) return
60
+ controller?.abort()
61
+ controller = new AbortController()
62
+ const mine = controller
63
+ loading.value = true
64
+ open.value = true
65
+ try {
66
+ results.value = await provider.value(q, mine.signal)
67
+ } catch {
68
+ if (mine.signal.aborted) return
69
+ results.value = []
70
+ } finally {
71
+ if (controller === mine) {
72
+ loading.value = false
73
+ searched.value = true
74
+ }
75
+ }
76
+ }
77
+
78
+ function onInput(value: string) {
79
+ query.value = value
80
+ if (!value) return clear()
81
+ if (props.instant) {
82
+ clearTimeout(debounce)
83
+ debounce = setTimeout(search, 350)
84
+ }
85
+ }
86
+
87
+ function select(result: MapSearchResult) {
88
+ picked.value = result
89
+ open.value = false
90
+ const m = map.value as Maplibre.Map | undefined
91
+ if (result.bbox && result.bbox[0] !== result.bbox[2]) m?.fitBounds([[result.bbox[0], result.bbox[1]], [result.bbox[2], result.bbox[3]]], { padding: 48, maxZoom: props.zoom })
92
+ else m?.flyTo({ center: result.lngLat, zoom: props.zoom })
93
+ emit('select', result)
94
+ }
95
+
96
+ function clear() {
97
+ controller?.abort()
98
+ clearTimeout(debounce)
99
+ query.value = ''
100
+ results.value = []
101
+ searched.value = false
102
+ loading.value = false
103
+ open.value = false
104
+ picked.value = null
105
+ }
106
+
107
+ onBeforeUnmount(() => {
108
+ controller?.abort()
109
+ clearTimeout(debounce)
110
+ })
111
+
112
+ const ICONS: Record<string, string> = {
113
+ city: 'location_city', town: 'location_city', village: 'holiday_village', hamlet: 'cottage', suburb: 'apartment',
114
+ neighbourhood: 'maps_home_work', road: 'road', residential: 'home', house: 'home', building: 'domain',
115
+ shop: 'storefront', park: 'park', water: 'water', river: 'water', lake: 'water', school: 'school',
116
+ university: 'school', hospital: 'local_hospital', restaurant: 'restaurant', cafe: 'local_cafe', hotel: 'hotel',
117
+ station: 'train', bus_stop: 'directions_bus', administrative: 'map', country: 'public', state: 'map',
118
+ }
119
+ const iconOf = (type?: string) => (type && ICONS[type]) || 'location_on'
120
+ </script>
121
+
122
+ <template>
123
+ <div class="hidden">
124
+ <MMapControl :position="position" :group="false">
125
+ <MCard variant="elevated" class="w-80 max-w-[calc(100vw-5rem)] overflow-hidden">
126
+ <form class="flex items-center gap-2 py-1 pr-1 pl-3" role="search" @submit.prevent="search">
127
+ <MIcon name="search" :size="20" class="shrink-0 text-on-surface-variant" />
128
+ <input
129
+ :value="query"
130
+ type="search"
131
+ enterkeyhint="search"
132
+ :placeholder="placeholder ?? t.mapSearchPlaces"
133
+ :aria-label="placeholder ?? t.mapSearchPlaces"
134
+ class="min-w-0 flex-1 bg-transparent py-2 text-body-medium text-on-surface outline-none placeholder:text-on-surface-variant [&::-webkit-search-cancel-button]:hidden"
135
+ @input="onInput(($event.target as HTMLInputElement).value)"
136
+ @focus="open = searched && !picked"
137
+ >
138
+ <MSpinner v-if="loading" :size="20" class="mr-2 shrink-0" />
139
+ <MIconButton v-else-if="query" icon="close" :label="t.clearSearch" size="sm" @click="clear" />
140
+ </form>
141
+ <div v-if="open && searched && !loading" class="border-t border-outline-variant">
142
+ <MList v-if="results.length" class="max-h-72 overflow-y-auto">
143
+ <MListItem
144
+ v-for="(r, i) in results"
145
+ :key="i"
146
+ :title="r.label"
147
+ :icon="iconOf(r.type)"
148
+ leading="icon"
149
+ clickable
150
+ @click="select(r)"
151
+ />
152
+ </MList>
153
+ <div v-else class="flex flex-col items-center gap-2 py-6">
154
+ <MIcon name="search_off" :size="28" class="text-on-surface-variant" />
155
+ <span class="text-body-small text-on-surface-variant">{{ t.noResults }}</span>
156
+ </div>
157
+ </div>
158
+ </MCard>
159
+ </MMapControl>
160
+ <MMapMarker v-if="marker && picked" :lng-lat="picked.lngLat" />
161
+ </div>
162
+ </template>
@@ -1,7 +1,10 @@
1
1
  <script setup lang="ts">
2
2
  /**
3
3
  * A collapsed search field that expands into a docked panel or a fullscreen overlay, with results shown below
4
- * the input.
4
+ * the input. The expanded panel is teleported to `<body>`; `class`, `style` and other attributes you pass land on
5
+ * the collapsed bar. So with a fullscreen variant you can hide the bar (e.g. `class="hidden"` on phones) and open
6
+ * search from your own icon button through `v-model:expanded`. The docked panel is placed under the bar, so it
7
+ * needs the bar visible.
5
8
  *
6
9
  * @slot leading Overrides the collapsed bar's leading icon
7
10
  * @slot trailing Trailing content in both the collapsed bar and the expanded header (e.g. an avatar)
@@ -25,18 +25,24 @@ export type ShaderStatus = 'loading' | 'ready' | 'error' | 'fallback'
25
25
  const props = withDefaults(
26
26
  defineProps<{
27
27
  /** GLSL fragment shader body (Shadertoy-style): must define `mainImage(out vec4 fragColor, in vec2 fragCoord)`.
28
- * Runs on WebGL2. Always required as the compatible baseline. */
28
+ * Runs on WebGL2. Always required as the compatible baseline. Don't write the `#version`, the precision or any
29
+ * uniform: the component puts them in front of your code, with Shadertoy's `iTime` (seconds, stops while
30
+ * paused), `iResolution` (canvas size in device pixels), `iMouse` and `iFrame`, plus one per `uniforms` key. */
29
31
  code: string
30
32
  /** Optional WGSL fragment shader module, e.g. `@fragment fn fs_main(@builtin(position) pos: vec4f) -> @location(0) vec4f`.
31
33
  * Runs on WebGPU when available. Must declare its own bindings — see docs for the required uniform buffer layout. */
32
34
  wgsl?: string
33
35
  /** Which backend to use. 'auto' picks WebGPU when `wgsl` is set and supported, else WebGL2. */
34
36
  renderer?: ShaderRenderer
35
- /** Custom uniforms. Keys/shape are locked in at mount time; only values are reactive per frame. */
37
+ /** Custom uniforms, read every frame. In GLSL each key is declared for you, as a `float` for a number or a
38
+ * `vec2`–`vec4` for an array; in WGSL they're binding 1, one `vec4f` per key in this order. Keys and shapes
39
+ * are fixed when the shader compiles (on mount, or when `code`/`wgsl`/`renderer` change); values can change
40
+ * freely, e.g. to drive the shader from your own clock instead of `iTime`. */
36
41
  uniforms?: Record<string, number | number[]>
37
42
  /** Freezes the render loop and the shader clock */
38
43
  paused?: boolean
39
- /** Device pixel ratio to render at. Defaults to devicePixelRatio, capped at 2 for performance. */
44
+ /** Device pixels per CSS pixel to render at. Defaults to devicePixelRatio, capped at 2 for performance. Lower it to
45
+ * render fewer pixels (a "quality" setting); the canvas is resized when it changes. */
40
46
  pixelRatio?: number
41
47
  }>(),
42
48
  { renderer: 'auto' },
@@ -532,6 +538,8 @@ watch(
532
538
  },
533
539
  )
534
540
 
541
+ watch(() => props.pixelRatio, () => resize())
542
+
535
543
  watch(
536
544
  () => props.paused,
537
545
  (isPaused) => {
@@ -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,10 @@
1
+ import { getCurrentInstance, inject, type InjectionKey } from 'vue'
2
+
3
+ // Internal: `createM3UI({ isHydrating })`. A server-rendered app's first client render has to match the server's
4
+ // HTML, so what the server can't know (the window's size) starts from the server's value until the app is mounted.
5
+ export const M3_HYDRATING_KEY: InjectionKey<() => boolean> = Symbol('m3-hydrating')
6
+
7
+ /** Whether the calling component is being hydrated from server-rendered HTML (false outside a component's setup). */
8
+ export function isHydrating(): boolean {
9
+ return getCurrentInstance() ? inject(M3_HYDRATING_KEY, null)?.() ?? false : false
10
+ }
@@ -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,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,42 @@
1
+ import { onBeforeUnmount, onMounted, ref, type Ref } from 'vue'
2
+ import { STYLE_ID } from './_storageKeys'
3
+
4
+ /**
5
+ * The current values of some color tokens (`['primary', 'surface']` → `--color-primary`…), kept up to date across
6
+ * theme, palette and contrast changes: for what can't use CSS variables (a MapLibre layer's paint, a canvas). Empty
7
+ * strings on the server.
8
+ */
9
+ export function useThemeTokens<T extends string>(names: readonly T[]): Ref<Record<T, string>> {
10
+ const read = () => {
11
+ const style = getComputedStyle(document.documentElement)
12
+ return Object.fromEntries(names.map((n) => [n, style.getPropertyValue(`--color-${n}`).trim()])) as Record<T, string>
13
+ }
14
+ const tokens = ref(typeof document === 'undefined' ? Object.fromEntries(names.map((n) => [n, ''])) as Record<T, string> : read()) as Ref<Record<T, string>>
15
+ let observer: MutationObserver | undefined
16
+ let settle: ReturnType<typeof setTimeout> | undefined
17
+
18
+ onMounted(() => {
19
+ const update = () => {
20
+ const next = read()
21
+ if (names.some((n) => next[n] !== tokens.value[n])) tokens.value = next
22
+ }
23
+ // Dark mode (class), a palette or contrast (attributes), or a generated palette rewriting its <style> in <head>
24
+ const isPaletteStyle = (node: Node | null) => (node instanceof Element ? node : node?.parentElement)?.id === STYLE_ID
25
+ observer = new MutationObserver((records) => {
26
+ if (!records.some((r) => r.target === document.documentElement || isPaletteStyle(r.target)
27
+ || Array.from(r.addedNodes).some(isPaletteStyle))) return
28
+ update()
29
+ // Chromium animates the tokens on a theme switch (_themeTransition, 250ms): read the settled values too
30
+ clearTimeout(settle)
31
+ settle = setTimeout(update, 300)
32
+ })
33
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'style', 'data-palette', 'data-contrast'] })
34
+ observer.observe(document.head, { childList: true, characterData: true, subtree: true })
35
+ })
36
+ onBeforeUnmount(() => {
37
+ observer?.disconnect()
38
+ clearTimeout(settle)
39
+ })
40
+
41
+ return tokens
42
+ }