@lt-ui/tree-dnd 0.0.0-stage → 0.0.2
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.
- package/cjs/index.js +17 -0
- package/cjs/locale/messages.js +21 -0
- package/cjs/locale/use-locale.js +10 -0
- package/cjs/tree-dnd/drag-row.js +26 -0
- package/cjs/tree-dnd/index.js +5 -0
- package/cjs/tree-dnd/pointer.js +94 -0
- package/cjs/tree-dnd/styles.module.css +79 -0
- package/cjs/tree-dnd/tree-dnd.js +190 -0
- package/cjs/tree-dnd/types.js +2 -0
- package/cjs/tree-dnd/use-drop-target.js +121 -0
- package/cjs/tree-dnd/use-hover-expand.js +53 -0
- package/cjs/tree-dnd/use-overlay-fade.js +22 -0
- package/index.d.ts +1 -0
- package/index.js +1 -0
- package/locale/messages.d.ts +12 -0
- package/locale/messages.js +18 -0
- package/locale/use-locale.d.ts +9 -0
- package/locale/use-locale.js +7 -0
- package/package.json +30 -4
- package/tree-dnd/drag-row.d.ts +19 -0
- package/tree-dnd/drag-row.js +20 -0
- package/tree-dnd/index.d.ts +2 -0
- package/tree-dnd/index.js +1 -0
- package/tree-dnd/pointer.d.ts +26 -0
- package/tree-dnd/pointer.js +87 -0
- package/tree-dnd/styles.module.css +79 -0
- package/tree-dnd/tree-dnd.d.ts +13 -0
- package/tree-dnd/tree-dnd.js +151 -0
- package/tree-dnd/types.d.ts +61 -0
- package/tree-dnd/types.js +1 -0
- package/tree-dnd/use-drop-target.d.ts +21 -0
- package/tree-dnd/use-drop-target.js +118 -0
- package/tree-dnd/use-hover-expand.d.ts +21 -0
- package/tree-dnd/use-hover-expand.js +50 -0
- package/tree-dnd/use-overlay-fade.d.ts +7 -0
- package/tree-dnd/use-overlay-fade.js +19 -0
- package/README.md +0 -3
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { useCallback, useRef, useState } from 'react';
|
|
3
|
+
import { getDropProjection } from '@lt-ui/uikit';
|
|
4
|
+
/**
|
|
5
|
+
* Центральная часть строки (доля высоты): указатель в ней не двигает место вставки, чтобы заготовка не прыгала между
|
|
6
|
+
* соседями. Там идёт раскрытие свёрнутой ветки; над раскрытой веткой узел кладётся первым потомком.
|
|
7
|
+
*/
|
|
8
|
+
const CENTER_ZONE = [0.15, 0.85];
|
|
9
|
+
const isCenter = (fraction) => fraction >= CENTER_ZONE[0] && fraction <= CENTER_ZONE[1];
|
|
10
|
+
/** Строки в том виде, в каком их видит пользователь: порядок и уровень берём из DOM, состояние раскрытия не дублируем */
|
|
11
|
+
function measure(root, origin) {
|
|
12
|
+
var _a;
|
|
13
|
+
// Заготовка сдвигает строки под собой; считаем так, будто её нет, иначе место вставки дребезжало бы
|
|
14
|
+
const ghostRect = (_a = root.querySelector('[data-testid="tree-placeholder"]')) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect();
|
|
15
|
+
const ghost = ghostRect ? { top: ghostRect.top - origin, bottom: ghostRect.bottom - origin } : null;
|
|
16
|
+
const shift = (value) => ghost && value >= ghost.bottom - 0.5 ? value - (ghost.bottom - ghost.top) : value;
|
|
17
|
+
const items = Array.from(root.querySelectorAll('[role="treeitem"][data-tree-id]'))
|
|
18
|
+
// Сворачиваемая ветка ещё может быть в DOM (`inert`), но пользователь её уже не видит
|
|
19
|
+
.filter(element => !element.closest('[inert]'))
|
|
20
|
+
.map(element => {
|
|
21
|
+
const rect = element.getBoundingClientRect();
|
|
22
|
+
return {
|
|
23
|
+
id: element.dataset.treeId,
|
|
24
|
+
level: Number(element.getAttribute('aria-level')),
|
|
25
|
+
expanded: element.getAttribute('aria-expanded') === 'true',
|
|
26
|
+
top: shift(rect.top - origin),
|
|
27
|
+
bottom: shift(rect.bottom - origin),
|
|
28
|
+
};
|
|
29
|
+
});
|
|
30
|
+
return { items, ghost };
|
|
31
|
+
}
|
|
32
|
+
/** Вычисляет место вставки по положению указателя над строками дерева */
|
|
33
|
+
export function useDropTarget({ treeRef, wrapperRef, model, indent, canDrop }) {
|
|
34
|
+
const [projection, setProjection] = useState(null);
|
|
35
|
+
const lastProjection = useRef(null);
|
|
36
|
+
// Уровень отсчитывается от последнего достигнутого, а не от точки захвата: упёршись в допустимый предел,
|
|
37
|
+
// движение в обратную сторону сразу меняет уровень, без «мёртвой зоны» накопленного смещения
|
|
38
|
+
const anchor = useRef(null);
|
|
39
|
+
const lastSlot = useRef(null);
|
|
40
|
+
const lastOver = useRef(false);
|
|
41
|
+
const update = useCallback((activeId, pointerY, offsetX) => {
|
|
42
|
+
const tree = treeRef.current;
|
|
43
|
+
const wrapper = wrapperRef.current;
|
|
44
|
+
if (!tree || !wrapper)
|
|
45
|
+
return { projection: null, centerId: null };
|
|
46
|
+
const wrapperRect = wrapper.getBoundingClientRect();
|
|
47
|
+
const active = model.entries.get(activeId);
|
|
48
|
+
if (!anchor.current && active)
|
|
49
|
+
anchor.current = { level: active.level, x: 0 };
|
|
50
|
+
const { items, ghost } = measure(tree, wrapperRect.top);
|
|
51
|
+
const y = pointerY - wrapperRect.top;
|
|
52
|
+
const rows = items.map(item => ({ id: item.id, level: item.level }));
|
|
53
|
+
const others = items.filter(item => item.id !== activeId);
|
|
54
|
+
/** Проекция для места `slot`: уровень = последний достигнутый + сдвиг указателя с тех пор */
|
|
55
|
+
// Указатель над самой исходной строкой (её призраком): место и уровень прежние, а не «прилипание» к строке выше
|
|
56
|
+
const activeItem = items.find(item => item.id === activeId);
|
|
57
|
+
const overActive = Boolean(activeItem && y >= activeItem.top && y < activeItem.bottom);
|
|
58
|
+
const project = (slot, forcedLevel) => {
|
|
59
|
+
var _a, _b, _c, _d, _e, _f;
|
|
60
|
+
// Указатель перешёл к другому месту: «прилипаем» к уровню строки выше (её сосед), а дальше уровень меняется
|
|
61
|
+
// сдвигом указателя вправо или влево от этой точки — независимо от того, за какую часть и где схвачен узел
|
|
62
|
+
if (slot !== lastSlot.current || overActive !== lastOver.current) {
|
|
63
|
+
anchor.current = {
|
|
64
|
+
level: overActive ? ((_a = active === null || active === void 0 ? void 0 : active.level) !== null && _a !== void 0 ? _a : 1) : ((_c = (_b = others[slot - 1]) === null || _b === void 0 ? void 0 : _b.level) !== null && _c !== void 0 ? _c : 1),
|
|
65
|
+
x: offsetX,
|
|
66
|
+
};
|
|
67
|
+
lastSlot.current = slot;
|
|
68
|
+
lastOver.current = overActive;
|
|
69
|
+
}
|
|
70
|
+
const from = (_d = anchor.current) !== null && _d !== void 0 ? _d : { level: (_e = active === null || active === void 0 ? void 0 : active.level) !== null && _e !== void 0 ? _e : 1, x: 0 };
|
|
71
|
+
const level = forcedLevel !== null && forcedLevel !== void 0 ? forcedLevel : from.level + Math.round((offsetX - from.x) / indent);
|
|
72
|
+
const result = getDropProjection({
|
|
73
|
+
model,
|
|
74
|
+
rows,
|
|
75
|
+
activeId,
|
|
76
|
+
slot,
|
|
77
|
+
offsetX: (level - ((_f = active === null || active === void 0 ? void 0 : active.level) !== null && _f !== void 0 ? _f : 1)) * indent,
|
|
78
|
+
indent,
|
|
79
|
+
canDrop,
|
|
80
|
+
});
|
|
81
|
+
// Уровень упёрся в предел или задан принудительно: дальше отсчитываем от него и от текущей позиции указателя
|
|
82
|
+
if (result && result.level !== level)
|
|
83
|
+
anchor.current = { level: result.level, x: offsetX };
|
|
84
|
+
lastProjection.current = result;
|
|
85
|
+
setProjection(result);
|
|
86
|
+
return result;
|
|
87
|
+
};
|
|
88
|
+
// Указатель над заготовкой или в центре свёрнутой строки: место не меняется, но уровень следует за указателем
|
|
89
|
+
const keepSlot = () => {
|
|
90
|
+
const last = lastProjection.current;
|
|
91
|
+
return last ? project(last.slot) : null;
|
|
92
|
+
};
|
|
93
|
+
if (ghost && y >= ghost.top && y < ghost.bottom)
|
|
94
|
+
return { projection: keepSlot(), centerId: null };
|
|
95
|
+
let slot = others.filter(item => (item.top + item.bottom) / 2 < y).length;
|
|
96
|
+
const hit = others.find(item => y >= item.top && y < item.bottom);
|
|
97
|
+
if (hit && isCenter((y - hit.top) / (hit.bottom - hit.top))) {
|
|
98
|
+
// Центр строки: место вставки не прыгает. Над раскрытой веткой узел кладём первым потомком, над остальными —
|
|
99
|
+
// ничего не меняем (свёрнутая ветка раскроется по удержанию)
|
|
100
|
+
if (!hit.expanded)
|
|
101
|
+
return { projection: keepSlot(), centerId: hit.id };
|
|
102
|
+
slot = others.indexOf(hit) + 1;
|
|
103
|
+
return { projection: project(slot, hit.level + 1), centerId: hit.id };
|
|
104
|
+
}
|
|
105
|
+
return { projection: project(slot), centerId: null };
|
|
106
|
+
}, [canDrop, indent, model, treeRef, wrapperRef]);
|
|
107
|
+
/** `keepLevel` — только убрать заготовку (раскладка изменилась), не теряя достигнутый уровень */
|
|
108
|
+
const reset = useCallback((keepLevel = false) => {
|
|
109
|
+
lastProjection.current = null;
|
|
110
|
+
if (!keepLevel) {
|
|
111
|
+
anchor.current = null;
|
|
112
|
+
lastSlot.current = null;
|
|
113
|
+
lastOver.current = false;
|
|
114
|
+
}
|
|
115
|
+
setProjection(null);
|
|
116
|
+
}, []);
|
|
117
|
+
return { projection, update, reset };
|
|
118
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { RefObject } from 'react';
|
|
2
|
+
import type { TreeModel } from '@lt-ui/uikit';
|
|
3
|
+
type Params = {
|
|
4
|
+
treeRef: RefObject<HTMLElement | null>;
|
|
5
|
+
model: TreeModel;
|
|
6
|
+
/** Сколько держать указатель над свёрнутой веткой, мс. `false` — не раскрывать */
|
|
7
|
+
delay: number | false;
|
|
8
|
+
onExpand: (id: string) => void;
|
|
9
|
+
/** Ветка, которая вот-вот раскроется (для подсветки); `null` — отсчёта нет */
|
|
10
|
+
onTarget: (id: string | null) => void;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Раскрытие ветки по удержанию: указатель задержался в центральной зоне свёрнутой ветки — она раскрывается,
|
|
14
|
+
* чтобы можно было положить узел внутрь. Над листом и уже раскрытой веткой ничего не происходит. Уход в другую
|
|
15
|
+
* строку (или на границу строк) сбрасывает отсчёт.
|
|
16
|
+
*/
|
|
17
|
+
export declare function useHoverExpand({ treeRef, model, delay, onExpand, onTarget }: Params): {
|
|
18
|
+
check: (activeId: string, centerId: string | null) => void;
|
|
19
|
+
clear: () => void;
|
|
20
|
+
};
|
|
21
|
+
export {};
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { useCallback, useEffect, useRef } from 'react';
|
|
3
|
+
/**
|
|
4
|
+
* Раскрытие ветки по удержанию: указатель задержался в центральной зоне свёрнутой ветки — она раскрывается,
|
|
5
|
+
* чтобы можно было положить узел внутрь. Над листом и уже раскрытой веткой ничего не происходит. Уход в другую
|
|
6
|
+
* строку (или на границу строк) сбрасывает отсчёт.
|
|
7
|
+
*/
|
|
8
|
+
export function useHoverExpand({ treeRef, model, delay, onExpand, onTarget }) {
|
|
9
|
+
const timer = useRef(undefined);
|
|
10
|
+
const current = useRef(null);
|
|
11
|
+
const callbacks = useRef({ onExpand, onTarget });
|
|
12
|
+
callbacks.current = { onExpand, onTarget };
|
|
13
|
+
const clear = useCallback(() => {
|
|
14
|
+
clearTimeout(timer.current);
|
|
15
|
+
timer.current = undefined;
|
|
16
|
+
if (current.current !== null)
|
|
17
|
+
callbacks.current.onTarget(null);
|
|
18
|
+
current.current = null;
|
|
19
|
+
}, []);
|
|
20
|
+
useEffect(() => clear, [clear]);
|
|
21
|
+
/** `centerId` — строка, в центральной зоне которой указатель (из `useDropTarget`) */
|
|
22
|
+
const check = useCallback((activeId, centerId) => {
|
|
23
|
+
var _a;
|
|
24
|
+
if (delay === false)
|
|
25
|
+
return;
|
|
26
|
+
if (centerId === current.current)
|
|
27
|
+
return;
|
|
28
|
+
clearTimeout(timer.current);
|
|
29
|
+
timer.current = undefined;
|
|
30
|
+
const hadTarget = current.current !== null;
|
|
31
|
+
current.current = centerId;
|
|
32
|
+
if (hadTarget)
|
|
33
|
+
callbacks.current.onTarget(null);
|
|
34
|
+
if (!centerId || centerId === activeId)
|
|
35
|
+
return;
|
|
36
|
+
const row = (_a = treeRef.current) === null || _a === void 0 ? void 0 : _a.querySelector(`[role="treeitem"][data-tree-id="${CSS.escape(centerId)}"]`);
|
|
37
|
+
const entry = model.entries.get(centerId);
|
|
38
|
+
const collapsed = (row === null || row === void 0 ? void 0 : row.getAttribute('aria-expanded')) === 'false';
|
|
39
|
+
if (!entry || !entry.childIds.length || !collapsed || entry.node.disabled)
|
|
40
|
+
return;
|
|
41
|
+
callbacks.current.onTarget(centerId);
|
|
42
|
+
timer.current = setTimeout(() => {
|
|
43
|
+
timer.current = undefined;
|
|
44
|
+
current.current = null;
|
|
45
|
+
callbacks.current.onTarget(null);
|
|
46
|
+
callbacks.current.onExpand(centerId);
|
|
47
|
+
}, delay);
|
|
48
|
+
}, [delay, model, treeRef]);
|
|
49
|
+
return { check, clear };
|
|
50
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { RefObject } from 'react';
|
|
2
|
+
import type { TreeDndOverlayFade } from './types';
|
|
3
|
+
/** Плавная прозрачность копии над отступом и линиями места вставки на время перетаскивания */
|
|
4
|
+
export declare function useOverlayFade(treeRef: RefObject<HTMLElement | null>, overlayRef: RefObject<HTMLElement | null>, config?: TreeDndOverlayFade | false): {
|
|
5
|
+
start: () => void;
|
|
6
|
+
stop: () => void | undefined;
|
|
7
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { useCallback, useEffect, useRef } from 'react';
|
|
3
|
+
import { startOverlayFade } from './pointer';
|
|
4
|
+
/** Плавная прозрачность копии над отступом и линиями места вставки на время перетаскивания */
|
|
5
|
+
export function useOverlayFade(treeRef, overlayRef, config = {}) {
|
|
6
|
+
const stopRef = useRef(null);
|
|
7
|
+
// Актуальные значения читаются каждый кадр: менять `overlayFade` можно и во время перетаскивания
|
|
8
|
+
const configRef = useRef(config);
|
|
9
|
+
configRef.current = config;
|
|
10
|
+
const stop = useCallback(() => { var _a; return (_a = stopRef.current) === null || _a === void 0 ? void 0 : _a.call(stopRef); }, []);
|
|
11
|
+
const start = useCallback(() => {
|
|
12
|
+
stop();
|
|
13
|
+
if (configRef.current === false)
|
|
14
|
+
return;
|
|
15
|
+
stopRef.current = startOverlayFade(() => treeRef.current, () => overlayRef.current, () => (configRef.current === false ? { alpha: 1 } : configRef.current));
|
|
16
|
+
}, [overlayRef, stop, treeRef]);
|
|
17
|
+
useEffect(() => stop, [stop]);
|
|
18
|
+
return { start, stop };
|
|
19
|
+
}
|
package/README.md
DELETED