-
Notifications
You must be signed in to change notification settings - Fork 889
/
Copy pathcontrol.ts
executable file
·40 lines (34 loc) · 1.07 KB
/
control.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import type { Control, ControlOptions } from 'leaflet'
import { useEffect, useRef } from 'react'
import { useLeafletContext } from './context.js'
import type { ElementHook } from './element.js'
export function createControlHook<E extends Control, P extends ControlOptions>(
useElement: ElementHook<E, P>,
) {
return function useLeafletControl(props: P): ReturnType<ElementHook<E, P>> {
const context = useLeafletContext()
const elementRef = useElement(props, context)
const { instance } = elementRef.current
const positionRef = useRef(props.position)
const { position } = props
useEffect(
function addControl() {
instance.addTo(context.map)
return function removeControl() {
instance.remove()
}
},
[context.map, instance],
)
useEffect(
function updateControl() {
if (position != null && position !== positionRef.current) {
instance.setPosition(position)
positionRef.current = position
}
},
[instance, position],
)
return elementRef
}
}