@defra/interactive-map 0.0.61-alpha → 0.0.63-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 (56) hide show
  1. package/dist/esm/im-core.js +1 -1
  2. package/dist/esm/im-shell.js +1 -1
  3. package/dist/umd/im-core.js +1 -1
  4. package/dist/umd/index.js +1 -1
  5. package/docs/api.md +20 -0
  6. package/package.json +1 -1
  7. package/plugins/datasets/dist/esm/im-datasets-esri-adapter.js +1 -1
  8. package/plugins/datasets/dist/esm/im-datasets-plugin.js +1 -1
  9. package/plugins/datasets/dist/umd/im-datasets-plugin.js +1 -1
  10. package/plugins/datasets/src/adapters/esri/esriLayerAdapter.js +27 -10
  11. package/plugins/datasets/src/adapters/esri/esriLayerAdapter.test.js +38 -0
  12. package/plugins/datasets/src/reducers/datasetsToMenu.js +12 -9
  13. package/plugins/datasets/src/reducers/datasetsToMenu.test.js +42 -0
  14. package/plugins/datasets/src/reducers/pluginState.test.js +12 -0
  15. package/plugins/draw/dist/esm/im-draw-plugin.js +1 -1
  16. package/plugins/draw/dist/umd/im-draw-plugin.js +1 -1
  17. package/plugins/interact/dist/umd/im-interact-plugin.js +1 -1
  18. package/providers/openlayers/dist/esm/im-openlayers-provider.js +1 -1
  19. package/providers/openlayers/dist/umd/im-openlayers-provider.js +1 -1
  20. package/providers/openlayers/src/openlayersProvider.js +2 -1
  21. package/providers/openlayers/src/openlayersProvider.test.js +1 -1
  22. package/src/App/components/MapControls/MapControls.jsx +2 -1
  23. package/src/App/components/MapControls/MapControls.test.jsx +1 -1
  24. package/src/App/components/PopupMenu/PopupMenu.test.jsx +22 -0
  25. package/src/App/components/PopupMenu/usePopupMenu.js +9 -6
  26. package/src/App/components/Viewport/MapController.jsx +2 -0
  27. package/src/App/components/Viewport/MapController.test.jsx +3 -0
  28. package/src/App/hooks/useMapProviderOverrides.js +10 -5
  29. package/src/App/hooks/useMapProviderOverrides.test.js +11 -0
  30. package/src/App/hooks/useResetViewTarget.js +135 -0
  31. package/src/App/hooks/useResetViewTarget.test.js +211 -0
  32. package/src/App/hooks/useUserMoveTracking.js +7 -0
  33. package/src/App/hooks/useUserMoveTracking.test.js +21 -3
  34. package/src/App/renderer/mapButtons.js +2 -1
  35. package/src/App/renderer/mapButtons.test.js +12 -0
  36. package/src/App/store/ServiceProvider.jsx +8 -2
  37. package/src/App/store/ServiceProvider.test.jsx +13 -0
  38. package/src/App/store/mapActionsMap.js +14 -0
  39. package/src/App/store/mapActionsMap.test.js +11 -0
  40. package/src/App/store/mapReducer.js +4 -0
  41. package/src/App/store/mapReducer.test.js +2 -0
  42. package/src/InteractiveMap/InteractiveMap.js +8 -0
  43. package/src/InteractiveMap/InteractiveMap.test.js +5 -0
  44. package/src/config/appConfig.js +17 -0
  45. package/src/config/appConfig.test.js +28 -0
  46. package/src/config/defaults.js +1 -0
  47. package/src/config/events.js +2 -0
  48. package/src/services/mapFocus.js +3 -2
  49. package/src/services/mapFocus.test.js +10 -0
  50. package/src/types.js +5 -0
  51. package/src/utils/focusAfterPanelClose.js +3 -1
  52. package/src/utils/getFocusOptions.js +3 -0
  53. package/src/utils/getFocusOptions.test.js +11 -0
  54. package/src/utils/mapStateSync.js +1 -0
  55. package/src/utils/resetView.js +61 -0
  56. package/src/utils/resetView.test.js +62 -0
@@ -110,7 +110,8 @@ export default class OpenLayersProvider extends MapProvider {
110
110
 
111
111
  if (bounds) {
112
112
  map.once('rendercomplete', () => {
113
- view.fit(bounds, { size: map.getSize(), duration: 0 })
113
+ // Fits inside the view's padding, as fitToBounds does
114
+ view.fit(bounds, { duration: 0 })
114
115
  })
115
116
  }
116
117
 
@@ -164,7 +164,7 @@ describe('OpenLayersProvider', () => {
164
164
  await provider.initMap({ ...defaultInitConfig, bounds })
165
165
  expect(mockMapOnce).toHaveBeenCalledWith('rendercomplete', expect.any(Function))
166
166
  renderCallback()
167
- expect(mockViewFit).toHaveBeenCalledWith(bounds, { size: [800, 600], duration: 0 })
167
+ expect(mockViewFit).toHaveBeenCalledWith(bounds, { duration: 0 })
168
168
  })
169
169
 
170
170
  it('does not call map.once when no bounds', async () => {
@@ -5,6 +5,7 @@ import { useConfig } from '../../store/configContext.js'
5
5
  import { useMap } from '../../store/mapContext.js'
6
6
  import { useService } from '../../store/serviceContext.js'
7
7
  import { resolveStepAmount } from '../../../utils/resolveNudgeStep.js'
8
+ import { getFocusOptions } from '../../../utils/getFocusOptions.js'
8
9
 
9
10
  const DIRECTIONS = [
10
11
  { id: 'panUp', verb: 'up', dx: 0, dy: -1, key: 'ArrowUp' },
@@ -52,7 +53,7 @@ export const MapControls = () => {
52
53
  // arrow keys right after without an extra click into the map first.
53
54
  const returnFocusToViewport = () => {
54
55
  if (interfaceType !== 'keyboard') {
55
- requestAnimationFrame(() => layoutRefs.viewportRef.current?.focus())
56
+ requestAnimationFrame(() => layoutRefs.viewportRef.current?.focus(getFocusOptions(interfaceType)))
56
57
  }
57
58
  }
58
59
 
@@ -180,7 +180,7 @@ describe('MapControls', () => {
180
180
  render(<MapControls />)
181
181
 
182
182
  fireEvent.click(screen.getByRole('button', { name: 'Move right' }))
183
- expect(appState.layoutRefs.viewportRef.current.focus).toHaveBeenCalled()
183
+ expect(appState.layoutRefs.viewportRef.current.focus).toHaveBeenCalledWith({ preventScroll: true })
184
184
  })
185
185
 
186
186
  it('keeps focus on the button when driven by keyboard, so repeated Enter/Space presses do not require re-tabbing', () => {
@@ -251,6 +251,28 @@ describe('PopupMenu', () => {
251
251
  expect(focusSpy).toHaveBeenCalled()
252
252
  })
253
253
 
254
+ it.each([
255
+ ['pointer', true],
256
+ ['keyboard', false]
257
+ ])('click on item focuses viewport with preventScroll for %s users', (interfaceType, preventScroll) => {
258
+ mockUseApp.interfaceType = interfaceType
259
+ renderMenu()
260
+ fireEvent.click(screen.getByText('Item 1'))
261
+ expect(mockUseApp.layoutRefs.viewportRef.current.focus).toHaveBeenCalledWith({ preventScroll })
262
+ delete mockUseApp.interfaceType
263
+ })
264
+
265
+ it('click on item with keepFocus passes preventScroll to the instigator for pointer users', () => {
266
+ const focusSpy = jest.fn()
267
+ mockUseApp.buttonRefs.current.instigator.focus = focusSpy
268
+ mockUseApp.buttonConfig = { item1: { keepFocus: true } }
269
+ mockUseApp.interfaceType = 'pointer'
270
+ renderMenu()
271
+ fireEvent.click(screen.getByText('Item 1'))
272
+ expect(focusSpy).toHaveBeenCalledWith({ preventScroll: true })
273
+ delete mockUseApp.interfaceType
274
+ })
275
+
254
276
  it('calls buttonConfig.onClick with evaluateProp if defined', () => {
255
277
  const mockOnClick = jest.fn()
256
278
  mockUseApp.buttonConfig = { item2: { onClick: mockOnClick } }
@@ -2,6 +2,7 @@ import { useState, useMemo, useEffect } from 'react'
2
2
  import { stringToKebab } from '../../../utils/stringToKebab.js'
3
3
  import { findTabStop } from '../../../utils/findNextTabStop.js'
4
4
  import { useApp } from '../../store/appContext.js'
5
+ import { getFocusOptions } from '../../../utils/getFocusOptions.js'
5
6
 
6
7
  /**
7
8
  * Computes the position and alignment style for the popup menu based on the
@@ -95,12 +96,13 @@ const resolveItemFocus = (item, buttonConfig) => ({
95
96
  *
96
97
  * @param {HTMLElement|null} instigator - DOM node of the trigger button, may no longer exist.
97
98
  * @param {object} viewportRef - Ref to the map viewport element, used as fallback.
99
+ * @param {object} [focusOptions] - Options passed to focus(), e.g. preventScroll.
98
100
  */
99
- const focusInstigatorOrViewport = (instigator, viewportRef) => {
101
+ const focusInstigatorOrViewport = (instigator, viewportRef, focusOptions) => {
100
102
  if (instigator) {
101
- instigator.focus()
103
+ instigator.focus(focusOptions)
102
104
  } else {
103
- viewportRef.current?.focus()
105
+ viewportRef.current?.focus(focusOptions)
104
106
  }
105
107
  }
106
108
 
@@ -284,7 +286,7 @@ export const usePopupMenu = ({
284
286
  items, hiddenButtons, startIndex, startPos, instigator, instigatorKey,
285
287
  buttonRefs, buttonConfig, disabledButtons, pluginId, evaluateProp, id, menuRef, setIsOpen, buttonRect, isOpen
286
288
  }) => {
287
- const { dispatch, layoutRefs } = useApp()
289
+ const { dispatch, layoutRefs, interfaceType } = useApp()
288
290
  const viewportRef = layoutRefs.viewportRef
289
291
 
290
292
  const visibleIndices = useMemo(() => {
@@ -324,10 +326,11 @@ export const usePopupMenu = ({
324
326
  }
325
327
  setIsOpen(false)
326
328
  activateItem(event, item, activateCtx)
329
+ const focusOptions = getFocusOptions(interfaceType)
327
330
  if (keepFocus) {
328
- focusInstigatorOrViewport(instigator, viewportRef)
331
+ focusInstigatorOrViewport(instigator, viewportRef, focusOptions)
329
332
  } else {
330
- viewportRef.current?.focus()
333
+ viewportRef.current?.focus(focusOptions)
331
334
  }
332
335
  }
333
336
 
@@ -4,6 +4,7 @@ import { useApp } from '../../store/appContext'
4
4
  import { useMap } from '../../store/mapContext'
5
5
  import { useMapStateSync } from '../../hooks/useMapStateSync'
6
6
  import { useUserMoveTracking } from '../../hooks/useUserMoveTracking'
7
+ import { useResetViewTarget } from '../../hooks/useResetViewTarget'
7
8
  import { useMapURLSync } from '../../hooks/useMapURLSync'
8
9
  import { useMapAnnouncements } from '../../hooks/useMapAnnouncements'
9
10
  import { useMapProviderOverrides } from '../../hooks/useMapProviderOverrides'
@@ -55,6 +56,7 @@ export const MapController = ({ mapContainerRef }) => {
55
56
  // Sync React state, handle URL persistence and announce to screen reader
56
57
  useMapStateSync()
57
58
  useUserMoveTracking()
59
+ useResetViewTarget()
58
60
  useMapURLSync()
59
61
  useMapAnnouncements()
60
62
 
@@ -6,6 +6,7 @@ import { useApp } from '../../store/appContext'
6
6
  import { useMap } from '../../store/mapContext'
7
7
  import { useMapStateSync } from '../../hooks/useMapStateSync'
8
8
  import { useUserMoveTracking } from '../../hooks/useUserMoveTracking'
9
+ import { useResetViewTarget } from '../../hooks/useResetViewTarget'
9
10
  import { useMapURLSync } from '../../hooks/useMapURLSync'
10
11
  import { useMapAnnouncements } from '../../hooks/useMapAnnouncements'
11
12
  import { useMapProviderOverrides } from '../../hooks/useMapProviderOverrides'
@@ -17,6 +18,7 @@ jest.mock('../../store/appContext', () => ({ useApp: jest.fn() }))
17
18
  jest.mock('../../store/mapContext', () => ({ useMap: jest.fn() }))
18
19
  jest.mock('../../hooks/useMapStateSync', () => ({ useMapStateSync: jest.fn() }))
19
20
  jest.mock('../../hooks/useUserMoveTracking', () => ({ useUserMoveTracking: jest.fn() }))
21
+ jest.mock('../../hooks/useResetViewTarget', () => ({ useResetViewTarget: jest.fn() }))
20
22
  jest.mock('../../hooks/useMapURLSync', () => ({ useMapURLSync: jest.fn() }))
21
23
  jest.mock('../../hooks/useMapAnnouncements', () => ({ useMapAnnouncements: jest.fn() }))
22
24
  jest.mock('../../hooks/useMapProviderOverrides', () => ({ useMapProviderOverrides: jest.fn() }))
@@ -94,6 +96,7 @@ describe('MapController', () => {
94
96
  render(<MapController mapContainerRef={containerRef} />)
95
97
  expect(useMapStateSync).toHaveBeenCalled()
96
98
  expect(useUserMoveTracking).toHaveBeenCalled()
99
+ expect(useResetViewTarget).toHaveBeenCalled()
97
100
  expect(useMapURLSync).toHaveBeenCalled()
98
101
  expect(useMapAnnouncements).toHaveBeenCalled()
99
102
  expect(useMapProviderOverrides).toHaveBeenCalled()
@@ -10,6 +10,7 @@ import { getMapSizeScale } from '../../config/mapSizeScales.js'
10
10
  import { SIDE_PANEL_SLOT_REFS } from '../../config/mapPanelSlots.js'
11
11
  import { getFitMove } from '../../utils/getFitMove.js'
12
12
  import { getScreenBox, getBoxCenter } from '../../utils/screenBox.js'
13
+ import { resetView } from '../../utils/resetView.js'
13
14
 
14
15
  const FIT_WITHOUT_MARGIN = { type: 'fit' }
15
16
 
@@ -61,9 +62,9 @@ const getMove = ({ bounds, safeZoneInset, mapProvider, layoutRefs, mapSize, pref
61
62
  }
62
63
 
63
64
  // Forward public API events to the (overridden) mapProvider methods so that
64
- // interactiveMap.fitToBounds() and interactiveMap.setView() respect safe zone padding.
65
+ // interactiveMap.fitToBounds(), setView() and resetView() respect safe zone padding.
65
66
  // fitToBounds' options are passed through.
66
- const useForwardMapEvents = (mapProvider, eventBus) => {
67
+ const useForwardMapEvents = (mapProvider, eventBus, appConfig) => {
67
68
  useEffect(() => {
68
69
  if (!mapProvider || !eventBus) {
69
70
  return undefined
@@ -71,19 +72,23 @@ const useForwardMapEvents = (mapProvider, eventBus) => {
71
72
 
72
73
  const handleFitToBounds = (bounds, options) => mapProvider.fitToBounds(bounds, options)
73
74
  const handleSetView = (opts) => mapProvider.setView(opts)
75
+ const handleResetView = () => resetView(mapProvider, appConfig)
74
76
 
75
77
  eventBus.on(events.MAP_FIT_TO_BOUNDS, handleFitToBounds)
76
78
  eventBus.on(events.MAP_SET_VIEW, handleSetView)
79
+ eventBus.on(events.MAP_RESET_VIEW, handleResetView)
77
80
 
78
81
  return () => {
79
82
  eventBus.off(events.MAP_FIT_TO_BOUNDS, handleFitToBounds)
80
83
  eventBus.off(events.MAP_SET_VIEW, handleSetView)
84
+ eventBus.off(events.MAP_RESET_VIEW, handleResetView)
81
85
  }
82
- }, [mapProvider, eventBus])
86
+ }, [mapProvider, eventBus, appConfig])
83
87
  }
84
88
 
85
89
  export const useMapProviderOverrides = () => {
86
- const { mapProvider, eventBus } = useConfig()
90
+ const appConfig = useConfig()
91
+ const { mapProvider, eventBus } = appConfig
87
92
  const { dispatch: appDispatch, layoutRefs, breakpoint } = useApp()
88
93
  const { mapSize } = useMap()
89
94
 
@@ -181,5 +186,5 @@ export const useMapProviderOverrides = () => {
181
186
  }
182
187
  }, [mapProvider, appDispatch, layoutRefs, mapSize])
183
188
 
184
- useForwardMapEvents(mapProvider, eventBus)
189
+ useForwardMapEvents(mapProvider, eventBus, appConfig)
185
190
  }
@@ -360,6 +360,16 @@ describe('useMapProviderOverrides', () => {
360
360
  expect(originalSetView).toHaveBeenCalledWith({ center: [1, 2], zoom: 10 })
361
361
  })
362
362
 
363
+ test('MAP_RESET_VIEW event moves the map to the configured view', () => {
364
+ const { mapProvider, capturedHandlers } = setup({ config: { center: [1, 2], zoom: 10 } })
365
+ const originalSetView = mapProvider.setView
366
+ renderHook(() => useMapProviderOverrides())
367
+
368
+ capturedHandlers['map:resetview']()
369
+
370
+ expect(originalSetView).toHaveBeenCalledWith({ center: [1, 2], zoom: 10 })
371
+ })
372
+
363
373
  test('unsubscribes from MAP_FIT_TO_BOUNDS and MAP_SET_VIEW on unmount', () => {
364
374
  const { eventBus } = setup()
365
375
  const { unmount } = renderHook(() => useMapProviderOverrides())
@@ -368,6 +378,7 @@ describe('useMapProviderOverrides', () => {
368
378
 
369
379
  expect(eventBus.off).toHaveBeenCalledWith('map:fittobounds', expect.any(Function))
370
380
  expect(eventBus.off).toHaveBeenCalledWith('map:setview', expect.any(Function))
381
+ expect(eventBus.off).toHaveBeenCalledWith('map:resetview', expect.any(Function))
371
382
  })
372
383
 
373
384
  test('skips event subscriptions when eventBus is null', () => {
@@ -0,0 +1,135 @@
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
+ import { getMapStateFromURL } from '../../utils/mapStateSync.js'
8
+ import { isAtResetViewTarget } from '../../utils/resetView.js'
9
+
10
+ // How long after a reset the map has to start moving. If it doesn't, it was already at the reset view.
11
+ export const RESET_MOVE_WINDOW_MS = 1000
12
+
13
+ // Input on the map that can move it, so a reset move the user takes over isn't recorded
14
+ const MAP_INPUT_EVENTS = ['pointerdown', 'wheel', 'keydown']
15
+
16
+ const getStorageKey = (id) => `${id}:resetViewTarget`
17
+
18
+ // Session storage can be blocked, so a target that can't be saved or read is just not remembered
19
+ const saveTarget = (id, target) => {
20
+ try {
21
+ globalThis.sessionStorage.setItem(getStorageKey(id), JSON.stringify(target))
22
+ } catch {
23
+ // Not remembered
24
+ }
25
+ }
26
+
27
+ const readTarget = (id) => {
28
+ try {
29
+ const target = JSON.parse(globalThis.sessionStorage.getItem(getStorageKey(id)))
30
+ return Array.isArray(target?.center) && typeof target.zoom === 'number' ? target : null
31
+ } catch {
32
+ return null
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Sets mapState.resetViewTarget to the center and zoom the map settles at when showing its
38
+ * configured view: on load, and at the end of each reset. The reset view button is disabled
39
+ * while the map is still there, and while the target isn't known: before the map first settles
40
+ * and during a reset. It's null when the map loads somewhere else, or the user takes over a reset.
41
+ *
42
+ * The target is what the map reports, not the configured values, as fitting bounds gives a center
43
+ * and zoom that depend on the map's size and safe zone. It's kept in session storage, so a page
44
+ * reloaded at the reset view, with the view in the URL, starts with the button disabled.
45
+ */
46
+ export function useResetViewTarget () {
47
+ const { id, mapProvider, urlPosition = 'sync' } = useConfig()
48
+ const { layoutRefs } = useApp()
49
+ const { dispatch } = useMap()
50
+ const { eventBus } = useService()
51
+
52
+ useEffect(() => {
53
+ const viewport = layoutRefs.viewportRef?.current
54
+ if (!mapProvider || !viewport) {
55
+ return undefined
56
+ }
57
+
58
+ const isInitialViewConfigured = urlPosition === 'none' || !getMapStateFromURL(id, globalThis.location.search)
59
+ let pendingReset = null
60
+
61
+ const dispatchTarget = (payload) => dispatch({ type: 'SET_RESET_VIEW_TARGET', payload })
62
+
63
+ const setTarget = ({ center, zoom }) => {
64
+ saveTarget(id, { center, zoom })
65
+ dispatchTarget({ center, zoom })
66
+ }
67
+
68
+ const cancelPendingReset = () => {
69
+ clearTimeout(pendingReset?.timer)
70
+ pendingReset = null
71
+ }
72
+
73
+ // A view from the URL is only the reset view if it's where the last reset in this session went
74
+ const handleFirstIdle = (state) => {
75
+ if (!state) {
76
+ return
77
+ }
78
+ if (isInitialViewConfigured) {
79
+ setTarget(state)
80
+ return
81
+ }
82
+ const savedTarget = readTarget(id)
83
+ dispatchTarget(isAtResetViewTarget({ ...state, resetViewTarget: savedTarget }, mapProvider) ? savedTarget : null)
84
+ }
85
+
86
+ const handleResetView = () => {
87
+ cancelPendingReset()
88
+ const timer = setTimeout(() => {
89
+ if (!pendingReset.hasMoved) {
90
+ cancelPendingReset()
91
+ setTarget({ center: mapProvider.getCenter(), zoom: mapProvider.getZoom() })
92
+ }
93
+ }, RESET_MOVE_WINDOW_MS)
94
+ pendingReset = { timer, hasMoved: false }
95
+ dispatch({ type: 'CLEAR_RESET_VIEW_TARGET' })
96
+ }
97
+
98
+ const handleMoveStart = () => {
99
+ if (pendingReset) {
100
+ pendingReset.hasMoved = true
101
+ }
102
+ }
103
+
104
+ // Move end is debounced by the providers, so it fires once after the safe zone padding and the reset move
105
+ const handleMoveEnd = (state) => {
106
+ if (pendingReset?.hasMoved && state) {
107
+ cancelPendingReset()
108
+ setTarget(state)
109
+ }
110
+ }
111
+
112
+ // The press of the reset button itself comes before the reset, so doesn't cancel it
113
+ const handleMapInput = () => {
114
+ if (pendingReset) {
115
+ cancelPendingReset()
116
+ dispatchTarget(null)
117
+ }
118
+ }
119
+
120
+ eventBus.on(events.MAP_FIRST_IDLE, handleFirstIdle)
121
+ eventBus.on(events.MAP_RESET_VIEW, handleResetView)
122
+ eventBus.on(events.MAP_MOVE_START, handleMoveStart)
123
+ eventBus.on(events.MAP_MOVE_END, handleMoveEnd)
124
+ MAP_INPUT_EVENTS.forEach(type => viewport.addEventListener(type, handleMapInput, true))
125
+
126
+ return () => {
127
+ cancelPendingReset()
128
+ eventBus.off(events.MAP_FIRST_IDLE, handleFirstIdle)
129
+ eventBus.off(events.MAP_RESET_VIEW, handleResetView)
130
+ eventBus.off(events.MAP_MOVE_START, handleMoveStart)
131
+ eventBus.off(events.MAP_MOVE_END, handleMoveEnd)
132
+ MAP_INPUT_EVENTS.forEach(type => viewport.removeEventListener(type, handleMapInput, true))
133
+ }
134
+ }, [mapProvider, eventBus, dispatch])
135
+ }
@@ -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
+ })
@@ -42,8 +42,15 @@ export function useUserMoveTracking () {
42
42
  const handlePointerUp = () => {
43
43
  isPointerDown = false
44
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
45
48
  const handleMoveStart = () => {
46
49
  const isUserMove = isPointerDown || Date.now() - lastInputAt <= USER_INPUT_WINDOW_MS
50
+ if (isUserMove === lastIsUserMove) {
51
+ return
52
+ }
53
+ lastIsUserMove = isUserMove
47
54
  dispatch({ type: 'MAP_MOVE_START', payload: { isUserMove } })
48
55
  }
49
56
 
@@ -14,7 +14,8 @@ describe('useUserMoveTracking', () => {
14
14
  let container, dispatch, eventBus, handlers
15
15
 
16
16
  const moveStart = () => handlers['map:movestart']()
17
- const lastIsUserMove = () => dispatch.mock.calls.at(-1)[0].payload.isUserMove
17
+ // mapState.isUserMove: false until the first change is sent
18
+ const lastIsUserMove = () => dispatch.mock.calls.at(-1)?.[0].payload.isUserMove ?? false
18
19
 
19
20
  beforeEach(() => {
20
21
  jest.useFakeTimers()
@@ -37,10 +38,27 @@ describe('useUserMoveTracking', () => {
37
38
  jest.useRealTimers()
38
39
  })
39
40
 
40
- it('marks a move as code-made when there was no user input', () => {
41
+ it('marks a move as code-made when there was no user input, without sending the unchanged value', () => {
41
42
  renderHook(() => useUserMoveTracking())
42
43
  moveStart()
43
- expect(dispatch).toHaveBeenCalledWith({ type: 'MAP_MOVE_START', payload: { isUserMove: false } })
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)
44
62
  })
45
63
 
46
64
  it.each(['wheel', 'keydown', 'keyup'])('marks a move straight after a %s as the user\'s', (type) => {
@@ -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
  }