@defra/interactive-map 0.0.60-alpha → 0.0.62-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 (84) 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/button-definition.md +11 -0
  7. package/docs/api/context.md +2 -0
  8. package/docs/api.md +20 -0
  9. package/docs/plugins/draw.md +26 -0
  10. package/package.json +1 -1
  11. package/plugins/datasets/dist/esm/im-datasets-plugin.js +1 -1
  12. package/plugins/datasets/dist/umd/im-datasets-plugin.js +1 -1
  13. package/plugins/datasets/src/reducers/datasetsToMenu.js +12 -9
  14. package/plugins/datasets/src/reducers/datasetsToMenu.test.js +42 -0
  15. package/plugins/datasets/src/reducers/pluginState.test.js +12 -0
  16. package/plugins/draw/dist/esm/im-draw-ml-adapter.js +1 -1
  17. package/plugins/draw/dist/esm/im-draw-ol-adapter.js +1 -1
  18. package/plugins/draw/dist/esm/im-draw-plugin.js +1 -1
  19. package/plugins/draw/dist/umd/im-draw-ml-adapter.js +1 -1
  20. package/plugins/draw/dist/umd/im-draw-ol-adapter.js +1 -1
  21. package/plugins/draw/dist/umd/im-draw-plugin.js +1 -1
  22. package/plugins/draw/dist/umd/index.js +1 -1
  23. package/plugins/draw/src/DrawInit.jsx +3 -0
  24. package/plugins/draw/src/DrawInit.test.jsx +16 -0
  25. package/plugins/draw/src/adapters/maplibre/MaplibreDrawAdapter.js +19 -3
  26. package/plugins/draw/src/adapters/maplibre/MaplibreDrawAdapter.test.js +27 -0
  27. package/plugins/draw/src/adapters/openlayers/OLDrawAdapter.js +10 -2
  28. package/plugins/draw/src/adapters/openlayers/OLDrawAdapter.test.js +14 -0
  29. package/plugins/draw/src/defaults.js +4 -0
  30. package/plugins/draw/src/hooks/useSnapMinZoom.js +29 -0
  31. package/plugins/draw/src/hooks/useSnapMinZoom.test.js +82 -0
  32. package/plugins/draw/src/manifest.js +4 -1
  33. package/plugins/draw/src/manifest.test.js +15 -2
  34. package/plugins/draw/src/utils/snapMinZoom.js +8 -0
  35. package/plugins/draw/src/utils/snapMinZoom.test.js +22 -0
  36. package/plugins/interact/dist/umd/im-interact-plugin.js +1 -1
  37. package/plugins/map-key/dist/esm/im-map-key-plugin.js +1 -1
  38. package/plugins/map-key/dist/umd/im-map-key-plugin.js +1 -1
  39. package/plugins/map-key/src/manifest.js +1 -1
  40. package/providers/openlayers/dist/esm/im-openlayers-provider.js +1 -1
  41. package/providers/openlayers/dist/umd/im-openlayers-provider.js +1 -1
  42. package/providers/openlayers/src/openlayersProvider.js +2 -1
  43. package/providers/openlayers/src/openlayersProvider.test.js +1 -1
  44. package/src/App/components/MapButton/MapButton.jsx +20 -2
  45. package/src/App/components/MapButton/MapButton.module.scss +15 -1
  46. package/src/App/components/MapButton/MapButton.test.jsx +21 -3
  47. package/src/App/components/MapControls/MapControls.jsx +2 -1
  48. package/src/App/components/MapControls/MapControls.test.jsx +1 -1
  49. package/src/App/components/PopupMenu/PopupMenu.test.jsx +22 -0
  50. package/src/App/components/PopupMenu/usePopupMenu.js +9 -6
  51. package/src/App/components/Tooltip/Tooltip.jsx +29 -11
  52. package/src/App/components/Tooltip/Tooltip.test.jsx +45 -3
  53. package/src/App/components/Viewport/MapController.jsx +4 -0
  54. package/src/App/components/Viewport/MapController.test.jsx +6 -0
  55. package/src/App/hooks/useMapProviderOverrides.js +10 -5
  56. package/src/App/hooks/useMapProviderOverrides.test.js +11 -0
  57. package/src/App/hooks/useResetViewTarget.js +135 -0
  58. package/src/App/hooks/useResetViewTarget.test.js +211 -0
  59. package/src/App/hooks/useUserMoveTracking.js +72 -0
  60. package/src/App/hooks/useUserMoveTracking.test.js +117 -0
  61. package/src/App/renderer/mapButtons.js +3 -1
  62. package/src/App/renderer/mapButtons.test.js +20 -0
  63. package/src/App/store/ServiceProvider.jsx +8 -2
  64. package/src/App/store/ServiceProvider.test.jsx +13 -0
  65. package/src/App/store/mapActionsMap.js +16 -1
  66. package/src/App/store/mapActionsMap.test.js +17 -0
  67. package/src/App/store/mapReducer.js +6 -0
  68. package/src/App/store/mapReducer.test.js +3 -0
  69. package/src/InteractiveMap/InteractiveMap.js +8 -0
  70. package/src/InteractiveMap/InteractiveMap.test.js +5 -0
  71. package/src/config/appConfig.js +17 -0
  72. package/src/config/appConfig.test.js +28 -0
  73. package/src/config/defaults.js +1 -0
  74. package/src/config/events.js +2 -0
  75. package/src/scss/settings/_colors.scss +4 -0
  76. package/src/services/mapFocus.js +3 -2
  77. package/src/services/mapFocus.test.js +10 -0
  78. package/src/types.js +9 -0
  79. package/src/utils/focusAfterPanelClose.js +3 -1
  80. package/src/utils/getFocusOptions.js +3 -0
  81. package/src/utils/getFocusOptions.test.js +11 -0
  82. package/src/utils/mapStateSync.js +1 -0
  83. package/src/utils/resetView.js +61 -0
  84. package/src/utils/resetView.test.js +62 -0
@@ -0,0 +1,211 @@
1
+ import { renderHook } from '@testing-library/react'
2
+ import { useResetViewTarget, RESET_MOVE_WINDOW_MS } from './useResetViewTarget'
3
+ import { useConfig } from '../store/configContext.js'
4
+ import { useApp } from '../store/appContext.js'
5
+ import { useMap } from '../store/mapContext.js'
6
+ import { useService } from '../store/serviceContext.js'
7
+
8
+ jest.mock('../store/configContext.js')
9
+ jest.mock('../store/appContext.js')
10
+ jest.mock('../store/mapContext.js')
11
+ jest.mock('../store/serviceContext.js')
12
+
13
+ const STORAGE_KEY = 'map:resetViewTarget'
14
+
15
+ describe('useResetViewTarget', () => {
16
+ let viewport, dispatch, eventBus, handlers, mapProvider
17
+
18
+ const settledState = { center: [1, 2], zoom: 10 }
19
+ const setTargetAction = (payload) => ({ type: 'SET_RESET_VIEW_TARGET', payload })
20
+ const clearTargetAction = { type: 'CLEAR_RESET_VIEW_TARGET' }
21
+ const lastAction = () => dispatch.mock.calls.at(-1)?.[0]
22
+ const lastTarget = () => lastAction()?.payload
23
+ const reset = () => handlers['map:resetview']()
24
+ const moveStart = () => handlers['map:movestart']()
25
+ const moveEnd = (state = settledState) => handlers['map:moveend'](state)
26
+ const firstIdle = (state = settledState) => handlers['map:firstidle'](state)
27
+ const loadFromURL = () => globalThis.history.replaceState(null, '', '/?map:center=1,2&map:zoom=10')
28
+
29
+ beforeEach(() => {
30
+ jest.useFakeTimers()
31
+ viewport = document.createElement('div')
32
+ document.body.appendChild(viewport)
33
+ dispatch = jest.fn()
34
+ handlers = {}
35
+ eventBus = {
36
+ on: jest.fn((name, handler) => { handlers[name] = handler }),
37
+ off: jest.fn()
38
+ }
39
+ mapProvider = {
40
+ getCenter: jest.fn(() => [3, 4]),
41
+ getZoom: jest.fn(() => 8),
42
+ mapToScreen: ([x, y]) => ({ x: x * 10, y: y * 10 })
43
+ }
44
+ useConfig.mockReturnValue({ id: 'map', mapProvider })
45
+ useApp.mockReturnValue({ layoutRefs: { viewportRef: { current: viewport } } })
46
+ useMap.mockReturnValue({ dispatch })
47
+ useService.mockReturnValue({ eventBus })
48
+ })
49
+
50
+ afterEach(() => {
51
+ viewport.remove()
52
+ globalThis.sessionStorage.clear()
53
+ globalThis.history.replaceState(null, '', '/')
54
+ jest.restoreAllMocks()
55
+ jest.useRealTimers()
56
+ })
57
+
58
+ it('does nothing without a map provider or viewport', () => {
59
+ useConfig.mockReturnValue({ id: 'map', mapProvider: null })
60
+ renderHook(() => useResetViewTarget())
61
+ useConfig.mockReturnValue({ id: 'map', mapProvider })
62
+ useApp.mockReturnValue({ layoutRefs: { viewportRef: { current: null } } })
63
+ renderHook(() => useResetViewTarget())
64
+ expect(eventBus.on).not.toHaveBeenCalled()
65
+ })
66
+
67
+ describe('on load', () => {
68
+ it('sets and saves the target when the map loaded at its configured view', () => {
69
+ renderHook(() => useResetViewTarget())
70
+ firstIdle()
71
+ expect(dispatch).toHaveBeenCalledWith(setTargetAction(settledState))
72
+ expect(JSON.parse(globalThis.sessionStorage.getItem(STORAGE_KEY))).toEqual(settledState)
73
+ })
74
+
75
+ it('ignores the URL when urlPosition is none', () => {
76
+ loadFromURL()
77
+ useConfig.mockReturnValue({ id: 'map', mapProvider, urlPosition: 'none' })
78
+ renderHook(() => useResetViewTarget())
79
+ firstIdle()
80
+ expect(lastTarget()).toEqual(settledState)
81
+ })
82
+
83
+ it('uses the saved target when the view from the URL is where the last reset went', () => {
84
+ loadFromURL()
85
+ globalThis.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(settledState))
86
+ renderHook(() => useResetViewTarget())
87
+ firstIdle()
88
+ expect(lastTarget()).toEqual(settledState)
89
+ })
90
+
91
+ it('has no target when the view from the URL is somewhere else', () => {
92
+ loadFromURL()
93
+ globalThis.sessionStorage.setItem(STORAGE_KEY, JSON.stringify({ center: [5, 5], zoom: 10 }))
94
+ renderHook(() => useResetViewTarget())
95
+ firstIdle()
96
+ expect(lastTarget()).toBeNull()
97
+ })
98
+
99
+ it.each([
100
+ ['nothing is saved', null],
101
+ ['the saved target is not valid', '{"center":"1,2"}'],
102
+ ['the saved target is not JSON', 'not json']
103
+ ])('has no target with a view from the URL when %s', (_case, saved) => {
104
+ loadFromURL()
105
+ if (saved) {
106
+ globalThis.sessionStorage.setItem(STORAGE_KEY, saved)
107
+ }
108
+ renderHook(() => useResetViewTarget())
109
+ firstIdle()
110
+ expect(lastTarget()).toBeNull()
111
+ })
112
+
113
+ it('ignores a first idle without a state', () => {
114
+ renderHook(() => useResetViewTarget())
115
+ firstIdle(null)
116
+ expect(dispatch).not.toHaveBeenCalled()
117
+ })
118
+ })
119
+
120
+ describe('on reset', () => {
121
+ it('marks the target as not known while the reset is in progress', () => {
122
+ renderHook(() => useResetViewTarget())
123
+ reset()
124
+ expect(dispatch).toHaveBeenCalledWith(clearTargetAction)
125
+ })
126
+
127
+ it('sets and saves the target where the map settles after a reset', () => {
128
+ renderHook(() => useResetViewTarget())
129
+ reset()
130
+ moveStart()
131
+ moveEnd()
132
+ expect(lastTarget()).toEqual(settledState)
133
+ expect(JSON.parse(globalThis.sessionStorage.getItem(STORAGE_KEY))).toEqual(settledState)
134
+ })
135
+
136
+ it('ignores move ends that are not from a reset, or have no state', () => {
137
+ renderHook(() => useResetViewTarget())
138
+ moveStart()
139
+ moveEnd()
140
+ expect(dispatch).not.toHaveBeenCalled()
141
+ reset()
142
+ moveStart()
143
+ moveEnd(null)
144
+ expect(lastAction()).toEqual(clearTargetAction)
145
+ })
146
+
147
+ it('sets the target to the current view when a reset does not move the map', () => {
148
+ renderHook(() => useResetViewTarget())
149
+ reset()
150
+ jest.advanceTimersByTime(RESET_MOVE_WINDOW_MS)
151
+ expect(lastTarget()).toEqual({ center: [3, 4], zoom: 8 })
152
+ })
153
+
154
+ it('waits for the move to end when a reset moves the map', () => {
155
+ renderHook(() => useResetViewTarget())
156
+ reset()
157
+ moveStart()
158
+ jest.advanceTimersByTime(RESET_MOVE_WINDOW_MS)
159
+ expect(lastAction()).toEqual(clearTargetAction)
160
+ moveEnd()
161
+ expect(lastTarget()).toEqual(settledState)
162
+ })
163
+
164
+ it.each(['pointerdown', 'wheel', 'keydown'])('has no target when the user takes over a reset with a %s on the map', (type) => {
165
+ renderHook(() => useResetViewTarget())
166
+ reset()
167
+ moveStart()
168
+ viewport.dispatchEvent(new Event(type))
169
+ moveEnd()
170
+ jest.advanceTimersByTime(RESET_MOVE_WINDOW_MS)
171
+ expect(lastTarget()).toBeNull()
172
+ expect(dispatch).toHaveBeenCalledTimes(2)
173
+ })
174
+
175
+ it('ignores map input when no reset is in progress', () => {
176
+ renderHook(() => useResetViewTarget())
177
+ viewport.dispatchEvent(new Event('pointerdown'))
178
+ expect(dispatch).not.toHaveBeenCalled()
179
+ })
180
+
181
+ it('restarts the wait when reset again', () => {
182
+ renderHook(() => useResetViewTarget())
183
+ reset()
184
+ jest.advanceTimersByTime(RESET_MOVE_WINDOW_MS - 1)
185
+ reset()
186
+ jest.advanceTimersByTime(RESET_MOVE_WINDOW_MS - 1)
187
+ expect(lastAction()).toEqual(clearTargetAction)
188
+ jest.advanceTimersByTime(1)
189
+ expect(lastTarget()).toEqual({ center: [3, 4], zoom: 8 })
190
+ })
191
+
192
+ it('still sets the target when session storage is blocked', () => {
193
+ jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new Error('blocked') })
194
+ renderHook(() => useResetViewTarget())
195
+ firstIdle()
196
+ expect(lastTarget()).toEqual(settledState)
197
+ })
198
+ })
199
+
200
+ it('cleans up on unmount', () => {
201
+ const { unmount } = renderHook(() => useResetViewTarget())
202
+ reset()
203
+ dispatch.mockClear()
204
+ unmount()
205
+ jest.advanceTimersByTime(RESET_MOVE_WINDOW_MS)
206
+ viewport.dispatchEvent(new Event('pointerdown'))
207
+ expect(dispatch).not.toHaveBeenCalled()
208
+ expect(eventBus.off).toHaveBeenCalledWith('map:resetview', expect.any(Function))
209
+ expect(eventBus.off).toHaveBeenCalledWith('map:firstidle', expect.any(Function))
210
+ })
211
+ })
@@ -0,0 +1,72 @@
1
+ import { useEffect } from 'react'
2
+ import { useConfig } from '../store/configContext.js'
3
+ import { useApp } from '../store/appContext.js'
4
+ import { useMap } from '../store/mapContext.js'
5
+ import { useService } from '../store/serviceContext.js'
6
+ import { EVENTS as events } from '../../config/events.js'
7
+
8
+ // How soon after the user's last input a map move still counts as theirs, covering the gap
9
+ // between a key press or wheel turn and the move it starts
10
+ export const USER_INPUT_WINDOW_MS = 500
11
+
12
+ const INPUT_EVENTS = ['wheel', 'keydown', 'keyup']
13
+
14
+ /**
15
+ * Sets mapState.isUserMove on each move start: true when the user started the move with a mouse,
16
+ * touch or the keyboard anywhere in the app (the map, or controls like the zoom buttons), false
17
+ * when code moved the map.
18
+ */
19
+ export function useUserMoveTracking () {
20
+ const { mapProvider } = useConfig()
21
+ const { layoutRefs } = useApp()
22
+ const { dispatch } = useMap()
23
+ const { eventBus } = useService()
24
+
25
+ useEffect(() => {
26
+ const container = layoutRefs.appContainerRef?.current
27
+ if (!mapProvider || !container) {
28
+ return undefined
29
+ }
30
+
31
+ let lastInputAt = -Infinity
32
+ let isPointerDown = false
33
+
34
+ const handleInput = () => {
35
+ lastInputAt = Date.now()
36
+ }
37
+ const handlePointerDown = () => {
38
+ isPointerDown = true
39
+ handleInput()
40
+ }
41
+ // Listened for on the document, as the pointer can be released outside the app
42
+ const handlePointerUp = () => {
43
+ isPointerDown = false
44
+ }
45
+ // Starts false, as in mapState. Only sent when it changes: a resize starts several moves inside
46
+ // MapLibre's ResizeObserver, and rendering for each one causes a ResizeObserver loop error.
47
+ let lastIsUserMove = false
48
+ const handleMoveStart = () => {
49
+ const isUserMove = isPointerDown || Date.now() - lastInputAt <= USER_INPUT_WINDOW_MS
50
+ if (isUserMove === lastIsUserMove) {
51
+ return
52
+ }
53
+ lastIsUserMove = isUserMove
54
+ dispatch({ type: 'MAP_MOVE_START', payload: { isUserMove } })
55
+ }
56
+
57
+ // Capture phase, so map libraries that stop propagation can't hide the input
58
+ container.addEventListener('pointerdown', handlePointerDown, true)
59
+ INPUT_EVENTS.forEach(type => container.addEventListener(type, handleInput, true))
60
+ document.addEventListener('pointerup', handlePointerUp, true)
61
+ document.addEventListener('pointercancel', handlePointerUp, true)
62
+ eventBus.on(events.MAP_MOVE_START, handleMoveStart)
63
+
64
+ return () => {
65
+ container.removeEventListener('pointerdown', handlePointerDown, true)
66
+ INPUT_EVENTS.forEach(type => container.removeEventListener(type, handleInput, true))
67
+ document.removeEventListener('pointerup', handlePointerUp, true)
68
+ document.removeEventListener('pointercancel', handlePointerUp, true)
69
+ eventBus.off(events.MAP_MOVE_START, handleMoveStart)
70
+ }
71
+ }, [mapProvider, eventBus, dispatch])
72
+ }
@@ -0,0 +1,117 @@
1
+ import { renderHook } from '@testing-library/react'
2
+ import { useUserMoveTracking, USER_INPUT_WINDOW_MS } from './useUserMoveTracking'
3
+ import { useConfig } from '../store/configContext.js'
4
+ import { useApp } from '../store/appContext.js'
5
+ import { useMap } from '../store/mapContext.js'
6
+ import { useService } from '../store/serviceContext.js'
7
+
8
+ jest.mock('../store/configContext.js')
9
+ jest.mock('../store/appContext.js')
10
+ jest.mock('../store/mapContext.js')
11
+ jest.mock('../store/serviceContext.js')
12
+
13
+ describe('useUserMoveTracking', () => {
14
+ let container, dispatch, eventBus, handlers
15
+
16
+ const moveStart = () => handlers['map:movestart']()
17
+ // mapState.isUserMove: false until the first change is sent
18
+ const lastIsUserMove = () => dispatch.mock.calls.at(-1)?.[0].payload.isUserMove ?? false
19
+
20
+ beforeEach(() => {
21
+ jest.useFakeTimers()
22
+ container = document.createElement('div')
23
+ document.body.appendChild(container)
24
+ dispatch = jest.fn()
25
+ handlers = {}
26
+ eventBus = {
27
+ on: jest.fn((name, handler) => { handlers[name] = handler }),
28
+ off: jest.fn()
29
+ }
30
+ useConfig.mockReturnValue({ mapProvider: {} })
31
+ useApp.mockReturnValue({ layoutRefs: { appContainerRef: { current: container } } })
32
+ useMap.mockReturnValue({ dispatch })
33
+ useService.mockReturnValue({ eventBus })
34
+ })
35
+
36
+ afterEach(() => {
37
+ container.remove()
38
+ jest.useRealTimers()
39
+ })
40
+
41
+ it('marks a move as code-made when there was no user input, without sending the unchanged value', () => {
42
+ renderHook(() => useUserMoveTracking())
43
+ moveStart()
44
+ expect(lastIsUserMove()).toBe(false)
45
+ expect(dispatch).not.toHaveBeenCalled()
46
+ })
47
+
48
+ it('only sends isUserMove when it changes', () => {
49
+ renderHook(() => useUserMoveTracking())
50
+ container.dispatchEvent(new Event('wheel'))
51
+ moveStart()
52
+ moveStart()
53
+ moveStart()
54
+ expect(dispatch).toHaveBeenCalledTimes(1)
55
+ expect(dispatch).toHaveBeenCalledWith({ type: 'MAP_MOVE_START', payload: { isUserMove: true } })
56
+
57
+ jest.advanceTimersByTime(USER_INPUT_WINDOW_MS + 1)
58
+ moveStart()
59
+ moveStart()
60
+ expect(dispatch).toHaveBeenCalledTimes(2)
61
+ expect(lastIsUserMove()).toBe(false)
62
+ })
63
+
64
+ it.each(['wheel', 'keydown', 'keyup'])('marks a move straight after a %s as the user\'s', (type) => {
65
+ renderHook(() => useUserMoveTracking())
66
+ container.dispatchEvent(new Event(type, { bubbles: true }))
67
+ moveStart()
68
+ expect(lastIsUserMove()).toBe(true)
69
+ })
70
+
71
+ it('stops counting input once the window has passed', () => {
72
+ renderHook(() => useUserMoveTracking())
73
+ container.dispatchEvent(new Event('wheel'))
74
+ jest.advanceTimersByTime(USER_INPUT_WINDOW_MS + 1)
75
+ moveStart()
76
+ expect(lastIsUserMove()).toBe(false)
77
+ })
78
+
79
+ it('counts moves while the pointer is down, however long the drag, until it\'s released', () => {
80
+ renderHook(() => useUserMoveTracking())
81
+ container.dispatchEvent(new Event('pointerdown'))
82
+ jest.advanceTimersByTime(USER_INPUT_WINDOW_MS * 4)
83
+ moveStart()
84
+ expect(lastIsUserMove()).toBe(true)
85
+
86
+ document.dispatchEvent(new Event('pointerup'))
87
+ jest.advanceTimersByTime(USER_INPUT_WINDOW_MS + 1)
88
+ moveStart()
89
+ expect(lastIsUserMove()).toBe(false)
90
+ })
91
+
92
+ it('ignores input outside the app', () => {
93
+ renderHook(() => useUserMoveTracking())
94
+ document.body.dispatchEvent(new Event('keydown'))
95
+ moveStart()
96
+ expect(lastIsUserMove()).toBe(false)
97
+ })
98
+
99
+ it('does nothing without a map provider or app container', () => {
100
+ useConfig.mockReturnValue({ mapProvider: null })
101
+ renderHook(() => useUserMoveTracking())
102
+ useConfig.mockReturnValue({ mapProvider: {} })
103
+ useApp.mockReturnValue({ layoutRefs: { appContainerRef: { current: null } } })
104
+ renderHook(() => useUserMoveTracking())
105
+ expect(eventBus.on).not.toHaveBeenCalled()
106
+ })
107
+
108
+ it('removes its listeners on unmount', () => {
109
+ const { unmount } = renderHook(() => useUserMoveTracking())
110
+ const moveStartHandler = handlers['map:movestart']
111
+ unmount()
112
+ expect(eventBus.off).toHaveBeenCalledWith('map:movestart', moveStartHandler)
113
+ container.dispatchEvent(new Event('wheel'))
114
+ moveStartHandler()
115
+ expect(lastIsUserMove()).toBe(false)
116
+ })
117
+ })
@@ -7,6 +7,7 @@ import { classifyPanel, getPanelRole } from '../../utils/getPanelRole.js'
7
7
  import { logger } from '../../services/logger.js'
8
8
  import { hidesNothing } from './applicationModes.js'
9
9
  import { groupBySlot } from './slotHelpers.js'
10
+ import { getFocusOptions } from '../../utils/getFocusOptions.js'
10
11
 
11
12
  // With no slot, matches buttons for every slot
12
13
  function getMatchingButtons ({ appState, buttonConfig, slot, evaluateProp }) {
@@ -57,7 +58,7 @@ function createButtonClickHandler (config, appState, evaluateProp) {
57
58
  if (typeof config.onClick === 'function') {
58
59
  config.onClick(e, evaluateProp(ctx => ctx, config.pluginId))
59
60
  if (!isToggle && !config.keepFocus) {
60
- requestAnimationFrame(() => appState.layoutRefs.viewportRef.current?.focus())
61
+ requestAnimationFrame(() => appState.layoutRefs.viewportRef.current?.focus(getFocusOptions(appState.interfaceType)))
61
62
  }
62
63
  return
63
64
  }
@@ -144,6 +145,7 @@ function SlotButton ({ buttonId, config, isHidden = false, appState, appConfig,
144
145
  menuItems={config.menuItems}
145
146
  idPrefix={appConfig.id}
146
147
  ariaControls={evaluateProp(config.ariaControls, config.pluginId)}
148
+ description={evaluateProp(config.description, config.pluginId)}
147
149
  />
148
150
  )
149
151
  }
@@ -174,6 +174,14 @@ describe('mapButtons module', () => {
174
174
  expect(render(baseBtn).props.isBusy).toBeUndefined()
175
175
  })
176
176
 
177
+ it('evaluates description, a string or a function of the context', () => {
178
+ const evaluate = jest.fn((prop) => (typeof prop === 'function' ? prop() : prop))
179
+ const fromFunction = SlotButton({ buttonId: 'id', config: { ...baseBtn, description: () => 'Zoom in' }, appState, appConfig, evaluateProp: evaluate })
180
+ expect(fromFunction.props.description).toBe('Zoom in')
181
+ const fromString = SlotButton({ buttonId: 'id', config: { ...baseBtn, description: 'Fixed' }, appState, appConfig, evaluateProp: evaluate })
182
+ expect(fromString.props.description).toBe('Fixed')
183
+ })
184
+
177
185
  it.each([
178
186
  [{ slot: 'right-top', open: false }, 'dialog'],
179
187
  [{ slot: 'right-top', open: false, dismissible: false }, 'region'],
@@ -219,6 +227,18 @@ describe('mapButtons module', () => {
219
227
  viewportFocusSpy.mockRestore()
220
228
  })
221
229
 
230
+ it.each([
231
+ ['pointer', true],
232
+ ['keyboard', false]
233
+ ])('focuses viewport after onClick with preventScroll for %s users', (interfaceType, preventScroll) => {
234
+ const rafSpy = jest.spyOn(global, 'requestAnimationFrame').mockImplementation(cb => { cb(); return 1 })
235
+ appState.interfaceType = interfaceType
236
+ const onClick = jest.fn()
237
+ render({ ...baseBtn, onClick }).props.onClick({})
238
+ expect(appState.layoutRefs.viewportRef.current.focus).toHaveBeenCalledWith({ preventScroll })
239
+ rafSpy.mockRestore()
240
+ })
241
+
222
242
  it('does not call requestAnimationFrame when keepFocus is true', () => {
223
243
  const rafSpy = jest.spyOn(global, 'requestAnimationFrame')
224
244
  const onClick = jest.fn()
@@ -17,8 +17,14 @@ export const ServiceProvider = ({ eventBus, pluginRegistry, children }) => {
17
17
  const mapStatusRef = useRef(null)
18
18
  const announce = useMemo(() => createAnnouncer(mapStatusRef), [])
19
19
  const hints = useMemo(() => createHints(announce), [announce])
20
- const { layoutRefs } = useApp()
21
- const mapFocus = useMemo(() => createMapFocus({ viewportRef: layoutRefs.viewportRef }), [])
20
+ const { layoutRefs, interfaceType } = useApp()
21
+ // Read through a ref so the memoised mapFocus always sees the current interface type
22
+ const interfaceTypeRef = useRef(interfaceType)
23
+ interfaceTypeRef.current = interfaceType
24
+ const mapFocus = useMemo(() => createMapFocus({
25
+ viewportRef: layoutRefs.viewportRef,
26
+ getInterfaceType: () => interfaceTypeRef.current
27
+ }), [])
22
28
  // One of each per map, so maps on the same page keep their own symbols, symbolDefaults and patterns
23
29
  const symbolRegistry = useMemo(() => createSymbolRegistry(), [])
24
30
  const patternRegistry = useMemo(() => createPatternRegistry(), [])
@@ -71,6 +71,19 @@ describe('ServiceProvider', () => {
71
71
  expect(result.current.mapFocus.isHoldingAnnouncements()).toBe(true)
72
72
  })
73
73
 
74
+ test('focusMap reads the current interface type each time it focuses', () => {
75
+ const { useApp } = jest.requireMock('../store/appContext.js')
76
+ useApp.mockReturnValue({ layoutRefs: { viewportRef: mockViewportRef }, interfaceType: 'pointer' })
77
+ const { result, rerender } = renderHook(() => React.useContext(ServiceContext), { wrapper })
78
+ result.current.focusMap()
79
+ expect(mockViewportRef.current.focus).toHaveBeenLastCalledWith({ preventScroll: true })
80
+
81
+ useApp.mockReturnValue({ layoutRefs: { viewportRef: mockViewportRef }, interfaceType: 'keyboard' })
82
+ rerender()
83
+ result.current.focusMap()
84
+ expect(mockViewportRef.current.focus).toHaveBeenLastCalledWith({ preventScroll: false })
85
+ })
86
+
74
87
  test('gives each map its own symbol registry, kept across renders, with that map\'s symbolDefaults', () => {
75
88
  const { useConfig } = jest.requireMock('../store/configContext.js')
76
89
  useConfig.mockReturnValue({ id: 'map-a', symbolDefaults: { backgroundColor: '#111111' } })
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Generic reducer action that shallow-merges the payload into state.
3
- * Shared by MAP_MOVE, MAP_MOVE_END and MAP_FIRST_IDLE.
3
+ * Shared by MAP_MOVE_START, MAP_MOVE, MAP_MOVE_END and MAP_FIRST_IDLE.
4
4
  */
5
5
  const mergePayload = (state, payload) => ({
6
6
  ...state,
@@ -29,6 +29,18 @@ const setMapSize = (state, payload) => {
29
29
  }
30
30
  }
31
31
 
32
+ const setResetViewTarget = (state, payload) => ({
33
+ ...state,
34
+ resetViewTarget: payload,
35
+ isResetViewTargetKnown: true
36
+ })
37
+
38
+ const clearResetViewTarget = (state) => ({
39
+ ...state,
40
+ resetViewTarget: null,
41
+ isResetViewTargetKnown: false
42
+ })
43
+
32
44
  const updateCrossHair = (state, payload) => {
33
45
  return {
34
46
  ...state,
@@ -68,12 +80,15 @@ const removeMarker = (state, payload) => {
68
80
 
69
81
  export const actionsMap = {
70
82
  SET_MAP_READY: setMapReady,
83
+ MAP_MOVE_START: mergePayload,
71
84
  MAP_MOVE: mergePayload,
72
85
  MAP_MOVE_END: mergePayload,
73
86
  MAP_FIRST_IDLE: mergePayload,
74
87
  SET_MAP_STYLE: setMapStyle,
75
88
  SET_MAP_STYLES: setMapStyles,
76
89
  SET_MAP_SIZE: setMapSize,
90
+ SET_RESET_VIEW_TARGET: setResetViewTarget,
91
+ CLEAR_RESET_VIEW_TARGET: clearResetViewTarget,
77
92
  UPDATE_CROSS_HAIR: updateCrossHair,
78
93
  UPSERT_LOCATION_MARKER: upsertMarker,
79
94
  REMOVE_LOCATION_MARKER: removeMarker
@@ -27,6 +27,23 @@ describe('actionsMap', () => {
27
27
  })
28
28
  })
29
29
 
30
+ test('MAP_MOVE_START merges payload into state', () => {
31
+ const payload = { isUserMove: true }
32
+ const result = actionsMap.MAP_MOVE_START(state, payload)
33
+ expect(result).toEqual({ ...state, ...payload })
34
+ })
35
+
36
+ test('SET_RESET_VIEW_TARGET sets resetViewTarget', () => {
37
+ const payload = { center: [1, 2], zoom: 10 }
38
+ const result = actionsMap.SET_RESET_VIEW_TARGET(state, payload)
39
+ expect(result).toEqual({ ...state, resetViewTarget: payload, isResetViewTargetKnown: true })
40
+ })
41
+
42
+ test('CLEAR_RESET_VIEW_TARGET marks the reset view target as not known', () => {
43
+ const result = actionsMap.CLEAR_RESET_VIEW_TARGET({ ...state, resetViewTarget: { center: [1, 2], zoom: 10 }, isResetViewTargetKnown: true })
44
+ expect(result).toEqual({ ...state, resetViewTarget: null, isResetViewTargetKnown: false })
45
+ })
46
+
30
47
  test('MAP_MOVE merges payload into state', () => {
31
48
  const payload = { center: [10, 20] }
32
49
  const result = actionsMap.MAP_MOVE(state, payload)
@@ -31,6 +31,12 @@ export const initialState = (config) => {
31
31
  resolution: null,
32
32
  isAtMaxZoom: null,
33
33
  isAtMinZoom: null,
34
+ // Whether the user started the latest move, rather than code (useUserMoveTracking)
35
+ isUserMove: false,
36
+ // The center and zoom the map settled at when last showing its configured view, or null when
37
+ // there isn't one (useResetViewTarget). Not known yet on load and during a reset.
38
+ resetViewTarget: null,
39
+ isResetViewTargetKnown: false,
34
40
 
35
41
  // Full target marker state
36
42
  crossHair: {
@@ -47,6 +47,9 @@ describe('mapReducer', () => {
47
47
  resolution: null,
48
48
  isAtMaxZoom: null,
49
49
  isAtMinZoom: null,
50
+ isUserMove: false,
51
+ resetViewTarget: null,
52
+ isResetViewTargetKnown: false,
50
53
  crossHair: {
51
54
  isVisible: false,
52
55
  isPinnedToMap: false,
@@ -554,6 +554,14 @@ export default class InteractiveMap {
554
554
  this.eventBus.emitWhenReady(events.MAP_SET_VIEW, opts)
555
555
  }
556
556
 
557
+ /**
558
+ * Move the map to its configured `bounds` or `extent`, or to `center` and `zoom` if no bounds are set,
559
+ * respecting the safe zone padding. Ignores any view read from the URL when the map loaded.
560
+ */
561
+ resetView () {
562
+ this.eventBus.emitWhenReady(events.MAP_RESET_VIEW)
563
+ }
564
+
557
565
  /**
558
566
  * Programmatically open the map.
559
567
  *
@@ -641,6 +641,11 @@ describe('InteractiveMap — Public API Methods', () => {
641
641
  expect(map.eventBus.emitWhenReady).toHaveBeenCalledWith('map:setview', { center, zoom: 12 })
642
642
  })
643
643
 
644
+ it('resetView emits the reset view event', () => {
645
+ map.resetView()
646
+ expect(map.eventBus.emitWhenReady).toHaveBeenCalledWith('map:resetview')
647
+ })
648
+
644
649
  it('showHint and dismissHint emit correct events', () => {
645
650
  map.showHint('Press <kbd>Enter</kbd> to select', { duration: 2000 })
646
651
  map.dismissHint()
@@ -1,5 +1,7 @@
1
1
  import { KeyboardHelp } from '../App/components/KeyboardHelp/KeyboardHelp.jsx'
2
2
  import { MapControls } from '../App/components/MapControls/MapControls.jsx'
3
+ import { EVENTS as events } from './events.js'
4
+ import { getConfiguredView, isAtResetViewTarget } from '../utils/resetView.js'
3
5
 
4
6
  const keyboardBasePanelSlots = {
5
7
  slot: 'middle',
@@ -116,6 +118,18 @@ export const defaultAppConfig = {
116
118
  mobile: buttonSlots,
117
119
  tablet: buttonSlots,
118
120
  desktop: buttonSlots
121
+ }, {
122
+ id: 'resetView',
123
+ label: 'Reset view',
124
+ iconId: 'reset',
125
+ keepFocus: true,
126
+ onClick: (_e, { services }) => services.eventBus.emit(events.MAP_RESET_VIEW),
127
+ excludeWhen: ({ appConfig }) => !appConfig.enableResetView || !getConfiguredView(appConfig),
128
+ // Disabled until the target is known, so it doesn't flash enabled on load or during a reset
129
+ enableWhen: ({ mapState, mapProvider }) => mapState.isResetViewTargetKnown && !isAtResetViewTarget(mapState, mapProvider),
130
+ mobile: buttonSlots,
131
+ tablet: buttonSlots,
132
+ desktop: buttonSlots
119
133
  }],
120
134
 
121
135
  panels: [{
@@ -157,6 +171,9 @@ export const defaultAppConfig = {
157
171
  }, {
158
172
  id: 'minus',
159
173
  svgContent: '<path d="M5 12h14"/>'
174
+ }, {
175
+ id: 'reset',
176
+ svgContent: '<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/>'
160
177
  }, {
161
178
  id: 'chevron',
162
179
  svgContent: '<path d="m6 9 6 6 6-6"/>'