From 95478afec796d09b4f8e9b366e793a54cd16fc6f Mon Sep 17 00:00:00 2001 From: romanskijdev Date: Thu, 16 Jul 2026 16:08:09 +0300 Subject: [PATCH] Upodate flow nodes constructor --- package-lock.json | 56 ++++ package.json | 3 + src/features/flowNodes/hooks/useFlowNodes.ts | 34 ++- src/features/flowNodes/utils/flattenTree.ts | 128 +++++++++ src/pages/flowNodes/FlowTreePage.tsx | 64 +---- .../components/FlowNodeEditModal.tsx | 43 ++- .../flowNodes/components/FlowTreeNode.tsx | 181 ------------ .../flowNodes/components/SortableFlowTree.tsx | 269 ++++++++++++++++++ 8 files changed, 539 insertions(+), 239 deletions(-) create mode 100644 src/features/flowNodes/utils/flattenTree.ts delete mode 100644 src/pages/flowNodes/components/FlowTreeNode.tsx create mode 100644 src/pages/flowNodes/components/SortableFlowTree.tsx diff --git a/package-lock.json b/package-lock.json index 075320d..0402a23 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,9 @@ "name": "ruspet_admin_frontend", "version": "0.0.0", "dependencies": { + "@dnd-kit/core": "^6.3.1", + "@dnd-kit/sortable": "^10.0.0", + "@dnd-kit/utilities": "^3.2.2", "@mantine/core": "^9.4.1", "@mantine/dates": "^9.4.1", "@mantine/form": "^9.3.1", @@ -298,6 +301,59 @@ "node": ">=6.9.0" } }, + "node_modules/@dnd-kit/accessibility": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz", + "integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0" + } + }, + "node_modules/@dnd-kit/core": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz", + "integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==", + "license": "MIT", + "dependencies": { + "@dnd-kit/accessibility": "^3.1.1", + "@dnd-kit/utilities": "^3.2.2", + "tslib": "^2.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@dnd-kit/sortable": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/@dnd-kit/sortable/-/sortable-10.0.0.tgz", + "integrity": "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==", + "license": "MIT", + "dependencies": { + "@dnd-kit/utilities": "^3.2.2", + "tslib": "^2.0.0" + }, + "peerDependencies": { + "@dnd-kit/core": "^6.3.0", + "react": ">=16.8.0" + } + }, + "node_modules/@dnd-kit/utilities": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz", + "integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0" + } + }, "node_modules/@emnapi/core": { "version": "1.10.0", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz", diff --git a/package.json b/package.json index 475a2dd..9a1d8e4 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,9 @@ "preview": "vite preview" }, "dependencies": { + "@dnd-kit/core": "^6.3.1", + "@dnd-kit/sortable": "^10.0.0", + "@dnd-kit/utilities": "^3.2.2", "@mantine/core": "^9.4.1", "@mantine/dates": "^9.4.1", "@mantine/form": "^9.3.1", diff --git a/src/features/flowNodes/hooks/useFlowNodes.ts b/src/features/flowNodes/hooks/useFlowNodes.ts index a3c1979..46102ea 100644 --- a/src/features/flowNodes/hooks/useFlowNodes.ts +++ b/src/features/flowNodes/hooks/useFlowNodes.ts @@ -76,8 +76,8 @@ export function useDeleteFlowNode() { }) } -// Перемещение узла — используется и для ↑/↓ среди соседей, и для -// "поднять/опустить уровень" (там просто другой new_parent_id). +// Перемещение узла — используется для ↑/↓ среди соседей и для +// "поднять/опустить уровень" точечно (см. treeWalk.ts). export function useMoveFlowNode() { const queryClient = useQueryClient() return useMutation({ @@ -95,6 +95,36 @@ export function useMoveFlowNode() { }) } +// НОВОЕ: пакетное перемещение для drag&drop — план из buildReorderPlan +// (см. treeFlatten.ts) может включать несколько узлов сразу (переиндексация +// старой и новой групп соседей). Отправляем всё параллельно и обновляем +// дерево ОДНИМ инвалидейтом в конце, а не на каждый отдельный вызов — +// иначе список будет дёргаться на каждом промежуточном ответе. +export function useReorderNodes() { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: async (ops: { id: number; new_parent_id: number | null; new_sort_order: number }[]) => { + await Promise.all( + ops.map((op) => + flowNodesApi.move(op.id, { new_parent_id: op.new_parent_id, new_sort_order: op.new_sort_order }) + ) + ) + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] }) + }, + onError: (error: any) => { + notifications.show({ + title: 'Не получилось', + message: + error.response?.data?.error_description || 'Не удалось переместить шаг — дерево вернётся к прежнему виду', + color: 'red', + }) + queryClient.invalidateQueries({ queryKey: [FLOW_NODES_QUERY_KEY] }) + }, + }) +} + export function useDuplicateFlowNode() { const queryClient = useQueryClient() return useMutation({ diff --git a/src/features/flowNodes/utils/flattenTree.ts b/src/features/flowNodes/utils/flattenTree.ts new file mode 100644 index 0000000..bdfcf0c --- /dev/null +++ b/src/features/flowNodes/utils/flattenTree.ts @@ -0,0 +1,128 @@ +import { arrayMove } from '@dnd-kit/sortable' +import type { ApprovalFlowNode } from '@/types/api' + +export interface FlatFlowNode extends ApprovalFlowNode { + depth: number +} + +// Разворачивает дерево в плоский список для отображения в виде сортируемого +// списка. parent_id уже есть на каждом узле (приходит с бэкенда) — отдельно +// его не вычисляем. +export function flattenTree(nodes: ApprovalFlowNode[], collapsed: Set): FlatFlowNode[] { + const result: FlatFlowNode[] = [] + const walk = (list: ApprovalFlowNode[], depth: number) => { + for (const node of list) { + result.push({ ...node, depth }) + if (node.children?.length && node.id != null && !collapsed.has(node.id)) { + walk(node.children, depth + 1) + } + } + } + walk(nodes, 0) + return result +} + +export interface Projection { + depth: number + parentId: number | null +} + +// Классический алгоритм проекции для sortable-дерева (как в примере +// "Sortable Tree" из документации dnd-kit): по горизонтальному смещению +// курсора во время перетаскивания решаем, на какую глубину и к какому +// родителю попадёт узел, если отпустить его над overId прямо сейчас. +// +// ВАЖНО: глубина никогда не может быть 0 — на верхнем уровне дерева +// категории всегда должен быть ровно один узел (корень с ключом, равным +// коду раздела), и он не участвует в перетаскивании. +export function getProjection( + items: FlatFlowNode[], + activeId: number, + overId: number, + dragOffsetX: number, + indentationWidth: number +): Projection { + const activeItemIndex = items.findIndex((n) => n.id === activeId) + const overItemIndex = items.findIndex((n) => n.id === overId) + if (activeItemIndex === -1 || overItemIndex === -1) { + return { depth: 1, parentId: null } + } + + const activeItem = items[activeItemIndex] + const newItems = arrayMove(items, activeItemIndex, overItemIndex) + const previousItem = newItems[overItemIndex - 1] + const nextItem = newItems[overItemIndex + 1] + + const dragDepthDelta = Math.round(dragOffsetX / indentationWidth) + const projectedDepth = activeItem.depth + dragDepthDelta + + const maxDepth = Math.max(previousItem ? previousItem.depth + 1 : 1, 1) + const minDepth = Math.max(nextItem ? nextItem.depth : 1, 1) + + let depth = projectedDepth + if (depth > maxDepth) depth = maxDepth + if (depth < minDepth) depth = minDepth + + let parentId: number | null = null + if (previousItem) { + if (depth === previousItem.depth) { + parentId = previousItem.parent_id ?? null + } else if (depth > previousItem.depth) { + parentId = previousItem.id ?? null + } else { + const newParent = [...newItems] + .slice(0, overItemIndex) + .reverse() + .find((n) => n.depth === depth) + parentId = newParent?.parent_id ?? null + } + } + + return { depth, parentId } +} + +export interface MoveOp { + id: number + new_parent_id: number | null + new_sort_order: number +} + +// Строит план обновлений после drag&drop одного узла: полностью +// переиндексирует группу соседей, откуда узел ушёл, и группу, куда он +// попал (несколько лишних вызовов API по сравнению со строгим минимумом, +// зато гарантированно нет дублей/дыр в sort_order). +export function buildReorderPlan( + tree: ApprovalFlowNode[], + activeId: number, + newParentId: number | null, + overId: number +): MoveOp[] { + const flat = flattenTree(tree, new Set()) + const active = flat.find((n) => n.id === activeId) + if (!active) return [] + + const oldParentId = active.parent_id ?? null + + const oldSiblings = flat.filter((n) => (n.parent_id ?? null) === oldParentId && n.id !== activeId) + const newSiblingsWithoutActive = flat.filter((n) => (n.parent_id ?? null) === newParentId && n.id !== activeId) + + const overIdx = newSiblingsWithoutActive.findIndex((n) => n.id === overId) + const insertAt = overIdx === -1 ? newSiblingsWithoutActive.length : overIdx + + const newSiblings = [...newSiblingsWithoutActive] + newSiblings.splice(insertAt, 0, active) + + const ops: MoveOp[] = newSiblings.map((n, idx) => ({ + id: n.id!, + new_parent_id: newParentId, + new_sort_order: idx, + })) + + if (oldParentId !== newParentId) { + oldSiblings.forEach((n, idx) => { + ops.push({ id: n.id!, new_parent_id: oldParentId, new_sort_order: idx }) + }) + } + + return ops +} \ No newline at end of file diff --git a/src/pages/flowNodes/FlowTreePage.tsx b/src/pages/flowNodes/FlowTreePage.tsx index 8bf2aa3..c1fe613 100644 --- a/src/pages/flowNodes/FlowTreePage.tsx +++ b/src/pages/flowNodes/FlowTreePage.tsx @@ -10,7 +10,6 @@ import { Stack, Badge, Alert, - ActionIcon, Tooltip, } from '@mantine/core' import { IconPlus, IconInfoCircle, IconBook, IconFolderPlus, IconRefresh } from '@tabler/icons-react' @@ -19,16 +18,15 @@ import { useCategories } from '@/features/categories/hooks/useCategories' import { useFlowNodesTree, useDeleteFlowNode, - useMoveFlowNode, useDuplicateFlowNode, useReloadBot, } from '@/features/flowNodes/hooks/useFlowNodes' -import { findParent, getPromoteMove, getDemoteMove } from '@/features/flowNodes/utils/treeWalk' +import { findParent } from '@/features/flowNodes/utils/treeWalk' import type { ApprovalFlowNode, ApprovalTopicCategory } from '@/types/api' import { useNavigate } from 'react-router-dom' import CategoryCreateModal from "@/pages/flowNodes/components/CategoryCreateModal.tsx"; import FlowNodeEditModal from "@/pages/flowNodes/components/FlowNodeEditModal.tsx"; -import FlowTreeNode from "@/pages/flowNodes/components/FlowTreeNode.tsx"; +import SortableFlowTree from "@/pages/flowNodes/components/SortableFlowTree.tsx"; import TreeHealthPanel from "@/pages/flowNodes/components/TreeHealthPanel.tsx"; export default function FlowTreePage() { @@ -48,7 +46,6 @@ export default function FlowTreePage() { const tree = treeData?.data || [] const deleteFlowNode = useDeleteFlowNode() - const moveFlowNode = useMoveFlowNode() const duplicateFlowNode = useDuplicateFlowNode() const reloadBot = useReloadBot() @@ -97,30 +94,6 @@ export default function FlowTreePage() { const handleDuplicate = (node: ApprovalFlowNode) => duplicateFlowNode.mutate(node.id!) - const handleMoveUp = (node: ApprovalFlowNode) => { - const parent = findParent(tree, node.id!) - const siblings = parent ? parent.children! : tree - const index = siblings.findIndex((n) => n.id === node.id) - if (index > 0) moveFlowNode.mutate({ id: node.id!, data: { new_sort_order: index - 1 } }) - } - - const handleMoveDown = (node: ApprovalFlowNode) => { - const parent = findParent(tree, node.id!) - const siblings = parent ? parent.children! : tree - const index = siblings.findIndex((n) => n.id === node.id) - if (index < siblings.length - 1) moveFlowNode.mutate({ id: node.id!, data: { new_sort_order: index + 1 } }) - } - - const handlePromote = (node: ApprovalFlowNode) => { - const target = getPromoteMove(tree, node) - if (target) moveFlowNode.mutate({ id: node.id!, data: target }) - } - - const handleDemote = (node: ApprovalFlowNode) => { - const target = getDemoteMove(tree, node) - if (target) moveFlowNode.mutate({ id: node.id!, data: target }) - } - return ( @@ -184,9 +157,10 @@ export default function FlowTreePage() { } color="blue" variant="light"> - Значки справа от каждого шага: ↑ ↓ — переставить среди соседних кнопок; стрелки с - отступом — поднять/опустить на другой уровень вложенности; + — добавить следующий - шаг; ✏️ — изменить; 📋 — сделать копию; 🗑 — удалить. Всё сохраняется сразу. + Перетаскивайте шаги за значок ⠿ слева, чтобы менять порядок и вложенность — тяните + влево/вправо во время перетаскивания, чтобы изменить уровень. Первый шаг дерева + (с пометкой «начало дерева») не перетаскивается. + — добавить следующий шаг; + ✏️ — изменить; 📋 — сделать копию; 🗑 — удалить. Всё сохраняется сразу. @@ -204,25 +178,13 @@ export default function FlowTreePage() { ) : ( - - {tree.map((node, idx) => ( - - ))} - + )} diff --git a/src/pages/flowNodes/components/FlowNodeEditModal.tsx b/src/pages/flowNodes/components/FlowNodeEditModal.tsx index 31b1034..108450c 100644 --- a/src/pages/flowNodes/components/FlowNodeEditModal.tsx +++ b/src/pages/flowNodes/components/FlowNodeEditModal.tsx @@ -31,6 +31,7 @@ import { } from '@tabler/icons-react' import { useCreateFlowNode, useUpdateFlowNode, usePreviewFlow } from '@/features/flowNodes/hooks/useFlowNodes' import { useCreateTopic } from '@/features/topics/hooks/useTopics' +import { useCategory } from '@/features/categories/hooks/useCategories' import type { CreateTopicRequest } from '@/api/topics' import { collectFromPath, @@ -97,6 +98,7 @@ export default function FlowNodeEditModal({ const updateFlowNode = useUpdateFlowNode() const createTopic = useCreateTopic() const previewFlow = usePreviewFlow(categoryId) + const { data: category } = useCategory(categoryId) const [showAdvanced, setShowAdvanced] = useState(false) const [showTemplates, setShowTemplates] = useState(false) @@ -128,6 +130,9 @@ export default function FlowNodeEditModal({ key: (v) => { if (!v || v.length < 2) return 'Слишком короткий технический ключ' if (!/^[a-z0-9_]+$/.test(v)) return 'Только латинские буквы, цифры и подчёркивания' + if (isRootNode && category?.code && v !== category.code) { + return 'Подождите загрузку раздела — ключ первого шага подставится сам' + } const existingKeys = collectAllKeys(tree) if (existingKeys.includes(v) && (!editNode || editNode.key !== v)) { return 'Такой ключ уже есть в этой категории — измените название' @@ -159,14 +164,27 @@ export default function FlowNodeEditModal({ return withKey?.multi_select_key || '' }, [parentNode]) - // Автогенерация ключа из названия + // Автогенерация ключа из названия — КРОМЕ корневого узла: его ключ + // ОБЯЗАН совпадать с кодом категории. Причина: когда сотрудник нажимает + // кнопку раздела в главном меню бота, бот ищет самый первый узел дерева + // по nodeKey == код категории (см. HandleCallback в telegram_service) — + // у Topic просто нет отдельного способа узнать реальный ключ корня. + // Если ключ корня не совпадёт с кодом раздела — бот не найдёт начало + // дерева и покажет "node not found" в логах, а сотрудник не увидит + // следующий шаг после нажатия кнопки раздела. useEffect(() => { + if (isRootNode) { + if (category?.code && form.values.key !== category.code) { + form.setFieldValue('key', category.code) + } + return + } if (form.values.auto_generate_key && form.values.label) { const parentPrefix = parentNode?.key ? `${parentNode.key}_` : '' form.setFieldValue('key', parentPrefix + slugify(form.values.label)) } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [form.values.label, form.values.auto_generate_key, parentNode]) + }, [form.values.label, form.values.auto_generate_key, parentNode, isRootNode, category?.code]) // Автоподстановка DataKey/DataValue при смене типа/названия useEffect(() => { @@ -398,6 +416,17 @@ export default function FlowNodeEditModal({ required {...form.getInputProps('label')} /> + {isRootNode && ( + } color="blue" variant="light"> + + Это первый шаг дерева — по нему бот находит начало сценария, когда + сотрудник нажимает кнопку раздела в главном меню. Технический ключ этого + шага всегда равен коду раздела:{' '} + {category?.code || '…'} — менять его нельзя, это сделано + автоматически. + + + )} @@ -535,7 +564,7 @@ export default function FlowNodeEditModal({ {showAdvanced ? : } - Дополнительно + Дополнительно (обычно не нужно трогать) @@ -543,8 +572,12 @@ export default function FlowNodeEditModal({ void - onAddChild: (parent: ApprovalFlowNode) => void - onDelete: (node: ApprovalFlowNode) => void - onDuplicate: (node: ApprovalFlowNode) => void - onMoveUp: (node: ApprovalFlowNode) => void - onMoveDown: (node: ApprovalFlowNode) => void - onPromote: (node: ApprovalFlowNode) => void - onDemote: (node: ApprovalFlowNode) => void -} - -function nodeIcon(node: ApprovalFlowNode): string { - if (node.is_input) return '📝' - if (node.is_multi_select) return '☑️' - return '🔘' -} - -function nodeKindLabel(node: ApprovalFlowNode): string { - if (node.is_input) return 'Текстовый ввод — здесь сотрудник пишет заявку' - if (node.is_multi_select) return 'Можно выбрать несколько вариантов' - return 'Кнопка' -} - -export default function FlowTreeNode({ - node, - depth, - siblings, - index, - onEdit, - onAddChild, - onDelete, - onDuplicate, - onMoveUp, - onMoveDown, - onPromote, - onDemote, - }: FlowTreeNodeProps) { - const [expanded, setExpanded] = useState(true) - const hasChildren = !!node.children && node.children.length > 0 - const isRoot = depth === 0 - const hasTemplates = !!(node.message_template || node.code_template) - - return ( - - - - - {hasChildren ? ( - setExpanded(!expanded)}> - {expanded ? : } - - ) : ( - - )} - {nodeIcon(node)} - - - - {node.label} - - {isRoot && ( - - - начало дерева - - - )} - {hasTemplates && ( - - - есть шаблон - - - )} - - - {nodeKindLabel(node)} - {node.data_key ? ` · запоминает: ${node.data_key} = ${node.data_value}` : ''} - - - - - - - onMoveUp(node)}> - - - - - onMoveDown(node)} - > - - - - - onPromote(node)}> - - - - - onDemote(node)}> - - - - - onAddChild(node)}> - - - - - onEdit(node)}> - - - - - onDuplicate(node)}> - - - - - onDelete(node)}> - - - - - - - - {expanded && hasChildren && ( - - {node.children!.map((child, i) => ( - - - - ))} - - )} - - ) -} \ No newline at end of file diff --git a/src/pages/flowNodes/components/SortableFlowTree.tsx b/src/pages/flowNodes/components/SortableFlowTree.tsx new file mode 100644 index 0000000..cb5f2b3 --- /dev/null +++ b/src/pages/flowNodes/components/SortableFlowTree.tsx @@ -0,0 +1,269 @@ +import { useMemo, useState } from 'react' +import { + DndContext, + DragOverlay, + PointerSensor, + useSensor, + useSensors, + closestCenter, + type DragStartEvent, + type DragMoveEvent, + type DragOverEvent, + type DragEndEvent, +} from '@dnd-kit/core' +import { SortableContext, verticalListSortingStrategy, useSortable } from '@dnd-kit/sortable' +import { CSS } from '@dnd-kit/utilities' +import { Paper, Group, Text, ActionIcon, Tooltip, Badge, Box, Alert } from '@mantine/core' +import { + IconGripVertical, + IconPlus, + IconEdit, + IconTrash, + IconCopy, + IconChevronDown, + IconChevronRight, + IconArrowsMove, +} from '@tabler/icons-react' +import type { ApprovalFlowNode } from '@/types/api' +import { useReorderNodes } from '@/features/flowNodes/hooks/useFlowNodes' +import {buildReorderPlan, FlatFlowNode, flattenTree, getProjection} from "@/features/flowNodes/utils/flattenTree.ts"; + +const INDENTATION = 24 + +interface SortableFlowTreeProps { + tree: ApprovalFlowNode[] + onEdit: (node: ApprovalFlowNode) => void + onAddChild: (parent: ApprovalFlowNode) => void + onDelete: (node: ApprovalFlowNode) => void + onDuplicate: (node: ApprovalFlowNode) => void +} + +function nodeIcon(node: ApprovalFlowNode): string { + if (node.is_input) return '📝' + if (node.is_multi_select) return '☑️' + return '🔘' +} + +function nodeKindLabel(node: ApprovalFlowNode): string { + if (node.is_input) return 'Текстовый ввод — здесь сотрудник пишет заявку' + if (node.is_multi_select) return 'Можно выбрать несколько вариантов' + return 'Кнопка' +} + +export default function SortableFlowTree({ tree, onEdit, onAddChild, onDelete, onDuplicate }: SortableFlowTreeProps) { + const [collapsed, setCollapsed] = useState>(new Set()) + const [activeId, setActiveId] = useState(null) + const [overId, setOverId] = useState(null) + const [offsetX, setOffsetX] = useState(0) + const reorder = useReorderNodes() + + const flatItems = useMemo(() => flattenTree(tree, collapsed), [tree, collapsed]) + const sortableIds = useMemo(() => flatItems.map((n) => n.id!), [flatItems]) + + const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } })) + + const projected = useMemo(() => { + if (activeId == null || overId == null) return null + return getProjection(flatItems, activeId, overId, offsetX, INDENTATION) + }, [flatItems, activeId, overId, offsetX]) + + const activeNode = flatItems.find((n) => n.id === activeId) || null + const projectedParentLabel = projected + ? flatItems.find((n) => n.id === projected.parentId)?.label || null + : null + + const toggleCollapse = (id: number) => { + setCollapsed((prev) => { + const next = new Set(prev) + if (next.has(id)) next.delete(id) + else next.add(id) + return next + }) + } + + const handleDragStart = (event: DragStartEvent) => { + setActiveId(event.active.id as number) + setOverId(event.active.id as number) + setOffsetX(0) + } + + const handleDragMove = (event: DragMoveEvent) => { + setOffsetX(event.delta.x) + } + + const handleDragOver = (event: DragOverEvent) => { + setOverId((event.over?.id as number) ?? null) + } + + const handleDragEnd = (event: DragEndEvent) => { + const { active, over } = event + const currentProjected = projected + + setActiveId(null) + setOverId(null) + setOffsetX(0) + + if (!over || !currentProjected) return + + const activeIdNum = active.id as number + const overIdNum = over.id as number + const activeNodeBefore = flatItems.find((n) => n.id === activeIdNum) + if (!activeNodeBefore) return + + const noParentChange = (activeNodeBefore.parent_id ?? null) === currentProjected.parentId + const droppedOnSelf = activeIdNum === overIdNum + if (noParentChange && droppedOnSelf) return + + const ops = buildReorderPlan(tree, activeIdNum, currentProjected.parentId, overIdNum) + if (ops.length > 0) { + reorder.mutate(ops) + } + } + + return ( + + {activeNode && ( + }> + + «{activeNode.label}» станет шагом внутри «{projectedParentLabel || '…'}» — потяните влево/вправо, + чтобы поменять уровень вложенности + + + )} + + + {flatItems.map((node) => ( + node.id != null && toggleCollapse(node.id)} + onEdit={onEdit} + onAddChild={onAddChild} + onDelete={onDelete} + onDuplicate={onDuplicate} + /> + ))} + + + + {activeNode ? ( + + + + {nodeIcon(activeNode)} + {activeNode.label} + + + ) : null} + + + ) +} + +interface SortableRowProps { + node: FlatFlowNode + hasChildren: boolean + collapsed: boolean + onToggleCollapse: () => void + onEdit: (node: ApprovalFlowNode) => void + onAddChild: (parent: ApprovalFlowNode) => void + onDelete: (node: ApprovalFlowNode) => void + onDuplicate: (node: ApprovalFlowNode) => void +} + +function SortableRow({ node, hasChildren, collapsed, onToggleCollapse, onEdit, onAddChild, onDelete, onDuplicate }: SortableRowProps) { + const isRoot = node.depth === 0 + const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ + id: node.id!, + disabled: isRoot, // корень дерева не перетаскивается — его ключ жёстко привязан к коду раздела + }) + + const style = { + transform: CSS.Translate.toString(transform), + transition, + marginLeft: node.depth * INDENTATION, + opacity: isDragging ? 0.4 : 1, + } + + return ( +
+ + + + {!isRoot ? ( + + + + ) : ( + + + + )} + {hasChildren ? ( + + {collapsed ? : } + + ) : ( + + )} + {nodeIcon(node)} + + + + {node.label} + + {isRoot && ( + + начало дерева + + )} + + + {nodeKindLabel(node)} + {node.data_key ? ` · запоминает: ${node.data_key} = ${node.data_value}` : ''} + + + + + + + onAddChild(node)}> + + + + + onEdit(node)}> + + + + + onDuplicate(node)}> + + + + + onDelete(node)}> + + + + + + +
+ ) +} \ No newline at end of file