본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

트리 컬렉션(Tree Collection)

원문 보기 위키 갱신

트리 컬렉션은 파일 시스템, 내비게이션 메뉴, 조직도 같은 계층적 데이터 구조를 관리하도록 설계된 컬렉션이에요. 트리 구조를 순회하고, 조작하고, 조회할 수 있는 강력한 메서드를 제공해요.

출처: 문서

본문

트리 컬렉션은 파일 시스템, 내비게이션 메뉴, 조직도 같은 계층적 데이터 구조를 관리하도록 설계돼요. 트리 구조를 순회하고, 조작하고, 조회하는 강력한 메서드를 제공해요.

import { createTreeCollection } from '@ark-ui/react/collection'

const treeData = {
  value: 'root',
  label: 'Root',
  children: [
    {
      value: 'folder1',
      label: 'Folder 1',
      children: [
        { value: 'file1', label: 'File 1.txt' },
        { value: 'file2', label: 'File 2.txt' },
      ],
    },
    {
      value: 'folder2',
      label: 'Folder 2',
      children: [
        {
          value: 'subfolder1',
          label: 'Subfolder 1',
          children: [{ value: 'file3', label: 'File 3.txt' }],
        },
      ],
    },
  ],
}

const tree = createTreeCollection({ rootNode: treeData })

내비게이션 메서드(Navigation Methods)

트리 컬렉션은 계층 구조를 탐색하는 다양한 메서드를 제공해요.

첫 번째와 마지막 노드 가져오기(Getting First and Last Nodes)

const firstNode = tree.getFirstNode()
console.log(firstNode?.value) // "folder1"

const lastNode = tree.getLastNode()
console.log(lastNode?.value) // "folder2"

순차 내비게이션(Sequential Navigation)

트리 순회 순서에 따라 다음 또는 이전 노드로 이동해요:

const nextNode = tree.getNextNode('file1')
console.log(nextNode?.value) // "file2"

const previousNode = tree.getPreviousNode('file2')
console.log(previousNode?.value) // "file1"

계층 관계(Hierarchical Relationships)

부모와 자식(Parent and Children)

부모 노드와 자손 노드를 가져와요:

// Get parent node
const parentNode = tree.getParentNode('file1')
console.log(parentNode?.value) // "folder1"

// Get all ancestor nodes
const ancestors = tree.getParentNodes('file3')
console.log(ancestors.map((n) => n.value)) // ["folder2", "subfolder1"]

// Get all descendant nodes
const descendants = tree.getDescendantNodes('folder1')
console.log(descendants.map((n) => n.value)) // ["file1", "file2"]

// Get descendant values only
const descendantValues = tree.getDescendantValues('folder2')
console.log(descendantValues) // ["subfolder1", "file3"]

형제 내비게이션(Sibling Navigation)

형제 노드 사이를 이동해요:

// Assuming we have the index path of "file1"
const indexPath = tree.getIndexPath('file1') // [0, 0]

const nextSibling = tree.getNextSibling(indexPath)
console.log(nextSibling?.value) // "file2"

const previousSibling = tree.getPreviousSibling(indexPath)
console.log(previousSibling) // undefined (no previous sibling)

// Get all siblings
const siblings = tree.getSiblingNodes(indexPath)
console.log(siblings.map((n) => n.value)) // ["file1", "file2"]

인덱스 경로 연산(Index Path Operations)

인덱스 경로를 사용해 노드의 위치를 식별해요:

// Get index path for a value
const indexPath = tree.getIndexPath('file3')
console.log(indexPath) // [1, 0, 0]

// Get value from index path
const value = tree.getValue([1, 0, 0])
console.log(value) // "file3"

// Get full value path (all ancestors + node)
const valuePath = tree.getValuePath([1, 0, 0])
console.log(valuePath) // ["folder2", "subfolder1", "file3"]

// Get node at specific index path
const node = tree.at([1, 0])
console.log(node?.value) // "subfolder1"

트리 조회(Tree Queries)

분기와 리프 감지(Branch and Leaf Detection)

// Check if a node is a branch (has children)
const folder1Node = tree.findNode('folder1')
const isBranch = tree.isBranchNode(folder1Node!)
console.log(isBranch) // true

// Get all branch values
const branchValues = tree.getBranchValues()
console.log(branchValues) // ["folder1", "folder2", "subfolder1"]

트리 순회(Tree Traversal)

커스텀 로직으로 모든 노드를 방문해요:

tree.visit({
  onEnter: (node, indexPath) => {
    console.log(`Visiting: ${node.value} at depth ${indexPath.length}`)

    // Skip certain branches
    if (node.value === 'folder2') {
      return 'skip' // Skip this branch and its children
    }
  },
})

필터링(Filtering)

필터링된 노드로 새 트리를 만들어요:

// Keep only nodes that match criteria
const filteredTree = tree.filter((node, indexPath) => {
  return node.value.includes('file') // Only keep files
})

console.log(filteredTree.getValues()) // ["file1", "file2", "file3"]

트리 조작(Tree Manipulation)

노드 추가(Adding Nodes)

const newFile = { value: 'newfile', label: 'New File.txt' }

// Insert after a specific node
const indexPath = tree.getIndexPath('file1')
const updatedTree = tree.insertAfter(indexPath!, [newFile])

// Insert before a specific node
const updatedTree2 = tree.insertBefore(indexPath!, [newFile])

노드 제거(Removing Nodes)

const indexPath = tree.getIndexPath('file2')
const updatedTree = tree.remove([indexPath!])

console.log(updatedTree.getValues()) // file2 is removed

노드 이동(Moving Nodes)

const fromIndexPaths = [tree.getIndexPath('file1')!]
const toIndexPath = tree.getIndexPath('folder2')!

const updatedTree = tree.move(fromIndexPaths, toIndexPath)
// file1 is now moved under folder2

노드 교체(Replacing Nodes)

const indexPath = tree.getIndexPath('file1')!
const newNode = { value: 'replacedfile', label: 'Replaced File.txt' }

const updatedTree = tree.replace(indexPath, newNode)

유틸리티 메서드(Utility Methods)

평탄화(Flattening)

트리를 평면 구조로 변환해요:

const flatNodes = tree.flatten()
console.log(flatNodes.map((n) => ({ value: n.value, depth: n._indexPath.length })))
// [{ value: "folder1", depth: 1 }, { value: "file1", depth: 2 }, ...]

모든 값 가져오기(Getting All Values)

const allValues = tree.getValues()
console.log(allValues) // ["folder1", "file1", "file2", "folder2", "subfolder1", "file3"]

깊이 계산(Depth Calculation)

const depth = tree.getDepth('file3')
console.log(depth) // 3 (root -> folder2 -> subfolder1 -> file3)

커스텀 노드 타입 다루기(Working with Custom Node Types)

트리 컬렉션이 데이터를 해석하는 방식을 커스터마이즈할 수 있어요:

interface CustomNode {
  id: string
  name: string
  items?: CustomNode[]
  isDisabled?: boolean
}

const customTree = createTreeCollection<CustomNode>({
  rootNode: {
    id: 'root',
    name: 'Root',
    items: [
      { id: '1', name: 'Item 1', isDisabled: false },
      { id: '2', name: 'Item 2', isDisabled: true },
    ],
  },
  nodeToValue: (node) => node.id,
  nodeToString: (node) => node.name,
  nodeToChildren: (node) => node.items,
  isNodeDisabled: (node) => node.isDisabled ?? false,
})

파일 경로로 트리 만들기(Creating Trees from File Paths)

파일 경로에서 트리 구조를 만들어요:

import { createFileTreeCollection } from '@ark-ui/react/collection'

const paths = ['src/components/Button.tsx', 'src/components/Input.tsx', 'src/utils/helpers.ts', 'docs/README.md']

const fileTree = createFileTreeCollection(paths)
console.log(fileTree.getBranchValues()) // ["src", "components", "utils", "docs"]

알아두면 좋은 점(Good to know): 트리 컬렉션은 불변(immutable)이에요. 모든 수정 메서드는 원본을 수정하는 대신 새 트리 인스턴스를 반환해요.

더 알아보기 (Learn more)