-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathcore-react.ts
298 lines (260 loc) · 9.45 KB
/
core-react.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
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import * as React from "react";
import { createStore } from "./core";
import {
ISpaceProps,
ISpaceStore,
ISpaceDefinition,
ResizeType,
CenterType,
ISpaceContext,
ICommonProps,
ResizeMouseEvent,
OnDragEnd,
ResizeTouchEvent,
} from "./core-types";
import { coalesce, shortuuid } from "./core-utils";
import { ResizeSensor } from "css-element-queries";
import * as PropTypes from "prop-types";
import { useEffect, useRef, useState } from "react";
// WORKAROUND for React18 strict mode
// https://blog.ag-grid.com/avoiding-react-18-double-mount/
export const useEffectOnce = (effect: () => void | (() => void)) => {
const destroyFunc = useRef<void | (() => void)>();
const effectCalled = useRef(false);
const renderAfterCalled = useRef(false);
const [_val, setVal] = useState<number>(0);
if (effectCalled.current) {
renderAfterCalled.current = true;
}
useEffect(() => {
// only execute the effect first time around
if (!effectCalled.current) {
destroyFunc.current = effect();
effectCalled.current = true;
}
// this forces one render after the effect is run
setVal((val) => val + 1);
return () => {
// if the comp didn't render since the useEffect was called,
// we know it's the dummy React cycle
if (!renderAfterCalled.current) {
return;
}
if (destroyFunc.current) {
destroyFunc.current();
}
};
}, []);
};
export const ParentContext = React.createContext<string | undefined>(undefined);
export const DOMRectContext = React.createContext<DOMRect | undefined>(undefined);
export const LayerContext = React.createContext<number | undefined>(undefined);
export const OptionsContext = React.createContext<IReactSpacesOptions>({});
export const currentStore = createStore();
export const commonProps = {
id: PropTypes.string,
className: PropTypes.string,
style: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
as: PropTypes.any,
centerContent: PropTypes.oneOf([CenterType.None, CenterType.Vertical, CenterType.HorizontalVertical]),
zIndex: PropTypes.number,
scrollable: PropTypes.bool,
trackSize: PropTypes.bool,
allowOverflow: PropTypes.bool,
handleRender: PropTypes.func,
onClick: PropTypes.func,
onDoubleClick: PropTypes.func,
onMouseDown: PropTypes.func,
onMouseEnter: PropTypes.func,
onMouseLeave: PropTypes.func,
onMouseMove: PropTypes.func,
onTouchStart: PropTypes.func,
onTouchMove: PropTypes.func,
onTouchEnd: PropTypes.func,
};
export interface IReactSpacesOptions {
debug?: boolean;
}
export interface IReactEvents {
onClick?: (event: React.MouseEvent<HTMLElement, MouseEvent>) => void;
onDoubleClick?: (event: React.MouseEvent<HTMLElement, MouseEvent>) => void;
onMouseDown?: (event: React.MouseEvent<HTMLElement, MouseEvent>) => void;
onMouseEnter?: (event: React.MouseEvent<HTMLElement, MouseEvent>) => void;
onMouseLeave?: (event: React.MouseEvent<HTMLElement, MouseEvent>) => void;
onMouseMove?: (event: React.MouseEvent<HTMLElement, MouseEvent>) => void;
onTouchStart?: (event: React.TouchEvent<HTMLElement>) => void;
onTouchMove?: (event: React.TouchEvent<HTMLElement>) => void;
onTouchEnd?: (event: React.TouchEvent<HTMLElement>) => void;
}
export interface IReactSpaceCommonProps extends ICommonProps, IReactEvents {
innerComponentStyle?: React.CSSProperties; // For people who like to modify the inner `as` component
as?: keyof React.ReactDOM | React.ComponentType<ICommonProps>;
children?: React.ReactNode;
style?: React.CSSProperties; // Normal styles for the wrapper itself as it is the main component that is resized
}
export interface IReactSpaceInnerProps extends IReactSpaceCommonProps, ISpaceProps, IReactEvents {
handleRender?: (handleProps: IResizeHandleProps) => React.ReactNode;
}
export interface IReactSpacesOptions {
debug?: boolean;
}
export function useForceUpdate() {
const [, setTick] = React.useState(0);
return React.useCallback(() => {
setTick((tick) => tick + 1);
}, []);
}
export function useUniqueId() {
if (SSR_SUPPORT_ENABLED) {
if (React.version.startsWith("18")) {
return `s${React.useId().replace(/\:/g, "")}`;
}
if ((React as any).unstable_useOpaqueIdentifier) {
return `s${(React as any).unstable_useOpaqueIdentifier().replace(/\:/g, "")}`;
}
}
return `s${shortuuid()}`;
}
export function useSpace(props: IReactSpaceInnerProps) {
const store = currentStore;
const update = useForceUpdate();
const parent = React.useContext(ParentContext);
const layer = React.useContext(LayerContext);
const { debug } = React.useContext(OptionsContext);
const uniqueId = useUniqueId();
const [spaceId] = React.useState(props.id || uniqueId);
const elementRef = React.useRef<HTMLElement>();
const resizeSensor = React.useRef<ResizeSensor>();
const [domRect, setDomRect] = React.useState<DOMRect>();
let space = store.getSpace(spaceId)!;
if (debug) {
console.table(store.getSpaces());
}
const parsedProps = {
...props,
...{
id: spaceId,
zIndex: coalesce(props.zIndex, layer),
},
};
if (!space) {
space = store.createSpace(parent, parsedProps, update);
store.addSpace(space);
} else {
store.updateSpace(space, parsedProps);
}
const resizeHandles = useSpaceResizeHandles(store, space);
useEffectOnce(() => {
const rect = elementRef.current ? elementRef.current.getBoundingClientRect() : new DOMRect();
space.dimension = {
...rect,
...{
left: Math.floor(rect.left),
top: Math.floor(rect.top),
right: Math.floor(rect.right),
bottom: Math.floor(rect.bottom),
width: Math.floor(rect.width),
height: Math.floor(rect.height),
x: Math.floor(rect.x),
y: Math.floor(rect.y),
},
};
setDomRect(space.dimension);
if (props.trackSize) {
resizeSensor.current = new ResizeSensor(elementRef.current!, (size) => {
space.dimension = {
...rect,
...{
width: Math.floor(size.width),
height: Math.floor(size.height),
},
};
setDomRect(space.dimension);
});
}
return () => {
resizeSensor.current && resizeSensor.current.detach();
store.removeSpace(space);
};
});
return { space: space, resizeHandles: resizeHandles, domRect: domRect, elementRef: elementRef };
}
export interface IResizeHandleProps {
id?: string;
key: string | number;
className?: string;
onMouseDown: (e: React.MouseEvent<HTMLElement, MouseEvent>) => void;
onTouchStart: (e: React.TouchEvent<HTMLElement>) => void;
}
const resizeSetup = [
{ id: "ml", className: "resize-left", resizeType: ResizeType.Left, condition: (space: ISpaceDefinition) => space.canResizeLeft },
{ id: "mr", className: "resize-right", resizeType: ResizeType.Right, condition: (space: ISpaceDefinition) => space.canResizeRight },
{ id: "mt", className: "resize-top", resizeType: ResizeType.Top, condition: (space: ISpaceDefinition) => space.canResizeTop },
{ id: "mb", className: "resize-bottom", resizeType: ResizeType.Bottom, condition: (space: ISpaceDefinition) => space.canResizeBottom },
{ id: "mtl", className: "resize-top-left", resizeType: ResizeType.TopLeft, condition: (space: ISpaceDefinition) => space.canResizeTopLeft },
{ id: "mtr", className: "resize-top-right", resizeType: ResizeType.TopRight, condition: (space: ISpaceDefinition) => space.canResizeTopRight },
{
id: "mbl",
className: "resize-bottom-left",
resizeType: ResizeType.BottomLeft,
condition: (space: ISpaceDefinition) => space.canResizeBottomLeft,
},
{
id: "mbr",
className: "resize-bottom-right",
resizeType: ResizeType.BottomRight,
condition: (space: ISpaceDefinition) => space.canResizeBottomRight,
},
];
export function useSpaceResizeHandles(store: ISpaceStore, space: ISpaceDefinition) {
const mouseHandles: IResizeHandleProps[] = [];
const setupResizeHandle = (id: string, className: string, resizeType: ResizeType) => {
mouseHandles.push({
id: `${space.id}-${id}`,
key: id,
className: `spaces-resize-handle ${className}`,
onMouseDown: (event) => store.startMouseResize(resizeType, space, event),
onTouchStart: (event) => store.startTouchResize(resizeType, space, event),
});
};
resizeSetup.forEach((resizeItem) => {
if (resizeItem.condition(space)) {
setupResizeHandle(resizeItem.id, resizeItem.className, resizeItem.resizeType);
}
});
return {
mouseHandles,
};
}
export function useCurrentSpace() {
const store = currentStore;
const spaceId = React.useContext(ParentContext);
const space = spaceId ? store.getSpace(spaceId) : undefined;
const domRect = React.useContext(DOMRectContext);
const layer = React.useContext(LayerContext);
const onMouseDrag = React.useCallback(
(e: ResizeMouseEvent, onDragEnd: OnDragEnd | undefined) => (space ? store.startMouseDrag(space, e, onDragEnd) : null),
[spaceId],
);
const onTouchDrag = React.useCallback(
(e: ResizeTouchEvent, onDragEnd: OnDragEnd | undefined) => (space ? store.startTouchDrag(space, e, onDragEnd) : null),
[spaceId],
);
const onForceUpdate = React.useCallback(() => (space ? store.updateStyles(space) : null), [spaceId]);
const defaults = { width: 0, height: 0, x: 0, y: 0 };
const size = {
...defaults,
...domRect,
};
return {
size: size,
layer: layer || 0,
startMouseDrag: onMouseDrag,
startTouchDrag: onTouchDrag,
forceUpdate: onForceUpdate,
} as ISpaceContext;
}
export let SSR_SUPPORT_ENABLED = false;
export function enabledSsrSupport() {
SSR_SUPPORT_ENABLED = true;
}