@defra/interactive-map 0.0.52-alpha → 0.0.54-alpha

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 (194) hide show
  1. package/dist/css/index.css +1 -1
  2. package/dist/esm/im-core.js +1 -1
  3. package/dist/esm/im-shell.js +1 -1
  4. package/dist/umd/im-core.js +1 -1
  5. package/dist/umd/index.js +1 -1
  6. package/docs/api/context.md +30 -12
  7. package/docs/api/marker-config.md +16 -8
  8. package/docs/api/symbol-config.md +24 -9
  9. package/docs/api/symbol-registry.md +49 -14
  10. package/docs/api.md +11 -3
  11. package/docs/plugins/datasets.md +6 -10
  12. package/docs/plugins/draw.md +2 -1
  13. package/docs/plugins/map-key.md +47 -4
  14. package/package.json +1 -1
  15. package/plugins/beta/map-styles/dist/esm/im-map-styles-plugin.js +1 -1
  16. package/plugins/beta/map-styles/dist/umd/im-map-styles-plugin.js +1 -1
  17. package/plugins/beta/map-styles/dist/umd/index.js +1 -1
  18. package/plugins/datasets/dist/esm/im-datasets-ml-adapter.js +1 -1
  19. package/plugins/datasets/dist/esm/im-datasets-ol-adapter.js +1 -1
  20. package/plugins/datasets/dist/esm/im-datasets-plugin.js +1 -1
  21. package/plugins/datasets/dist/esm/mapboxStyleLayerAdapter.js +1 -1
  22. package/plugins/datasets/dist/umd/im-datasets-ml-adapter.js +1 -1
  23. package/plugins/datasets/dist/umd/im-datasets-ol-adapter.js +1 -1
  24. package/plugins/datasets/dist/umd/im-datasets-plugin.js +1 -1
  25. package/plugins/datasets/src/adapters/esri/esriLayerAdapter.js +6 -6
  26. package/plugins/datasets/src/adapters/esri/registry/esriDataset.test.js +1 -1
  27. package/plugins/datasets/src/adapters/maplibre/layerBuilders.js +10 -10
  28. package/plugins/datasets/src/adapters/maplibre/layerBuilders.test.js +22 -6
  29. package/plugins/datasets/src/adapters/maplibre/maplibreLayerAdapter.js +9 -3
  30. package/plugins/datasets/src/adapters/maplibre/maplibreLayerAdapter.test.js +18 -3
  31. package/plugins/datasets/src/adapters/maplibre/registry/mapLibreDataset.js +3 -3
  32. package/plugins/datasets/src/adapters/maplibre/registry/mapLibreDataset.test.js +20 -27
  33. package/plugins/datasets/src/adapters/openlayers/canvasPatternStyle.js +16 -70
  34. package/plugins/datasets/src/adapters/openlayers/canvasPatternStyle.test.js +30 -115
  35. package/plugins/datasets/src/adapters/openlayers/layerBuilders.js +11 -13
  36. package/plugins/datasets/src/adapters/openlayers/layerBuilders.test.js +11 -3
  37. package/plugins/datasets/src/adapters/openlayers/openlayersLayerAdapter.js +48 -19
  38. package/plugins/datasets/src/adapters/openlayers/openlayersLayerAdapter.test.js +101 -13
  39. package/plugins/datasets/src/adapters/openlayers/registry/openLayersDataset.js +27 -28
  40. package/plugins/datasets/src/adapters/openlayers/registry/openLayersDataset.test.js +51 -32
  41. package/plugins/datasets/src/fetch/createDynamicSource.js +2 -2
  42. package/plugins/datasets/src/initialise/DatasetsInit.jsx +2 -2
  43. package/plugins/datasets/src/initialise/defaults.js +16 -27
  44. package/plugins/datasets/src/initialise/defaults.test.js +25 -57
  45. package/plugins/datasets/src/initialise/initialiseDatasets.js +1 -4
  46. package/plugins/datasets/src/reducers/__data__/demoDatasets.js +1 -3
  47. package/plugins/datasets/src/reducers/mappedDatasetsReducer.test.js +1 -1
  48. package/plugins/datasets/src/registry/dataset.js +23 -17
  49. package/plugins/datasets/src/registry/dataset.test.js +114 -11
  50. package/plugins/datasets/src/registry/mapboxStyleDataset.js +1 -1
  51. package/plugins/datasets/src/registry/mapboxStyleDataset.test.js +1 -1
  52. package/plugins/draw/dist/esm/im-draw-ml-adapter.js +1 -1
  53. package/plugins/draw/dist/esm/im-draw-ol-adapter.js +1 -1
  54. package/plugins/draw/dist/esm/im-draw-plugin.js +1 -1
  55. package/plugins/draw/dist/esm/index.js +1 -1
  56. package/plugins/draw/dist/esm/liveDrawChecks.js +1 -1
  57. package/plugins/draw/dist/umd/im-draw-ml-adapter.js +1 -1
  58. package/plugins/draw/dist/umd/im-draw-ol-adapter.js +1 -1
  59. package/plugins/draw/dist/umd/im-draw-plugin.js +1 -1
  60. package/plugins/draw/dist/umd/index.js +1 -1
  61. package/plugins/draw/src/DrawInit.jsx +7 -5
  62. package/plugins/draw/src/DrawInit.test.jsx +18 -2
  63. package/plugins/draw/src/adapters/maplibre/MaplibreDrawAdapter.js +11 -5
  64. package/plugins/draw/src/adapters/maplibre/MaplibreDrawAdapter.test.js +27 -11
  65. package/plugins/draw/src/adapters/maplibre/mapboxDraw.js +12 -9
  66. package/plugins/draw/src/adapters/maplibre/mapboxDraw.test.js +18 -0
  67. package/plugins/draw/src/adapters/maplibre/pointSymbolImages.js +81 -56
  68. package/plugins/draw/src/adapters/maplibre/pointSymbolImages.test.js +149 -80
  69. package/plugins/draw/src/adapters/openlayers/OLDrawAdapter.js +7 -6
  70. package/plugins/draw/src/adapters/openlayers/OLDrawAdapter.test.js +22 -25
  71. package/plugins/draw/src/adapters/openlayers/core/OLDrawManager.js +26 -8
  72. package/plugins/draw/src/adapters/openlayers/core/OLDrawManager.test.js +58 -16
  73. package/plugins/draw/src/adapters/openlayers/core/styles.js +33 -20
  74. package/plugins/draw/src/adapters/openlayers/core/styles.test.js +47 -21
  75. package/plugins/draw/src/adapters/openlayers/olDraw.js +16 -12
  76. package/plugins/draw/src/adapters/openlayers/olDraw.test.js +27 -32
  77. package/plugins/draw/src/adapters/openlayers/point/pointSymbolImages.js +44 -49
  78. package/plugins/draw/src/adapters/openlayers/point/pointSymbolImages.test.js +100 -119
  79. package/plugins/draw/src/defaults.js +2 -6
  80. package/plugins/draw/src/utils/stripInternalProperties.test.js +2 -1
  81. package/plugins/draw/src/utils/symbolKeys.js +3 -4
  82. package/plugins/interact/dist/esm/im-interact-plugin.js +1 -1
  83. package/plugins/interact/dist/umd/im-interact-plugin.js +1 -1
  84. package/plugins/interact/dist/umd/index.js +1 -1
  85. package/plugins/map-key/dist/css/index.css +1 -1
  86. package/plugins/map-key/dist/esm/im-map-key-plugin.js +1 -1
  87. package/plugins/map-key/dist/umd/im-map-key-plugin.js +1 -2
  88. package/plugins/map-key/dist/umd/index.js +1 -1
  89. package/plugins/map-key/src/components/Key/Key.jsx +8 -4
  90. package/plugins/map-key/src/components/Key/Key.module.scss +144 -53
  91. package/plugins/map-key/src/components/Key/KeyGroupItem.jsx +36 -3
  92. package/plugins/map-key/src/components/Key/KeyGroupItem.test.jsx +44 -2
  93. package/plugins/map-key/src/components/Key/KeyItem.jsx +2 -2
  94. package/plugins/map-key/src/components/Key/KeySvg.jsx +19 -18
  95. package/plugins/map-key/src/components/Key/KeySvg.test.jsx +25 -18
  96. package/plugins/map-key/src/components/Key/KeySvgPattern.jsx +1 -2
  97. package/plugins/map-key/src/components/Key/KeySvgPattern.test.jsx +3 -1
  98. package/plugins/map-key/src/components/Key/KeySvgRamp.jsx +35 -6
  99. package/plugins/map-key/src/components/Key/KeySvgRamp.test.jsx +56 -16
  100. package/plugins/map-key/src/components/Key/KeySvgSymbol.jsx +26 -12
  101. package/plugins/map-key/src/components/Key/KeySvgSymbol.test.jsx +24 -74
  102. package/plugins/map-key/src/components/Key/MapKey.jsx +3 -1
  103. package/plugins/map-key/src/components/Key/svgProperties.js +8 -2
  104. package/plugins/map-key/src/components/Key/useRampOrientation.js +61 -0
  105. package/plugins/map-key/src/components/Key/useRampOrientation.test.jsx +155 -0
  106. package/plugins/map-key/src/index.js +34 -0
  107. package/plugins/map-key/src/reducers/mergeKeyGroupItems.test.js +15 -0
  108. package/plugins/map-key/src/registry/index.js +0 -2
  109. package/plugins/map-key/src/registry/index.test.js +1 -9
  110. package/plugins/map-key/src/utils/groupStyles.js +5 -2
  111. package/plugins/menu/src/registry/index.js +0 -2
  112. package/plugins/menu/src/registry/index.test.js +1 -9
  113. package/plugins/search/dist/esm/im-search-plugin.js +1 -1
  114. package/plugins/search/dist/umd/im-search-plugin.js +1 -1
  115. package/plugins/search/dist/umd/index.js +1 -1
  116. package/plugins/search/src/Search.jsx +0 -1
  117. package/plugins/search/src/components/Form/Form.jsx +3 -3
  118. package/plugins/search/src/components/Suggestions/Suggestions.jsx +2 -0
  119. package/plugins/search/src/components/Suggestions/Suggestions.test.jsx +6 -0
  120. package/plugins/search/src/defaults.js +3 -0
  121. package/plugins/search/src/events/formHandlers.js +3 -9
  122. package/plugins/search/src/events/formHandlers.test.js +6 -9
  123. package/plugins/search/src/events/inputHandlers.js +8 -2
  124. package/plugins/search/src/events/inputHandlers.test.js +20 -0
  125. package/plugins/search/src/events/suggestionHandlers.js +3 -5
  126. package/plugins/search/src/events/suggestionHandlers.test.js +5 -8
  127. package/plugins/search/src/utils/showResult.js +9 -0
  128. package/plugins/search/src/utils/showResult.test.js +16 -0
  129. package/providers/beta/esri/dist/esm/im-esri-provider.js +1 -1
  130. package/providers/beta/openlayers/dist/esm/im-openlayers-provider.js +1 -1
  131. package/providers/beta/openlayers/dist/umd/im-openlayers-provider.js +1 -1
  132. package/providers/beta/openlayers/dist/umd/index.js +1 -1
  133. package/providers/beta/openlayers/src/openlayersProvider.js +102 -2
  134. package/providers/beta/openlayers/src/openlayersProvider.test.js +95 -0
  135. package/providers/beta/openlayers/src/utils/highlightFeatures.js +20 -25
  136. package/providers/beta/openlayers/src/utils/highlightFeatures.test.js +73 -38
  137. package/providers/beta/openlayers/src/utils/patternImages.js +61 -0
  138. package/providers/beta/openlayers/src/utils/patternImages.test.js +74 -0
  139. package/providers/beta/openlayers/src/utils/symbolImages.js +103 -95
  140. package/providers/beta/openlayers/src/utils/symbolImages.test.js +136 -85
  141. package/providers/mapProvider.js +53 -1
  142. package/providers/mapProvider.test.js +6 -0
  143. package/providers/maplibre/dist/esm/im-maplibre-provider.js +1 -1
  144. package/providers/maplibre/dist/umd/im-maplibre-provider.js +1 -1
  145. package/providers/maplibre/dist/umd/index.js +1 -1
  146. package/providers/maplibre/src/maplibreProvider.js +50 -17
  147. package/providers/maplibre/src/maplibreProvider.test.js +74 -20
  148. package/providers/maplibre/src/utils/highlightFeatures.js +19 -14
  149. package/providers/maplibre/src/utils/highlightFeatures.test.js +20 -14
  150. package/providers/maplibre/src/utils/patternImages.js +46 -29
  151. package/providers/maplibre/src/utils/patternImages.test.js +52 -4
  152. package/providers/maplibre/src/utils/symbolImages.js +80 -39
  153. package/providers/maplibre/src/utils/symbolImages.test.js +157 -54
  154. package/src/App/components/Hints/Hints.module.scss +1 -1
  155. package/src/App/components/Markers/Markers.jsx +16 -25
  156. package/src/App/components/Markers/Markers.test.jsx +34 -48
  157. package/src/App/components/Markers/SymbolLabelMarker.jsx +1 -1
  158. package/src/App/components/Markers/SymbolMarker.jsx +1 -1
  159. package/src/App/components/Viewport/Viewport.jsx +6 -4
  160. package/src/App/components/Viewport/Viewport.test.jsx +18 -1
  161. package/src/App/hooks/useMapAnnouncements.js +7 -2
  162. package/src/App/hooks/useMapAnnouncements.test.js +13 -2
  163. package/src/App/hooks/useModalPanelBehaviour.js +3 -1
  164. package/src/App/initialiseApp.js +1 -1
  165. package/src/App/store/ServiceProvider.jsx +12 -3
  166. package/src/App/store/ServiceProvider.test.jsx +39 -0
  167. package/src/InteractiveMap/InteractiveMap.js +3 -3
  168. package/src/config/appConfig.js +1 -5
  169. package/src/config/mapSizeScales.js +8 -0
  170. package/src/config/symbolConfig.js +101 -25
  171. package/src/services/mapFocus.js +64 -0
  172. package/src/services/mapFocus.test.js +76 -0
  173. package/src/services/patternRegistry.js +97 -76
  174. package/src/services/patternRegistry.test.js +19 -1
  175. package/src/services/symbolComposer.js +184 -0
  176. package/src/services/symbolComposer.test.js +132 -0
  177. package/src/services/symbolRegistry.js +326 -155
  178. package/src/services/symbolRegistry.test.js +334 -32
  179. package/src/types.js +11 -5
  180. package/src/utils/detectInterfaceType.js +16 -5
  181. package/src/utils/detectInterfaceType.test.js +32 -0
  182. package/src/utils/hashString.js +23 -0
  183. package/src/utils/hashString.test.js +29 -0
  184. package/src/utils/imageDataCache.js +43 -0
  185. package/src/utils/imageDataCache.test.js +38 -0
  186. package/src/utils/pathBounds.js +330 -0
  187. package/src/utils/pathBounds.test.js +145 -0
  188. package/src/utils/patternUtils.js +0 -8
  189. package/src/utils/patternUtils.test.js +0 -25
  190. package/src/utils/recentImageSets.js +35 -0
  191. package/src/utils/recentImageSets.test.js +46 -0
  192. package/src/utils/symbolUtils.js +26 -29
  193. package/src/utils/symbolUtils.test.js +27 -41
  194. package/plugins/map-key/dist/umd/im-map-key-plugin.js.LICENSE.txt +0 -1
@@ -0,0 +1,64 @@
1
+ // services/mapFocus.js
2
+
3
+ /**
4
+ * Moves focus to the map viewport, optionally with a message that stands in
5
+ * for the viewport's accessible name. Being the name, the message is spoken
6
+ * reliably and straight away as part of the focus announcement, where a live
7
+ * region update would race the focus change. The original name returns when
8
+ * focus leaves the viewport, so the name never changes while it has focus.
9
+ *
10
+ * A message also holds back map state announcements ("New area
11
+ * approximately...") until the user next presses a key or pointer on the map,
12
+ * since it already describes the move that follows.
13
+ */
14
+ const ARIA_LABEL = 'aria-label'
15
+
16
+ export function createMapFocus ({ viewportRef }) {
17
+ let originalLabel = null
18
+ let hasMessage = false
19
+ let isHoldingAnnouncements = false
20
+
21
+ const focus = ({ message } = {}) => {
22
+ const viewport = viewportRef.current
23
+ if (!viewport) {
24
+ return
25
+ }
26
+ if (message) {
27
+ if (!hasMessage) {
28
+ originalLabel = viewport.getAttribute(ARIA_LABEL)
29
+ }
30
+ viewport.setAttribute(ARIA_LABEL, message)
31
+ hasMessage = true
32
+ isHoldingAnnouncements = true
33
+ }
34
+ viewport.focus()
35
+ }
36
+
37
+ const clear = () => {
38
+ isHoldingAnnouncements = false
39
+ if (!hasMessage) {
40
+ return
41
+ }
42
+ hasMessage = false
43
+ const viewport = viewportRef.current
44
+ if (!viewport) {
45
+ return
46
+ }
47
+ if (originalLabel === null) {
48
+ viewport.removeAttribute(ARIA_LABEL)
49
+ } else {
50
+ viewport.setAttribute(ARIA_LABEL, originalLabel)
51
+ }
52
+ }
53
+
54
+ const releaseAnnouncements = () => {
55
+ isHoldingAnnouncements = false
56
+ }
57
+
58
+ return {
59
+ focus,
60
+ clear,
61
+ releaseAnnouncements,
62
+ isHoldingAnnouncements: () => isHoldingAnnouncements
63
+ }
64
+ }
@@ -0,0 +1,76 @@
1
+ import { createMapFocus } from './mapFocus.js'
2
+
3
+ describe('createMapFocus', () => {
4
+ let viewport
5
+ let mapFocus
6
+
7
+ beforeEach(() => {
8
+ viewport = document.createElement('div')
9
+ viewport.tabIndex = 0
10
+ viewport.setAttribute('aria-label', 'Interactive map')
11
+ document.body.appendChild(viewport)
12
+ mapFocus = createMapFocus({ viewportRef: { current: viewport } })
13
+ })
14
+
15
+ afterEach(() => {
16
+ viewport.remove()
17
+ })
18
+
19
+ it('focuses the viewport without changing its name or holding announcements', () => {
20
+ mapFocus.focus()
21
+ expect(document.activeElement).toBe(viewport)
22
+ expect(viewport.getAttribute('aria-label')).toBe('Interactive map')
23
+ expect(mapFocus.isHoldingAnnouncements()).toBe(false)
24
+ })
25
+
26
+ it('replaces the name with the message before focusing and holds announcements', () => {
27
+ viewport.addEventListener('focus', () => {
28
+ expect(viewport.getAttribute('aria-label')).toBe('Map moved to Carlisle')
29
+ })
30
+ mapFocus.focus({ message: 'Map moved to Carlisle' })
31
+ expect(document.activeElement).toBe(viewport)
32
+ expect(mapFocus.isHoldingAnnouncements()).toBe(true)
33
+ })
34
+
35
+ it('releaseAnnouncements ends the hold but keeps the message', () => {
36
+ mapFocus.focus({ message: 'Map moved to Carlisle' })
37
+ mapFocus.releaseAnnouncements()
38
+ expect(mapFocus.isHoldingAnnouncements()).toBe(false)
39
+ expect(viewport.getAttribute('aria-label')).toBe('Map moved to Carlisle')
40
+ })
41
+
42
+ it('clear restores the original name and ends the hold', () => {
43
+ mapFocus.focus({ message: 'Map moved to Carlisle' })
44
+ mapFocus.focus({ message: 'Map moved to Leeds' })
45
+ mapFocus.clear()
46
+ expect(viewport.getAttribute('aria-label')).toBe('Interactive map')
47
+ expect(mapFocus.isHoldingAnnouncements()).toBe(false)
48
+ })
49
+
50
+ it('clear leaves the name alone when no message was set', () => {
51
+ viewport.setAttribute('aria-label', 'Changed by the app')
52
+ mapFocus.clear()
53
+ expect(viewport.getAttribute('aria-label')).toBe('Changed by the app')
54
+ })
55
+
56
+ it('clear removes the name again when the viewport had none', () => {
57
+ viewport.removeAttribute('aria-label')
58
+ mapFocus.focus({ message: 'Map moved to Carlisle' })
59
+ mapFocus.clear()
60
+ expect(viewport.hasAttribute('aria-label')).toBe(false)
61
+ })
62
+
63
+ it('copes with the viewport not being mounted', () => {
64
+ const viewportRef = { current: null }
65
+ mapFocus = createMapFocus({ viewportRef })
66
+ expect(() => mapFocus.focus({ message: 'Map moved to Carlisle' })).not.toThrow()
67
+ expect(mapFocus.isHoldingAnnouncements()).toBe(false)
68
+ expect(() => mapFocus.clear()).not.toThrow()
69
+
70
+ // Unmounted between focus and clear
71
+ viewportRef.current = viewport
72
+ mapFocus.focus({ message: 'Map moved to Carlisle' })
73
+ viewportRef.current = null
74
+ expect(() => mapFocus.clear()).not.toThrow()
75
+ })
76
+ })
@@ -1,56 +1,21 @@
1
1
  import { BUILT_IN_PATTERNS } from '../config/patternConfig.js'
2
2
  import { getValueForStyle } from '../utils/getValueForStyle.js'
3
- import { KEY_BORDER_PATH, getEffectivePixelRatio, injectColors, hashString } from '../utils/patternUtils.js'
3
+ import { KEY_BORDER_PATH, getEffectivePixelRatio, injectColors } from '../utils/patternUtils.js'
4
4
  import { rasteriseToImageData } from '../utils/rasteriseToImageData.js'
5
- const patterns = new Map()
6
- // Module-level cache: imageId → ImageData. Avoids re-rasterising identical patterns.
7
- const imageDataCache = new Map()
5
+ import { hashString } from '../utils/hashString.js'
6
+ import { createImageDataCache } from '../utils/imageDataCache.js'
8
7
 
9
- export const patternRegistry = {
10
- /**
11
- * Register a named pattern.
12
- *
13
- * @param {string} id - Unique pattern name (e.g. 'my-hatch')
14
- * @param {string} svgContent - Inner SVG path content in a 16×16 coordinate space.
15
- * Use {{foregroundColor}} and {{backgroundColor}} tokens for colour injection.
16
- */
17
- register (id, svgContent) {
18
- patterns.set(id, { id, svgContent })
19
- },
20
-
21
- /**
22
- * Retrieve a registered pattern by name.
23
- *
24
- * @param {string} id
25
- * @returns {{ id: string, svgContent: string }|undefined}
26
- */
27
- get (id) {
28
- return patterns.get(id)
29
- },
30
-
31
- /**
32
- * Returns all registered patterns.
33
- *
34
- * @returns {{ id: string, svgContent: string }[]}
35
- */
36
- list () {
37
- return [...patterns.values()]
38
- },
39
-
40
- /**
41
- * Clears all registered patterns (including built-ins). Mainly for testing purposes.
42
- */
43
- clear () {
44
- patterns.clear()
45
- },
8
+ // Shared by every registry: imageId → ImageData. Every style or pixel-ratio change brings new
9
+ // ids, so it's bounded.
10
+ const IMAGE_DATA_CACHE_SIZE = 128
11
+ const imageDataCache = createImageDataCache(IMAGE_DATA_CACHE_SIZE)
46
12
 
47
- initialise () {
48
- // Seed built-in patterns
49
- Object.entries(BUILT_IN_PATTERNS).forEach(([id, svgContent]) => {
50
- this.register(id, svgContent)
51
- })
52
- },
13
+ const PATTERN_VIEWBOX_SIZE = 16 // patterns are authored in a 16×16 space...
14
+ const PATTERN_TILE_SIZE = 8 // ...and tiled at 8 CSS pixels
53
15
 
16
+ // Colouring, image ids and rasterising. They read the registry only through `this` (its
17
+ // registered patterns), so every registry shares them.
18
+ const patternImageMethods = {
54
19
  /**
55
20
  * Returns the raw (un-coloured) inner SVG content for a style's pattern.
56
21
  * Precedence: inline fillPatternSvgContent → named fillPattern from registry.
@@ -69,14 +34,14 @@ export const patternRegistry = {
69
34
  },
70
35
 
71
36
  /**
72
- * Returns colour-injected SVG path content for use in Key panel pattern symbols.
73
- * Returns { border, content } where border is the rounded-rect outline and content
74
- * is the pattern fill. Returns null if the style has no pattern.
75
- *
76
- * @param {Object} style
77
- * @param {string} mapStyleId
78
- * @returns {{ border: string, content: string }|null}
79
- */
37
+ * Returns colour-injected SVG path content for use in Key panel pattern symbols.
38
+ * Returns { border, content } where border is the rounded-rect outline and content
39
+ * is the pattern fill. Returns null if the style has no pattern.
40
+ *
41
+ * @param {Object} style
42
+ * @param {string} mapStyleId
43
+ * @returns {{ border: string, content: string }|null}
44
+ */
80
45
  getKeyPatternPaths (style, mapStyleId) {
81
46
  const innerContent = this.getPatternInnerContent(style)
82
47
  if (!innerContent) {
@@ -93,14 +58,14 @@ export const patternRegistry = {
93
58
  },
94
59
 
95
60
  /**
96
- * Returns a deterministic image ID for a pattern + resolved colour + pixel ratio combination.
97
- *
98
- * @param {Object} dataset
99
- * @param {string} mapStyleId
100
- * @param {number} [pixelRatio=1]
101
- * @returns {string|null}
102
- */
103
- getPatternImageId (dataset, mapStyleId, pixelRatio = 1) {
61
+ * Returns a deterministic image ID for a pattern + resolved colour + pixel ratio combination.
62
+ *
63
+ * @param {Object} dataset
64
+ * @param {string} mapStyleId
65
+ * @param {number} pixelRatio - Device pixel ratio × map size scale factor
66
+ * @returns {string|null}
67
+ */
68
+ getPatternImageId (dataset, mapStyleId, pixelRatio) {
104
69
  const innerContent = this.getPatternInnerContent(dataset)
105
70
  if (!innerContent) {
106
71
  return null
@@ -112,17 +77,14 @@ export const patternRegistry = {
112
77
  },
113
78
 
114
79
  /**
115
- * Rasterise a pattern to ImageData, cached by imageId — shared by MapLibre's map.addImage()
116
- * and OpenLayers' CanvasPattern (canvasPatternStyle.js). Note: the two currently render the
117
- * pattern tile at different on-screen sizes (8px vs 16px CSS) — not yet confirmed if that
118
- * needs aligning.
80
+ * Rasterise a pattern to ImageData, cached by imageId, for a map provider to register.
119
81
  *
120
82
  * @param {Object} style - Dataset or marker config with fillPattern* properties
121
83
  * @param {string} mapStyleId - Current style/theme identifier
122
- * @param {number} [pixelRatio=1] - Device pixel ratio × map size scale factor
84
+ * @param {number} pixelRatio - Device pixel ratio × map size scale factor
123
85
  * @returns {Promise<{imageId: string, imageData: ImageData}|null>}
124
86
  */
125
- async rasterisePatternImage (style, mapStyleId, pixelRatio = 1) {
87
+ async rasterisePatternImage (style, mapStyleId, pixelRatio) {
126
88
  const innerContent = this.getPatternInnerContent(style)
127
89
  if (!innerContent) {
128
90
  return null
@@ -136,15 +98,74 @@ export const patternRegistry = {
136
98
  const fg = getValueForStyle(style.fillPatternForegroundColor, mapStyleId) || 'black'
137
99
  const bg = getValueForStyle(style.fillPatternBackgroundColor, mapStyleId) || 'transparent'
138
100
  const colored = injectColors(innerContent, fg, bg)
139
- const bgRect = `<rect width="16" height="16" fill="${bg}"/>`
140
- const effectiveRatio = getEffectivePixelRatio(pixelRatio)
141
- const physicalSize = Math.round(8 * effectiveRatio)
142
- const svgString = `<svg xmlns="http://www.w3.org/2000/svg" width="${physicalSize}" height="${physicalSize}" viewBox="0 0 16 16">${bgRect}${colored}</svg>`
143
- imageData = await rasteriseToImageData(svgString, physicalSize, physicalSize)
144
- imageDataCache.set(imageId, imageData)
101
+ const bgRect = `<rect width="${PATTERN_VIEWBOX_SIZE}" height="${PATTERN_VIEWBOX_SIZE}" fill="${bg}"/>`
102
+ const physicalSize = Math.round(PATTERN_TILE_SIZE * getEffectivePixelRatio(pixelRatio))
103
+ const svgString = `<svg xmlns="http://www.w3.org/2000/svg" width="${physicalSize}" height="${physicalSize}" viewBox="0 0 ${PATTERN_VIEWBOX_SIZE} ${PATTERN_VIEWBOX_SIZE}">${bgRect}${colored}</svg>`
104
+ imageData = await imageDataCache.rasteriseOnce(imageId, () => rasteriseToImageData(svgString, physicalSize, physicalSize))
145
105
  }
146
106
  return { imageId, imageData }
147
107
  }
148
108
  }
149
109
 
150
- patternRegistry.initialise() // Seed built-in patterns
110
+ /**
111
+ * Creates a pattern registry: the built-in fill patterns plus any registered custom ones. Each
112
+ * map instance has its own, so maps on the same page can register different patterns.
113
+ *
114
+ * @returns {Object} the registry
115
+ */
116
+ export const createPatternRegistry = () => {
117
+ const patterns = new Map()
118
+
119
+ const registry = {
120
+ /**
121
+ * Register a named pattern.
122
+ *
123
+ * @param {string} id - Unique pattern name (e.g. 'my-hatch')
124
+ * @param {string} svgContent - Inner SVG path content in a 16×16 coordinate space.
125
+ * Use {{foregroundColor}} and {{backgroundColor}} tokens for colour injection.
126
+ */
127
+ register (id, svgContent) {
128
+ patterns.set(id, { id, svgContent })
129
+ },
130
+
131
+ /**
132
+ * Retrieve a registered pattern by name.
133
+ *
134
+ * @param {string} id
135
+ * @returns {{ id: string, svgContent: string }|undefined}
136
+ */
137
+ get (id) {
138
+ return patterns.get(id)
139
+ },
140
+
141
+ /**
142
+ * Returns all registered patterns.
143
+ *
144
+ * @returns {{ id: string, svgContent: string }[]}
145
+ */
146
+ list () {
147
+ return [...patterns.values()]
148
+ },
149
+
150
+ /**
151
+ * Clears all registered patterns (including built-ins). Mainly for testing purposes.
152
+ */
153
+ clear () {
154
+ patterns.clear()
155
+ },
156
+
157
+ /**
158
+ * Registers the built-in patterns. Called when the registry is created.
159
+ */
160
+ initialise () {
161
+ Object.entries(BUILT_IN_PATTERNS).forEach(([id, svgContent]) => {
162
+ this.register(id, svgContent)
163
+ })
164
+ },
165
+
166
+ ...patternImageMethods
167
+ }
168
+
169
+ registry.initialise()
170
+ return registry
171
+ }
@@ -1,6 +1,8 @@
1
- import { patternRegistry } from './patternRegistry.js'
1
+ import { createPatternRegistry } from './patternRegistry.js'
2
2
  import { KEY_BORDER_PATH } from '../utils/patternUtils.js'
3
3
 
4
+ const patternRegistry = createPatternRegistry()
5
+
4
6
  beforeAll(() => {
5
7
  globalThis.Image = class {
6
8
  constructor (w, h) {
@@ -19,6 +21,22 @@ beforeAll(() => {
19
21
  }))
20
22
  })
21
23
 
24
+ describe('createPatternRegistry', () => {
25
+ it('gives each registry its own patterns, each starting with the built-ins', () => {
26
+ const first = createPatternRegistry()
27
+ const second = createPatternRegistry()
28
+ first.register('my-hatch', '<path d="M0 0 L16 16"/>')
29
+ expect(second.get('my-hatch')).toBeUndefined()
30
+ expect(second.list().map((pattern) => pattern.id)).toEqual(first.list().map((pattern) => pattern.id).filter((id) => id !== 'my-hatch'))
31
+ })
32
+
33
+ it('clear removes every pattern, built-ins included', () => {
34
+ const registry = createPatternRegistry()
35
+ registry.clear()
36
+ expect(registry.list()).toEqual([])
37
+ })
38
+ })
39
+
22
40
  describe('patternRegistry', () => {
23
41
  describe('built-in patterns', () => {
24
42
  test.each([
@@ -0,0 +1,184 @@
1
+ import {
2
+ HALO_STROKE_WIDTH, SELECTED_RING_STROKE_WIDTH, ACTIVE_RING_STROKE_WIDTH, SYMBOL_PADDING, DEFAULT_SYMBOL_ANCHOR
3
+ } from '../config/symbolConfig.js'
4
+ import { getPathBounds } from '../utils/pathBounds.js'
5
+ import { logger } from './logger.js'
6
+
7
+ // Pure geometry and SVG building for symbols — no registry state. symbolRegistry resolves which
8
+ // definition and token values apply; this turns them into a sized definition and SVG markup.
9
+
10
+ const GRAPHIC_SIZE = 16 // graphics are authored in a 16×16 space...
11
+ const GRAPHIC_SCALE = 0.8 // ...and drawn at 0.8 of that, centred on the shape's graphicCentre
12
+ const PRECISION = 1000 // 3dp: sub-pixel precision for SVG attributes
13
+ const HALF = 0.5
14
+ const BOTH_SIDES = 2
15
+ // Built-in viewBoxes are rounded up to a multiple of this, so viewBox × pixel ratio is a whole
16
+ // number of pixels at every common ratio (device 1, 1.25, 1.5, 2 × map size 1, 1.5, 2 — all but
17
+ // 1.875). A fractional size would be truncated when rasterised, squashing the image slightly
18
+ // and shifting its anchor.
19
+ const SIZE_STEP = 4
20
+ const roundUpToStep = (value) => Math.ceil(value / SIZE_STEP) * SIZE_STEP
21
+ const round3 = (value) => Math.round(value * PRECISION) / PRECISION
22
+
23
+ // Each invalid symbolAnchor is reported once, rather than on every render
24
+ const reportedAnchors = new Set()
25
+ const ANCHOR_LENGTH = 2
26
+ const isValidAnchor = (anchor) => Array.isArray(anchor) && anchor.length === ANCHOR_LENGTH && anchor.every(Number.isFinite)
27
+
28
+ // Built-in (path-based) shapes, composed per scale: symbolDef → Map(scale → sized def)
29
+ const composedCache = new WeakMap()
30
+
31
+ /**
32
+ * Sizes a path-based built-in shape. The body and graphic scale; the halo and rings are drawn
33
+ * as strokes at a fixed width (see renderComposed), so the viewBox is the scaled body plus a
34
+ * fixed SYMBOL_PADDING, rounded up to a SIZE_STEP so rasterised images have exact dimensions.
35
+ *
36
+ * @param {Object} symbolDef - { path, bounds, anchorPoint, graphicCentre, ... }
37
+ * @param {number} scale
38
+ * @returns {Object} the def plus scale, viewBox, anchor (fractional), bodyBox and transform
39
+ */
40
+ export const composeSymbolDef = (symbolDef, scale) => {
41
+ let byScale = composedCache.get(symbolDef)
42
+ if (!byScale) {
43
+ byScale = new Map()
44
+ composedCache.set(symbolDef, byScale)
45
+ }
46
+ if (byScale.has(scale)) {
47
+ return byScale.get(scale)
48
+ }
49
+ const [boundsX, boundsY, boundsWidth, boundsHeight] = symbolDef.bounds
50
+ const width = roundUpToStep(boundsWidth * scale + SYMBOL_PADDING * BOTH_SIDES)
51
+ const height = roundUpToStep(boundsHeight * scale + SYMBOL_PADDING * BOTH_SIDES)
52
+ const offsetX = (width - boundsWidth * scale) * HALF
53
+ const offsetY = (height - boundsHeight * scale) * HALF
54
+ const [anchorX, anchorY] = symbolDef.anchorPoint
55
+ const sized = {
56
+ ...symbolDef,
57
+ scale,
58
+ viewBox: `0 0 ${width} ${height}`,
59
+ anchor: [((anchorX - boundsX) * scale + offsetX) / width, ((anchorY - boundsY) * scale + offsetY) / height],
60
+ // The body's own box within the viewBox — what a symbolAnchor override is a fraction of
61
+ bodyBox: [offsetX, offsetY, boundsWidth * scale, boundsHeight * scale],
62
+ transform: `translate(${round3(offsetX)}, ${round3(offsetY)}) scale(${scale}) translate(${-boundsX}, ${-boundsY})`
63
+ }
64
+ byScale.set(scale, sized)
65
+ return sized
66
+ }
67
+
68
+ /**
69
+ * Applies a symbolAnchor override to a sized def. For a built-in shape the override is a
70
+ * fraction of the shape itself ([0.5, 1] = its bottom edge), so it stays on the same point of the
71
+ * shape at every size; for an SVG-template symbol it's a fraction of its own viewBox. An invalid
72
+ * override is warned about (once) and ignored, keeping the symbol's own anchor.
73
+ *
74
+ * @param {Object} sizedDef
75
+ * @param {number[]} [anchor] - [x, y] in 0–1
76
+ * @returns {Object}
77
+ */
78
+ export const applyAnchorOverride = (sizedDef, anchor) => {
79
+ if (!anchor) {
80
+ return sizedDef
81
+ }
82
+ if (!isValidAnchor(anchor)) {
83
+ const reportKey = JSON.stringify(anchor)
84
+ if (!reportedAnchors.has(reportKey)) {
85
+ reportedAnchors.add(reportKey)
86
+ logger.warn(`Invalid symbolAnchor ${reportKey} — expected [x, y] numbers. Using the symbol's own anchor.`)
87
+ }
88
+ return sizedDef
89
+ }
90
+ if (!sizedDef.bodyBox) {
91
+ return { ...sizedDef, anchor }
92
+ }
93
+ const [bodyX, bodyY, bodyWidth, bodyHeight] = sizedDef.bodyBox
94
+ const [,, width, height] = sizedDef.viewBox.split(' ').map(Number)
95
+ return { ...sizedDef, anchor: [(bodyX + anchor[0] * bodyWidth) / width, (bodyY + anchor[1] * bodyHeight) / height] }
96
+ }
97
+
98
+ /**
99
+ * Sizes an SVG-template symbol (a custom symbol, or symbolSvgContent) by scaling it as a whole —
100
+ * its own rings, if it draws any, scale with it. A symbol with no anchor of its own is centred.
101
+ *
102
+ * @param {Object} symbolDef - { svg, anchor?, ... }
103
+ * @param {string} viewBox
104
+ * @param {number} scale
105
+ * @returns {Object}
106
+ */
107
+ export const scaleSvgSymbolDef = (symbolDef, viewBox, scale) => {
108
+ const anchored = { anchor: DEFAULT_SYMBOL_ANCHOR, ...symbolDef }
109
+ if (scale === 1) {
110
+ return { ...anchored, viewBox }
111
+ }
112
+ const scaledViewBox = viewBox.split(' ').map((value) => round3(Number(value) * scale)).join(' ')
113
+ return { ...anchored, viewBox: scaledViewBox, svg: `<g transform="scale(${scale})">${symbolDef.svg}</g>` }
114
+ }
115
+
116
+ // graphic path → transform that centres it and, if bigger than 16×16, shrinks it to fit
117
+ const graphicFitCache = new Map()
118
+
119
+ /**
120
+ * Transform for a graphic, placing it on the shape's graphic centre. The graphic's own bounds are centred there
121
+ * and it's shrunk (never enlarged) to fit the 16×16 graphic area — so an icon drawn in any
122
+ * coordinate space (e.g. a 24×24 Material icon) still sits centred inside the shape. A graphic
123
+ * that can't be measured falls back to the 16×16 space's own centre.
124
+ *
125
+ * @param {string} graphic - SVG path data
126
+ * @param {number} centreX - the shape's graphic centre
127
+ * @param {number} centreY
128
+ * @returns {string}
129
+ */
130
+ export const getGraphicTransform = (graphic, centreX, centreY) => {
131
+ if (!graphicFitCache.has(graphic)) {
132
+ let fit = { scale: 1, graphicCentreX: GRAPHIC_SIZE * HALF, graphicCentreY: GRAPHIC_SIZE * HALF }
133
+ if (graphic) {
134
+ try {
135
+ const [graphicX, graphicY, graphicWidth, graphicHeight] = getPathBounds(graphic)
136
+ fit = {
137
+ scale: Math.min(1, GRAPHIC_SIZE / Math.max(graphicWidth, graphicHeight, Number.EPSILON)),
138
+ graphicCentreX: graphicX + graphicWidth * HALF,
139
+ graphicCentreY: graphicY + graphicHeight * HALF
140
+ }
141
+ } catch (error) {
142
+ logger.warn(`Symbol graphic could not be measured, so it isn't centred — ${error.message}`)
143
+ }
144
+ }
145
+ graphicFitCache.set(graphic, fit)
146
+ }
147
+ const { scale, graphicCentreX, graphicCentreY } = graphicFitCache.get(graphic)
148
+ return `translate(${centreX}, ${centreY}) scale(${round3(GRAPHIC_SCALE * scale)}) translate(${round3(-graphicCentreX)}, ${round3(-graphicCentreY)})`
149
+ }
150
+
151
+ const hasColor = (color) => !!color && color !== 'none'
152
+
153
+ /**
154
+ * SVG markup for a sized built-in shape. Rings are only emitted when shown, so an unselected
155
+ * symbol is a single path plus its graphic.
156
+ *
157
+ * @param {Object} sizedDef - from composeSymbolDef
158
+ * @param {Object} values - resolved tokens (backgroundColor, foregroundColor, haloColor, selectedColor, activeColor, graphic)
159
+ * @returns {string}
160
+ */
161
+ export const renderComposed = (sizedDef, values) => {
162
+ const { path, scale, transform, graphicCentre: [centreX, centreY] } = sizedDef
163
+ const ring = (color, strokeWidth) =>
164
+ `<path d="${path}" fill="none" stroke="${color}" stroke-width="${round3(strokeWidth / scale)}" stroke-linejoin="round"/>`
165
+ const layers = [
166
+ hasColor(values.activeColor) ? ring(values.activeColor, ACTIVE_RING_STROKE_WIDTH) : '',
167
+ hasColor(values.selectedColor) ? ring(values.selectedColor, SELECTED_RING_STROKE_WIDTH) : '',
168
+ `<path d="${path}" fill="${values.backgroundColor}" stroke="${values.haloColor}" stroke-width="${round3(HALO_STROKE_WIDTH / scale)}" stroke-linejoin="round" paint-order="stroke fill"/>`,
169
+ `<g transform="${getGraphicTransform(values.graphic, centreX, centreY)}"><path d="${values.graphic}" fill="${values.foregroundColor}"/></g>`
170
+ ]
171
+ return `<g transform="${transform}">${layers.join('')}</g>`
172
+ }
173
+
174
+ /**
175
+ * Substitutes {{token}} placeholders in an SVG template.
176
+ *
177
+ * @param {string} svgString
178
+ * @param {Object} values
179
+ * @returns {string}
180
+ */
181
+ export const renderTemplate = (svgString, values) => Object.entries(values).reduce(
182
+ (svg, [token, value]) => svg.replaceAll(`{{${token}}}`, value),
183
+ svgString
184
+ )