/
use-draggable-publisher.js
87 lines (77 loc) · 2.25 KB
/
use-draggable-publisher.js
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// @flow
import { type Position } from 'css-box-model';
import { useMemo, useCallback } from 'use-memo-one';
import { useRef } from 'react';
import { invariant } from '../../invariant';
import type {
DraggableDescriptor,
DraggableDimension,
Id,
DraggableOptions,
} from '../../types';
import type {
Registry,
DraggableEntry,
} from '../../state/registry/registry-types';
import makeDimension from './get-dimension';
import useLayoutEffect from '../use-isomorphic-layout-effect';
import useUniqueId from '../use-unique-id';
export type Args = {|
descriptor: DraggableDescriptor,
getDraggableRef: () => ?HTMLElement,
registry: Registry,
...DraggableOptions,
|};
export default function useDraggablePublisher(args: Args) {
const uniqueId: Id = useUniqueId('draggable');
const {
descriptor,
registry,
getDraggableRef,
canDragInteractiveElements,
shouldRespectForcePress,
isEnabled,
} = args;
const options: DraggableOptions = useMemo(
() => ({
canDragInteractiveElements,
shouldRespectForcePress,
isEnabled,
}),
[canDragInteractiveElements, isEnabled, shouldRespectForcePress],
);
const getDimension = useCallback(
(windowScroll?: Position): DraggableDimension => {
const el: ?HTMLElement = getDraggableRef();
invariant(el, 'Cannot get dimension when no ref is set');
return makeDimension(descriptor, el, windowScroll);
},
[descriptor, getDraggableRef],
);
const entry: DraggableEntry = useMemo(
() => ({
uniqueId,
descriptor,
options,
getDimension,
}),
[descriptor, getDimension, options, uniqueId],
);
const publishedRef = useRef<DraggableEntry>(entry);
const isFirstPublishRef = useRef<boolean>(true);
// mounting and unmounting
useLayoutEffect(() => {
registry.draggable.register(publishedRef.current);
return () => registry.draggable.unregister(publishedRef.current);
}, [registry.draggable]);
// updates while mounted
useLayoutEffect(() => {
if (isFirstPublishRef.current) {
isFirstPublishRef.current = false;
return;
}
const last: DraggableEntry = publishedRef.current;
publishedRef.current = entry;
registry.draggable.update(entry, last);
}, [entry, registry.draggable]);
}