### Install and Run Hugo Starter Site Source: https://github.com/jorgedanisc/react-arborist/blob/main/modules/docs/README.md This snippet outlines the steps to clone the Hugo starter project, rename it, install dependencies using Yarn, and start the development server. ```shell git clone https://github.com/jameskerr/hugo-starter mv hugo-starter my-cool-site # rename to something you want cd my-cool-site yarn hugo server ``` -------------------------------- ### Install React Arborist with Yarn or NPM Source: https://github.com/jorgedanisc/react-arborist/blob/main/README.md Instructions for adding the react-arborist package to your project using either Yarn or NPM package managers. ```bash yarn add react-arborist ``` ```bash npm install react-arborist ``` -------------------------------- ### Select All Functionality with Keybindings in React Arborist Source: https://github.com/jorgedanisc/react-arborist/blob/main/modules/docs/content/_index.md Shows how to implement a 'select all' feature using custom keybindings. This example configures the `useTree` hook to respond to keyboard shortcuts for common tree operations. ```jsx const tree = useTree(data, { nodes: { id: (d) => d.path, children: (d) => d.items, searchTerm: 'hi', searchFilter: leavesOnly }, selection: { id: (data) => select(Current.getPath) }, opens: { id: (d) => d.path, isOpen: (d) => d.isOpen }, keybindings: (defaults) => { return { ...defaults(), "cmd+a": () => tree.thisThat() "up": () => tree.focus.up() } } }); return ( {} row: () => {} cursor: () => {} }} /> ); ``` -------------------------------- ### Sync Tree State with External Data Store using Callbacks in React Arborist Source: https://github.com/jorgedanisc/react-arborist/blob/main/modules/docs/content/_index.md Provides an example of how to synchronize the React Arborist tree's state (nodes, selection, opens, focus, dnd, treeState) with an external data store using various callback props like `onMove`, `onEdit`, `onCreate`, `onDelete`, and `onOpen`. ```jsx const nodes = useNodes(data) api.move(args)} onEdit={(args) => api.edit(args)} onCreate={() => api.create(args)} onDelete={() => api.destroy(args)} onOpen={(args) => { nodes.addChild(id, {loading: true}) api.fetchChildren(id) }} onSelect={} onFocus={} nodes={{ value: nodes.value, onChange: nodes.set }} selection={{ value: selection.value, onChange: selection.set }} opens={{ value: opens.value, onChange: opens.set }} focus={{ value: focus.value, onChange: focus.set }} dnd={{ value: dnd.value, onChange: dnd.set }} treeState={{ value: state.value, onChange: state.set }} /> ``` -------------------------------- ### Synchronize Tree Selection with External State (React) Source: https://context7.com/jorgedanisc/react-arborist/llms.txt This example shows how to synchronize the selection state of a React Arborist tree with external state management. By providing a `selection` prop, the tree can auto-select and scroll to specific nodes. Event handlers like `onActivate` and `onSelect` are included to manage user interactions and update the external state. ```tsx import { Tree, NodeApi } from "react-arborist"; import { useState } from "react"; function SyncedSelectionTree() { const [selectedId, setSelectedId] = useState(null); const handleActivate = (node: NodeApi) => { // Called on double-click or Enter key setSelectedId(node.id); console.log("Activated:", node.data); }; const handleSelect = (nodes: NodeApi[]) => { // Called whenever selection changes console.log("Selection changed:", nodes.map((n) => n.id)); }; return (
); } ``` -------------------------------- ### Access Tree API Instance via Ref in React Source: https://github.com/jorgedanisc/react-arborist/blob/main/README.md Shows how to get a reference to the Tree API instance using the useRef hook, allowing direct manipulation of the tree, such as selecting all nodes. ```jsx import { useRef, useEffect } from 'react'; function App() { const treeRef = useRef(); useEffect(() => { const tree = treeRef.current; tree.selectAll(); /* See the Tree API reference for all you can do with it. */ }, []); return ; } ``` -------------------------------- ### Define Tree Data Structure Source: https://github.com/jorgedanisc/react-arborist/blob/main/README.md Example of the data structure used to represent the tree nodes. Each node can have an id, name, and an optional children array for nested structures. ```javascript const data = [ { id: "1", name: "Unread" }, { id: "2", name: "Threads" }, { id: "3", name: "Chat Rooms", children: [ { id: "c1", name: "General" }, { id: "c2", name: "Random" }, { id: "c3", name: "Open Source Projects" }, ], }, { id: "4", name: "Direct Messages", children: [ { id: "d1", name: "Alice" }, { id: "d2", name: "Bob" }, { id: "d3", name: "Charlie" }, ], }, ]; ``` -------------------------------- ### Integrate Dynamic Sizing with use-resize-observer Source: https://github.com/jorgedanisc/react-arborist/blob/main/README.md Explains how to use the `use-resize-observer` hook to dynamically obtain the dimensions of a parent container. These dimensions (`width` and `height`) are then passed to the Tree component to enable responsive sizing. ```javascript const { ref, width, height } = useResizeObserver();
``` -------------------------------- ### Drag and Drop Methods Source: https://github.com/jorgedanisc/react-arborist/blob/main/README.md Methods for querying the drag and drop state of nodes. ```APIDOC ## Drag and Drop ### `isDragging(id)` **Description**: Returns true if the node with the specified ID is currently being dragged. **Method**: GET **Endpoint**: N/A (Instance method) **Parameters**: #### Path Parameters - **id** (string) - Required - The ID of the node to check. **Returns**: boolean ### `willReceiveDrop(id)` **Description**: Returns true if the node with the specified ID is internal and is under the currently dragged node, indicating it will receive a drop. **Method**: GET **Endpoint**: N/A (Instance method) **Parameters**: #### Path Parameters - **id** (string) - Required - The ID of the node to check. **Returns**: boolean ``` -------------------------------- ### Change Selection Externally in React Arborist Source: https://github.com/jorgedanisc/react-arborist/blob/main/modules/docs/content/_index.md Demonstrates how to programmatically change the tree's selection from outside the component, for example, based on a chat ID. It uses `useEffect` to synchronize the selection with external state. ```jsx const chatId = useCurrentChatId(); const selection = useSelection(); useEffect(() => { selection.selectOne(chatId, {scroll: 'center'}); }, [chatId]); return ( ); ``` -------------------------------- ### Build and Fingerprint JavaScript for Production Source: https://github.com/jorgedanisc/react-arborist/blob/main/modules/docs/layouts/partials/head/js.html Builds and minifies the main JavaScript file for production environments. It also applies fingerprinting for cache-busting. This configuration is used when the Hugo environment is not 'development'. ```gohtml {{- with resources.Get "js/main.js" }} {{- else }} {{- $opts := dict "minify" true }} {{- with . | js.Build $opts | fingerprint }} {{- end }} {{- end }} {{- end }} ``` -------------------------------- ### Focus Methods Source: https://github.com/jorgedanisc/react-arborist/blob/main/README.md Methods for managing and querying the focus state of nodes within the tree. ```APIDOC ## Focus Methods ### `hasFocus()` **Description**: Returns true if the tree has focus somewhere within it. **Method**: GET **Endpoint**: N/A (Instance method) ### `focus(id)` **Description**: Focus on the node with the specified ID. **Method**: POST **Endpoint**: N/A (Instance method) **Parameters**: #### Path Parameters - **id** (string) - Required - The ID of the node to focus on. ### `isFocused(id)` **Description**: Check if the node with the specified ID is focused. **Method**: GET **Endpoint**: N/A (Instance method) **Parameters**: #### Path Parameters - **id** (string) - Required - The ID of the node to check focus for. **Returns**: boolean ### `pageUp()` **Description**: Move focus up one page within the tree. **Method**: POST **Endpoint**: N/A (Instance method) ### `pageDown()` **Description**: Move focus down one page within the tree. **Method**: POST **Endpoint**: N/A (Instance method) ``` -------------------------------- ### Node API Methods Source: https://context7.com/jorgedanisc/react-arborist/llms.txt Each node instance provides methods and properties for state inspection and manipulation within custom renderers. ```APIDOC ## Node API Methods Each node instance provides methods and properties for state inspection and manipulation within custom renderers. ### Properties - `isRoot` (boolean): True if the node is a root node. - `isLeaf` (boolean): True if the node has no children. - `isInternal` (boolean): True if the node has children. - `isOpen` (boolean): True if the node is expanded. - `isClosed` (boolean): True if the node is collapsed. - `isEditing` (boolean): True if the node is currently in edit mode. - `isSelected` (boolean): True if the node is selected. - `isSelectedStart` (boolean): True if the node is the first in a contiguous selection. - `isSelectedEnd` (boolean): True if the node is the last in a contiguous selection. - `isOnlySelection` (boolean): True if the node is the only selected node. - `isFocused` (boolean): True if the node has focus. - `isDragging` (boolean): True if the node is being dragged. - `willReceiveDrop` (boolean): True if the node is a highlighted drop target. - `next` (Node | null): The next visible node in the tree. - `prev` (Node | null): The previous visible node in the tree. - `nextSibling` (Node | null): The next sibling node in the data structure. - `childIndex` (number): The index of the node among its siblings. ### Methods - `select()`: Selects only this node. - `selectMulti()`: Adds this node to the selection (e.g., for Cmd+click). - `selectContiguous()`: Selects a range of nodes (e.g., for Shift+click). - `deselect()`: Removes this node from the selection. - `toggle()`: Toggles the open/closed state of the node. - `open()`: Expands the node. - `close()`: Collapses the node. - `openParents()`: Expands all ancestor nodes of this node. - `edit()`: Puts the node into edit mode. - `submit(newName)`: Saves the node's name and exits edit mode. - `reset()`: Cancels edit mode without saving changes. - `handleClick(event)`: Built-in click handler that manages selection modifiers (Cmd/Shift). ### Example Usage in Custom Renderer ```tsx import { NodeRendererProps } from "react-arborist"; function NodeWithFullApi({ node, style, dragHandle }: NodeRendererProps) { // State properties (all boolean) const { /* ... properties ... */ } = node; // Navigation accessors const nextVisible = node.next; // Next visible node const prevVisible = node.prev; // Previous visible node const nextSib = node.nextSibling; // Next sibling in data const index = node.childIndex; // Index among siblings // Selection methods const handleSelect = () => { node.select(); // Select only this node // node.selectMulti(); // Add to selection (Cmd+click) // node.selectContiguous(); // Range select (Shift+click) // node.deselect(); // Remove from selection }; // Visibility methods const handleToggle = () => { node.toggle(); // Toggle open/closed // node.open(); // Expand // node.close(); // Collapse // node.openParents(); // Expand all ancestors }; // Edit methods const handleEdit = () => { node.edit(); // Enter edit mode // node.submit("New Name"); // Save and exit edit // node.reset(); // Cancel edit }; // Built-in click handler (handles Cmd/Shift modifiers) return (
{node.isInternal && ( )} {node.data.name}
); } ``` ``` -------------------------------- ### Conditional Rendering in React Templates Source: https://github.com/jorgedanisc/react-arborist/blob/main/modules/docs/layouts/partials/head.html This snippet demonstrates conditional rendering within a React template using Go's templating syntax. It displays the site title on the homepage and a formatted title with the site title on other pages. This pattern is useful for dynamic page titles. ```go {{ if .IsHome }} {{ site.Title }} {{ else }} {{ printf "%s | %s" .Title site.Title }} {{ end }} ``` -------------------------------- ### Render Basic Tree Component with React Arborist Source: https://context7.com/jorgedanisc/react-arborist/llms.txt Demonstrates how to render a basic virtualized and interactive tree view using the `Tree` component from React Arborist. It utilizes `initialData` for setting up the tree structure and configures properties like width, height, and row rendering details. ```tsx import { Tree } from "react-arborist"; // Sample hierarchical data structure const data = [ { id: "1", name: "Documents" }, { id: "2", name: "Pictures" }, { id: "3", name: "Projects", children: [ { id: "3-1", name: "react-app" }, { id: "3-2", name: "node-server" }, { id: "3-3", name: "shared-libs", children: [ { id: "3-3-1", name: "utils" }, { id: "3-3-2", name: "components" }, ], }, ], }, ]; function FileExplorer() { return ( ); } ``` -------------------------------- ### Visibility Methods Source: https://github.com/jorgedanisc/react-arborist/blob/main/README.md Methods for controlling and querying the open/closed state of nodes and their parents. ```APIDOC ## Visibility ### `open(id)` **Description**: Open the node with the specified ID. **Method**: POST **Endpoint**: N/A (Instance method) **Parameters**: #### Path Parameters - **id** (string) - Required - The ID of the node to open. ### `close(id)` **Description**: Close the node with the specified ID. **Method**: POST **Endpoint**: N/A (Instance method) **Parameters**: #### Path Parameters - **id** (string) - Required - The ID of the node to close. ### `toggle(id)` **Description**: Toggle the open state of the node with the specified ID. **Method**: POST **Endpoint**: N/A (Instance method) **Parameters**: #### Path Parameters - **id** (string) - Required - The ID of the node to toggle. ### `openParents(id)` **Description**: Open all parent nodes of the node with the specified ID. **Method**: POST **Endpoint**: N/A (Instance method) **Parameters**: #### Path Parameters - **id** (string) - Required - The ID of the node whose parents should be opened. ### `openSiblings(id)` **Description**: Open all sibling nodes of the node with the specified ID. **Method**: POST **Endpoint**: N/A (Instance method) **Parameters**: #### Path Parameters - **id** (string) - Required - The ID of the node whose siblings should be opened. ### `openAll()` **Description**: Open all internal nodes in the tree. **Method**: POST **Endpoint**: N/A (Instance method) ### `closeAll()` **Description**: Close all internal nodes in the tree. **Method**: POST **Endpoint**: N/A (Instance method) ### `isOpen(id)` **Description**: Returns true if the node with the specified ID is open. **Method**: GET **Endpoint**: N/A (Instance method) **Parameters**: #### Path Parameters - **id** (string) - Required - The ID of the node to check. **Returns**: boolean ``` -------------------------------- ### Build JavaScript for Development (ESM) Source: https://github.com/jorgedanisc/react-arborist/blob/main/modules/docs/layouts/partials/head/js.html Builds the main JavaScript file for development using the ESM format. This configuration is applied when the Hugo environment is set to 'development'. It does not include minification. ```gohtml {{- with resources.Get "js/main.js" }} {{- if eq hugo.Environment "development" }} {{- $opts := dict "format" "esm" }} {{- with . | js.Build }} {{- end }} {{- end }} {{- end }} ``` -------------------------------- ### Selection Methods Source: https://github.com/jorgedanisc/react-arborist/blob/main/README.md Methods for managing and querying the selection state of nodes within the tree. ```APIDOC ## Selection Methods ### `selectedIds` **Description**: Returns a set of IDs of the currently selected nodes. **Method**: GET **Endpoint**: N/A (Instance property) **Returns**: Set ### `selectedNodes` **Description**: Returns an array of the currently selected nodes. **Method**: GET **Endpoint**: N/A (Instance property) **Returns**: NodeApi[] ### `hasNoSelection` **Description**: Returns true if nothing is selected in the tree. **Method**: GET **Endpoint**: N/A (Instance property) **Returns**: boolean ### `hasSingleSelection` **Description**: Returns true if there is only one selection. **Method**: GET **Endpoint**: N/A (Instance property) **Returns**: boolean ### `hasMultipleSelections` **Description**: Returns true if there is more than one selection. **Method**: GET **Endpoint**: N/A (Instance property) **Returns**: boolean ### `isSelected(id)` **Description**: Returns true if the node with the specified ID is selected. **Method**: GET **Endpoint**: N/A (Instance method) **Parameters**: #### Path Parameters - **id** (string) - Required - The ID of the node to check. **Returns**: boolean ### `select(id)` **Description**: Select only the node with the specified ID. **Method**: POST **Endpoint**: N/A (Instance method) **Parameters**: #### Path Parameters - **id** (string) - Required - The ID of the node to select. ### `deselect(id)` **Description**: Deselect the node with the specified ID. **Method**: POST **Endpoint**: N/A (Instance method) **Parameters**: #### Path Parameters - **id** (string) - Required - The ID of the node to deselect. ### `selectMulti(id)` **Description**: Add the node with the specified ID to the current selection. **Method**: POST **Endpoint**: N/A (Instance method) **Parameters**: #### Path Parameters - **id** (string) - Required - The ID of the node to add to the selection. ### `selectContiguous(id)` **Description**: Deselect nodes between the anchor and the last selected node, then select the nodes between the anchor and the node with the specified ID. **Method**: POST **Endpoint**: N/A (Instance method) **Parameters**: #### Path Parameters - **id** (string) - Required - The ID of the node to select contiguously. ### `deselectAll()` **Description**: Deselect all nodes in the tree. **Method**: POST **Endpoint**: N/A (Instance method) ### `selectAll()` **Description**: Select all nodes in the tree. **Method**: POST **Endpoint**: N/A (Instance method) ``` -------------------------------- ### Including CSS in React Templates Source: https://github.com/jorgedanisc/react-arborist/blob/main/modules/docs/layouts/partials/head.html This Go template code includes CSS assets for a React application. It utilizes the `partialCached` function to efficiently load CSS files, ensuring optimal performance. This is a standard practice for managing frontend assets in Go-templated projects. ```go {{ partialCached "head/css.html" . }} ``` -------------------------------- ### Tree API Access Source: https://context7.com/jorgedanisc/react-arborist/llms.txt Access the Tree API instance via a ref to programmatically control selection, focus, scrolling, and visibility of nodes. ```APIDOC ## Tree API Reference Access Access the Tree API instance via ref to programmatically control selection, focus, scrolling, and visibility. ### Usage ```tsx import { Tree, TreeApi } from "react-arborist"; import { useRef, useEffect } from "react"; function TreeWithApiAccess() { const treeRef = useRef>(null); useEffect(() => { const tree = treeRef.current; if (!tree) return; // Selection operations tree.selectAll(); tree.deselectAll(); tree.select("node-id"); tree.selectMulti("another-id"); // Access selected nodes console.log("Selected IDs:", tree.selectedIds); console.log("Selected nodes:", tree.selectedNodes); // Focus and navigation tree.focus("node-id"); tree.pageUp(); tree.pageDown(); // Visibility operations tree.openAll(); tree.closeAll(); tree.toggle("folder-id"); tree.openParents("deeply-nested-id"); // Scrolling tree.scrollTo("target-id", "center"); // Node access const node = tree.get("node-id"); const firstVisible = tree.firstNode; const nodeAtIndex = tree.at(5); // Create/Edit operations tree.createLeaf(); tree.createInternal(); tree.edit("node-id"); tree.delete(["id1", "id2"]); }, []); return ; } ``` ### Methods - `selectAll()`: Selects all nodes in the tree. - `deselectAll()`: Deselects all nodes in the tree. - `select(nodeId)`: Selects a specific node by its ID. - `selectMulti(nodeId)`: Adds a node to the current selection (e.g., for Cmd+click). - `focus(nodeId)`: Sets focus to a specific node. - `pageUp()`: Scrolls the tree view up by one page. - `pageDown()`: Scrolls the tree view down by one page. - `openAll()`: Expands all nodes in the tree. - `closeAll()`: Collapses all nodes in the tree. - `toggle(nodeId)`: Toggles the open/closed state of a node. - `openParents(nodeId)`: Expands all ancestor nodes of a given node. - `scrollTo(nodeId, align)`: Scrolls the tree to bring a specific node into view. `align` can be 'auto', 'start', 'center', 'end'. - `get(nodeId)`: Retrieves a node instance by its ID. - `firstNode`: Returns the first visible node in the tree. - `at(index)`: Returns the node at a specific visible index. - `createLeaf()`: Initiates the creation of a new leaf node. - `createInternal()`: Initiates the creation of a new internal node. - `edit(nodeId)`: Puts a node into edit mode. - `delete(nodeIds)`: Deletes one or more nodes by their IDs. ``` -------------------------------- ### Manage Expanded/Collapsed State with `useOpens` in React Arborist Source: https://github.com/jorgedanisc/react-arborist/blob/main/modules/docs/content/_index.md Explains how to control the expanded and collapsed state of nodes in the React Arborist tree. It demonstrates using the `useOpens` hook to manage this state, either by extracting it from data or by providing an external state object. ```jsx // If you keep the open data within your tree data, // you can extract it with the useOpens hook. const [opens, setOpens] = useOpens(data, { id: (d) => d.path isOpen = (d) => d.isOpen }) // Otherwise, you can provide your own object // to keep track of it. const [opens, setOpens] = useState({}) setOpens(newValue) }} /> ``` -------------------------------- ### Properties Source: https://github.com/jorgedanisc/react-arborist/blob/main/README.md Properties that provide information about the current state of the tree. ```APIDOC ## Properties ### `isEditing` **Description**: Returns true if the tree is currently editing a node. **Method**: GET **Endpoint**: N/A (Instance property) **Returns**: boolean ### `isFiltered` **Description**: Returns true if the `searchTerm` prop is not an empty string when trimmed. **Method**: GET **Endpoint**: N/A (Instance property) **Returns**: boolean ### `props` **Description**: Returns all the props that were passed to the `` component. **Method**: GET **Endpoint**: N/A (Instance property) **Returns**: TreeProps ### `root` **Description**: Returns the root `NodeApi` instance. Its children are the Node representations of the `data` prop array. **Method**: GET **Endpoint**: N/A (Instance property) **Returns**: NodeApi ``` -------------------------------- ### Including JavaScript in React Templates Source: https://github.com/jorgedanisc/react-arborist/blob/main/modules/docs/layouts/partials/head.html This Go template code includes JavaScript assets for a React application. It uses the `partialCached` function for efficient loading of JS files, which is crucial for application performance. This pattern is common for integrating frontend scripts. ```go {{ partialCached "head/js.html" . }} ``` -------------------------------- ### Configure Data Accessors for Tree Component Source: https://github.com/jorgedanisc/react-arborist/blob/main/README.md Demonstrates how to use `idAccessor` and `childrenAccessor` props to specify custom property names for node IDs and children in the Tree component. This allows flexibility in data structure. ```jsx function App() { const data = [ { category: "Food", subCategories: [{ category: "Restaurants" }, { category: "Groceries" }], }, ]; return ( d.subCategories} /> ); } ``` -------------------------------- ### Access Tree API via Ref for Programmatic Control Source: https://context7.com/jorgedanisc/react-arborist/llms.txt The Tree API can be accessed using a ref to programmatically control various aspects of the tree, such as selection, focus, scrolling, and visibility. This allows for dynamic manipulation of the tree's state and behavior. ```tsx import { Tree, TreeApi } from "react-arborist"; import { useRef, useEffect } from "react"; function TreeWithApiAccess() { const treeRef = useRef>(null); useEffect(() => { const tree = treeRef.current; if (!tree) return; // Selection operations tree.selectAll(); tree.deselectAll(); tree.select("node-id"); tree.selectMulti("another-id"); // Access selected nodes console.log("Selected IDs:", tree.selectedIds); console.log("Selected nodes:", tree.selectedNodes); // Focus and navigation tree.focus("node-id"); tree.pageUp(); tree.pageDown(); // Visibility operations tree.openAll(); tree.closeAll(); tree.toggle("folder-id"); tree.openParents("deeply-nested-id"); // Scrolling tree.scrollTo("target-id", "center"); // Node access const node = tree.get("node-id"); const firstVisible = tree.firstNode; const nodeAtIndex = tree.at(5); // Create/Edit operations tree.createLeaf(); tree.createInternal(); tree.edit("node-id"); tree.delete(["id1", "id2"]); }, []); return ; } ``` -------------------------------- ### Implement Controlled Tree Data Management in React Source: https://github.com/jorgedanisc/react-arborist/blob/main/README.md Illustrates how to use the Tree component as a controlled component by passing the data prop and handling data modifications through callback functions like onCreate, onRename, onMove, and onDelete. ```jsx function App() { /* Handle the data modifications outside the tree component */ const onCreate = ({ parentId, index, type }) => {}; const onRename = ({ id, name }) => {}; const onMove = ({ dragIds, parentId, index }) => {}; const onDelete = ({ ids }) => {}; return ( ); } ``` -------------------------------- ### Node API Methods for Custom Renderers Source: https://context7.com/jorgedanisc/react-arborist/llms.txt Each node instance in react-arborist exposes an API with methods and properties for inspecting and manipulating its state. This is particularly useful within custom node renderers to provide interactive elements and access node-specific information. ```tsx import { NodeRendererProps } from "react-arborist"; function NodeWithFullApi({ node, style, dragHandle }: NodeRendererProps) { // State properties (all boolean) const { isRoot, // True if root node isLeaf, // True if no children array isInternal, // True if has children array isOpen, // True if expanded isClosed, // True if collapsed isEditing, // True if in edit mode isSelected, // True if selected isSelectedStart, // First in contiguous selection isSelectedEnd, // Last in contiguous selection isOnlySelection, // Only selected node isFocused, // Has focus isDragging, // Being dragged willReceiveDrop, // Drop target highlighted } = node; // Navigation accessors const nextVisible = node.next; // Next visible node const prevVisible = node.prev; // Previous visible node const nextSib = node.nextSibling; // Next sibling in data const index = node.childIndex; // Index among siblings // Selection methods const handleSelect = () => { node.select(); // Select only this node // node.selectMulti(); // Add to selection (Cmd+click) // node.selectContiguous(); // Range select (Shift+click) // node.deselect(); // Remove from selection }; // Visibility methods const handleToggle = () => { node.toggle(); // Toggle open/closed // node.open(); // Expand // node.close(); // Collapse // node.openParents(); // Expand all ancestors }; // Edit methods const handleEdit = () => { node.edit(); // Enter edit mode // node.submit("New Name"); // Save and exit edit // node.reset(); // Cancel edit }; // Built-in click handler (handles Cmd/Shift modifiers) return (
{node.isInternal && ( )} {node.data.name}
); } ``` -------------------------------- ### Custom Row, Cursor, and Drag Preview Renderers in React Source: https://context7.com/jorgedanisc/react-arborist/llms.txt Replace default rendering components for rows, drop cursor, and drag preview with custom implementations in React Arborist. This allows for tailored visual feedback and interaction during tree manipulation. ```tsx import { Tree, RowRendererProps, CursorProps, DragPreviewProps } from "react-arborist"; // Custom row wrapper (handles drop target, positioning, aria) function CustomRow({ node, attrs, innerRef, children }: RowRendererProps) { return (
{children}
); } // Custom drop indicator line function CustomCursor({ top, left, indent }: CursorProps) { return (
); } // Custom drag preview ghost function CustomDragPreview({ offset, dragIds, isDragging }: DragPreviewProps) { if (!isDragging || !offset) return null; return (
Moving {dragIds.length} item(s)
); } function FullyCustomizedTree() { return ( {CustomNode} ); } ``` -------------------------------- ### Convert Data to Nodes for React Arborist Tree Component Source: https://github.com/jorgedanisc/react-arborist/blob/main/modules/docs/content/_index.md Demonstrates how to convert arbitrary data into a format suitable for the React Arborist `Tree` component using the `createNodes` utility. It allows customization of node properties like id, name, children, and leaf status. ```jsx // #APPROVED const [data, setData] = useState(myRandomData); const nodes = createNodes(data, { id: (d) => d.path, name: (d) => d.name, children: (d) => d.files, isLeaf: (d) => !('files' in d), sort: (a, b) => a.name - b.name, isVisible: (node) => true // not sure about his yet }); setData(nodes.handleChange(e)) }} > ``` -------------------------------- ### Handle Internal/External Selection Changes in React Source: https://github.com/jorgedanisc/react-arborist/blob/main/modules/docs/content/_index.md Demonstrates how to manage component state and user input, ensuring that internal state changes do not trigger external callbacks. This pattern is applied to the React Arborist's selection handling. ```jsx const [value, setValue] = useState('hello world'); return setValue(e.target.value)} />; ``` ```jsx const selection = useMultiSelection(); return ( { // Now we will include all the relevant information // to perform side effects in here. // This will run if changed internally, // This will not run if changed externally selection.set(e.target.value); } }} /> ); ``` -------------------------------- ### Render Tree Component with Nodes in React Arborist Source: https://github.com/jorgedanisc/react-arborist/blob/main/modules/docs/content/_index.md Illustrates how to pass the generated nodes to the React Arborist `Tree` component for rendering. It also shows how to handle node changes via the `onChange` prop. ```jsx setNodes(newValue) }} > {Node} ``` -------------------------------- ### Render Menu Partial (Hugo Template) Source: https://github.com/jorgedanisc/react-arborist/blob/main/modules/docs/layouts/partials/menu.html This Hugo template partial renders a menu for a given menu ID and page context. It retrieves menu data from the site configuration and uses a recursive partial to walk through menu entries. ```html {{- /* Renders a menu for the given menu ID. @context {page} page The current page. @context {string} menuID The menu ID. @example: {{ partial "menu.html" (dict "menuID" "main" "page" .) }} */ -}} {{- $page := .page }} {{- $menuID := .menuID }} {{- with index site.Menus $menuID }} {{- partial "inline/menu/walk.html" (dict "page" $page "menuEntries" .) }} {{- end }} ``` -------------------------------- ### Recursive Menu Walkthrough Partial (Hugo Template) Source: https://github.com/jorgedanisc/react-arborist/blob/main/modules/docs/layouts/partials/menu.html This Hugo template partial recursively traverses menu entries, applying CSS classes and ARIA attributes for active and ancestor states. It handles menu item names and recursively calls itself for nested children. ```html {{- define "partials/inline/menu/walk.html" }} {{- $page := .page }} {{- range .menuEntries }} {{- $attrs := dict "href" .URL }} {{- if $page.IsMenuCurrent .Menu . }} {{- $attrs = merge $attrs (dict "class" "active" "aria-current" "page") }} {{- else if $page.HasMenuCurrent .Menu .}} {{- $attrs = merge $attrs (dict "class" "ancestor" "aria-current" "true") }} {{- end }} {{- $name := .Name }} {{- with .Identifier }} {{- with T . }} {{- $name = . }} {{- end }} {{- end }} * {{ $name }} {{- with .Children }} {{- partial "inline/menu/walk.html" (dict "page" $page "menuEntries" .) }} {{- end }} {{- end }} {{- end }} ``` -------------------------------- ### Create Custom Node Renderer in React Arborist Source: https://context7.com/jorgedanisc/react-arborist/llms.txt Illustrates how to customize the appearance and behavior of individual nodes in a React Arborist tree. This is achieved by providing a custom React component to the `Tree` that receives node state and styling props, allowing for unique UI elements and interactions. ```tsx import { Tree, NodeRendererProps } from "react-arborist"; function CustomNode({ node, style, dragHandle }: NodeRendererProps) { return (
{/* Folder toggle */} {node.isInternal && ( node.toggle()}> {node.isOpen ? "📂" : "📁"} )} {node.isLeaf && 📄} {/* Inline editing or display */} {node.isEditing ? ( node.submit(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") node.submit(e.currentTarget.value); if (e.key === "Escape") node.reset(); }} /> ) : ( node.edit()}>{node.data.name} )}
); } function App() { return ( {CustomNode} ); } ``` -------------------------------- ### Render a Simple Uncontrolled Tree in React Source: https://github.com/jorgedanisc/react-arborist/blob/main/README.md Demonstrates the basic usage of the Tree component with the initialData prop, making it an uncontrolled component that handles its own data modifications. ```jsx import { Tree } from 'react-arborist'; function App() { return ; } ``` -------------------------------- ### Implement Tree Filtering in React Source: https://github.com/jorgedanisc/react-arborist/blob/main/README.md Demonstrates how to filter tree nodes based on a search term. The filtering can be customized with a searchMatch function, and matching children will cause their parents to be displayed. ```jsx function App() { const term = useSearchTermString() node.data.name.toLowerCase().includes(term.toLowerCase()) } /> } ``` -------------------------------- ### Customize Tree Appearance and Behavior in React Source: https://github.com/jorgedanisc/react-arborist/blob/main/README.md Shows how to customize the appearance and behavior of the Tree component by setting props like width, height, indent, rowHeight, and providing a custom Node component. ```jsx function App() { return ( {Node} ); } function Node({ node, style, dragHandle }) { /* This node instance can do many things. See the API reference. */ return (
{node.isLeaf ? "🍁" : "🗀"} {node.data.name}
); } ``` -------------------------------- ### Scrolling Methods Source: https://github.com/jorgedanisc/react-arborist/blob/main/README.md Methods for scrolling the tree view to a specific node. ```APIDOC ## Scrolling ### `scrollTo(id, [align])` **Description**: Scroll to the node with the specified ID. If this node is not visible, this method will open all its parents. The `align` argument can be used to control the scroll position within the viewport. **Method**: POST **Endpoint**: N/A (Instance method) **Parameters**: #### Path Parameters - **id** (string) - Required - The ID of the node to scroll to. - **align** (string) - Optional - The alignment of the node within the viewport. Can be one of: `"auto"`, `"smart"`, `"center"`, `"end"`, `"start"`. ``` -------------------------------- ### Manage Selection State with `useMultiSelection` in React Arborist Source: https://github.com/jorgedanisc/react-arborist/blob/main/modules/docs/content/_index.md Demonstrates how to manage the selection state of nodes within the React Arborist tree. It utilizes the `useMultiSelection` hook and `useEffect` to synchronize the selection with an external ID. ```jsx const id = useSelector(Current.fileId) const selection = useMultiSelection(id) useEffect(() => { selection.only(id) }, [id]) ``` -------------------------------- ### Use `useNodes` Hook for Data to Nodes Conversion in React Arborist Source: https://github.com/jorgedanisc/react-arborist/blob/main/modules/docs/content/_index.md Shows an alternative method using the `useNodes` hook to transform data into nodes for the React Arborist `Tree` component. This hook simplifies the data-to-node conversion process within a React component. ```jsx // #APPROVED const nodes = useNodes(myRandomData, { id: (d) => d.path, name: (d) => d.name, children: (d) => d.files, isLeaf: (d) => !('files' in d), sort: (a, b) => a.name - b.name, isVisible: (node) => true // not sure about his yet }); ; ``` -------------------------------- ### Implement Custom Rendering for Tree Components Source: https://github.com/jorgedanisc/react-arborist/blob/main/README.md Shows how to replace default rendering logic for different parts of the tree, such as rows, drag previews, and cursors, using dedicated props like `renderRow`, `renderDragPreview`, and `renderCursor`. The `MyNode` component is passed as the Tree's only child for inner element rendering. ```jsx function App() { return ( {/* The inner element that shows the indentation and data */} {MyNode} ); } ``` -------------------------------- ### Use Simple Tree Hook for Uncontrolled Tree Management Source: https://context7.com/jorgedanisc/react-arborist/llms.txt The useSimpleTree hook simplifies managing tree data in uncontrolled scenarios. It provides pre-built handlers for CRUD operations and returns a data state and a controller object that can be spread onto the Tree component. ```tsx import { Tree, useSimpleTree } from "react-arborist"; const initialData = [ { id: "1", name: "src", children: [ { id: "1-1", name: "index.ts" }, { id: "1-2", name: "App.tsx" }, { id: "1-3", name: "components", children: [ { id: "1-3-1", name: "Button.tsx" }, { id: "1-3-2", name: "Input.tsx" }, ], }, ], }, { id: "2", name: "package.json" }, { id: "3", name: "README.md" }, ]; function TreeWithSimpleState() { // Hook returns [data, handlers] tuple const [data, controller] = useSimpleTree(initialData); return ( ); } ``` -------------------------------- ### Tree Filtering with useNodes Hook in React Arborist Source: https://github.com/jorgedanisc/react-arborist/blob/main/modules/docs/content/_index.md Illustrates how to implement filtering directly within the `useNodes` hook. This allows for dynamic searching and filtering of tree nodes based on various matching strategies. ```jsx const nodes = useNodes({ searchTerm: '', searchMatch: leafs | leavesAndInternal | custom }); ```