Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(react-component): Add TreeView #4987

Merged
merged 25 commits into from
Feb 21, 2025
Merged
Show file tree
Hide file tree
Changes from 24 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
9453c0d
Adding tree
nilscognite Feb 4, 2025
aed40b9
Merge branch 'master' into np/tree
nilscognite Feb 4, 2025
30512bb
Prepare for the three
nilscognite Feb 5, 2025
e90a3c7
Merge branch 'master' into np/tree
nilscognite Feb 6, 2025
32a7f7b
Implement tree view
nilscognite Feb 8, 2025
b2157ca
Merge branch 'master' into np/tree
nilscognite Feb 10, 2025
c2a7508
Make info box more flexible
nilscognite Feb 10, 2025
94d2ce5
Remove AAA comments
nilscognite Feb 10, 2025
fbc6146
Merge branch 'master' into np/tree
nilscognite Feb 18, 2025
0c11d8c
Fix build error after update
nilscognite Feb 18, 2025
bb7fb56
Merge branch 'master' into np/tree
nilscognite Feb 18, 2025
75d0032
Fine tuning
nilscognite Feb 18, 2025
f1dcf8f
Merge branch 'master' into np/tree
nilscognite Feb 19, 2025
aea7f75
Merge branch 'master' into np/tree
nilscognite Feb 19, 2025
8a22d9b
Merge branch 'master' into np/tree
pramod-cog Feb 21, 2025
7bd8dc4
Remove lint
nilscognite Feb 21, 2025
b7c6722
Create NodeTreeView.tsx
nilscognite Feb 21, 2025
b768749
updated export
pramod-cog Feb 21, 2025
5f258e0
Merge branch 'master' into np/tree
nilscognite Feb 21, 2025
adea98a
fixed unit test and added new mock data for 360 images icon visibility
pramod-cog Feb 21, 2025
2979d47
Merge branch 'master' into np/tree
pramod-cog Feb 21, 2025
f6fb6e4
fixed merge conflict
pramod-cog Feb 21, 2025
14ce5f0
Fix test
nilscognite Feb 21, 2025
997e4c4
Update RevealModelsUtils.test.ts
nilscognite Feb 21, 2025
9565014
fix: include coverage default excludes
Feb 21, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 117 additions & 0 deletions react-components/src/advanced-tree-view/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
## How to use the `AdvancedTreeView`:

### Overview

This tree contains the following features to be used:

- Label (Required)
- Bold label
- Icon
- Color on icon
- Checkbox with 3 different states
- Disable/enable the checkbox
- Selection
- Lazy loading av nodes
- isVisibleInTree

### Using the `TreeNodeType`.

The type of the tree node is called [`TreeNodeType`](./model/tree-node-type.ts).
This is the minimum of what you will need as a tree node.

You can either implement your own version of `TreeNodeType` and make all necessary methods or
use the default implementation `TreeNode` directly.

### Using the `TreeNode` class:

An implementation of `TreeNodeType` is [`TreeNode`](./model/tree-node.ts) and contains more,
like navigation in the tree, colors, icons etc.
You can build up the tree view by using the `TreeNode`,
by recursive adding children node to parent nodes.

### Using the `AdvancedTreeView` component:

There is 3 optional functions that can be set on the [`AdvancedTreeViewProps`](./view/advanced-tree-view-props.ts).

- `onSelectNode` is called when a node is selected
- `onToggleNode` is called when a checkbox is toggled
- `onClickInfo` is called when the info is clicked, if undefined, no info icon will appear.

There are some default implementations that can be used in the
file [`tree-node-functions.ts`](./model/tree-node-functions.ts).
Here different strategies for selection and checkboxes are implemented.

There are also some other property for appearance of the tree in the properties.

### Examples of how the `AdvancedTreeView` component can be used:

(There are several other examples in Storybook)

```typescript
function createTree(): TreeNode {
const root = new TreeNode();
root.label = 'Root';
root.isExpanded = true;

for (let i = 1; i <= 100; i++) {
const parent = new TreeNode();
parent.label = 'Parent ' + i;
parent.isExpanded = true;
root.addChild(parent);

for (let j = 1; j <= 10; j++) {
const child = new TreeNode();
child.label = 'Child ' + i + '.' + j;
parent.addChild(child);
}
}
return root;
}

const root = createTree();

<AdvancedTreeView
root={root}
onSelectNode={onSingleSelectNode} // When select a node
onCheckNode={onSimpleToggleNode} // When toggle the checkbox
hasCheckboxes
hasIcons
/>;
```

### Lazy loading

Lazy loading is optional. It will be applied when the `loader` property in the `AdvancedTreeViewProps` is set.
This property is a refer to the interface [`ILazyLoader`](./model/i-lazy-loader.ts). Look in the file for
description of the methods.

There is two methods that need to be implemented:

- `root` get the root of the tree
- `loadChildren` load the children of a parent
- `loadSiblings` load the siblings, typically when having a large number of children,
so loadChildren doesn't load all.

When using the `loader` property in the `AdvancedTreeViewProps` is set, the `root` property is not used.
Instead the root is taken from `loader` itself. This is done in order to not double buffer the root in 2
different places, since the root is needed in the loader. If the `root` is not set in the loader it will
call the method `loadInitialRoot` if it is implemented.

When nodes are lazy loaded into the tree, the function `onNodeLoaded` will optionally be called. This method is
made in order to synchronize the checkboxes if needed. If for instance the parent checkbox is toggled on, it is
natural that the children checkbox should be toggled. The implementation below shows this:

```typescript
onNodeLoaded(child: TreeNodeType, parent?: TreeNodeType): void {
if (parent === undefined) {
return; // No parent when root
}
if (parent.checkboxState === undefined) {
return; // No parent checkboxState exist
}
child.checkboxState = parent.checkboxState;
if (child.checkboxState == CheckboxState.All) {
// Set the node visible in the viewer
}
}
```
24 changes: 24 additions & 0 deletions react-components/src/advanced-tree-view/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*!
* Copyright 2025 Cognite AS
*/
export { AdvancedTreeView } from './view/advanced-tree-view';
export type { AdvancedTreeViewProps, GetIconFromIconNameFn } from './view/advanced-tree-view-props';
export type { TreeNodeType } from './model/tree-node-type';
export type { ILazyLoader } from './model/i-lazy-loader';
export { TreeNode } from './model/tree-node';
export type { IconName, IconColor, TreeNodeAction, OnNodeLoadedAction } from './model/types';

export { CheckboxState } from './model/types';

export {
scrollToNode,
scrollToElementId,
scrollToFirst,
scrollToLast
} from './view/advanced-tree-view-utils';
export {
onSingleSelectNode,
onMultiSelectNode,
onSimpleToggleNode,
onRecursiveToggleNode
} from './model/tree-node-functions';
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*!
* Copyright 2025 Cognite AS
*/
import { type ILazyLoader } from './i-lazy-loader';
import { type TreeNodeType } from './tree-node-type';

export function getChildrenAsArray(
node: TreeNodeType,
loader?: ILazyLoader,
shouldUseExpanded = true
): TreeNodeType[] | undefined {
if (shouldUseExpanded && !node.isExpanded) {
return undefined;
}
if (node.getChildren(loader).next().value === undefined) {
return undefined;
}
return Array.from(node.getChildren(loader));
}
70 changes: 70 additions & 0 deletions react-components/src/advanced-tree-view/model/i-lazy-loader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*!
* Copyright 2025 Cognite AS
*/
import { type TreeNodeType } from './tree-node-type';
import { type OnNodeLoadedAction } from './types';

/** Interface for lazy loading tree nodes
*
* */
export type ILazyLoader = {
/**
* Gets the root node of the tree. If loadInitialRoot is not called, the root node is undefined.
*
* @returns {TreeNodeType | undefined} The root node of the tree, or undefined if the root node is not set.
*/
root: TreeNodeType | undefined;

/**
* Loads the initial root node of the tree.
*
* @returns {Promise<TreeNodeType>} A promise that resolves to the root node of the tree.
*
* @remarks
* If the root node has already been loaded, it returns the cached root node.
* Otherwise, it should fetch the root node ,
* sets it as the root node, marks it as expanded, and caches it for future use.
*
* @throws {Error} If there is an issue with fetching the root node from the SDK.
*/
loadInitialRoot?: () => Promise<TreeNodeType>;

/**
* Load children for for a given parent node
* @param node - The parent node for which to load children
* @returns A promise that resolves to an array of tree nodes or undefined.
*/

loadChildren: (parent: TreeNodeType) => Promise<TreeNodeType[] | undefined>;

/**
* Load siblings for a given node (the sibling will be inserted just after the node)
* @param sibling - The sibling to where th other siblings are loaded from
* @returns A promise that resolves to an array of tree nodes or undefined.
*/

loadSiblings: (sibling: TreeNodeType) => Promise<TreeNodeType[] | undefined>;

/**
* Forces a node to be present in the tree by an nodeIdentifier. If the node is already in the tree,
* it expands all its ancestors and returns the node. If the node is not in the tree, it fetches
* the ancestors of the node, inserts them into the tree, expands all ancestors of the new node,
* and returns the new node.
*
* @param nodeIdentifier - The identifier of the node to be forced into the tree. What the nodeIdentifier
* will be is up to the implementation of the lazy loader, since this method is not called by the tree view.
* @returns A promise that resolves to the tree node if it is successfully forced into the tree,
* or undefined if the root is undefined or the node could not be inserted.
*/
forceNodeInTree?: (nodeIdentifier: number) => Promise<TreeNodeType | undefined>;

/**
* Callback function that is triggered when a node is loaded and just after it is
* added/inserted into the tree.
*
* @param child - The child node that has been loaded.
* @param parent - (Optional) The parent node of the loaded child node.
*/

onNodeLoaded?: OnNodeLoadedAction;
};
130 changes: 130 additions & 0 deletions react-components/src/advanced-tree-view/model/tree-node-functions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/*!
* Copyright 2025 Cognite AS
*/
import { TreeNode } from './tree-node';
import { type TreeNodeType } from './tree-node-type';
import { CheckboxState } from './types';

/**
* Handles the single selection of a tree node.
* If the node is selected, it will deselect all other nodes in the tree.
* If the node is not selected, it will select the node.
*
* @param node - The tree node to be selected or deselected.
*/
export function onSingleSelectNode(node: TreeNodeType): void {
if (!(node instanceof TreeNode)) {
return;
}
// Deselect all others
const root = node.getRoot();
for (const descendant of root.getThisAndDescendants()) {
if (descendant !== node) {
descendant.isSelected = false;
}
}
node.isSelected = !node.isSelected;
}

/**
* Handles the multi-selection of a tree node.
* Toggles the selection state of the node without affecting other nodes.
*
* @param node - The tree node to be selected or deselected.
*/
export function onMultiSelectNode(node: TreeNodeType): void {
if (!(node instanceof TreeNode)) {
return;
}
node.isSelected = !node.isSelected;
}

/**
* Handles the independent checkbox state of a tree node.
* Toggles the checkbox state between `All` and `None`without affecting other nodes.
*
* @param node - The tree node whose checkbox state is to be toggled.
*/
export function onSimpleToggleNode(node: TreeNodeType): void {
if (!(node instanceof TreeNode)) {
return;
}
if (node.checkboxState === undefined) {
return;
}
if (node.checkboxState === CheckboxState.All) {
node.checkboxState = CheckboxState.None;
} else {
node.checkboxState = CheckboxState.All;
}
}

/**
* Handles the event when a node's checkbox is clicked, toggling its state between `All` and `None`.
* It also updates the checkbox states of all its descendants and ancestors.
*
* @param node - The tree node that was clicked.
*
* @remarks
* - If the node's checkbox state is `All`, it will be set to `None`, and vice versa.
* - All descendants of the node will have their checkbox states updated to match the node's
* new state, unless their state is undefined.
* - All ancestors of the node will have their checkbox states recalculated,
* unless their state is undefined.
*/
export function onRecursiveToggleNode(node: TreeNodeType): void {
if (!(node instanceof TreeNode)) {
return;
}
if (node.checkboxState === undefined) {
return;
}
if (node.checkboxState === CheckboxState.All) {
node.checkboxState = CheckboxState.None;
} else {
node.checkboxState = CheckboxState.All;
}
// Recalculate all descendants and ancestors
for (const descendant of node.getDescendants()) {
if (descendant.checkboxState !== undefined) {
descendant.checkboxState = node.checkboxState;
}
}
for (const ancestor of node.getAncestors()) {
if (ancestor.checkboxState !== undefined) {
ancestor.checkboxState = calculateCheckboxState(ancestor);
}
}
}

function calculateCheckboxState(node: TreeNodeType): CheckboxState | undefined {
let numCandidates = 0;
let numAll = 0;
let numNone = 0;

for (const child of node.getChildren()) {
const checkboxState = child.checkboxState;
if (child.isCheckboxEnabled !== true || checkboxState === undefined) {
continue;
}
numCandidates += 1;
if (checkboxState === CheckboxState.All) {
numAll++;
} else if (checkboxState === CheckboxState.None) {
numNone++;
}
if (numNone < numCandidates && numCandidates < numAll) {
return CheckboxState.Some; // Optimization by early return
}
}
if (numCandidates === 0) {
return node.checkboxState;
}
if (numCandidates === numAll) {
return CheckboxState.All;
}
if (numCandidates === numNone) {
return CheckboxState.None;
}
return CheckboxState.Some;
}
Loading
Loading