269 lines
11 KiB
TypeScript
269 lines
11 KiB
TypeScript
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<Set<number>>(new Set())
|
||
const [activeId, setActiveId] = useState<number | null>(null)
|
||
const [overId, setOverId] = useState<number | null>(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 (
|
||
<DndContext
|
||
sensors={sensors}
|
||
collisionDetection={closestCenter}
|
||
onDragStart={handleDragStart}
|
||
onDragMove={handleDragMove}
|
||
onDragOver={handleDragOver}
|
||
onDragEnd={handleDragEnd}
|
||
>
|
||
{activeNode && (
|
||
<Alert color="blue" variant="light" mb={6} icon={<IconArrowsMove size={16} />}>
|
||
<Text size="xs">
|
||
«{activeNode.label}» станет шагом внутри «{projectedParentLabel || '…'}» — потяните влево/вправо,
|
||
чтобы поменять уровень вложенности
|
||
</Text>
|
||
</Alert>
|
||
)}
|
||
<SortableContext items={sortableIds} strategy={verticalListSortingStrategy}>
|
||
<Box>
|
||
{flatItems.map((node) => (
|
||
<SortableRow
|
||
key={node.id}
|
||
node={node}
|
||
hasChildren={!!node.children?.length}
|
||
collapsed={node.id != null && collapsed.has(node.id)}
|
||
onToggleCollapse={() => node.id != null && toggleCollapse(node.id)}
|
||
onEdit={onEdit}
|
||
onAddChild={onAddChild}
|
||
onDelete={onDelete}
|
||
onDuplicate={onDuplicate}
|
||
/>
|
||
))}
|
||
</Box>
|
||
</SortableContext>
|
||
<DragOverlay>
|
||
{activeNode ? (
|
||
<Paper withBorder p="xs" shadow="md">
|
||
<Group gap={6}>
|
||
<IconGripVertical size={14} />
|
||
<Text size="lg">{nodeIcon(activeNode)}</Text>
|
||
<Text fw={600}>{activeNode.label}</Text>
|
||
</Group>
|
||
</Paper>
|
||
) : null}
|
||
</DragOverlay>
|
||
</DndContext>
|
||
)
|
||
}
|
||
|
||
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 (
|
||
<div ref={setNodeRef} style={style}>
|
||
<Paper withBorder p="xs" mb={4} bg={isRoot ? 'var(--mantine-color-blue-0)' : undefined}>
|
||
<Group justify="space-between" wrap="nowrap">
|
||
<Group gap={6} wrap="nowrap" style={{ minWidth: 0 }}>
|
||
{!isRoot ? (
|
||
<ActionIcon
|
||
variant="subtle"
|
||
size="sm"
|
||
{...attributes}
|
||
{...listeners}
|
||
style={{ cursor: 'grab', touchAction: 'none' }}
|
||
>
|
||
<IconGripVertical size={14} />
|
||
</ActionIcon>
|
||
) : (
|
||
<Tooltip label="Первый шаг дерева нельзя перемещать">
|
||
<Box w={28} />
|
||
</Tooltip>
|
||
)}
|
||
{hasChildren ? (
|
||
<ActionIcon size="sm" variant="subtle" onClick={onToggleCollapse}>
|
||
{collapsed ? <IconChevronRight size={14} /> : <IconChevronDown size={14} />}
|
||
</ActionIcon>
|
||
) : (
|
||
<Box w={22} />
|
||
)}
|
||
<Text size="lg">{nodeIcon(node)}</Text>
|
||
<Box style={{ minWidth: 0 }}>
|
||
<Group gap={6}>
|
||
<Text fw={600} truncate>
|
||
{node.label}
|
||
</Text>
|
||
{isRoot && (
|
||
<Badge size="xs" color="blue" variant="light">
|
||
начало дерева
|
||
</Badge>
|
||
)}
|
||
</Group>
|
||
<Text size="xs" c="dimmed">
|
||
{nodeKindLabel(node)}
|
||
{node.data_key ? ` · запоминает: ${node.data_key} = ${node.data_value}` : ''}
|
||
</Text>
|
||
</Box>
|
||
</Group>
|
||
|
||
<Group gap={2} wrap="nowrap">
|
||
<Tooltip label="Добавить следующий шаг после этой кнопки">
|
||
<ActionIcon variant="subtle" size="sm" color="blue" onClick={() => onAddChild(node)}>
|
||
<IconPlus size={14} />
|
||
</ActionIcon>
|
||
</Tooltip>
|
||
<Tooltip label="Изменить">
|
||
<ActionIcon variant="subtle" size="sm" onClick={() => onEdit(node)}>
|
||
<IconEdit size={14} />
|
||
</ActionIcon>
|
||
</Tooltip>
|
||
<Tooltip label="Сделать копию этого шага со всеми вложенными">
|
||
<ActionIcon variant="subtle" size="sm" onClick={() => onDuplicate(node)}>
|
||
<IconCopy size={14} />
|
||
</ActionIcon>
|
||
</Tooltip>
|
||
<Tooltip label="Удалить (вместе со всеми вложенными шагами)">
|
||
<ActionIcon variant="subtle" size="sm" color="red" onClick={() => onDelete(node)}>
|
||
<IconTrash size={14} />
|
||
</ActionIcon>
|
||
</Tooltip>
|
||
</Group>
|
||
</Group>
|
||
</Paper>
|
||
</div>
|
||
)
|
||
} |