### LazyTreeView Quick Start Example (React)
Source: https://github.com/javierortega95/lazy-tree-view/blob/dev/src/stories/Welcome.mdx
Demonstrates how to initialize and use the LazyTreeView component with initial data and a function to load children lazily. It showcases basic setup for rendering a tree structure with drag and drop enabled.
```tsx
import LazyTreeView from 'lazy-tree-view'
const tree = [
{
id: '1',
name: 'Documents',
children: [
{ id: '2', name: 'Resume.pdf' },
{ id: '3', name: 'Cover Letter.docx' },
],
},
{ id: '4', name: 'README.md' },
]
async function loadChildren(branch) {
const response = await fetch(`/api/branches/${branch.id}/children`)
return response.json()
}
function App() {
return (
)
}
```
--------------------------------
### Development Commands for Lazy Tree View
Source: https://github.com/javierortega95/lazy-tree-view/blob/dev/README.md
Provides essential commands for developing and testing the lazy-tree-view library. Includes installation, running the development environment via Storybook, executing tests, and building the library.
```bash
pnpm install
pnpm storybook # Development environment
pnpm test # Run tests
pnpm build # Build the library
```
--------------------------------
### Install lazy-tree-view using pnpm or npm
Source: https://github.com/javierortega95/lazy-tree-view/blob/dev/README.md
This snippet shows how to add the lazy-tree-view package to your project using either pnpm or npm package managers. It's a prerequisite for using the component in your React application.
```bash
pnpm add lazy-tree-view
# or
npm install lazy-tree-view
```
--------------------------------
### Imperative API Usage in React
Source: https://github.com/javierortega95/lazy-tree-view/blob/dev/README.md
Demonstrates how to control the Lazy Tree View component programmatically using a ref in a React application. It shows examples of adding a node and retrieving the current tree structure.
```tsx
import { useRef } from 'react';
import { LazyTreeViewHandle } from 'lazy-tree-view';
const treeRef = useRef(null);
// Add a node to a branch
treeRef.current?.addNode('branch-1', { id: 'new', name: 'New File' });
// Read the current tree
const tree = treeRef.current?.getTree();
```
--------------------------------
### Configure Tree View Animations with TypeScript/React
Source: https://context7.com/javierortega95/lazy-tree-view/llms.txt
Demonstrates how to configure animation durations or disable animations in the LazyTreeView component. It shows examples of default animations, faster animations using a specified duration, and disabling animations entirely for instant transitions. This component is built with React and TypeScript.
```tsx
import { LazyTreeView } from 'lazy-tree-view'
function App() {
return (
)
}
```
--------------------------------
### Custom React Tree View Renderers with Typed Props
Source: https://context7.com/javierortega95/lazy-tree-view/llms.txt
This React component demonstrates custom rendering for a lazy tree view. It defines typed data for nodes (TaskData, CategoryData) and custom props for item renderers. The example includes a `CategoryBranch` component for rendering categories with specific styling and a `TaskItem` component for rendering tasks with checkboxes and priority indicators. It also shows how to integrate these custom renderers with the `LazyTreeView` component, including handling node updates via a ref.
```tsx
import { useRef, useCallback, FC } from 'react'
import { LazyTreeView } from 'lazy-tree-view'
import type { BranchProps, BaseNodeProps, LazyTreeViewHandle, TreeNode } from 'lazy-tree-view'
// Define custom data types for your nodes
type TaskData = {
priority: 'high' | 'medium' | 'low'
done: boolean
}
type CategoryData = {
color: string
}
// Extra props passed to item renderer
type ItemExtra = {
onToggle: (id: string) => void
}
// Custom branch renderer with typed props
const CategoryBranch: FC> = ({
name,
children,
isOpen,
depth,
data,
onToggleOpen,
}) => {
const doneCount = children.filter(
(c) => (c as { data?: TaskData }).data?.done
).length
return (
)
}
function TaskList() {
const treeRef = useRef(null)
const handleToggle = useCallback((taskId: string) => {
const node = treeRef.current?.getNode(taskId) as { data?: TaskData } | undefined
if (node?.data) {
treeRef.current?.updateNode(taskId, {
data: { ...node.data, done: !node.data.done },
} as Partial)
}
}, [])
const tree: TreeNode<{ data?: TaskData | CategoryData }>[] = [
{
id: 'work',
name: 'Work',
data: { color: '#3b82f6' },
children: [
{ id: 't1', name: 'Review PRs', data: { priority: 'high', done: false } },
{ id: 't2', name: 'Update docs', data: { priority: 'medium', done: true } },
],
isOpen: true,
hasFetched: true,
},
{
id: 'personal',
name: 'Personal',
data: { color: '#10b981' },
children: [
{ id: 't3', name: 'Grocery shopping', data: { priority: 'low', done: false } },
],
isOpen: true,
hasFetched: true,
},
]
return (
[]}
branch={CategoryBranch}
item={TaskItem}
itemProps={{ onToggle: handleToggle }}
/>
)
}
```
--------------------------------
### Lazy Loading Callbacks for Lifecycle Monitoring in React
Source: https://context7.com/javierortega95/lazy-tree-view/llms.txt
Illustrates how to use the `onLoadStart`, `onLoadSuccess`, and `onLoadError` callbacks provided by LazyTreeView to monitor and react to the lazy loading process. This enables custom feedback mechanisms like logging or analytics during asynchronous data fetching.
```tsx
import { LazyTreeView } from 'lazy-tree-view'
import type { BranchNode, TreeNode } from 'lazy-tree-view'
async function loadChildren(branch: BranchNode): Promise {
// Simulate different scenarios based on branch name
await new Promise(resolve => setTimeout(resolve, 800))
if (branch.name === 'Error Folder') {
throw new Error('Server error: permission denied')
}
return [
{ id: `${branch.id}-child-1`, name: 'Child A' },
{ id: `${branch.id}-child-2`, name: 'Child B' },
]
}
function App() {
return (
{
console.log(`Loading children for: ${branch.name}`)
}}
onLoadSuccess={(branch, children) => {
console.log(`Loaded ${children.length} children for: ${branch.name}`)
}}
onLoadError={(branch, error) => {
console.error(`Failed to load ${branch.name}:`, (error as Error).message)
// The component shows a retry button automatically
}}
/>
)
}
```
--------------------------------
### Basic LazyTreeView Component Usage in React
Source: https://context7.com/javierortega95/lazy-tree-view/llms.txt
Demonstrates the fundamental usage of the LazyTreeView component in a React application. It shows how to define initial tree data and provide an asynchronous function to load children when branches are expanded. Includes essential props like `initialTree`, `loadChildren`, `allowDragAndDrop`, and event handlers.
```tsx
import { LazyTreeView } from 'lazy-tree-view'
import 'lazy-tree-view/styles.css'
import type { TreeNode, BranchNode } from 'lazy-tree-view'
// Define initial tree structure
const initialTree: TreeNode[] = [
{
id: 'folder-1',
name: 'Documents',
children: [
{ id: 'file-1', name: 'Resume.pdf' },
{ id: 'file-2', name: 'Cover Letter.docx' },
],
isOpen: true,
hasFetched: true,
},
{
id: 'folder-2',
name: 'Projects',
children: [], // Children will be loaded on expand
},
{ id: 'file-3', name: 'README.md' },
]
// Async function to load children when a branch expands
async function loadChildren(branch: BranchNode): Promise {
const response = await fetch(`/api/folders/${branch.id}/children`)
if (!response.ok) throw new Error('Failed to load children')
return response.json()
}
function App() {
return (
console.log('Tree updated:', newTree)}
onDrop={(data) => console.log('Dropped:', data.source.name, data.position, data.target.name)}
style={{ minWidth: 300, minHeight: 400 }}
/>
)
}
```
--------------------------------
### Basic React Tree View with Lazy Loading
Source: https://github.com/javierortega95/lazy-tree-view/blob/dev/README.md
Demonstrates a minimal implementation of the LazyTreeView component. It includes importing the component and its CSS, defining initial tree data, and providing an asynchronous function to load children for branches on demand. This is the core usage pattern for the library.
```tsx
import { LazyTreeView } from 'lazy-tree-view'
import 'lazy-tree-view/styles.css'
const tree = [
{
id: '1',
name: 'Documents',
children: [
{ id: '2', name: 'Resume.pdf' },
{ id: '3', name: 'Cover Letter.docx' },
],
},
{ id: '4', name: 'README.md' },
]
async function loadChildren(branch) {
const res = await fetch(`/api/branches/${branch.id}/children`)
return res.json()
}
function App() {
return (
)
}
```
--------------------------------
### Control Lazy Tree View with Imperative API (React)
Source: https://context7.com/javierortega95/lazy-tree-view/llms.txt
Demonstrates programmatic control of the Lazy Tree View component using a ref. It covers adding, removing, updating, moving nodes, replacing the entire tree, and reading its current state. Requires React and the 'lazy-tree-view' library.
```tsx
import { useRef } from 'react'
import { LazyTreeView, DropPosition } from 'lazy-tree-view'
import type { LazyTreeViewHandle, TreeNode } from 'lazy-tree-view'
function TreeManager() {
const treeRef = useRef(null)
const handleAddNode = () => {
// Add a new item to root level (parentId = null)
treeRef.current?.addNode(null, {
id: 'new-file',
name: 'New Document.txt',
})
// Add a new folder with children to a specific parent
treeRef.current?.addNode('folder-1', {
id: 'new-folder',
name: 'New Folder',
children: [],
hasFetched: true,
})
}
const handleRemoveNode = () => {
// Remove a node and all its children
treeRef.current?.removeNode('node-to-delete')
}
const handleUpdateNode = () => {
// Update node properties (e.g., rename)
treeRef.current?.updateNode('file-1', { name: 'Renamed Document.pdf' })
}
const handleMoveNode = () => {
// Move a node: before, inside, or after another node
treeRef.current?.moveNode('file-1', 'folder-2', DropPosition.Inside)
treeRef.current?.moveNode('file-2', 'file-3', DropPosition.Before)
treeRef.current?.moveNode('file-4', 'file-3', DropPosition.After)
}
const handleReplaceTree = () => {
// Replace the entire tree
treeRef.current?.setTree([
{ id: 'new-1', name: 'Fresh Start' },
{ id: 'new-2', name: 'New Folder', children: [], hasFetched: true },
])
}
const handleReadTree = () => {
// Get current tree structure
const tree = treeRef.current?.getTree()
console.log('Current tree:', JSON.stringify(tree, null, 2))
// Find a specific node
const node = treeRef.current?.getNode('file-1')
console.log('Found node:', node?.name)
}
return (
[]}
/>
)
}
```
--------------------------------
### Enable Keyboard Navigation in React Lazy Tree View
Source: https://context7.com/javierortega95/lazy-tree-view/llms.txt
This snippet demonstrates the usage of the `LazyTreeView` component with its built-in keyboard navigation enabled. No specific configuration is required for keyboard navigation; it automatically follows the WAI-ARIA TreeView pattern. Users can interact with the tree using standard keyboard shortcuts once the tree component is focused.
```tsx
import { LazyTreeView } from 'lazy-tree-view'
import type { TreeNode } from 'lazy-tree-view'
// Keyboard shortcuts (automatic):
// ↑ / ↓ - Navigate between visible nodes
// → - Expand branch or move to first child
// ← - Collapse branch or move to parent
// Enter / Space - Toggle branch open/close
// Home - Jump to first node
// End - Jump to last visible node
// Tab - Move to next node
// Shift + Tab - Move to previous node
const tree: TreeNode[] = [
{
id: '1',
name: 'Fruits',
children: [
{ id: '2', name: 'Apple' },
{ id: '3', name: 'Banana' },
],
isOpen: true,
hasFetched: true,
},
{
id: '4',
name: 'Vegetables',
children: [
{ id: '5', name: 'Carrot' },
{
id: '6',
name: 'Peppers',
children: [
{ id: '7', name: 'Red' },
{ id: '8', name: 'Green' },
],
hasFetched: true,
},
],
isOpen: true,
hasFetched: true,
},
]
function App() {
return (
[]}
allowDragAndDrop={false}
/>
)
}
```
--------------------------------
### Custom Tree View Renderers with TypeScript
Source: https://github.com/javierortega95/lazy-tree-view/blob/dev/README.md
Demonstrates how to replace default branch and item components in LazyTreeView with custom React components. It utilizes TypeScript generics to pass additional props like 'icon' for branches and 'onSelect' for items, enhancing component flexibility.
```tsx
import { LazyTreeView, type BranchProps, type BaseNodeProps } from 'lazy-tree-view'
type BranchExtra = { icon: string }
type ItemExtra = { onSelect: (id: string) => void }
const MyBranch = ({ isOpen, name, icon, onToggleOpen }: BranchProps) => (
)
console.log('Selected:', id) }}
/>
```
--------------------------------
### Lazy Tree View Type Definitions
Source: https://context7.com/javierortega95/lazy-tree-view/llms.txt
This snippet showcases the core type definitions provided by the lazy-tree-view library. These types are essential for building type-safe tree structures and custom components. It includes definitions for nodes, functions, component props, and drag-and-drop data structures, along with utility functions like `isBranchNode`.
```tsx
import type {
// Node types
NodeId, // string - unique identifier for a tree node
BaseNode, // { id: NodeId; name: string } & T - leaf node
BranchNode, // BaseNode with children array and state
TreeNode, // BaseNode | BranchNode - union type
BranchState, // { isOpen?, isLoading?, hasFetched?, error? }
// Function types
LoadChildrenFn, // (branch: BranchNode) => Promise
CanDropFn, // (data: DropData) => boolean
// Component props
LazyTreeViewProps,
LazyTreeViewHandle,
BranchProps, // Props for custom branch renderer
BaseNodeProps, // Props for custom item renderer
// Drag and drop
DropData, // { source, target, position, prevParent, nextParent, prevIndex, nextIndex }
DragClassNames, // { dragOver, dragBefore, dragAfter, dropNotAllowed }
} from 'lazy-tree-view'
import { DropPosition, isBranchNode } from 'lazy-tree-view'
// DropPosition enum values
DropPosition.Before // 'before'
DropPosition.Inside // 'inside'
DropPosition.After // 'after'
// Type guard to check if a node is a branch
const node: TreeNode = { id: '1', name: 'Test' }
if (isBranchNode(node)) {
console.log('Has children:', node.children.length)
}
```
--------------------------------
### Implement Drag Handle Mode in React
Source: https://context7.com/javierortega95/lazy-tree-view/llms.txt
This snippet demonstrates how to enable drag handle mode in a React application using the lazy-tree-view component. It involves creating custom branch and item renderers that include a draggable element, allowing users to initiate drag operations on specific elements within a tree node. The `useDragHandle` prop must be set to `true` on the `LazyTreeView` component.
```tsx
import { FC, useRef, DragEvent } from 'react'
import { LazyTreeView } from 'lazy-tree-view'
import type { BranchProps, BaseNodeProps, TreeNode } from 'lazy-tree-view'
const DragHandleIcon: FC = () => (
)
const HandleBranch: FC = ({ name, isOpen, depth, onToggleOpen, onDragStart }) => {
const nodeRef = useRef(null)
const handleDragStart = (e: DragEvent) => {
if (nodeRef.current) e.dataTransfer.setDragImage(nodeRef.current, 0, 0)
onDragStart?.(e)
}
return (