@m3ui-vue/m3ui-vue 1.1.3 → 1.2.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 (236) hide show
  1. package/README.md +1 -1
  2. package/dist/API.md +579 -40
  3. package/dist/MMenuItem-DI351kIf.js +929 -0
  4. package/dist/MMenuItem-DI351kIf.js.map +1 -0
  5. package/dist/MSlider-BnEy5ieZ.js +1500 -0
  6. package/dist/MSlider-BnEy5ieZ.js.map +1 -0
  7. package/dist/MTextField-BBmkaIbO.js +633 -0
  8. package/dist/MTextField-BBmkaIbO.js.map +1 -0
  9. package/dist/api.json +1 -1
  10. package/dist/chart.js +83 -49
  11. package/dist/chart.js.map +1 -1
  12. package/dist/code-editor.js +1 -1
  13. package/dist/components/MAnimatedNumber.vue.d.ts +3 -1
  14. package/dist/components/MButton.vue.d.ts +9 -1
  15. package/dist/components/MButtonGroup.vue.d.ts +40 -31
  16. package/dist/components/MCarousel.vue.d.ts +2 -0
  17. package/dist/components/MChart.vue.d.ts +6 -0
  18. package/dist/components/MCircleProgressBar.vue.d.ts +5 -3
  19. package/dist/components/MContainerTransform.vue.d.ts +59 -0
  20. package/dist/components/MContextMenu.vue.d.ts +2 -2
  21. package/dist/components/MCopyButton.vue.d.ts +1 -1
  22. package/dist/components/MDialog.vue.d.ts +8 -5
  23. package/dist/components/MExportButton.vue.d.ts +1 -1
  24. package/dist/components/MFab.vue.d.ts +2 -2
  25. package/dist/components/MFabMenu.vue.d.ts +1 -1
  26. package/dist/components/MFlex.vue.d.ts +1 -1
  27. package/dist/components/MIconButton.vue.d.ts +15 -1
  28. package/dist/components/MInfiniteScroll.vue.d.ts +1 -1
  29. package/dist/components/MListItem.vue.d.ts +5 -5
  30. package/dist/components/MMap.vue.d.ts +20 -2
  31. package/dist/components/MMapBaseLayers.vue.d.ts +3 -0
  32. package/dist/components/MMapFilter.vue.d.ts +3 -0
  33. package/dist/components/MMapLayers.vue.d.ts +3 -0
  34. package/dist/components/MMenu.vue.d.ts +2 -2
  35. package/dist/components/MMenuItem.vue.d.ts +7 -3
  36. package/dist/components/MNavigationDrawer.vue.d.ts +13 -2
  37. package/dist/components/MNavigationRail.vue.d.ts +1 -1
  38. package/dist/components/MOverlay.vue.d.ts +12 -1
  39. package/dist/components/MProgressBar.vue.d.ts +5 -3
  40. package/dist/components/MPullToRefresh.vue.d.ts +7 -2
  41. package/dist/components/MRichTextEditor.vue.d.ts +7 -1
  42. package/dist/components/MSearchField.vue.d.ts +58 -0
  43. package/dist/components/MSegmentedButton.vue.d.ts +31 -23
  44. package/dist/components/MSimpleCarousel.vue.d.ts +2 -0
  45. package/dist/components/MSkeleton.vue.d.ts +6 -3
  46. package/dist/components/MSplitter.vue.d.ts +1 -1
  47. package/dist/components/MStack.vue.d.ts +1 -1
  48. package/dist/components/MSwipeToDismiss.vue.d.ts +1 -1
  49. package/dist/components/MSwitch.vue.d.ts +1 -1
  50. package/dist/components/MTextField.vue.d.ts +5 -1
  51. package/dist/components/MTimeline.vue.d.ts +85 -22
  52. package/dist/components/MToolbar.vue.d.ts +32 -5
  53. package/dist/components/MTooltip.vue.d.ts +1 -1
  54. package/dist/components/_MDrawerItemList.vue.d.ts +2 -0
  55. package/dist/components/_MToolbarFab.vue.d.ts +16 -0
  56. package/dist/composables/_containerTransform.d.ts +48 -0
  57. package/dist/composables/_mapStyle.d.ts +13 -0
  58. package/dist/composables/_themeTransition.d.ts +2 -0
  59. package/dist/composables/_tooltipTrigger.d.ts +22 -0
  60. package/dist/composables/_useMenuNav.d.ts +28 -0
  61. package/dist/composables/useAutoGrow.d.ts +21 -0
  62. package/dist/composables/useColorPalette.d.ts +1 -1
  63. package/dist/composables/useContainerTransform.d.ts +30 -0
  64. package/dist/composables/useLocale.d.ts +6 -0
  65. package/dist/composables/useMap.d.ts +19 -3
  66. package/dist/composables/useMapFilter.d.ts +4 -1
  67. package/dist/composables/useMapLayers.d.ts +5 -2
  68. package/dist/composables/useScrollReveal.d.ts +44 -0
  69. package/dist/composables/useThemeTokens.d.ts +21 -0
  70. package/dist/composables/viewportHints.d.ts +27 -0
  71. package/dist/directives/vClickOutside.d.ts +25 -0
  72. package/dist/directives/vFocusRing.d.ts +22 -0
  73. package/dist/directives/vLongPress.d.ts +27 -0
  74. package/dist/directives/vReveal.d.ts +10 -0
  75. package/dist/directives/vScrollElevation.d.ts +31 -0
  76. package/dist/directives/vSkeleton.d.ts +19 -0
  77. package/dist/directives/vStateLayer.d.ts +20 -0
  78. package/dist/directives/vSwipe.d.ts +45 -0
  79. package/dist/directives/vTooltip.d.ts +23 -0
  80. package/dist/index.d.ts +31 -1
  81. package/dist/locales/index.js +35 -7
  82. package/dist/locales/index.js.map +1 -1
  83. package/dist/m3ui-vue.css +1 -1
  84. package/dist/m3ui.js +7692 -6273
  85. package/dist/m3ui.js.map +1 -1
  86. package/dist/map.d.ts +1 -1
  87. package/dist/map.js +823 -793
  88. package/dist/map.js.map +1 -1
  89. package/dist/motion-DZiXG09o.js +150 -0
  90. package/dist/motion-DZiXG09o.js.map +1 -0
  91. package/dist/plugin.d.ts +24 -0
  92. package/dist/rich-text-editor.js +20 -16
  93. package/dist/rich-text-editor.js.map +1 -1
  94. package/dist/styles/theme.css +63 -0
  95. package/dist/styles.css +1 -1
  96. package/dist/{useLocale-SfQHnJfp.js → useLocale-JYxDDeXC.js} +6 -2
  97. package/dist/useLocale-JYxDDeXC.js.map +1 -0
  98. package/dist/useThemeTokens-Bv-Uv8eX.js +135 -0
  99. package/dist/useThemeTokens-Bv-Uv8eX.js.map +1 -0
  100. package/package.json +2 -1
  101. package/src/__tests__/MAnimatedNumber.test.ts +24 -2
  102. package/src/__tests__/MButton.test.ts +22 -0
  103. package/src/__tests__/MCarousel.test.ts +9 -0
  104. package/src/__tests__/MChart.test.ts +77 -5
  105. package/src/__tests__/MContainerTransform.test.ts +279 -0
  106. package/src/__tests__/MDialog.test.ts +27 -0
  107. package/src/__tests__/MIconButton.test.ts +33 -0
  108. package/src/__tests__/MListItemExpandable.test.ts +48 -0
  109. package/src/__tests__/MListItemShape.test.ts +9 -6
  110. package/src/__tests__/MListKeyboard.test.ts +90 -0
  111. package/src/__tests__/MMap.test.ts +53 -1
  112. package/src/__tests__/MMapLayers.test.ts +46 -2
  113. package/src/__tests__/MMapTools.test.ts +2 -1
  114. package/src/__tests__/MMenu.test.ts +104 -1
  115. package/src/__tests__/MMenuItem.test.ts +18 -0
  116. package/src/__tests__/MNavigationDrawer.test.ts +80 -0
  117. package/src/__tests__/MNavigationRail.test.ts +33 -0
  118. package/src/__tests__/MOverlay.test.ts +49 -0
  119. package/src/__tests__/MProgressBar.test.ts +41 -0
  120. package/src/__tests__/MPullToRefresh.test.ts +33 -0
  121. package/src/__tests__/MRichTextEditor.test.ts +22 -0
  122. package/src/__tests__/MSearchField.test.ts +71 -0
  123. package/src/__tests__/MSkeleton.test.ts +38 -0
  124. package/src/__tests__/MSlider.test.ts +161 -0
  125. package/src/__tests__/MTimeline.test.ts +238 -0
  126. package/src/__tests__/MToolbar.test.ts +157 -0
  127. package/src/__tests__/_fakeMaplibre.ts +3 -1
  128. package/src/__tests__/attrsFallthrough.test.ts +9 -0
  129. package/src/__tests__/escapeStack.test.ts +93 -0
  130. package/src/__tests__/hydration.test.ts +25 -0
  131. package/src/__tests__/ssr.test.ts +21 -2
  132. package/src/__tests__/useAutoGrow.test.ts +103 -0
  133. package/src/__tests__/useScrollReveal.test.ts +102 -0
  134. package/src/__tests__/useThemeTokens.test.ts +114 -0
  135. package/src/__tests__/vClickOutside.test.ts +82 -0
  136. package/src/__tests__/vFocusRing.test.ts +36 -0
  137. package/src/__tests__/vLongPress.test.ts +81 -0
  138. package/src/__tests__/vScrollElevation.test.ts +89 -0
  139. package/src/__tests__/vSkeleton.test.ts +48 -0
  140. package/src/__tests__/vStateLayer.test.ts +53 -0
  141. package/src/__tests__/vSwipe.test.ts +93 -0
  142. package/src/__tests__/vTooltip.test.ts +95 -0
  143. package/src/__tests__/viewportHints.test.ts +41 -0
  144. package/src/components/MAnimatedNumber.vue +32 -6
  145. package/src/components/MAutocomplete.vue +5 -0
  146. package/src/components/MBottomSheet.vue +4 -1
  147. package/src/components/MButton.vue +19 -3
  148. package/src/components/MButtonGroup.vue +22 -17
  149. package/src/components/MCarousel.vue +7 -1
  150. package/src/components/MChart.vue +74 -34
  151. package/src/components/MCircleProgressBar.vue +14 -9
  152. package/src/components/MCommandPalette.vue +3 -2
  153. package/src/components/MContainerTransform.vue +321 -0
  154. package/src/components/MContextMenu.vue +19 -60
  155. package/src/components/MDialog.vue +31 -6
  156. package/src/components/MDragDropList.vue +2 -0
  157. package/src/components/MFab.vue +10 -5
  158. package/src/components/MIconButton.vue +43 -2
  159. package/src/components/MKanban.vue +2 -0
  160. package/src/components/MLightbox.vue +7 -2
  161. package/src/components/MList.vue +26 -2
  162. package/src/components/MListItem.vue +138 -84
  163. package/src/components/MMap.vue +38 -5
  164. package/src/components/MMapBaseLayers.vue +7 -3
  165. package/src/components/MMapFilter.vue +7 -4
  166. package/src/components/MMapGeoJson.vue +1 -1
  167. package/src/components/MMapLayers.vue +6 -2
  168. package/src/components/MMapMeasure.vue +5 -2
  169. package/src/components/MMenu.vue +18 -59
  170. package/src/components/MMenuItem.vue +11 -2
  171. package/src/components/MMultiAutocomplete.vue +5 -0
  172. package/src/components/MNavigationDrawer.vue +96 -11
  173. package/src/components/MNavigationRail.vue +44 -25
  174. package/src/components/MOverlay.vue +32 -13
  175. package/src/components/MProgressBar.vue +25 -27
  176. package/src/components/MPullToRefresh.vue +20 -1
  177. package/src/components/MRichTextEditor.vue +19 -5
  178. package/src/components/MSearchBar.vue +5 -0
  179. package/src/components/MSearchField.vue +142 -0
  180. package/src/components/MSegmentedButton.vue +19 -17
  181. package/src/components/MSelect.vue +10 -1
  182. package/src/components/MSideSheet.vue +5 -2
  183. package/src/components/MSimpleCarousel.vue +10 -1
  184. package/src/components/MSkeleton.vue +30 -8
  185. package/src/components/MSlider.vue +161 -42
  186. package/src/components/MSpotlightSearch.vue +3 -2
  187. package/src/components/MTextField.vue +15 -2
  188. package/src/components/MTimeline.vue +370 -81
  189. package/src/components/MToolbar.vue +256 -15
  190. package/src/components/MTooltip.vue +20 -152
  191. package/src/components/_MDrawerItemList.vue +25 -6
  192. package/src/components/_MToolbarFab.vue +14 -0
  193. package/src/composables/_containerTransform.ts +179 -0
  194. package/src/composables/_mapStyle.ts +45 -0
  195. package/src/composables/_themeTransition.ts +2 -0
  196. package/src/composables/_tooltipTrigger.ts +184 -0
  197. package/src/composables/_useEscapeStack.ts +2 -0
  198. package/src/composables/_useMenuNav.ts +209 -0
  199. package/src/composables/useAutoGrow.ts +78 -0
  200. package/src/composables/useContainerTransform.ts +59 -0
  201. package/src/composables/useLocale.ts +10 -0
  202. package/src/composables/useMap.ts +43 -5
  203. package/src/composables/useMapFilter.ts +6 -5
  204. package/src/composables/useMapLayers.ts +7 -6
  205. package/src/composables/useScrollReveal.ts +151 -0
  206. package/src/composables/useThemeTokens.ts +116 -0
  207. package/src/composables/viewportHints.ts +80 -0
  208. package/src/directives/vClickOutside.ts +90 -0
  209. package/src/directives/vFocusRing.ts +60 -0
  210. package/src/directives/vLongPress.ts +134 -0
  211. package/src/directives/vReveal.ts +57 -0
  212. package/src/directives/vScrollElevation.ts +116 -0
  213. package/src/directives/vSkeleton.ts +87 -0
  214. package/src/directives/vStateLayer.ts +83 -0
  215. package/src/directives/vSwipe.ts +197 -0
  216. package/src/directives/vTooltip.ts +128 -0
  217. package/src/index.ts +31 -1
  218. package/src/locales/de.ts +4 -0
  219. package/src/locales/es.ts +4 -0
  220. package/src/locales/fr.ts +4 -0
  221. package/src/locales/ja.ts +4 -0
  222. package/src/locales/ko.ts +4 -0
  223. package/src/locales/pt.ts +4 -0
  224. package/src/locales/zh.ts +4 -0
  225. package/src/map.ts +1 -1
  226. package/src/plugin.ts +34 -0
  227. package/src/styles/theme.css +63 -0
  228. package/dist/MMenuItem-BckcR0nW.js +0 -809
  229. package/dist/MMenuItem-BckcR0nW.js.map +0 -1
  230. package/dist/MSlider-LyH_gy8D.js +0 -1411
  231. package/dist/MSlider-LyH_gy8D.js.map +0 -1
  232. package/dist/MTextField-FCPOTB0o.js +0 -672
  233. package/dist/MTextField-FCPOTB0o.js.map +0 -1
  234. package/dist/composables/_useThemeTokens.d.ts +0 -7
  235. package/dist/useLocale-SfQHnJfp.js.map +0 -1
  236. package/src/composables/_useThemeTokens.ts +0 -42
@@ -0,0 +1,78 @@
1
+ import { getCurrentInstance, onBeforeUnmount, toValue, watch, type MaybeRefOrGetter, type WatchSource } from 'vue'
2
+
3
+ export interface AutoGrowOptions {
4
+ /** Fewest rows it shrinks to (default 1) */
5
+ minRows?: MaybeRefOrGetter<number | undefined>
6
+ /** Most rows it grows to; past them it scrolls. Unset grows without limit */
7
+ maxRows?: MaybeRefOrGetter<number | undefined>
8
+ /**
9
+ * The text, when it can change without typing (cleared after sending, an emoji inserted…): a ref or getter, so the
10
+ * height follows. Typing is followed on its own
11
+ */
12
+ value?: WatchSource<unknown>
13
+ }
14
+
15
+ /**
16
+ * Makes a `<textarea>` grow with its text, between `minRows` and `maxRows` rows, scrolling past the last one: a chat
17
+ * composer, a comment box. Works on any textarea, styled however you like (rows are measured from its computed line
18
+ * height, padding and border). It also follows width changes, which rewrap the text. Returns `resize()` for anything
19
+ * else that changes the text.
20
+ */
21
+ export function useAutoGrow(target: MaybeRefOrGetter<HTMLTextAreaElement | null | undefined>, options: AutoGrowOptions = {}) {
22
+ let el: HTMLTextAreaElement | null = null
23
+ let observer: ResizeObserver | null = null
24
+ let lastWidth = 0
25
+
26
+ function resize() {
27
+ if (!el) return
28
+ const cs = getComputedStyle(el)
29
+ const px = (v: string) => parseFloat(v) || 0
30
+ // `normal` line height has no number: about 1.5× the font size
31
+ const lineHeight = px(cs.lineHeight) || px(cs.fontSize) * 1.5 || 24
32
+ const padding = px(cs.paddingTop) + px(cs.paddingBottom)
33
+ const border = cs.boxSizing === 'border-box' ? px(cs.borderTopWidth) + px(cs.borderBottomWidth) : 0
34
+ const extra = (cs.boxSizing === 'border-box' ? padding : 0) + border
35
+ const min = (toValue(options.minRows) ?? 1) * lineHeight + extra
36
+ const maxRows = toValue(options.maxRows)
37
+ const max = maxRows ? maxRows * lineHeight + extra : Infinity
38
+
39
+ // Collapse first so scrollHeight measures the text, not the current height
40
+ el.style.height = 'auto'
41
+ const content = el.scrollHeight + border + (cs.boxSizing === 'border-box' ? 0 : -padding)
42
+ const height = Math.min(max, Math.max(min, content))
43
+ el.style.height = `${height}px`
44
+ el.style.overflowY = content > max ? 'auto' : 'hidden'
45
+ }
46
+
47
+ function attach(next: HTMLTextAreaElement | null | undefined) {
48
+ if (el) {
49
+ el.removeEventListener('input', resize)
50
+ observer?.disconnect()
51
+ // Released (autoGrow turned off, another element): back to its own height
52
+ el.style.height = ''
53
+ el.style.overflowY = ''
54
+ }
55
+ el = next ?? null
56
+ if (!el) return
57
+ el.addEventListener('input', resize)
58
+ if (typeof ResizeObserver !== 'undefined') {
59
+ // Only width changes rewrap the text; our own height writes would otherwise loop
60
+ observer ??= new ResizeObserver(([entry]) => {
61
+ const w = entry!.contentRect.width
62
+ if (w !== lastWidth) {
63
+ lastWidth = w
64
+ resize()
65
+ }
66
+ })
67
+ observer.observe(el)
68
+ }
69
+ resize()
70
+ }
71
+
72
+ watch(() => toValue(target), attach, { immediate: true, flush: 'post' })
73
+ watch([() => toValue(options.minRows), () => toValue(options.maxRows)], () => resize(), { flush: 'post' })
74
+ if (options.value) watch(options.value, () => resize(), { flush: 'post' })
75
+ if (getCurrentInstance()) onBeforeUnmount(() => attach(null))
76
+
77
+ return { resize }
78
+ }
@@ -0,0 +1,59 @@
1
+ import { ref, shallowRef, type ComponentPublicInstance, type Ref, type ShallowRef } from 'vue'
2
+
3
+ /** What a container transform opens from: a click (its element), an element, or a component */
4
+ export type ContainerTransformOrigin = Event | Element | ComponentPublicInstance | null | undefined
5
+
6
+ /** The state MContainerTransform plays, shared between the elements that open it and the panel they open */
7
+ export interface ContainerTransformController<T = unknown> {
8
+ /** Whether the expanded view is open (or opening) */
9
+ isOpen: Ref<boolean>
10
+ /** What `open` was given, for the expanded view to show */
11
+ item: Ref<T | undefined>
12
+ /** The element it grows from and shrinks back into */
13
+ source: ShallowRef<HTMLElement | null>
14
+ /** Opens from `origin` (a click's element, an element or a component), with an optional `item` */
15
+ open: (origin?: ContainerTransformOrigin, item?: T) => void
16
+ /** Shrinks the expanded view back into the element it opened from */
17
+ close: () => void
18
+ }
19
+
20
+ /** The element an origin stands for: a click's `currentTarget` (or `target`), a component's root element */
21
+ export function originElement(origin: ContainerTransformOrigin): HTMLElement | null {
22
+ if (!origin) return null
23
+ if (typeof Event !== 'undefined' && origin instanceof Event) {
24
+ return ((origin.currentTarget as HTMLElement | null) ?? (origin.target as HTMLElement | null)) || null
25
+ }
26
+ if (typeof Element !== 'undefined' && origin instanceof Element) return origin as HTMLElement
27
+ const el = (origin as ComponentPublicInstance).$el
28
+ return el instanceof Element ? (el as HTMLElement) : null
29
+ }
30
+
31
+ /**
32
+ * Material's container transform for elements that live apart from their expanded view: one controller, many
33
+ * elements opening it (a grid of cards), and one `<MContainerTransform :controller>` wherever the expanded view
34
+ * belongs. `open(event, item)` from a click grows that element into the expanded view, with `item` for it to show.
35
+ *
36
+ * ```ts
37
+ * const detail = useContainerTransform<Recipe>()
38
+ * // <MCard v-for="r in recipes" @click="detail.open($event, r)">…</MCard>
39
+ * // <MContainerTransform :controller="detail"><template #expanded="{ item }">…</template></MContainerTransform>
40
+ * ```
41
+ */
42
+ export function useContainerTransform<T = unknown>(): ContainerTransformController<T> {
43
+ const isOpen = ref(false)
44
+ const item = ref<T>() as Ref<T | undefined>
45
+ const source = shallowRef<HTMLElement | null>(null)
46
+ return {
47
+ isOpen,
48
+ item,
49
+ source,
50
+ open(origin, value) {
51
+ source.value = originElement(origin) ?? source.value
52
+ item.value = value
53
+ isOpen.value = true
54
+ },
55
+ close() {
56
+ isOpen.value = false
57
+ },
58
+ }
59
+ }
@@ -201,6 +201,9 @@ export interface M3Locale {
201
201
  carouselItem: string
202
202
  /** MSparkline's summary for screen readers: {first}, {last}, {min}, {max} */
203
203
  sparklineSummary: string
204
+ /** MSlider range: its two thumbs */
205
+ sliderRangeStart: string
206
+ sliderRangeEnd: string
204
207
  // MMap (maplibre controls)
205
208
  mapTitle: string
206
209
  mapMarker: string
@@ -232,6 +235,9 @@ export interface M3Locale {
232
235
  mapDeleteMeasurement: string
233
236
  mapTotal: string
234
237
  mapSearchPlaces: string
238
+ /** MTimeline's button past `limit`; `{count}` is how many entries are hidden */
239
+ timelineShowMore: string
240
+ timelineShowLess: string
235
241
  }
236
242
 
237
243
  export const defaultLocale: M3Locale = {
@@ -415,6 +421,8 @@ export const defaultLocale: M3Locale = {
415
421
  carousel: 'Carousel',
416
422
  carouselItem: '{index} of {count}',
417
423
  sparklineSummary: 'From {first} to {last}, low {min}, high {max}',
424
+ sliderRangeStart: 'Range start',
425
+ sliderRangeEnd: 'Range end',
418
426
  // MMap (maplibre controls)
419
427
  mapTitle: 'Map',
420
428
  mapMarker: 'Map marker',
@@ -446,6 +454,8 @@ export const defaultLocale: M3Locale = {
446
454
  mapDeleteMeasurement: 'Delete measurement',
447
455
  mapTotal: 'Total',
448
456
  mapSearchPlaces: 'Search places',
457
+ timelineShowMore: 'Show {count} more',
458
+ timelineShowLess: 'Show less',
449
459
  }
450
460
 
451
461
  export const M3_LOCALE_KEY: InjectionKey<MaybeRef<Partial<M3Locale>>> = Symbol('m3-locale')
@@ -1,4 +1,4 @@
1
- import { computed, getCurrentInstance, inject, onBeforeUnmount, onMounted, watch, type ComputedRef, type InjectionKey, type Ref, type ShallowRef } from 'vue'
1
+ import { computed, getCurrentInstance, inject, onBeforeUnmount, onMounted, provide, toValue, watch, type ComputedRef, type InjectionKey, type MaybeRefOrGetter, type Ref, type ShallowRef } from 'vue'
2
2
  import type * as Maplibre from 'maplibre-gl'
3
3
  import type { MapLayerModel } from './mapAdapters'
4
4
  import type { MapLayerState } from './useMapLayers'
@@ -28,21 +28,59 @@ export interface MapContext {
28
28
  // Internal: provided by MMap
29
29
  export const MAP_KEY: InjectionKey<MapContext> = Symbol('m3-map')
30
30
 
31
+ /**
32
+ * A map to use from outside `<MMap>`: the `MMap` itself (a template ref: `<MMap ref="map">` → `:map="map"`) or its
33
+ * `context`. Null or undefined until it mounts.
34
+ */
35
+ export type MapSource = { context: MapContext } | MapContext | null | undefined
36
+
37
+ /**
38
+ * Internal: the enclosing MMap's context or, outside one, a context that follows `source` (empty until it's
39
+ * there), provided to the caller's children too. Null when there's neither.
40
+ */
41
+ export function resolveMapContext(source?: MaybeRefOrGetter<MapSource>): MapContext | null {
42
+ const injected = inject(MAP_KEY, null)
43
+ if (injected || source === undefined) return injected
44
+ const ctx = computed(() => {
45
+ const s = toValue(source)
46
+ return !s ? undefined : 'context' in s ? s.context : s
47
+ })
48
+ const empty = { visible: {} as Record<string, boolean>, opacity: {} as Record<string, number> }
49
+ const forwarded = {
50
+ map: computed(() => ctx.value?.map.value),
51
+ maplibre: computed(() => ctx.value?.maplibre.value),
52
+ styleVersion: computed(() => ctx.value?.styleVersion.value ?? 0),
53
+ model: computed(() => ctx.value?.model.value),
54
+ // Reads and writes reach the map's own state once it's there
55
+ layerState: new Proxy(empty, { get: (target, key) => Reflect.get(ctx.value?.layerState ?? target, key) }),
56
+ activeTool: computed({
57
+ get: () => ctx.value?.activeTool.value ?? null,
58
+ set: (v) => { if (ctx.value) ctx.value.activeTool.value = v },
59
+ }),
60
+ } as unknown as MapContext
61
+ provide(MAP_KEY, forwarded)
62
+ return forwarded
63
+ }
64
+
31
65
  type MapEventType = keyof Maplibre.MapEventType
32
66
  type LayerEventType = keyof Maplibre.MapLayerEventType
33
67
 
34
68
  /**
35
69
  * The map of the enclosing `MMap`, for your own controls, layers and handlers (call it in a component inside
36
- * `MMap`). Listeners added through it are removed when the component unmounts.
70
+ * `MMap`). Listeners added through it are removed when the component unmounts. Outside an `MMap` (a side panel),
71
+ * pass it one: the `MMap`'s template ref, or a getter for it; until it mounts, `map` is undefined and `onReady` waits.
37
72
  *
38
73
  * ```ts
39
74
  * const { map, onLayer } = useMap()
40
75
  * onLayer('click', 'parcels-fill', (e) => console.log(e.features?.[0]?.properties))
76
+ *
77
+ * // In a panel next to the map: <MMap ref="mapRef"> … <MyPanel :map="mapRef" />
78
+ * const { map } = useMap(() => props.map)
41
79
  * ```
42
80
  */
43
- export function useMap() {
44
- const ctx = inject(MAP_KEY, null)
45
- if (!ctx) throw new Error('useMap() must be called in a component inside <MMap>')
81
+ export function useMap(source?: MaybeRefOrGetter<MapSource>) {
82
+ const ctx = resolveMapContext(source)
83
+ if (!ctx) throw new Error('useMap() must be called in a component inside <MMap>, or be given one')
46
84
  const cleanups: (() => void)[] = []
47
85
  if (getCurrentInstance()) onBeforeUnmount(() => cleanups.splice(0).forEach((fn) => fn()))
48
86
 
@@ -1,6 +1,6 @@
1
- import { inject } from 'vue'
1
+ import type { MaybeRefOrGetter } from 'vue'
2
2
  import type * as Maplibre from 'maplibre-gl'
3
- import { MAP_KEY } from './useMap'
3
+ import { resolveMapContext, type MapSource } from './useMap'
4
4
 
5
5
  // The style's own filter of each layer we filter (undefined: none), per map
6
6
  const originals = new WeakMap<Maplibre.Map, Map<string, Maplibre.FilterSpecification | undefined>>()
@@ -9,10 +9,11 @@ const originals = new WeakMap<Maplibre.Map, Map<string, Maplibre.FilterSpecifica
9
9
  * Filters for the layers of the enclosing `MMap`, on top of the filters their style already has (a layer that only
10
10
  * draws parks keeps doing so): `setFilter(layer, expression)` combines both, `setFilter(layer, null)` brings the
11
11
  * style's back. `MMapFilter` is built on it; use it for filters of your own (a range slider, a date, a search…).
12
+ * Outside an `MMap`, pass it one (its template ref), as with `useMap`.
12
13
  */
13
- export function useMapFilter() {
14
- const ctx = inject(MAP_KEY, null)
15
- if (!ctx) throw new Error('useMapFilter() must be called in a component inside <MMap>')
14
+ export function useMapFilter(source?: MaybeRefOrGetter<MapSource>) {
15
+ const ctx = resolveMapContext(source)
16
+ if (!ctx) throw new Error('useMapFilter() must be called in a component inside <MMap>, or be given one')
16
17
 
17
18
  function setFilter(layerId: string, filter: Maplibre.FilterSpecification | null) {
18
19
  const map = ctx!.map.value
@@ -1,6 +1,6 @@
1
- import { computed, inject, reactive } from 'vue'
1
+ import { computed, reactive, type MaybeRefOrGetter } from 'vue'
2
2
  import type * as Maplibre from 'maplibre-gl'
3
- import { MAP_KEY } from './useMap'
3
+ import { resolveMapContext, type MapSource } from './useMap'
4
4
  import type { MapLayerInfo, MapLayerModel } from './mapAdapters'
5
5
 
6
6
  /** The paint properties that make each layer type transparent. */
@@ -43,11 +43,12 @@ export function readLayerState(state: MapLayerState, map: Maplibre.Map, model: M
43
43
  /**
44
44
  * The layers of the enclosing `MMap`'s style as its `adapter` describes them, with their visibility and opacity, for a
45
45
  * layer panel or a base layer switcher of your own (`MMapLayers` and `MMapBaseLayers` are built on it). Changes go to
46
- * the map and to every component using it; a layer's `children` follow it.
46
+ * the map and to every component using it; a layer's `children` follow it. Outside an `MMap`, pass it one (its
47
+ * template ref), as with `useMap`.
47
48
  */
48
- export function useMapLayers() {
49
- const ctx = inject(MAP_KEY, null)
50
- if (!ctx) throw new Error('useMapLayers() must be called in a component inside <MMap>')
49
+ export function useMapLayers(source?: MaybeRefOrGetter<MapSource>) {
50
+ const ctx = resolveMapContext(source)
51
+ if (!ctx) throw new Error('useMapLayers() must be called in a component inside <MMap>, or be given one')
51
52
  const { map, model, layerState: state } = ctx
52
53
 
53
54
  const layers = computed(() => model.value?.layers ?? [])
@@ -0,0 +1,151 @@
1
+ import { getCurrentInstance, onBeforeUnmount, toValue, watch, type MaybeRefOrGetter } from 'vue'
2
+ import { motionSprings } from './motion'
3
+ import { playSamples, prefersReducedMotion, sampleSpring } from './_springAnimation'
4
+
5
+ /** How an element enters: from below, from a side, growing, or only fading. */
6
+ export type RevealEffect = 'fade-up' | 'fade' | 'scale' | 'slide-left' | 'slide-right'
7
+
8
+ export interface ScrollRevealOptions {
9
+ /** How it enters (default `'fade-up'`) */
10
+ effect?: RevealEffect
11
+ /** Distance in px for the slide effects (default 24) */
12
+ distance?: number
13
+ /** Delay in ms before it starts (default 0) */
14
+ delay?: number
15
+ /** Extra delay in ms for each next element revealed at the same time, so a list cascades in (default 60) */
16
+ stagger?: number
17
+ /** Reveal only the first time (default `true`); with `false` it hides again once it leaves the screen */
18
+ once?: boolean
19
+ /** How much of the element has to be visible, 0 to 1 (default 0.15) */
20
+ threshold?: number
21
+ /** Grows or shrinks the area that counts as visible, like IntersectionObserver's `rootMargin` (default `'0px'`) */
22
+ rootMargin?: string
23
+ /** Motion scheme of the springs: `'standard'` (default) or `'expressive'` (a little bounce) */
24
+ scheme?: 'standard' | 'expressive'
25
+ /** Pace: M3's fast, default or slow springs (default `'default'`); slow suits large, calm entrances */
26
+ speed?: 'fast' | 'default' | 'slow'
27
+ }
28
+
29
+ const OFFSET: Record<RevealEffect, (d: number) => { x: number; y: number; scale: number }> = {
30
+ 'fade-up': (d) => ({ x: 0, y: d, scale: 1 }),
31
+ fade: () => ({ x: 0, y: 0, scale: 1 }),
32
+ scale: () => ({ x: 0, y: 0, scale: 0.92 }),
33
+ 'slide-left': (d) => ({ x: d, y: 0, scale: 1 }),
34
+ 'slide-right': (d) => ({ x: -d, y: 0, scale: 1 }),
35
+ }
36
+
37
+ const hiddenStyle = (o: ReturnType<(typeof OFFSET)[RevealEffect]>) =>
38
+ ({ opacity: '0', transform: `translate(${o.x}px, ${o.y}px) scale(${o.scale})` })
39
+
40
+ /**
41
+ * Internal engine shared by `useScrollReveal` and `v-reveal`: one IntersectionObserver for a set of options.
42
+ * Elements are hidden (inline opacity/transform) when observed and play the springs in as they enter; the ones
43
+ * entering together cascade by `stagger`.
44
+ */
45
+ export function createReveal(options: ScrollRevealOptions = {}) {
46
+ const { effect = 'fade-up', distance = 24, delay = 0, stagger = 60, once = true, threshold = 0.15, rootMargin = '0px', scheme = 'standard', speed = 'default' } = options
47
+ const offset = OFFSET[effect](distance)
48
+ const springs = motionSprings[scheme]
49
+ const shown = new WeakSet<Element>()
50
+ const anims = new WeakMap<Element, Animation>()
51
+ const reduced = prefersReducedMotion()
52
+
53
+ function show(el: HTMLElement, wait: number) {
54
+ shown.add(el)
55
+ anims.get(el)?.cancel()
56
+ // End state inline, then the samples over it: nothing jumps when the animation ends
57
+ el.style.opacity = ''
58
+ el.style.transform = ''
59
+ const move = sampleSpring(0, 1, 0, springs[`${speed}Spatial`], 0.001)
60
+ const fade = sampleSpring(0, 1, 0, springs[`${speed}Effects`], 0.001)
61
+ const n = Math.max(move.length, fade.length)
62
+ const at = (s: number[], i: number) => s[Math.min(i, s.length - 1)]!
63
+ const frames = Array.from({ length: n }, (_, i) => i)
64
+ const anim = playSamples(el, frames, (i) => {
65
+ const m = at(move, i)
66
+ const k = 1 - m
67
+ return {
68
+ opacity: String(at(fade, i)),
69
+ transform: `translate(${offset.x * k}px, ${offset.y * k}px) scale(${1 - (1 - offset.scale) * k})`,
70
+ }
71
+ }, wait)
72
+ if (anim) {
73
+ // Before its delay the animation isn't applying yet: keep it hidden until then
74
+ anim.effect?.updateTiming({ fill: 'backwards' })
75
+ anims.set(el, anim)
76
+ }
77
+ }
78
+
79
+ function hide(el: HTMLElement) {
80
+ shown.delete(el)
81
+ anims.get(el)?.cancel()
82
+ Object.assign(el.style, hiddenStyle(offset))
83
+ }
84
+
85
+ const observer =
86
+ typeof IntersectionObserver === 'undefined' || reduced
87
+ ? null
88
+ : new IntersectionObserver(
89
+ (entries) => {
90
+ // Cascade in document order among the ones entering in this batch
91
+ const entering = entries
92
+ .filter((e) => e.isIntersecting && !shown.has(e.target))
93
+ .map((e) => e.target as HTMLElement)
94
+ .sort((a, b) => (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1))
95
+ entering.forEach((el, i) => {
96
+ show(el, delay + i * stagger)
97
+ if (once) observer!.unobserve(el)
98
+ })
99
+ if (!once) {
100
+ for (const e of entries) if (!e.isIntersecting && shown.has(e.target)) hide(e.target as HTMLElement)
101
+ }
102
+ },
103
+ { threshold, rootMargin },
104
+ )
105
+
106
+ return {
107
+ observe(el: Element) {
108
+ // Without an observer (server, old browser) or with reduced motion, it's simply there
109
+ if (!observer || shown.has(el)) return
110
+ hide(el as HTMLElement)
111
+ observer.observe(el)
112
+ },
113
+ unobserve(el: Element) {
114
+ observer?.unobserve(el)
115
+ anims.get(el)?.cancel()
116
+ },
117
+ disconnect() {
118
+ observer?.disconnect()
119
+ },
120
+ }
121
+ }
122
+
123
+ type Target = Element | null | undefined | Iterable<Element | null | undefined>
124
+
125
+ /**
126
+ * Reveals elements as they scroll into view: they fade (and slide or grow) in on M3's springs, cascading when
127
+ * several enter together. Pass an element, a template ref, an array of them, or a getter. Off with reduced motion:
128
+ * everything is simply there. For a single element in a template, `v-reveal` does the same.
129
+ */
130
+ export function useScrollReveal(target: MaybeRefOrGetter<Target>, options: ScrollRevealOptions = {}) {
131
+ const reveal = createReveal(options)
132
+ let current: Element[] = []
133
+ const list = (t: Target): Element[] =>
134
+ !t ? [] : t instanceof Element ? [t] : [...t].filter((e): e is Element => !!e)
135
+
136
+ watch(
137
+ () => list(toValue(target)),
138
+ (next) => {
139
+ for (const el of current) if (!next.includes(el)) reveal.unobserve(el)
140
+ for (const el of next) if (!current.includes(el)) reveal.observe(el)
141
+ current = next
142
+ },
143
+ { immediate: true, flush: 'post' },
144
+ )
145
+ if (getCurrentInstance()) onBeforeUnmount(() => reveal.disconnect())
146
+
147
+ return {
148
+ /** Stops watching (elements already revealed stay) */
149
+ stop: () => reveal.disconnect(),
150
+ }
151
+ }
@@ -0,0 +1,116 @@
1
+ import { onBeforeUnmount, onMounted, ref, type Ref } from 'vue'
2
+ import { STYLE_ID } from './_storageKeys'
3
+ import { THEME_TRANSITION_MS } from './_themeTransition'
4
+ import { cubicBezier } from './motion'
5
+
6
+ export interface ThemeTokensOptions {
7
+ /**
8
+ * Updates every animation frame while the theme switch's colors fade, so a canvas redrawn on change fades with
9
+ * the page instead of jumping to the new colors. Off by default: what animates color changes itself (Chart.js,
10
+ * MChart, maps) only needs the final values, and would otherwise redraw ~15 times per switch.
11
+ */
12
+ live?: boolean
13
+ }
14
+
15
+ // The CSS `ease` the switch uses (_themeTransition.ts, and `.theme-transitioning` in theme.css)
16
+ const ease = cubicBezier(0.25, 0.1, 0.25, 1)
17
+
18
+ type Rgba = [number, number, number, number]
19
+
20
+ // Hex (#rgb, #rgba, #rrggbb, #rrggbbaa) or rgb()/rgba(), the forms tokens are written in or computed to; null for
21
+ // anything else (that token then switches at once)
22
+ function parseColor(value: string): Rgba | null {
23
+ const v = value.trim()
24
+ const hex = /^#([0-9a-f]{3,8})$/i.exec(v)?.[1]
25
+ if (hex && hex.length !== 5 && hex.length !== 7) {
26
+ const full = hex.length <= 4 ? [...hex].map((c) => c + c).join('') : hex
27
+ const n = (i: number) => parseInt(full.slice(i, i + 2), 16)
28
+ return [n(0), n(2), n(4), full.length === 8 ? n(6) / 255 : 1]
29
+ }
30
+ const fn = /^rgba?\(([^)]+)\)$/i.exec(v)?.[1]
31
+ if (!fn) return null
32
+ const parts = fn.split(/[\s,/]+/).filter(Boolean)
33
+ if (parts.length < 3) return null
34
+ const channel = (p: string) => (p.endsWith('%') ? parseFloat(p) * 2.55 : parseFloat(p))
35
+ const alpha = parts[3] == null ? 1 : parts[3].endsWith('%') ? parseFloat(parts[3]) / 100 : parseFloat(parts[3])
36
+ const rgba = [channel(parts[0]!), channel(parts[1]!), channel(parts[2]!), alpha] as Rgba
37
+ return rgba.every(Number.isFinite) ? rgba : null
38
+ }
39
+
40
+ function mix(from: string, to: string, t: number): string {
41
+ const a = parseColor(from)
42
+ const b = parseColor(to)
43
+ if (!a || !b) return t < 1 ? from : to
44
+ const [r, g, bl, al] = a.map((x, i) => x + (b[i]! - x) * t)
45
+ return `rgba(${Math.round(r!)}, ${Math.round(g!)}, ${Math.round(bl!)}, ${+al!.toFixed(3)})`
46
+ }
47
+
48
+ /**
49
+ * The current values of some color tokens (`['primary', 'surface']` → `--color-primary`…), kept up to date across
50
+ * light/dark, palette, contrast and generated (seed) palette changes: for what can't use CSS variables, like a
51
+ * Chart.js dataset, a canvas or a MapLibre layer's paint. Values settle after the theme switch's color transition;
52
+ * with `{ live: true }` they also follow it frame by frame (as `rgba()` midway). Empty strings on the server.
53
+ *
54
+ * ```ts
55
+ * const colors = useThemeTokens(['primary', 'tertiary', 'outline-variant'] as const)
56
+ * const data = computed(() => ({ datasets: [{ data: sales, borderColor: colors.value.primary }] }))
57
+ * ```
58
+ */
59
+ export function useThemeTokens<T extends string>(names: readonly T[], options: ThemeTokensOptions = {}): Ref<Record<T, string>> {
60
+ const read = () => {
61
+ const style = getComputedStyle(document.documentElement)
62
+ return Object.fromEntries(names.map((n) => [n, style.getPropertyValue(`--color-${n}`).trim()])) as Record<T, string>
63
+ }
64
+ const tokens = ref(typeof document === 'undefined' ? Object.fromEntries(names.map((n) => [n, ''])) as Record<T, string> : read()) as Ref<Record<T, string>>
65
+ let observer: MutationObserver | undefined
66
+ let settle: ReturnType<typeof setTimeout> | undefined
67
+ let frame = 0
68
+
69
+ const set = (next: Record<T, string>) => {
70
+ if (names.some((n) => next[n] !== tokens.value[n])) tokens.value = next
71
+ }
72
+ const update = () => set(read())
73
+
74
+ // Follows a switch already under way. Chromium/WebKit animate the tokens themselves (`theme-switching`), so
75
+ // reading them each frame gives the page's own colors; Firefox fades each element's colors instead
76
+ // (`theme-transitioning`) while the tokens jump, so the same `ease` is replayed here from the old values
77
+ function follow(root: HTMLElement) {
78
+ cancelAnimationFrame(frame)
79
+ const native = root.classList.contains('theme-switching')
80
+ const from = { ...tokens.value }
81
+ const to = native ? null : read()
82
+ const start = performance.now()
83
+ const step = (now: number) => {
84
+ const t = Math.min(1, (now - start) / THEME_TRANSITION_MS)
85
+ // The last frame lands on the values as written, not their rgba() form
86
+ if (to) set(t < 1 ? Object.fromEntries(names.map((n) => [n, mix(from[n], to[n], ease(t))])) as Record<T, string> : to)
87
+ else update()
88
+ if (t < 1) frame = requestAnimationFrame(step)
89
+ }
90
+ frame = requestAnimationFrame(step)
91
+ }
92
+
93
+ onMounted(() => {
94
+ const root = document.documentElement
95
+ // Dark mode (class), a palette or contrast (attributes), or a generated palette rewriting its <style> in <head>
96
+ const isPaletteStyle = (node: Node | null) => (node instanceof Element ? node : node?.parentElement)?.id === STYLE_ID
97
+ observer = new MutationObserver((records) => {
98
+ if (!records.some((r) => r.target === root || isPaletteStyle(r.target)
99
+ || Array.from(r.addedNodes).some(isPaletteStyle))) return
100
+ if (options.live && (root.classList.contains('theme-switching') || root.classList.contains('theme-transitioning'))) follow(root)
101
+ else update()
102
+ // Chromium animates the tokens on a theme switch (_themeTransition, 250ms): read the settled values too
103
+ clearTimeout(settle)
104
+ settle = setTimeout(update, THEME_TRANSITION_MS + 50)
105
+ })
106
+ observer.observe(root, { attributes: true, attributeFilter: ['class', 'style', 'data-palette', 'data-contrast'] })
107
+ observer.observe(document.head, { childList: true, characterData: true, subtree: true })
108
+ })
109
+ onBeforeUnmount(() => {
110
+ observer?.disconnect()
111
+ clearTimeout(settle)
112
+ cancelAnimationFrame(frame)
113
+ })
114
+
115
+ return tokens
116
+ }
@@ -0,0 +1,80 @@
1
+ import { VIEWPORT_KEY } from './_storageKeys'
2
+
3
+ /** A request's headers as server frameworks hand them over: a `Headers`, or a plain object (Node's, h3's). */
4
+ export type RequestHeaders = Headers | Record<string, string | string[] | undefined>
5
+
6
+ /** A window size, for `createM3UI({ initialState: { viewport } })` */
7
+ export interface ViewportSize {
8
+ width: number
9
+ height: number
10
+ }
11
+
12
+ /**
13
+ * The client hints that carry the window's size (Chromium), for a server's `Accept-CH` and `Critical-CH` response
14
+ * headers. With `Critical-CH`, Chromium repeats the very first request once to send them; later requests carry them
15
+ * after `Accept-CH` alone.
16
+ */
17
+ export const VIEWPORT_HINTS = 'Sec-CH-Viewport-Width, Sec-CH-Viewport-Height'
18
+
19
+ // Sizes standing for a kind of device when that's all a request tells: a phone (compact), a tablet held upright
20
+ // (medium), a laptop (large)
21
+ const GUESSES = {
22
+ phone: { width: 412, height: 915 },
23
+ tablet: { width: 820, height: 1180 },
24
+ desktop: { width: 1280, height: 800 },
25
+ } as const
26
+
27
+ function header(headers: RequestHeaders, name: string): string | undefined {
28
+ if (typeof Headers !== 'undefined' && headers instanceof Headers) return headers.get(name) ?? undefined
29
+ const record = headers as Record<string, string | string[] | undefined>
30
+ const value = record[name] ?? record[Object.keys(record).find((k) => k.toLowerCase() === name) ?? '']
31
+ return Array.isArray(value) ? value[0] : value
32
+ }
33
+
34
+ const size = (n: number) => Number.isFinite(n) && n > 0 && n < 20000
35
+
36
+ function fromCookie(cookies: string | undefined): ViewportSize | undefined {
37
+ const raw = cookies?.match(new RegExp(`(?:^|;\\s*)${VIEWPORT_KEY}=([^;]*)`))?.[1]
38
+ if (!raw) return undefined
39
+ let value = raw
40
+ try { value = decodeURIComponent(raw) } catch { /* as it is */ }
41
+ const [width, height] = value.split('x').map(Number)
42
+ return size(width!) && size(height!) ? { width: width!, height: height! } : undefined
43
+ }
44
+
45
+ /** The kind of device a request comes from: Chromium says whether it's mobile; otherwise the user agent */
46
+ function guess(headers: RequestHeaders): ViewportSize | undefined {
47
+ const ua = header(headers, 'user-agent') ?? ''
48
+ const mobileHint = header(headers, 'sec-ch-ua-mobile')
49
+ // Chromium on an Android tablet says ?0 and leaves "Mobile" out of its user agent, so the hint goes first only for
50
+ // phones
51
+ if (mobileHint === '?1') return { ...GUESSES.phone }
52
+ if (/iPad|Tablet|PlayBook|Silk|Kindle|Android(?!.*Mobile)/i.test(ua)) return { ...GUESSES.tablet }
53
+ if (mobileHint === '?0') return { ...GUESSES.desktop }
54
+ if (/Mobi|iPhone|iPod|Android|BlackBerry|Opera Mini|IEMobile/i.test(ua)) return { ...GUESSES.phone }
55
+ if (ua) return { ...GUESSES.desktop }
56
+ return undefined
57
+ }
58
+
59
+ /**
60
+ * The window size to server-render the adaptive layouts at, from a request's headers: the size `createM3UI({
61
+ * cookies: true })` keeps in the `m3-viewport` cookie (any visit after the first); the viewport client hints
62
+ * (Chromium, once the server asked for them with `VIEWPORT_HINTS`); or, on a first visit, a size standing for the
63
+ * kind of device (`Sec-CH-UA-Mobile`, then the user agent: a phone, a tablet or a desktop), unless `guess: false`.
64
+ * Undefined when nothing tells: the layouts then render compact.
65
+ *
66
+ * ```ts
67
+ * createM3UI({ cookies: true, initialState: { viewport: viewportFromHeaders(request.headers) } })
68
+ * ```
69
+ */
70
+ export function viewportFromHeaders(headers: RequestHeaders, options: { guess?: boolean } = {}): ViewportSize | undefined {
71
+ const cookie = fromCookie(header(headers, 'cookie'))
72
+ if (cookie) return cookie
73
+ const width = Number(header(headers, 'sec-ch-viewport-width'))
74
+ if (size(width)) {
75
+ const height = Number(header(headers, 'sec-ch-viewport-height'))
76
+ // Older Chromium sends only the width
77
+ return { width, height: size(height) ? height : Math.round(width * (width < 600 ? 2.2 : 0.625)) }
78
+ }
79
+ return options.guess === false ? undefined : guess(headers)
80
+ }