/
kaws
/
ui-kit-ce
Обзор
Документация
Войти
/
kaws
/
ui-kit-ce
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
develop
packages/tree-dnd/src/common/utils/getProjection/getProjection.ts
87 строк
2 KB
Pavel Uryadyshev
feat(tree-dnd): реализован новый компонент Tree с поддержкой drag-and-drop
09 июл 2025, 13:07
09 июл 2025, 13:07
a06fe68
Код
Авторство
О чём код?
import { arrayMove } from '@dnd-kit/sortable' import { TreeNodeItem, TreeItem } from '../../../types' import { getMaxDepth } from '../getMaxDepth' import { getMinDepth } from '../getMinDepth' import { getParentKey } from '../getParentKey' import { getDepth } from '../getDepth' import { TreeGetters } from '../types' export type GetProjectionArgs<TItem = TreeItem> = { nodes: TreeNodeItem<TItem>[] activeKey: React.Key overKey?: React.Key levelSpacer?: number getters: TreeGetters<TItem> dropzoneOwnerNodeKey?: React.Key } export type Projection = { depth: number parentKey?: React.Key | null } export const getProjection = <TItem = TreeItem>({ nodes, activeKey, overKey, getters, }: GetProjectionArgs<TItem>): Projection => { const { getTreeItemKey } = getters const overKeyIndex = nodes.findIndex( (node) => getTreeItemKey(node as unknown as TItem) === overKey ) const activeKeyIndex = nodes.findIndex( (node) => getTreeItemKey(node as unknown as TItem) === activeKey ) const activeNode = nodes[activeKeyIndex] const activeItemDepth = getDepth(activeNode) const newNodes = arrayMove(nodes, activeKeyIndex, overKeyIndex) const previousNode = newNodes[overKeyIndex - 1] const previousNodeDepth = getDepth(previousNode) const nextNode = newNodes[overKeyIndex + 1] const nextNodeDepth = getDepth(nextNode) const maxDepth = getMaxDepth(previousNode) const minDepth = getMinDepth(nextNode) let depth = activeItemDepth if (previousNodeDepth === nextNodeDepth) { depth = previousNodeDepth || nextNodeDepth } else if (activeItemDepth >= maxDepth) { depth = maxDepth } else if (activeItemDepth < minDepth) { depth = minDepth } const findParentKey = () => { if (depth === 0 || !previousNode) { return undefined } const previousNodeDepth = getDepth(previousNode) const previousNodeParentKey = getParentKey(previousNode) if (previousNodeParentKey && depth === previousNodeDepth) { return previousNodeParentKey } if ( previousNode && previousNodeDepth !== undefined && depth > previousNodeDepth ) { return getTreeItemKey(previousNode as unknown as TItem) } const newParent = newNodes .slice(0, overKeyIndex) .reverse() .find((node) => getDepth(node) === depth) return getParentKey(newParent) } return { depth, parentKey: findParentKey(), } }