@lt-ui/tree-dnd 0.0.0-stage → 0.0.1
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
package/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './tree-dnd';
|
package/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './tree-dnd';
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Строки `@lt-ui/tree-dnd`: объявления для скринридера при перетаскивании. Переопределяются через `messages` провайдера */
|
|
2
|
+
export interface TreeDndMessages {
|
|
3
|
+
treeDnd: {
|
|
4
|
+
instructions: string;
|
|
5
|
+
start: string;
|
|
6
|
+
over: string;
|
|
7
|
+
end: string;
|
|
8
|
+
cancel: string;
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
export declare const ru: TreeDndMessages;
|
|
12
|
+
export declare const en: TreeDndMessages;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export const ru = {
|
|
2
|
+
treeDnd: {
|
|
3
|
+
instructions: 'Чтобы переместить узел, зажмите его и перетащите на новое место в дереве',
|
|
4
|
+
start: 'Взят узел «{name}»',
|
|
5
|
+
over: 'Узел «{name}» над узлом «{target}»',
|
|
6
|
+
end: 'Узел «{name}» перемещён',
|
|
7
|
+
cancel: 'Перемещение узла «{name}» отменено',
|
|
8
|
+
},
|
|
9
|
+
};
|
|
10
|
+
export const en = {
|
|
11
|
+
treeDnd: {
|
|
12
|
+
instructions: 'To move a node, press and hold it, then drag it to a new place in the tree',
|
|
13
|
+
start: 'Picked up “{name}”',
|
|
14
|
+
over: '“{name}” is over “{target}”',
|
|
15
|
+
end: '“{name}” was moved',
|
|
16
|
+
cancel: 'Moving “{name}” was cancelled',
|
|
17
|
+
},
|
|
18
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { TreeDndMessages } from './messages';
|
|
2
|
+
/**
|
|
3
|
+
* Язык и переводчик строк пакета: язык берётся у ближайшего `ThemeProvider` или `LocaleProvider`
|
|
4
|
+
* из `@lt-ui/uikit`, строки переопределяются в `messages` под своим ключом.
|
|
5
|
+
*/
|
|
6
|
+
export declare const useLocale: () => {
|
|
7
|
+
locale: import("@lt-ui/i18n").Locale;
|
|
8
|
+
t: import("@lt-ui/i18n").Translate<TreeDndMessages>;
|
|
9
|
+
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createUseLocale } from '@lt-ui/i18n';
|
|
2
|
+
import { en, ru } from './messages';
|
|
3
|
+
/**
|
|
4
|
+
* Язык и переводчик строк пакета: язык берётся у ближайшего `ThemeProvider` или `LocaleProvider`
|
|
5
|
+
* из `@lt-ui/uikit`, строки переопределяются в `messages` под своим ключом.
|
|
6
|
+
*/
|
|
7
|
+
export const useLocale = createUseLocale({ en, ru });
|
package/package.json
CHANGED
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lt-ui/tree-dnd",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "LT UI",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"peerDependencies": {
|
|
7
|
+
"@dnd-kit/core": "^6.3.1",
|
|
8
|
+
"@lt-ui/uikit": "0.0.1",
|
|
9
|
+
"react": "^18.0.0 || ^19.0.0"
|
|
10
|
+
},
|
|
11
|
+
"dependencies": {
|
|
12
|
+
"@lt-ui/i18n": "0.0.1",
|
|
13
|
+
"clsx": "^2.1.1"
|
|
14
|
+
},
|
|
15
|
+
"main": "./cjs/index.js",
|
|
16
|
+
"module": "./index.js",
|
|
17
|
+
"types": "./index.d.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./index.d.ts",
|
|
21
|
+
"import": "./index.js",
|
|
22
|
+
"require": "./cjs/index.js"
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"sideEffects": [
|
|
26
|
+
"*.css"
|
|
27
|
+
],
|
|
28
|
+
"private": false,
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public"
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
import type { TreeRowContext } from '@lt-ui/uikit';
|
|
3
|
+
type Props = {
|
|
4
|
+
context: TreeRowContext;
|
|
5
|
+
/** Узел нельзя тащить */
|
|
6
|
+
locked: boolean;
|
|
7
|
+
/** Над строкой идёт отсчёт раскрытия по удержанию */
|
|
8
|
+
expanding?: boolean;
|
|
9
|
+
/** Длительность отсчёта, мс (для анимации подсветки) */
|
|
10
|
+
expandDelay?: number;
|
|
11
|
+
/** Узел сейчас встанет на прежнее место (или места ещё нет): исходная строка вместо серой рамки оранжевая */
|
|
12
|
+
atOrigin?: boolean;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Строка дерева как источник перетаскивания. Из атрибутов dnd kit берём только слушатели указателя: роль и `tabindex`
|
|
16
|
+
* остаются у `treeitem`, иначе строка перестала бы быть элементом дерева для скринридеров.
|
|
17
|
+
*/
|
|
18
|
+
export declare function DragRow({ context, locked, expanding, expandDelay, atOrigin }: Readonly<Props>): React.JSX.Element;
|
|
19
|
+
export {};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
|
|
3
|
+
import React from 'react';
|
|
4
|
+
import { useDraggable } from '@dnd-kit/core';
|
|
5
|
+
import clsx from 'clsx';
|
|
6
|
+
import styles from './styles.module.css';
|
|
7
|
+
/**
|
|
8
|
+
* Строка дерева как источник перетаскивания. Из атрибутов dnd kit берём только слушатели указателя: роль и `tabindex`
|
|
9
|
+
* остаются у `treeitem`, иначе строка перестала бы быть элементом дерева для скринридеров.
|
|
10
|
+
*/
|
|
11
|
+
export function DragRow({ context, locked, expanding, expandDelay, atOrigin }) {
|
|
12
|
+
const { listeners, setNodeRef, isDragging } = useDraggable({ id: context.id, disabled: locked });
|
|
13
|
+
return (_jsx(_Fragment, { children: context.render({
|
|
14
|
+
ref: setNodeRef,
|
|
15
|
+
className: clsx(!locked && styles.draggable, isDragging && styles.ghost, isDragging && atOrigin && styles.ghostTarget, expanding && styles.expanding),
|
|
16
|
+
style: expanding && expandDelay ? { '--tree-dnd-hover-delay': `${expandDelay}ms` } : undefined,
|
|
17
|
+
...(locked ? {} : listeners),
|
|
18
|
+
...(isDragging ? { 'data-dnd-ghost': '' } : {}),
|
|
19
|
+
}) }));
|
|
20
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { TreeDnd } from './tree-dnd';
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { Modifier } from '@dnd-kit/core';
|
|
2
|
+
import type { DropProjection, TreeModel } from '@lt-ui/uikit';
|
|
3
|
+
import type { TreeDndOverlayFade } from './types';
|
|
4
|
+
/** Вертикаль указателя в координатах окна: точка захвата + смещение (не зависит от сдвига копии модификаторами) */
|
|
5
|
+
export declare const getPointerY: (activatorEvent: Event | null, deltaY: number) => number | null;
|
|
6
|
+
/** Проекция совпадает с исходным положением узла (тот же родитель и позиция): отпускание равно отмене */
|
|
7
|
+
export declare const isOriginProjection: (model: TreeModel, id: string | null, target: DropProjection | null) => boolean;
|
|
8
|
+
/**
|
|
9
|
+
* Копия держится под указателем там, где узел схватили: по горизонтали — на том же расстоянии от левого края
|
|
10
|
+
* (но не дальше, чем копия шире), по вертикали — серединой. Копия уже и ниже строки, поэтому без поправки
|
|
11
|
+
* dnd kit оставлял её на месте строки и указатель оказывался вне её или у края.
|
|
12
|
+
*/
|
|
13
|
+
export declare const placeOverlay: Modifier;
|
|
14
|
+
/** Значения прозрачности копии по умолчанию (см. `overlayFade`) */
|
|
15
|
+
export declare const DEFAULT_OVERLAY_FADE: {
|
|
16
|
+
width: number;
|
|
17
|
+
alpha: number;
|
|
18
|
+
duration: number;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Копия налезает на отступ и линии места вставки: эта часть полупрозрачная, остальная — нет. Граница считается по
|
|
22
|
+
* реальному положению колонок линий каждый кадр (она всегда точная), а сама прозрачность включается и выключается
|
|
23
|
+
* анимацией по времени: налезание — «включить», ушла — «выключить», без зависимости от координаты указателя.
|
|
24
|
+
* Возвращает остановку.
|
|
25
|
+
*/
|
|
26
|
+
export declare const startOverlayFade: (getTree: () => HTMLElement | null, getOverlay: () => HTMLElement | null, getConfig?: () => TreeDndOverlayFade) => () => void;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/** Вертикаль указателя в координатах окна: точка захвата + смещение (не зависит от сдвига копии модификаторами) */
|
|
2
|
+
export const getPointerY = (activatorEvent, deltaY) => {
|
|
3
|
+
var _a, _b, _c;
|
|
4
|
+
if (!activatorEvent)
|
|
5
|
+
return null;
|
|
6
|
+
const touch = (_b = (_a = activatorEvent.touches) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : (_c = activatorEvent.changedTouches) === null || _c === void 0 ? void 0 : _c[0];
|
|
7
|
+
const startY = touch ? touch.clientY : activatorEvent.clientY;
|
|
8
|
+
return typeof startY === 'number' ? startY + deltaY : null;
|
|
9
|
+
};
|
|
10
|
+
/** Проекция совпадает с исходным положением узла (тот же родитель и позиция): отпускание равно отмене */
|
|
11
|
+
export const isOriginProjection = (model, id, target) => {
|
|
12
|
+
var _a, _b;
|
|
13
|
+
const entry = id ? model.entries.get(id) : undefined;
|
|
14
|
+
if (!id || !entry || !target)
|
|
15
|
+
return false;
|
|
16
|
+
const siblings = entry.parentId ? ((_b = (_a = model.entries.get(entry.parentId)) === null || _a === void 0 ? void 0 : _a.childIds) !== null && _b !== void 0 ? _b : []) : model.rootIds;
|
|
17
|
+
return target.move.parentId === entry.parentId && target.move.index === siblings.indexOf(id);
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Копия держится под указателем там, где узел схватили: по горизонтали — на том же расстоянии от левого края
|
|
21
|
+
* (но не дальше, чем копия шире), по вертикали — серединой. Копия уже и ниже строки, поэтому без поправки
|
|
22
|
+
* dnd kit оставлял её на месте строки и указатель оказывался вне её или у края.
|
|
23
|
+
*/
|
|
24
|
+
export const placeOverlay = ({ transform, activatorEvent, draggingNodeRect, overlayNodeRect }) => {
|
|
25
|
+
var _a, _b, _c, _d, _e;
|
|
26
|
+
if (!activatorEvent || !draggingNodeRect)
|
|
27
|
+
return transform;
|
|
28
|
+
const touch = (_b = (_a = activatorEvent.touches) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : (_c = activatorEvent.changedTouches) === null || _c === void 0 ? void 0 : _c[0];
|
|
29
|
+
const start = touch !== null && touch !== void 0 ? touch : activatorEvent;
|
|
30
|
+
if (typeof start.clientX !== 'number' || typeof start.clientY !== 'number')
|
|
31
|
+
return transform;
|
|
32
|
+
const width = (_d = overlayNodeRect === null || overlayNodeRect === void 0 ? void 0 : overlayNodeRect.width) !== null && _d !== void 0 ? _d : draggingNodeRect.width;
|
|
33
|
+
const height = (_e = overlayNodeRect === null || overlayNodeRect === void 0 ? void 0 : overlayNodeRect.height) !== null && _e !== void 0 ? _e : draggingNodeRect.height;
|
|
34
|
+
const grabX = start.clientX - draggingNodeRect.left;
|
|
35
|
+
const grabY = start.clientY - draggingNodeRect.top;
|
|
36
|
+
return {
|
|
37
|
+
...transform,
|
|
38
|
+
x: transform.x + grabX - Math.min(grabX, Math.max(width - 16, 0), 24),
|
|
39
|
+
y: transform.y + grabY - height / 2,
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
/** Значения прозрачности копии по умолчанию (см. `overlayFade`) */
|
|
43
|
+
export const DEFAULT_OVERLAY_FADE = { width: 28, alpha: 0.25, duration: 220 };
|
|
44
|
+
const easeInOut = (t) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2);
|
|
45
|
+
/** Правый край иерархии у места вставки: колонки линий строки-заготовки или призрака */
|
|
46
|
+
const getHierarchyEdge = (tree) => {
|
|
47
|
+
const row = tree.querySelector('[data-testid="tree-placeholder"], [data-dnd-ghost]');
|
|
48
|
+
if (!row)
|
|
49
|
+
return null;
|
|
50
|
+
const guides = row.querySelectorAll('[class*="guide"]');
|
|
51
|
+
const last = guides[guides.length - 1];
|
|
52
|
+
return last ? last.getBoundingClientRect().right : row.getBoundingClientRect().left + 8;
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Копия налезает на отступ и линии места вставки: эта часть полупрозрачная, остальная — нет. Граница считается по
|
|
56
|
+
* реальному положению колонок линий каждый кадр (она всегда точная), а сама прозрачность включается и выключается
|
|
57
|
+
* анимацией по времени: налезание — «включить», ушла — «выключить», без зависимости от координаты указателя.
|
|
58
|
+
* Возвращает остановку.
|
|
59
|
+
*/
|
|
60
|
+
export const startOverlayFade = (getTree, getOverlay, getConfig = () => ({})) => {
|
|
61
|
+
let frame = 0;
|
|
62
|
+
let strength = 0;
|
|
63
|
+
let last = null;
|
|
64
|
+
const tick = (now) => {
|
|
65
|
+
frame = requestAnimationFrame(tick);
|
|
66
|
+
const { width, alpha: minAlpha, duration } = { ...DEFAULT_OVERLAY_FADE, ...getConfig() };
|
|
67
|
+
const step = last === null ? 0 : (now - last) / Math.max(1, duration);
|
|
68
|
+
last = now;
|
|
69
|
+
const tree = getTree();
|
|
70
|
+
const overlay = getOverlay();
|
|
71
|
+
if (!tree || !overlay)
|
|
72
|
+
return;
|
|
73
|
+
const edge = getHierarchyEdge(tree);
|
|
74
|
+
const solid = edge === null ? 0 : Math.max(0, edge - overlay.getBoundingClientRect().left);
|
|
75
|
+
strength = Math.min(1, Math.max(0, strength + (solid > 0 ? step : -step)));
|
|
76
|
+
const alpha = 1 - (1 - minAlpha) * easeInOut(strength);
|
|
77
|
+
let mask = '';
|
|
78
|
+
if (alpha < 0.995) {
|
|
79
|
+
const a = alpha.toFixed(3);
|
|
80
|
+
mask = `linear-gradient(to right, rgba(0,0,0,${a}) 0, rgba(0,0,0,${a}) ${solid.toFixed(1)}px, #000 ${(solid + width).toFixed(1)}px)`;
|
|
81
|
+
}
|
|
82
|
+
overlay.style.maskImage = mask;
|
|
83
|
+
overlay.style.setProperty('-webkit-mask-image', mask);
|
|
84
|
+
};
|
|
85
|
+
frame = requestAnimationFrame(tick);
|
|
86
|
+
return () => cancelAnimationFrame(frame);
|
|
87
|
+
};
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
.wrapper {
|
|
2
|
+
position: relative;
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
.draggable {
|
|
6
|
+
touch-action: manipulation;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
.overlay {
|
|
10
|
+
box-sizing: border-box;
|
|
11
|
+
max-width: 100%;
|
|
12
|
+
padding: 6px 12px;
|
|
13
|
+
overflow: hidden;
|
|
14
|
+
text-overflow: ellipsis;
|
|
15
|
+
font-size: 16px;
|
|
16
|
+
line-height: 24px;
|
|
17
|
+
color: var(--text-primary);
|
|
18
|
+
white-space: nowrap;
|
|
19
|
+
cursor: grabbing;
|
|
20
|
+
background-color: var(--background-primary);
|
|
21
|
+
border: 1px solid var(--control-secondary);
|
|
22
|
+
border-radius: var(--rounding-l);
|
|
23
|
+
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
.overlayFull {
|
|
27
|
+
box-sizing: border-box;
|
|
28
|
+
max-width: 100%;
|
|
29
|
+
cursor: grabbing;
|
|
30
|
+
opacity: 0.95;
|
|
31
|
+
filter: drop-shadow(0 4px 16px rgba(0, 0, 0, 0.16));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
.ghost {
|
|
35
|
+
color: var(--text-minor);
|
|
36
|
+
pointer-events: none;
|
|
37
|
+
outline: 1px dashed var(--control-secondary);
|
|
38
|
+
outline-offset: -1px;
|
|
39
|
+
background-color: transparent;
|
|
40
|
+
}
|
|
41
|
+
.ghost > * {
|
|
42
|
+
opacity: 0.5;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
.ghostTarget {
|
|
46
|
+
outline-color: var(--accent-primary);
|
|
47
|
+
background-color: var(--accent-light);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
.expanding {
|
|
51
|
+
outline: 1px dashed var(--accent-primary);
|
|
52
|
+
outline-offset: -1px;
|
|
53
|
+
isolation: isolate;
|
|
54
|
+
}
|
|
55
|
+
.expanding::before {
|
|
56
|
+
position: absolute;
|
|
57
|
+
inset: 0;
|
|
58
|
+
z-index: -1;
|
|
59
|
+
pointer-events: none;
|
|
60
|
+
content: "";
|
|
61
|
+
background-color: var(--accent-light);
|
|
62
|
+
border-radius: inherit;
|
|
63
|
+
transform-origin: left;
|
|
64
|
+
animation: expand-fill var(--tree-dnd-hover-delay, 600ms) linear forwards;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
@keyframes expand-fill {
|
|
68
|
+
from {
|
|
69
|
+
transform: scaleX(0);
|
|
70
|
+
}
|
|
71
|
+
to {
|
|
72
|
+
transform: scaleX(1);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
@media (prefers-reduced-motion: reduce) {
|
|
76
|
+
.expanding::before {
|
|
77
|
+
animation: none;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
import type { TreeDndProps } from './types';
|
|
3
|
+
/**
|
|
4
|
+
* `<TreeDnd />` — `Tree` с перетаскиванием узлов (dnd kit): мышь и касание.
|
|
5
|
+
* Схваченный узел «поднимается» копией шириной не больше половины дерева, на месте остаётся
|
|
6
|
+
* скрытым (раскрытая ветка сворачивается), а в дереве на месте вставки рисуется заготовка узла с отступом и
|
|
7
|
+
* линиями нужного уровня — уровень выбирается сдвигом указателя вправо/влево.
|
|
8
|
+
*
|
|
9
|
+
* @example ```tsx
|
|
10
|
+
* <TreeDnd aria-label="Каталог" nodes={nodes} onMove={move => setNodes(moveTreeNode(nodes, move))} />
|
|
11
|
+
* ```
|
|
12
|
+
*/
|
|
13
|
+
export declare function TreeDnd<T = unknown>({ nodes, onMove, canDrag, canDrop, indent, expandOnHoverDelay, renderOverlay, overlay, overlayFade, onDragStateChange, ...treeProps }: TreeDndProps<T>): React.JSX.Element;
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
/* eslint-disable max-lines */
|
|
4
|
+
import React, { useCallback, useMemo, useRef, useState } from 'react';
|
|
5
|
+
import { DndContext, DragOverlay, MouseSensor, TouchSensor, useSensor, useSensors } from '@dnd-kit/core';
|
|
6
|
+
import { Tree, buildTreeModel, getPlaceholderGuides } from '@lt-ui/uikit';
|
|
7
|
+
import { useLocale } from '../locale/use-locale';
|
|
8
|
+
import { DragRow } from './drag-row';
|
|
9
|
+
import { useDropTarget } from './use-drop-target';
|
|
10
|
+
import { getPointerY, isOriginProjection, placeOverlay } from './pointer';
|
|
11
|
+
import { useOverlayFade } from './use-overlay-fade';
|
|
12
|
+
import { useHoverExpand } from './use-hover-expand';
|
|
13
|
+
import styles from './styles.module.css';
|
|
14
|
+
const OVERLAY_MAX_RATIO = 0.5;
|
|
15
|
+
const nodeTitle = (node) => { var _a; return (_a = node.text) !== null && _a !== void 0 ? _a : node.label; };
|
|
16
|
+
/**
|
|
17
|
+
* `<TreeDnd />` — `Tree` с перетаскиванием узлов (dnd kit): мышь и касание.
|
|
18
|
+
* Схваченный узел «поднимается» копией шириной не больше половины дерева, на месте остаётся
|
|
19
|
+
* скрытым (раскрытая ветка сворачивается), а в дереве на месте вставки рисуется заготовка узла с отступом и
|
|
20
|
+
* линиями нужного уровня — уровень выбирается сдвигом указателя вправо/влево.
|
|
21
|
+
*
|
|
22
|
+
* @example ```tsx
|
|
23
|
+
* <TreeDnd aria-label="Каталог" nodes={nodes} onMove={move => setNodes(moveTreeNode(nodes, move))} />
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
export function TreeDnd({ nodes, onMove, canDrag, canDrop, indent = 28, expandOnHoverDelay = 600, renderOverlay, overlay = 'compact', overlayFade, onDragStateChange, ...treeProps }) {
|
|
27
|
+
var _a, _b;
|
|
28
|
+
const { t } = useLocale();
|
|
29
|
+
const model = useMemo(() => buildTreeModel(nodes), [nodes]);
|
|
30
|
+
const wrapperRef = useRef(null);
|
|
31
|
+
const treeRef = useRef(null);
|
|
32
|
+
const overlayRef = useRef(null);
|
|
33
|
+
const fade = useOverlayFade(treeRef, overlayRef, overlayFade);
|
|
34
|
+
const [activeId, setActiveId] = useState(null);
|
|
35
|
+
const [overlayWidth, setOverlayWidth] = useState();
|
|
36
|
+
const sensors = useSensors(useSensor(MouseSensor, { activationConstraint: { distance: 6 } }),
|
|
37
|
+
// На касании перетаскивание начинается после удержания, чтобы не мешать прокрутке
|
|
38
|
+
useSensor(TouchSensor, { activationConstraint: { delay: 250, tolerance: 6 } }));
|
|
39
|
+
// Раскрытием ведём сами: ветка раскрывается по удержанию, а состояние остаётся контролируемым снаружи
|
|
40
|
+
const [expandedState, setExpandedState] = useState(() => {
|
|
41
|
+
var _a;
|
|
42
|
+
return treeProps.defaultExpanded === 'all'
|
|
43
|
+
? Array.from(model.entries.values())
|
|
44
|
+
.filter(entry => entry.childIds.length)
|
|
45
|
+
.map(entry => entry.id)
|
|
46
|
+
: ((_a = treeProps.defaultExpanded) !== null && _a !== void 0 ? _a : []);
|
|
47
|
+
});
|
|
48
|
+
const expanded = (_a = treeProps.expanded) !== null && _a !== void 0 ? _a : expandedState;
|
|
49
|
+
const expandedRef = useRef(expanded);
|
|
50
|
+
expandedRef.current = expanded;
|
|
51
|
+
const { onExpandedChange } = treeProps;
|
|
52
|
+
const changeExpanded = useCallback((next, info) => {
|
|
53
|
+
if (treeProps.expanded === undefined)
|
|
54
|
+
setExpandedState(next);
|
|
55
|
+
onExpandedChange === null || onExpandedChange === void 0 ? void 0 : onExpandedChange(next, info);
|
|
56
|
+
}, [onExpandedChange, treeProps.expanded]);
|
|
57
|
+
const isLocked = (node) => Boolean(node.disabled) || (canDrag ? !canDrag(node) : false);
|
|
58
|
+
const dropTarget = useDropTarget({
|
|
59
|
+
treeRef,
|
|
60
|
+
wrapperRef,
|
|
61
|
+
model,
|
|
62
|
+
indent,
|
|
63
|
+
canDrop: canDrop
|
|
64
|
+
? parentId => { var _a; return canDrop(parentId, (_a = model.entries.get(activeId !== null && activeId !== void 0 ? activeId : '')) === null || _a === void 0 ? void 0 : _a.node); }
|
|
65
|
+
: undefined,
|
|
66
|
+
});
|
|
67
|
+
const [expandingId, setExpandingId] = useState(null);
|
|
68
|
+
const lastPointer = useRef(null);
|
|
69
|
+
const hoverExpand = useHoverExpand({
|
|
70
|
+
treeRef,
|
|
71
|
+
model,
|
|
72
|
+
delay: expandOnHoverDelay,
|
|
73
|
+
onTarget: setExpandingId,
|
|
74
|
+
onExpand: id => {
|
|
75
|
+
if (expandedRef.current.includes(id))
|
|
76
|
+
return;
|
|
77
|
+
changeExpanded([...expandedRef.current, id], { id, expanded: true });
|
|
78
|
+
// Раскладка изменилась: заготовку убираем, место вставки пересчитается на следующем шаге
|
|
79
|
+
dropTarget.reset(true);
|
|
80
|
+
const last = lastPointer.current;
|
|
81
|
+
if (last)
|
|
82
|
+
setTimeout(() => dropTarget.update(last.id, last.y, last.x), 50);
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
const onDragStart = ({ active }) => {
|
|
86
|
+
var _a, _b, _c, _d;
|
|
87
|
+
fade.start();
|
|
88
|
+
const id = String(active.id);
|
|
89
|
+
setActiveId(id);
|
|
90
|
+
onDragStateChange === null || onDragStateChange === void 0 ? void 0 : onDragStateChange(id);
|
|
91
|
+
const treeWidth = (_b = (_a = treeRef.current) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect().width) !== null && _b !== void 0 ? _b : 0;
|
|
92
|
+
const rowWidth = (_d = (_c = active.rect.current.initial) === null || _c === void 0 ? void 0 : _c.width) !== null && _d !== void 0 ? _d : treeWidth;
|
|
93
|
+
setOverlayWidth(overlay === 'full' ? rowWidth : Math.min(rowWidth, treeWidth * OVERLAY_MAX_RATIO));
|
|
94
|
+
};
|
|
95
|
+
const onDragMove = ({ active, delta, activatorEvent }) => {
|
|
96
|
+
var _a;
|
|
97
|
+
const rect = active.rect.current.translated;
|
|
98
|
+
const pointerY = (_a = getPointerY(activatorEvent, delta.y)) !== null && _a !== void 0 ? _a : (rect ? rect.top + rect.height / 2 : null);
|
|
99
|
+
if (pointerY === null)
|
|
100
|
+
return;
|
|
101
|
+
lastPointer.current = { id: String(active.id), y: pointerY, x: delta.x };
|
|
102
|
+
const { centerId } = dropTarget.update(String(active.id), pointerY, delta.x);
|
|
103
|
+
hoverExpand.check(String(active.id), centerId);
|
|
104
|
+
};
|
|
105
|
+
const isOrigin = (id, target) => isOriginProjection(model, id, target);
|
|
106
|
+
const finish = (apply) => {
|
|
107
|
+
var _a;
|
|
108
|
+
const { projection } = dropTarget;
|
|
109
|
+
const id = activeId;
|
|
110
|
+
setActiveId(null);
|
|
111
|
+
onDragStateChange === null || onDragStateChange === void 0 ? void 0 : onDragStateChange(null);
|
|
112
|
+
hoverExpand.clear();
|
|
113
|
+
fade.stop();
|
|
114
|
+
lastPointer.current = null;
|
|
115
|
+
dropTarget.reset();
|
|
116
|
+
const node = id ? (_a = model.entries.get(id)) === null || _a === void 0 ? void 0 : _a.node : undefined;
|
|
117
|
+
// Узел вернули на прежнее место — как отмена (Escape): ничего не меняется
|
|
118
|
+
if (apply && projection && node && !isOrigin(id, projection))
|
|
119
|
+
onMove(projection.move, { node, projection });
|
|
120
|
+
};
|
|
121
|
+
const activeNode = activeId ? (_b = model.entries.get(activeId)) === null || _b === void 0 ? void 0 : _b.node : undefined;
|
|
122
|
+
const renderRow = (context) => (_jsx(DragRow, { context: context, locked: isLocked(context.node), expanding: context.id === expandingId, expandDelay: expandOnHoverDelay || undefined, atOrigin: atOrigin }));
|
|
123
|
+
// dnd kit по умолчанию объявляет перетаскивание по-английски: подставляем строки языка
|
|
124
|
+
const nameOf = (id) => {
|
|
125
|
+
const entry = model.entries.get(String(id));
|
|
126
|
+
const title = entry ? nodeTitle(entry.node) : undefined;
|
|
127
|
+
return typeof title === 'string' || typeof title === 'number' ? String(title) : String(id);
|
|
128
|
+
};
|
|
129
|
+
const accessibility = {
|
|
130
|
+
screenReaderInstructions: { draggable: t('treeDnd.instructions') },
|
|
131
|
+
announcements: {
|
|
132
|
+
onDragStart: ({ active }) => t('treeDnd.start', { name: nameOf(active.id) }),
|
|
133
|
+
onDragOver: ({ active, over, }) => over && over.id !== active.id
|
|
134
|
+
? t('treeDnd.over', { name: nameOf(active.id), target: nameOf(over.id) })
|
|
135
|
+
: undefined,
|
|
136
|
+
onDragEnd: ({ active }) => t('treeDnd.end', { name: nameOf(active.id) }),
|
|
137
|
+
onDragCancel: ({ active }) => t('treeDnd.cancel', { name: nameOf(active.id) }),
|
|
138
|
+
},
|
|
139
|
+
};
|
|
140
|
+
const { projection } = dropTarget;
|
|
141
|
+
// Место вставки совпало с прежним (или его пока нет): отдельная заготовка не нужна, ею служит исходная строка
|
|
142
|
+
const atOrigin = Boolean(activeId) && (!projection || isOrigin(activeId, projection));
|
|
143
|
+
const placeholder = projection && activeNode && !atOrigin
|
|
144
|
+
? {
|
|
145
|
+
afterId: projection.afterId,
|
|
146
|
+
guides: getPlaceholderGuides(model, projection.move),
|
|
147
|
+
node: activeNode,
|
|
148
|
+
}
|
|
149
|
+
: undefined;
|
|
150
|
+
return (_jsxs(DndContext, { sensors: sensors, accessibility: accessibility, onDragStart: onDragStart, onDragMove: onDragMove, onDragEnd: () => finish(true), onDragCancel: () => finish(false), children: [_jsx("div", { ref: wrapperRef, className: styles.wrapper, "data-dragging": activeId ? '' : undefined, children: _jsx(Tree, { ...treeProps, ref: treeRef, nodes: nodes, renderRow: renderRow, expanded: expanded, onExpandedChange: changeExpanded, pauseMotion: Boolean(activeId), forceCollapsed: activeId ? [activeId] : undefined, placeholder: placeholder }) }), _jsx(DragOverlay, { dropAnimation: null, modifiers: [placeOverlay], children: activeNode ? (_jsx("div", { ref: overlayRef, className: overlay === 'full' ? styles.overlayFull : styles.overlay, style: { width: overlayWidth }, "data-testid": "tree-dnd-overlay", children: renderOverlay ? renderOverlay(activeNode) : nodeTitle(activeNode) })) : null })] }));
|
|
151
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
import type { DropProjection, TreeMove, TreeNodeData, TreeProps } from '@lt-ui/uikit';
|
|
3
|
+
/** Настройка прозрачности копии над отступом и линиями места вставки */
|
|
4
|
+
export type TreeDndOverlayFade = {
|
|
5
|
+
/**
|
|
6
|
+
* Ширина мягкого края прозрачной части, px.
|
|
7
|
+
* @default 28
|
|
8
|
+
*/
|
|
9
|
+
width?: number;
|
|
10
|
+
/**
|
|
11
|
+
* Непрозрачность части копии над отступом и линиями (0 — полностью прозрачная, 1 — эффекта нет).
|
|
12
|
+
* @default 0.25
|
|
13
|
+
*/
|
|
14
|
+
alpha?: number;
|
|
15
|
+
/**
|
|
16
|
+
* За сколько мс эффект включается и выключается.
|
|
17
|
+
* @default 220
|
|
18
|
+
*/
|
|
19
|
+
duration?: number;
|
|
20
|
+
};
|
|
21
|
+
export type TreeDndMoveInfo<T = unknown> = {
|
|
22
|
+
node: TreeNodeData<T>;
|
|
23
|
+
/** Куда встал узел: родитель, позиция и уровень */
|
|
24
|
+
projection: DropProjection;
|
|
25
|
+
};
|
|
26
|
+
export type TreeDndProps<T = unknown> = Omit<TreeProps<T>, 'renderRow' | 'forceCollapsed'> & {
|
|
27
|
+
/**
|
|
28
|
+
* Узел отпущен в допустимом месте. Примените перемещение к данным: `setNodes(moveTreeNode(nodes, move))`.
|
|
29
|
+
* Ветка, в которую положили узел, при необходимости раскройте через `expanded`.
|
|
30
|
+
*/
|
|
31
|
+
onMove: (move: TreeMove, info: TreeDndMoveInfo<T>) => void;
|
|
32
|
+
/** Можно ли тащить узел. По умолчанию — любой, кроме отключённых */
|
|
33
|
+
canDrag?: (node: TreeNodeData<T>) => boolean;
|
|
34
|
+
/** Можно ли положить узел в родителя (`null` — корень) */
|
|
35
|
+
canDrop?: (parentId: string | null, node: TreeNodeData<T>) => boolean;
|
|
36
|
+
/**
|
|
37
|
+
* Ширина отступа уровня, px: по горизонтальному смещению указателя выбирается уровень вложенности.
|
|
38
|
+
* @default 28
|
|
39
|
+
*/
|
|
40
|
+
indent?: number;
|
|
41
|
+
/**
|
|
42
|
+
* Раскрывать свёрнутую ветку, если указатель задержался над ней, мс. `false` — не раскрывать.
|
|
43
|
+
* @default 600
|
|
44
|
+
*/
|
|
45
|
+
expandOnHoverDelay?: number | false;
|
|
46
|
+
/**
|
|
47
|
+
* Копия перетаскиваемого узла: `compact` — небольшая плашка с заголовком (не шире половины дерева), `full` — копия
|
|
48
|
+
* строки целиком в её ширину с содержимым `renderOverlay`. Для своих карточек (`renderItem`) нужен `full`.
|
|
49
|
+
* @default 'compact'
|
|
50
|
+
*/
|
|
51
|
+
overlay?: 'compact' | 'full';
|
|
52
|
+
/**
|
|
53
|
+
* Прозрачность части копии, налезающей на отступ и линии места вставки: `width`, `alpha`, `duration`.
|
|
54
|
+
* Незаданные значения берутся по умолчанию; `false` — не делать копию прозрачной.
|
|
55
|
+
*/
|
|
56
|
+
overlayFade?: TreeDndOverlayFade | false;
|
|
57
|
+
/** Содержимое «поднятой» копии узла (по умолчанию — иконка и заголовок) */
|
|
58
|
+
renderOverlay?: (node: TreeNodeData<T>) => ReactNode;
|
|
59
|
+
/** Вызывается при начале и конце перетаскивания */
|
|
60
|
+
onDragStateChange?: (draggingId: string | null) => void;
|
|
61
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { RefObject } from 'react';
|
|
2
|
+
import type { DropProjection, TreeModel } from '@lt-ui/uikit';
|
|
3
|
+
type Params = {
|
|
4
|
+
treeRef: RefObject<HTMLElement | null>;
|
|
5
|
+
wrapperRef: RefObject<HTMLElement | null>;
|
|
6
|
+
model: TreeModel;
|
|
7
|
+
indent: number;
|
|
8
|
+
canDrop?: (parentId: string | null) => boolean;
|
|
9
|
+
};
|
|
10
|
+
export type DropUpdate = {
|
|
11
|
+
projection: DropProjection | null;
|
|
12
|
+
/** Строка, в центральной зоне которой находится указатель (`null` — на границе строк или вне дерева) */
|
|
13
|
+
centerId: string | null;
|
|
14
|
+
};
|
|
15
|
+
/** Вычисляет место вставки по положению указателя над строками дерева */
|
|
16
|
+
export declare function useDropTarget({ treeRef, wrapperRef, model, indent, canDrop }: Params): {
|
|
17
|
+
projection: DropProjection | null;
|
|
18
|
+
update: (activeId: string, pointerY: number, offsetX: number) => DropUpdate;
|
|
19
|
+
reset: (keepLevel?: boolean) => void;
|
|
20
|
+
};
|
|
21
|
+
export {};
|