@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
@@ -1,7 +1,12 @@
1
- import { symbolRegistry } from './symbolRegistry.js'
1
+ import { createSymbolRegistry } from './symbolRegistry.js'
2
2
  import { symbolDefaults, pin } from '../config/symbolConfig.js'
3
3
  import { THEME_COLORS } from '../config/mapTheme.js'
4
4
  import { getValueForStyle } from '../utils/getValueForStyle.js'
5
+ import { rasteriseToImageData } from '../utils/rasteriseToImageData.js'
6
+
7
+ const symbolRegistry = createSymbolRegistry()
8
+
9
+ jest.mock('../utils/rasteriseToImageData.js', () => ({ rasteriseToImageData: jest.fn(async (svg, width, height) => ({ width, height })) }))
5
10
 
6
11
  const STYLE_ID = 'test'
7
12
  const mapStyle = { id: STYLE_ID }
@@ -14,26 +19,212 @@ beforeEach(() => {
14
19
  symbolRegistry.setDefaults({})
15
20
  })
16
21
 
17
- describe('symbolRegistry — built-in symbols', () => {
18
- it('registers pin by default', () => {
19
- const pin = symbolRegistry.get('pin')
20
- expect(pin).toBeDefined()
21
- expect(pin.id).toBe('pin')
22
- expect(pin.anchor).toEqual([0.5, 0.9])
23
- expect(typeof pin.svg).toBe('string')
22
+ const BUILT_IN_IDS = ['pin', 'circle', 'square', 'hexagon', 'triangle', 'diamond']
23
+ const SIZES = { small: 0.75, medium: 1, large: 1.25 }
24
+ const dims = (viewBox) => viewBox.split(' ').map(Number).slice(2)
25
+ const countPaths = (svg) => svg.match(/<path /g).length
26
+
27
+ describe('getMarkerSymbolDef', () => {
28
+ afterEach(() => symbolRegistry.setDefaults({}))
29
+
30
+ it('sizes the marker\'s symbol for its size, falling back to the map\'s default size', () => {
31
+ symbolRegistry.setDefaults({ size: 'small' })
32
+ expect(symbolRegistry.getMarkerSymbolDef({ symbol: 'pin', size: 'large' })).toBe(symbolRegistry.getSymbolDef({ symbol: 'pin', symbolSize: 'large' }))
33
+ expect(symbolRegistry.getMarkerSymbolDef({ symbol: 'pin' })).toBe(symbolRegistry.getSymbolDef({ symbol: 'pin', symbolSize: 'small' }))
24
34
  })
25
35
 
26
- it('registers circle by default', () => {
27
- const circle = symbolRegistry.get('circle')
28
- expect(circle).toBeDefined()
29
- expect(circle.id).toBe('circle')
30
- expect(circle.anchor).toEqual([0.5, 0.5])
36
+ it('falls back to the map\'s default symbol', () => {
37
+ symbolRegistry.setDefaults({ symbol: 'circle' })
38
+ expect(symbolRegistry.getMarkerSymbolDef({})).toBe(symbolRegistry.getSymbolDef({ symbol: 'circle' }))
39
+ })
40
+
41
+ it('uses inline svgContent over a symbol id, with the marker\'s viewBox and anchor', () => {
42
+ const symbolDef = symbolRegistry.getMarkerSymbolDef({ symbol: 'pin', svgContent: '<rect/>', viewBox: '0 0 50 60', anchor: [0.5, 1] })
43
+ expect(symbolDef.svg).toBe('<rect/>')
44
+ expect(symbolDef.viewBox).toBe('0 0 50 60')
45
+ expect(symbolDef.anchor).toEqual([0.5, 1])
31
46
  })
32
47
 
33
- it('lists both built-in symbols', () => {
48
+ it('falls back to the map\'s default svgContent', () => {
49
+ symbolRegistry.setDefaults({ svgContent: '<default-svg/>' })
50
+ expect(symbolRegistry.getMarkerSymbolDef({ symbol: null }).svg).toBe('<default-svg/>')
51
+ })
52
+
53
+ it('is undefined for an unknown symbol', () => {
54
+ expect(symbolRegistry.getMarkerSymbolDef({ symbol: 'does-not-exist' })).toBeUndefined()
55
+ })
56
+ })
57
+
58
+ describe('resolveVariant', () => {
59
+ it.each([
60
+ ['normal', 'resolve'],
61
+ ['active', 'resolveActive'],
62
+ ['selected', 'resolveSelected']
63
+ ])('resolves the %s variant with %s', (variant, method) => {
64
+ const symbolDef = symbolRegistry.getSymbolDef({ symbol: 'pin' })
65
+ expect(symbolRegistry.resolveVariant(symbolDef, {}, mapStyle, variant)).toBe(symbolRegistry[method](symbolDef, {}, mapStyle))
66
+ })
67
+ })
68
+
69
+ describe('getKeySymbol', () => {
70
+ it('draws a dataset style\'s symbol at medium, whatever size the style asks for', () => {
71
+ const keySymbol = symbolRegistry.getKeySymbol({ symbol: 'pin', symbolSize: 'large' }, mapStyle)
72
+ expect(keySymbol.viewBox).toBe(symbolRegistry.getSymbolDef({ symbol: 'pin', symbolSize: 'medium' }).viewBox)
73
+ expect(keySymbol.svg).toContain('<path')
74
+ })
75
+
76
+ it('uses the style\'s colours, in the page\'s colour scheme rather than the map\'s', () => {
77
+ const style = { symbol: 'circle', symbolBackgroundColor: '#123456' }
78
+ const darkMap = { ...mapStyle, mapColorScheme: 'dark', appColorScheme: 'light' }
79
+ const { svg } = symbolRegistry.getKeySymbol(style, darkMap)
80
+ expect(svg).toContain('#123456')
81
+ expect(svg).toBe(symbolRegistry.getKeySymbol(style, { ...mapStyle, mapColorScheme: 'light', appColorScheme: 'light' }).svg)
82
+ })
83
+
84
+ it('is null for a style with no known symbol', () => {
85
+ expect(symbolRegistry.getKeySymbol({ symbol: 'does-not-exist' }, mapStyle)).toBeNull()
86
+ })
87
+ })
88
+
89
+ describe('createSymbolRegistry', () => {
90
+ it('gives each registry its own symbols and defaults', () => {
91
+ const first = createSymbolRegistry()
92
+ const second = createSymbolRegistry()
93
+ first.register({ id: 'flag', svg: '<path/>', viewBox: '0 0 10 10' })
94
+ first.setDefaults({ symbol: 'circle' })
95
+ expect(second.get('flag')).toBeUndefined()
96
+ expect(second.getDefaults().symbol).toBe('pin')
97
+ expect(first.getDefaults().symbol).toBe('circle')
98
+ })
99
+
100
+ it('starts with the built-in symbols', () => {
101
+ expect(createSymbolRegistry().list().map((symbolDef) => symbolDef.id)).toEqual(BUILT_IN_IDS)
102
+ })
103
+ })
104
+
105
+ describe('symbolRegistry — built-in symbols', () => {
106
+ it('registers every built-in as a single body path with bounds, anchor point and graphic centre', () => {
107
+ BUILT_IN_IDS.forEach((id) => {
108
+ const def = symbolRegistry.get(id)
109
+ expect(def.id).toBe(id)
110
+ expect(typeof def.path).toBe('string')
111
+ expect(def.bounds).toHaveLength(4)
112
+ expect(def.anchorPoint).toHaveLength(2)
113
+ expect(def.graphicCentre).toHaveLength(2)
114
+ })
115
+ })
116
+
117
+ it('lists all built-in symbols', () => {
34
118
  const ids = symbolRegistry.list().map(s => s.id)
35
- expect(ids).toContain('pin')
36
- expect(ids).toContain('circle')
119
+ expect(ids).toEqual(expect.arrayContaining(BUILT_IN_IDS))
120
+ })
121
+
122
+ it('sizes pin at medium to a 44×52 viewBox, anchored on the tip of its halo', () => {
123
+ const sized = symbolRegistry.getSymbolDef({ symbol: 'pin' })
124
+ expect(sized.viewBox).toBe('0 0 44 52')
125
+ expect(sized.anchor[0]).toBe(0.5)
126
+ expect(sized.anchor[1]).toBeCloseTo(0.8317, 4)
127
+ })
128
+
129
+ it('keeps each anchor on its anchorPoint at every size', () => {
130
+ BUILT_IN_IDS.forEach((id) => {
131
+ const { bounds: [bx, by, bw, bh], anchorPoint: [ax, ay] } = symbolRegistry.get(id)
132
+ Object.entries(SIZES).forEach(([symbolSize, scale]) => {
133
+ const { viewBox, anchor } = symbolRegistry.getSymbolDef({ symbol: id, symbolSize })
134
+ const [width, height] = dims(viewBox)
135
+ // body is centred in the viewBox, so the anchor point lands at centring offset + scaled distance
136
+ expect(anchor[0] * width).toBeCloseTo((width - bw * scale) / 2 + (ax - bx) * scale, 1)
137
+ expect(anchor[1] * height).toBeCloseTo((height - bh * scale) / 2 + (ay - by) * scale, 1)
138
+ })
139
+ })
140
+ })
141
+
142
+ it('scales the body but keeps at least an 8px margin for the rings, rounding the viewBox up to a multiple of 4', () => {
143
+ BUILT_IN_IDS.forEach((id) => {
144
+ const [,, bw, bh] = symbolRegistry.get(id).bounds
145
+ Object.entries(SIZES).forEach(([symbolSize, scale]) => {
146
+ const [width, height] = dims(symbolRegistry.getSymbolDef({ symbol: id, symbolSize }).viewBox)
147
+ expect(width % 4).toBe(0)
148
+ expect(height % 4).toBe(0)
149
+ expect(width - bw * scale).toBeGreaterThanOrEqual(16)
150
+ expect(width - bw * scale).toBeLessThan(20)
151
+ expect(height - bh * scale).toBeGreaterThanOrEqual(16)
152
+ expect(height - bh * scale).toBeLessThan(20)
153
+ })
154
+ })
155
+ })
156
+
157
+ it('gives a whole-pixel image size at every common pixel ratio except 1.875', () => {
158
+ const ratios = [1, 1.25, 1.5, 2, 2.25, 2.5, 3, 4] // device 1 / 1.25 / 1.5 / 2 × map size 1 / 1.5 / 2
159
+ BUILT_IN_IDS.forEach((id) => {
160
+ Object.keys(SIZES).forEach((symbolSize) => {
161
+ const [width, height] = dims(symbolRegistry.getSymbolDef({ symbol: id, symbolSize }).viewBox)
162
+ ratios.forEach((ratio) => {
163
+ expect(Number.isInteger(width * ratio)).toBe(true)
164
+ expect(Number.isInteger(height * ratio)).toBe(true)
165
+ })
166
+ })
167
+ })
168
+ })
169
+
170
+ it('draws the halo and rings at a fixed width whatever the scale', () => {
171
+ const small = symbolRegistry.resolveActive(symbolRegistry.getSymbolDef({ symbol: 'circle', symbolSize: 'small' }), {}, mapStyle)
172
+ expect(small).toContain('scale(0.75)')
173
+ // stroke widths are divided by the scale so they render at 14 / 8 / 2 px
174
+ expect(small).toContain('stroke-width="18.667"')
175
+ expect(small).toContain('stroke-width="10.667"')
176
+ expect(small).toContain('stroke-width="2.667"')
177
+ const large = symbolRegistry.resolveActive(symbolRegistry.getSymbolDef({ symbol: 'circle', symbolSize: 'large' }), {}, mapStyle)
178
+ expect(large).toContain('stroke-width="11.2"')
179
+ expect(large).toContain('stroke-width="6.4"')
180
+ expect(large).toContain('stroke-width="1.6"')
181
+ })
182
+
183
+ it('only emits the rings that are showing', () => {
184
+ const def = symbolRegistry.getSymbolDef({ symbol: 'hexagon' })
185
+ expect(countPaths(symbolRegistry.resolve(def, {}, mapStyle))).toBe(2) // body + graphic
186
+ expect(countPaths(symbolRegistry.resolveSelected(def, {}, mapStyle))).toBe(3)
187
+ expect(countPaths(symbolRegistry.resolveActive(def, {}, mapStyle))).toBe(4)
188
+ })
189
+
190
+ it('renders an unsized registered built-in at medium', () => {
191
+ const fromRaw = symbolRegistry.resolve(symbolRegistry.get('square'), {}, mapStyle)
192
+ expect(fromRaw).toBe(symbolRegistry.resolve(symbolRegistry.getSymbolDef({ symbol: 'square' }), {}, mapStyle))
193
+ })
194
+
195
+ it('uses the map\'s default size when a style has none', () => {
196
+ symbolRegistry.setDefaults({ size: 'large' })
197
+ expect(symbolRegistry.getSymbolDef({ symbol: 'circle' }).scale).toBe(1.25)
198
+ })
199
+
200
+ it('falls back to medium for an unknown symbolSize', () => {
201
+ expect(symbolRegistry.getSymbolDef({ symbol: 'circle', symbolSize: 'huge' }).scale).toBe(1)
202
+ })
203
+ })
204
+
205
+ describe('symbolRegistry — SVG-template symbols', () => {
206
+ const custom = { id: 'custom', svg: '<rect fill="{{backgroundColor}}"/>', viewBox: '0 0 20 10', anchor: [0.5, 1] }
207
+
208
+ it('leaves the svg and viewBox as they are at medium', () => {
209
+ const sized = symbolRegistry.getSizedSymbolDef(custom)
210
+ expect(sized.viewBox).toBe('0 0 20 10')
211
+ expect(sized.svg).toBe(custom.svg)
212
+ expect(sized.anchor).toEqual([0.5, 1])
213
+ })
214
+
215
+ it('scales the whole symbol, viewBox included, at other sizes', () => {
216
+ const sized = symbolRegistry.getSizedSymbolDef(custom, { size: 'large' })
217
+ expect(sized.viewBox).toBe('0 0 25 12.5')
218
+ expect(sized.svg).toBe(`<g transform="scale(1.25)">${custom.svg}</g>`)
219
+ })
220
+
221
+ it('folds a symbolViewBox override into inline symbolSvgContent before scaling', () => {
222
+ const sized = symbolRegistry.getSymbolDef({ symbolSvgContent: '<circle/>', symbolViewBox: '0 0 10 10', symbolSize: 'small' })
223
+ expect(sized.viewBox).toBe('0 0 7.5 7.5')
224
+ })
225
+
226
+ it('defaults inline symbolSvgContent to a 44×44 viewBox', () => {
227
+ expect(symbolRegistry.getSymbolDef({ symbolSvgContent: '<circle/>' }).viewBox).toBe('0 0 44 44')
37
228
  })
38
229
  })
39
230
 
@@ -52,6 +243,110 @@ describe('symbolRegistry — register / get', () => {
52
243
  it('returns undefined for an unregistered id', () => {
53
244
  expect(symbolRegistry.get('does-not-exist')).toBeUndefined()
54
245
  })
246
+
247
+ it.each([
248
+ [{ svg: '<rect/>', viewBox: '0 0 1 1' }, 'needs a string "id"'],
249
+ [{ id: 'no-svg', viewBox: '0 0 1 1' }, 'symbol "no-svg" needs an "svg" template'],
250
+ [{ id: 'no-viewbox', svg: '<rect/>' }, 'symbol "no-viewbox" needs a "viewBox"'],
251
+ [{ id: 'bad-viewbox', svg: '<rect/>', viewBox: '0 0 10' }, 'symbol "bad-viewbox" needs a "viewBox"'],
252
+ [{ id: 'bad-anchor', svg: '<rect/>', viewBox: '0 0 1 1', anchor: [0.5] }, 'symbol "bad-anchor" has an invalid "anchor"'],
253
+ [{ id: 'no-bounds', path: 'M0 0H1V1Z', anchorPoint: [0, 0], graphicCentre: [0, 0] }, 'symbol "no-bounds" has a "path" but no valid "bounds"'],
254
+ [{ id: 'no-points', path: 'M0 0H1V1Z', bounds: [0, 0, 1, 1] }, 'symbol "no-points" has a "path" but no valid "anchorPoint" and "graphicCentre"']
255
+ ])('rejects an incomplete definition with a clear error (%#)', (symbolDef, message) => {
256
+ expect(() => symbolRegistry.register(symbolDef)).toThrow(message)
257
+ })
258
+
259
+ it('accepts a viewBox written with commas', () => {
260
+ expect(() => symbolRegistry.register({ id: 'commas', svg: '<rect/>', viewBox: '0,0,10,10' })).not.toThrow()
261
+ })
262
+ })
263
+
264
+ describe('symbolRegistry — image ids and rasterising', () => {
265
+ it('gives the same SVG content at different viewBoxes different image ids', () => {
266
+ const style = { symbolSvgContent: '<circle r="4" fill="{{backgroundColor}}"/>' }
267
+ const small = symbolRegistry.getSymbolImageId({ ...style, symbolViewBox: '0 0 10 10' }, mapStyle, 'normal', 2)
268
+ const big = symbolRegistry.getSymbolImageId({ ...style, symbolViewBox: '0 0 20 20' }, mapStyle, 'normal', 2)
269
+ expect(small).not.toBe(big)
270
+ })
271
+
272
+ it('rasterises at the sized viewBox × pixelRatio, under the same id getSymbolImageId gives', async () => {
273
+ const style = { symbol: 'circle', symbolSize: 'large' }
274
+ const { imageId, imageData } = await symbolRegistry.rasteriseSymbolImage(style, mapStyle, 'normal', 2)
275
+ const [,, width, height] = symbolRegistry.getSymbolDef(style).viewBox.split(' ').map(Number)
276
+ expect(imageData).toEqual({ width: width * 2, height: height * 2 })
277
+ expect(imageId).toBe(symbolRegistry.getSymbolImageId(style, mapStyle, 'normal', 2))
278
+ })
279
+
280
+ it('gives each variant its own id, the same one rasterising it gives, without rasterising', async () => {
281
+ const style = { symbol: 'pin' }
282
+ const variants = ['normal', 'active', 'selected']
283
+ rasteriseToImageData.mockClear()
284
+ const ids = variants.map((variant) => symbolRegistry.getSymbolImageId(style, mapStyle, variant, 2))
285
+ expect(rasteriseToImageData).not.toHaveBeenCalled()
286
+ expect(new Set(ids).size).toBe(variants.length)
287
+ for (const [index, variant] of variants.entries()) {
288
+ const { imageId } = await symbolRegistry.rasteriseSymbolImage(style, mapStyle, variant, 2)
289
+ expect(imageId).toBe(ids[index])
290
+ }
291
+ })
292
+
293
+ it('gives all three variant ids at once, matching getSymbolImageId, or null for an unknown symbol', () => {
294
+ const style = { symbol: 'pin' }
295
+ expect(symbolRegistry.getSymbolImageIds(style, mapStyle, 2)).toEqual({
296
+ normal: symbolRegistry.getSymbolImageId(style, mapStyle, 'normal', 2),
297
+ active: symbolRegistry.getSymbolImageId(style, mapStyle, 'active', 2),
298
+ selected: symbolRegistry.getSymbolImageId(style, mapStyle, 'selected', 2)
299
+ })
300
+ expect(symbolRegistry.getSymbolImageIds({ symbol: 'does-not-exist' }, mapStyle, 2)).toBeNull()
301
+ })
302
+
303
+ it('rasterises nothing for an unknown symbol', async () => {
304
+ await expect(symbolRegistry.rasteriseSymbolImage({ symbol: 'does-not-exist' }, mapStyle, 'normal', 2)).resolves.toBeNull()
305
+ })
306
+
307
+ it('treats an unrecognised variant as normal', () => {
308
+ const style = { symbol: 'pin' }
309
+ expect(symbolRegistry.getSymbolImageId(style, mapStyle, 'unknown', 2)).toBe(symbolRegistry.getSymbolImageId(style, mapStyle, 'normal', 2))
310
+ })
311
+
312
+ it('shares one rasterisation between callers asking for the same image at once', async () => {
313
+ const style = { symbol: 'hexagon', symbolSize: 'small' }
314
+ rasteriseToImageData.mockClear()
315
+ const [first, second] = await Promise.all([
316
+ symbolRegistry.rasteriseSymbolImage(style, mapStyle, 'normal', 11),
317
+ symbolRegistry.rasteriseSymbolImage(style, mapStyle, 'normal', 11)
318
+ ])
319
+ expect(rasteriseToImageData).toHaveBeenCalledTimes(1)
320
+ expect(second.imageData).toBe(first.imageData)
321
+ })
322
+
323
+ it('tries again after a failed rasterisation, rather than sharing the failure', async () => {
324
+ const style = { symbol: 'diamond', symbolSize: 'small' }
325
+ rasteriseToImageData.mockRejectedValueOnce(new Error('image failed to load'))
326
+ await expect(symbolRegistry.rasteriseSymbolImage(style, mapStyle, 'normal', 13)).rejects.toThrow('image failed to load')
327
+ await expect(symbolRegistry.rasteriseSymbolImage(style, mapStyle, 'normal', 13)).resolves.toEqual(expect.objectContaining({ imageData: expect.any(Object) }))
328
+ })
329
+
330
+ it('gives image ids a long (about 64-bit) hash', () => {
331
+ const imageId = symbolRegistry.getSymbolImageId({ symbol: 'pin' }, mapStyle, 'normal', 2)
332
+ const [, hash] = imageId.match(/^symbol-([a-z0-9]+)-2x$/)
333
+ expect(hash.length).toBeGreaterThanOrEqual(10) // NOSONAR S109 — two base-36 32-bit hashes
334
+ })
335
+
336
+ it('reuses a cached image, but drops the least recently used once the cache is full', async () => {
337
+ const colour = (i) => ({ symbol: 'circle', symbolBackgroundColor: `#${i.toString(16).padStart(6, '0')}` })
338
+ await symbolRegistry.rasteriseSymbolImage(colour(0), mapStyle, 'normal', 1)
339
+ rasteriseToImageData.mockClear()
340
+ await symbolRegistry.rasteriseSymbolImage(colour(0), mapStyle, 'normal', 1)
341
+ expect(rasteriseToImageData).not.toHaveBeenCalled()
342
+
343
+ for (let i = 1; i <= 256; i++) { // NOSONAR — fills the 256-entry cache, pushing colour(0) out
344
+ await symbolRegistry.rasteriseSymbolImage(colour(i), mapStyle, 'normal', 1)
345
+ }
346
+ rasteriseToImageData.mockClear()
347
+ await symbolRegistry.rasteriseSymbolImage(colour(0), mapStyle, 'normal', 1)
348
+ expect(rasteriseToImageData).toHaveBeenCalledTimes(1)
349
+ })
55
350
  })
56
351
 
57
352
  describe('symbolRegistry — setDefaults / getDefaults', () => {
@@ -282,7 +577,7 @@ describe('symbolRegistry — graphic token', () => {
282
577
  const pin = symbolRegistry.get('pin')
283
578
  const resolved = symbolRegistry.resolve(pin, {}, mapStyle)
284
579
  expect(resolved).toContain(`d="${pin.graphic}"`)
285
- expect(resolved).toContain('translate(22, 19) scale(0.8) translate(-8, -8)')
580
+ expect(resolved).toContain('translate(22, 20) scale(0.8) translate(-8, -8)')
286
581
  })
287
582
  })
288
583
 
@@ -293,8 +588,15 @@ describe('getSymbolDef', () => {
293
588
  expect(symbolRegistry.getSymbolDef({})).toBeUndefined()
294
589
  })
295
590
 
296
- it('looks up string symbol id in the registry', () => {
297
- expect(symbolRegistry.getSymbolDef({ symbol: 'pin' })).toBe(pin)
591
+ it('looks up string symbol id in the registry, sized for rendering', () => {
592
+ const sized = symbolRegistry.getSymbolDef({ symbol: 'pin' })
593
+ expect(sized).toMatchObject({ id: 'pin', path: pin.path, scale: 1 })
594
+ expect(sized.viewBox).toBeDefined()
595
+ })
596
+
597
+ it('returns the same sized def for the same symbol and size', () => {
598
+ expect(symbolRegistry.getSymbolDef({ symbol: 'pin', symbolSize: 'large' }))
599
+ .toBe(symbolRegistry.getSymbolDef({ symbol: 'pin', symbolSize: 'large' }))
298
600
  })
299
601
 
300
602
  it('returns undefined for an unregistered string symbol', () => {
@@ -317,46 +619,46 @@ describe('getSymbolDef', () => {
317
619
 
318
620
  describe('getSymbolImageId', () => {
319
621
  it('returns null when dataset has no symbol', () => {
320
- expect(symbolRegistry.getSymbolImageId({}, mapStyle)).toBeNull()
622
+ expect(symbolRegistry.getSymbolImageId({}, mapStyle, 'normal', 2)).toBeNull()
321
623
  })
322
624
 
323
625
  it('returns null for an unregistered symbol id', () => {
324
- expect(symbolRegistry.getSymbolImageId({ symbol: 'does-not-exist' }, mapStyle)).toBeNull()
626
+ expect(symbolRegistry.getSymbolImageId({ symbol: 'does-not-exist' }, mapStyle, 'normal', 2)).toBeNull()
325
627
  })
326
628
 
327
629
  it('returns a string prefixed symbol- for normal state', () => {
328
- const id = symbolRegistry.getSymbolImageId({ symbol: 'pin' }, mapStyle)
630
+ const id = symbolRegistry.getSymbolImageId({ symbol: 'pin' }, mapStyle, 'normal', 2)
329
631
  expect(typeof id).toBe('string')
330
632
  expect(id).toMatch(/^symbol-[a-z0-9]+-\d+(\.\d+)?x$/)
331
633
  })
332
634
 
333
635
  it('returns a string prefixed symbol-act- for active state', () => {
334
- const id = symbolRegistry.getSymbolImageId({ symbol: 'pin' }, mapStyle, true)
636
+ const id = symbolRegistry.getSymbolImageId({ symbol: 'pin' }, mapStyle, 'active', 2)
335
637
  expect(typeof id).toBe('string')
336
638
  expect(id).toMatch(/^symbol-act-[a-z0-9]+-\d+(\.\d+)?x$/)
337
639
  })
338
640
 
339
641
  it('normal and active ids differ for the same dataset', () => {
340
- const normalId = symbolRegistry.getSymbolImageId({ symbol: 'pin' }, mapStyle, false)
341
- const activeId = symbolRegistry.getSymbolImageId({ symbol: 'pin' }, mapStyle, true)
642
+ const normalId = symbolRegistry.getSymbolImageId({ symbol: 'pin' }, mapStyle, 'normal', 2)
643
+ const activeId = symbolRegistry.getSymbolImageId({ symbol: 'pin' }, mapStyle, 'active', 2)
342
644
  expect(normalId).not.toBe(activeId)
343
645
  })
344
646
 
345
647
  it('same dataset and style always produces the same id', () => {
346
- const id1 = symbolRegistry.getSymbolImageId({ symbol: 'pin' }, mapStyle)
347
- const id2 = symbolRegistry.getSymbolImageId({ symbol: 'pin' }, mapStyle)
648
+ const id1 = symbolRegistry.getSymbolImageId({ symbol: 'pin' }, mapStyle, 'normal', 2)
649
+ const id2 = symbolRegistry.getSymbolImageId({ symbol: 'pin' }, mapStyle, 'normal', 2)
348
650
  expect(id1).toBe(id2)
349
651
  })
350
652
 
351
653
  it('different symbols produce different ids', () => {
352
- const pinId = symbolRegistry.getSymbolImageId({ symbol: 'pin' }, mapStyle)
353
- const circleId = symbolRegistry.getSymbolImageId({ symbol: 'circle' }, mapStyle)
654
+ const pinId = symbolRegistry.getSymbolImageId({ symbol: 'pin' }, mapStyle, 'normal', 2)
655
+ const circleId = symbolRegistry.getSymbolImageId({ symbol: 'circle' }, mapStyle, 'normal', 2)
354
656
  expect(pinId).not.toBe(circleId)
355
657
  })
356
658
 
357
659
  it('different backgrounds produce different ids', () => {
358
- const redId = symbolRegistry.getSymbolImageId({ symbol: 'pin', symbolBackgroundColor: '#ff0000' }, mapStyle)
359
- const blueId = symbolRegistry.getSymbolImageId({ symbol: 'pin', symbolBackgroundColor: '#0000ff' }, mapStyle)
660
+ const redId = symbolRegistry.getSymbolImageId({ symbol: 'pin', symbolBackgroundColor: '#ff0000' }, mapStyle, 'normal', 2)
661
+ const blueId = symbolRegistry.getSymbolImageId({ symbol: 'pin', symbolBackgroundColor: '#0000ff' }, mapStyle, 'normal', 2)
360
662
  expect(redId).not.toBe(blueId)
361
663
  })
362
664
 
@@ -366,7 +668,7 @@ describe('getSymbolImageId', () => {
366
668
  symbolViewBox: '0 0 38 38',
367
669
  symbolAnchor: [0.5, 0.5]
368
670
  }
369
- const id = symbolRegistry.getSymbolImageId(dataset, mapStyle)
671
+ const id = symbolRegistry.getSymbolImageId(dataset, mapStyle, 'normal', 2)
370
672
  expect(id).toMatch(/^symbol-[a-z0-9]+-\d+(\.\d+)?x$/)
371
673
  })
372
674
  })
package/src/types.js CHANGED
@@ -112,7 +112,7 @@
112
112
  * Plugin-specific state.
113
113
  *
114
114
  * @property {Object} [services]
115
- * Core services (announce, reverseGeocode, closeApp, etc.).
115
+ * Core services (announce, focusMap, reverseGeocode, closeApp, etc.).
116
116
  *
117
117
  * @property {(id: string, options?: ApplicationModeOptions) => void} [setApplicationMode]
118
118
  * Plugin components only. Enters an application mode, putting it on top of the stack (or moving it to
@@ -525,9 +525,12 @@
525
525
  * @typedef {Object} SymbolDefaults
526
526
  *
527
527
  * @property {string} [symbol='pin']
528
- * Default symbol ID. Built-in values: `'pin'`, `'circle'`.
528
+ * Default symbol ID. Built-in values: `'pin'`, `'circle'`, `'square'`, `'hexagon'`, `'triangle'`, `'diamond'`.
529
529
  *
530
- * @property {string} [symbolSvgContent]
530
+ * @property {'small' | 'medium' | 'large'} [size='medium']
531
+ * Default symbol size: small is 75% and large 125% of medium. Rings and halo stay a fixed width.
532
+ *
533
+ * @property {string} [svgContent]
531
534
  * Default inner SVG path content. When set, overrides `symbol`.
532
535
  *
533
536
  * @property {string} [viewBox='0 0 44 44']
@@ -572,7 +575,10 @@
572
575
  * @property {string} [symbol]
573
576
  * Symbol id to use for this marker (e.g. 'pin', 'circle'). Overrides the default `symbolDefaults.symbol` option.
574
577
  *
575
- * @property {string} [symbolSvgContent]
578
+ * @property {'small' | 'medium' | 'large'} [size]
579
+ * Symbol size for this marker. Overrides the default `symbolDefaults.size` option.
580
+ *
581
+ * @property {string} [svgContent]
576
582
  * Inner SVG path content (no `<svg>` wrapper) to use instead of a registered symbol.
577
583
  * Use `{{token}}` placeholders for colours — e.g. `fill="{{backgroundColor}}"`.
578
584
  * When set, `symbol` is ignored.
@@ -873,7 +879,7 @@
873
879
  * @property {string} [mapHintText]
874
880
  * Visually hidden text, rendered immediately before the map for screen reader users, explaining that it must be focused before keyboard commands work. Prefixed with mapLabel, so multiple maps on one page can be told apart.
875
881
  *
876
- * @property {string} [mapLabel='Interactive map']
882
+ * @property {string} [mapLabel='Interactive map application']
877
883
  * Accessible label for the map, announced by screen readers. Also prefixed onto mapHintText, so give each map on a page a distinct label.
878
884
  *
879
885
  * @property {string} [mapControlsHintText]
@@ -18,6 +18,19 @@ function normalizePointerType (pointerType) {
18
18
  return 'unknown'
19
19
  }
20
20
 
21
+ const KEYBOARD_MODE_KEYS = new Set(['Enter', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Escape'])
22
+ const NON_TEXT_INPUT_TYPES = new Set(['button', 'checkbox', 'color', 'file', 'image', 'radio', 'range', 'reset', 'submit'])
23
+
24
+ function isTextField (el) {
25
+ if (!el) {
26
+ return false
27
+ }
28
+ if (el.tagName === 'TEXTAREA' || el.isContentEditable) {
29
+ return true
30
+ }
31
+ return el.tagName === 'INPUT' && !NON_TEXT_INPUT_TYPES.has(el.type)
32
+ }
33
+
21
34
  function notifyListeners (newType) {
22
35
  if (lastInterfaceType !== newType) {
23
36
  lastInterfaceType = newType
@@ -59,11 +72,9 @@ function createInterfaceDetector () {
59
72
  }
60
73
 
61
74
  const handleKeyDown = e => {
62
- // Recognize keyboard mode from Tab (explicit focus), arrow keys (navigation),
63
- // Enter (confirmation), or other significant keys. This allows the interface type
64
- // to update even when keyboard input happens during drawing (where focus is on map).
65
- const keyboardModeKeys = new Set(['Tab', 'Enter', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Escape'])
66
- if (keyboardModeKeys.has(e.key)) {
75
+ // Tab, and arrows/Enter/Escape outside text fields, switch to keyboard mode. The
76
+ // latter cover a pointer user who clicks the map then pans or draws by keyboard.
77
+ if (e.key === 'Tab' || (KEYBOARD_MODE_KEYS.has(e.key) && !isTextField(e.target))) {
67
78
  notifyListeners('keyboard')
68
79
  }
69
80
  }
@@ -178,6 +178,38 @@ describe('Interface Detector Utility Module', () => {
178
178
  expect(handler).toHaveBeenCalledTimes(2) // no longer called after unsubscribe
179
179
  })
180
180
 
181
+ it('ignores Enter, arrows and Escape typed in a text field but still honours Tab there', () => {
182
+ cleanup = createInterfaceDetector()
183
+ triggerDomEvent('pointerdown', { pointerType: 'mouse' })
184
+
185
+ const input = document.createElement('input')
186
+ const textarea = document.createElement('textarea')
187
+ const editable = { tagName: 'DIV', isContentEditable: true }
188
+ const textFields = [input, textarea, editable]
189
+ textFields.forEach(target => {
190
+ ['Enter', 'ArrowDown', 'ArrowUp', 'Escape'].forEach(key => {
191
+ triggerDomEvent('keydown', { key, target })
192
+ expect(getInterfaceType()).toBe('mouse')
193
+ })
194
+ })
195
+
196
+ triggerDomEvent('keydown', { key: 'Tab', target: input })
197
+ expect(getInterfaceType()).toBe('keyboard')
198
+ })
199
+
200
+ it('switches to keyboard on Enter from non-text controls', () => {
201
+ cleanup = createInterfaceDetector()
202
+ const checkbox = document.createElement('input')
203
+ checkbox.type = 'checkbox'
204
+ const button = document.createElement('button')
205
+ const targets = [checkbox, button, undefined]
206
+ targets.forEach(target => {
207
+ triggerDomEvent('pointerdown', { pointerType: 'mouse' })
208
+ triggerDomEvent('keydown', { key: 'Enter', target })
209
+ expect(getInterfaceType()).toBe('keyboard')
210
+ })
211
+ })
212
+
181
213
  it('should return "touch" when matchMedia initially matches coarse pointer', async () => {
182
214
  jest.resetModules()
183
215
 
@@ -0,0 +1,23 @@
1
+ const HASH_BASE = 36
2
+ const HASH_MULTIPLIER = 31
3
+ const FNV_OFFSET = 0x811c9dc5
4
+ const FNV_PRIME = 0x01000193
5
+
6
+ /**
7
+ * A short, deterministic base-36 hash of a string: two independent 32-bit hashes (×31 and
8
+ * FNV-1a), together about 64 bits, so two different inputs sharing a hash is vanishingly unlikely.
9
+ *
10
+ * @param {string} str
11
+ * @returns {string}
12
+ */
13
+ export const hashString = (str) => {
14
+ let multiplied = 0
15
+ let fnv = FNV_OFFSET
16
+ for (const character of str) {
17
+ const code = character.codePointAt(0)
18
+ // Math.imul takes its inputs as 32-bit integers, so multiplied wraps to 32 bits each pass
19
+ multiplied = Math.imul(multiplied, HASH_MULTIPLIER) + code
20
+ fnv = Math.imul(fnv ^ code, FNV_PRIME)
21
+ }
22
+ return (multiplied >>> 0).toString(HASH_BASE) + (fnv >>> 0).toString(HASH_BASE)
23
+ }
@@ -0,0 +1,29 @@
1
+ import { hashString } from './hashString.js'
2
+
3
+ describe('hashString', () => {
4
+ test('returns a non-empty string', () => {
5
+ expect(typeof hashString('hello')).toBe('string')
6
+ expect(hashString('hello').length).toBeGreaterThan(0)
7
+ })
8
+
9
+ test('is deterministic', () => {
10
+ expect(hashString('hello')).toBe(hashString('hello'))
11
+ })
12
+
13
+ it('returns the same hash for the same input', () => {
14
+ expect(hashString('https://tiles.example.com/{z}/{x}/{y}'))
15
+ .toBe(hashString('https://tiles.example.com/{z}/{x}/{y}'))
16
+ })
17
+
18
+ test('produces different values for different inputs', () => {
19
+ expect(hashString('a')).not.toBe(hashString('b'))
20
+ })
21
+
22
+ it('handles an empty string without throwing', () => {
23
+ expect(() => hashString('')).not.toThrow()
24
+ })
25
+
26
+ it('is two 32-bit hashes in base 36', () => {
27
+ expect(hashString('<path d="M0 0"/>')).toMatch(/^[a-z0-9]{2,14}$/)
28
+ })
29
+ })
@@ -0,0 +1,43 @@
1
+ /**
2
+ * A cache of rasterised ImageData by image id, holding up to maxSize entries and dropping the
3
+ * least recently used — at worst that means rasterising an image again. Callers asking for the
4
+ * same image while it's being rasterised share that one rasterisation.
5
+ *
6
+ * @param {number} maxSize
7
+ * @returns {{ get: (imageId: string) => ImageData|undefined, rasteriseOnce: (imageId: string, rasterise: () => Promise<ImageData>) => Promise<ImageData> }}
8
+ */
9
+ export const createImageDataCache = (maxSize) => {
10
+ const cache = new Map() // imageId → ImageData, least recently used first
11
+ const pending = new Map() // imageId → Promise<ImageData>
12
+
13
+ const get = (imageId) => {
14
+ const imageData = cache.get(imageId)
15
+ if (imageData) {
16
+ cache.delete(imageId)
17
+ cache.set(imageId, imageData)
18
+ }
19
+ return imageData
20
+ }
21
+
22
+ const set = (imageId, imageData) => {
23
+ cache.set(imageId, imageData)
24
+ if (cache.size > maxSize) {
25
+ cache.delete(cache.keys().next().value)
26
+ }
27
+ }
28
+
29
+ const rasteriseOnce = (imageId, rasterise) => {
30
+ if (!pending.has(imageId)) {
31
+ const rasterising = rasterise()
32
+ .then((imageData) => {
33
+ set(imageId, imageData)
34
+ return imageData
35
+ })
36
+ .finally(() => pending.delete(imageId))
37
+ pending.set(imageId, rasterising)
38
+ }
39
+ return pending.get(imageId)
40
+ }
41
+
42
+ return { get, rasteriseOnce }
43
+ }