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: add toHierarchy utility for TreeView, RecursiveList #2072

Merged
merged 10 commits into from
Dec 9, 2024
9 changes: 8 additions & 1 deletion docs/src/pages/components/RecursiveList.svx
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,11 @@ Set `type` to `"ordered"` to use the ordered list variant.

Set `type` to `"ordered-native"` to use the native styles for an ordered list.

<FileSource src="/framed/RecursiveList/RecursiveListOrderedNative" />
<FileSource src="/framed/RecursiveList/RecursiveListOrderedNative" />

## Flat data structure

If working with a flat data structure, use the `toHierarchy` utility
to convert a flat data structure into a hierarchical array accepted by the `nodes` prop.

<FileSource src="/framed/RecursiveList/RecursiveListFlatArray" />
7 changes: 7 additions & 0 deletions docs/src/pages/components/TreeView.svx
Original file line number Diff line number Diff line change
Expand Up @@ -107,3 +107,10 @@ Use the `TreeView.showNode` method to show a specific node.
If a matching node is found, it will be expanded, selected, and focused.

<FileSource src="/framed/TreeView/TreeViewShowNode" />

## Flat data structure

If working with a flat data structure, use the `toHierarchy` utility
to convert a flat data structure into a hierarchical array accepted by the `nodes` prop.

<FileSource src="/framed/TreeView/TreeViewFlatArray" />
20 changes: 20 additions & 0 deletions docs/src/pages/framed/RecursiveList/RecursiveListFlatArray.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<script>
import { RecursiveList, toHierarchy } from "carbon-components-svelte";

const nodesFlat = [
{ id: 1, text: "Item 1" },
{ id: 2, text: "Item 1a", pid: 1 },
{ id: 3, html: "<h5>HTML content</h5>", pid: 2 },
{ id: 4, text: "Item 2" },
{ id: 5, href: "https://svelte.dev/", pid: 4 },
{
id: 6,
href: "https://svelte.dev/",
text: "Link with custom text",
pid: 4,
},
{ id: 7, text: "Item 3" },
];
</script>

<RecursiveList nodes={toHierarchy(nodesFlat, (node) => node.pid)} />
28 changes: 28 additions & 0 deletions docs/src/pages/framed/TreeView/TreeViewFlatArray.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<script>
import { TreeView, toHierarchy } from "carbon-components-svelte";
import Analytics from "carbon-icons-svelte/lib/Analytics.svelte";

let nodesFlat = [
{ id: 0, text: "AI / Machine learning", icon: Analytics },
{ id: 1, text: "Analytics" },
{ id: 2, text: "IBM Analytics Engine", pid: 1 },
{ id: 3, text: "Apache Spark", pid: 2 },
{ id: 4, text: "Hadoop", pid: 2 },
{ id: 5, text: "IBM Cloud SQL Query", pid: 1 },
{ id: 6, text: "IBM Db2 Warehouse on Cloud", pid: 1 },
{ id: 7, text: "Blockchain" },
{ id: 8, text: "IBM Blockchain Platform", pid: 7 },
{ id: 9, text: "Databases" },
{ id: 10, text: "IBM Cloud Databases for Elasticsearch", pid: 9 },
{ id: 11, text: "IBM Cloud Databases for Enterprise DB", pid: 9 },
{ id: 12, text: "IBM Cloud Databases for MongoDB", pid: 9 },
{ id: 13, text: "IBM Cloud Databases for PostgreSQL", pid: 9 },
{ id: 14, text: "Integration", disabled: true },
{ id: 15, text: "IBM API Connect", disabled: true, pid: 14 },
];
</script>

<TreeView
labelText="Cloud Products"
nodes={toHierarchy(nodesFlat, (node) => node.pid)}
/>
1 change: 1 addition & 0 deletions src/TreeView/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as TreeView } from "./TreeView.svelte";
1 change: 1 addition & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -152,3 +152,4 @@ export {
HeaderSearch,
} from "./UIShell";
export { UnorderedList } from "./UnorderedList";
export { toHierarchy } from "./utils/toHierarchy";
21 changes: 21 additions & 0 deletions src/utils/toHierarchy.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
type NodeLike = {
id: string | number;
nodes?: NodeLike[];
[key: string]: any;
};

/** Create a hierarchical tree from a flat array. */
export function toHierarchy<
T extends NodeLike,
K extends keyof Omit<T, "id" | "nodes">,
>(
flatArray: T[] | readonly T[],
/**
* Function that returns the parent ID for a given node.
* @example
* toHierarchy(flatArray, (node) => node.parentId);
*/
getParentId: (node: T) => T[K] | null,
): (T & { nodes?: (T & { nodes?: T[] })[] })[];

export default toHierarchy;
49 changes: 49 additions & 0 deletions src/utils/toHierarchy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// @ts-check
/**
* Create a nested array from a flat array.
* @typedef {Object} NodeLike
* @property {string | number} id - Unique identifier for the node
* @property {NodeLike[]} [nodes] - Optional array of child nodes
* @property {Record<string, any>} [additionalProperties] - Any additional properties
*
* @param {NodeLike[]} flatArray - Array of flat nodes to convert
* @param {function(NodeLike): (string|number|null)} getParentId - Function to get parent ID for a node
* @returns {NodeLike[]} Hierarchical tree structure
*/
export function toHierarchy(flatArray, getParentId) {
/** @type {NodeLike[]} */
const tree = [];
const childrenOf = new Map();
const itemsMap = new Map(flatArray.map((item) => [item.id, item]));

flatArray.forEach((item) => {
const parentId = getParentId(item);

// Only create nodes array if we have children.
const children = childrenOf.get(item.id);
if (children) {
item.nodes = children;
}

// Check if parentId exists using Map instead of array lookup.
const parentExists = parentId && itemsMap.has(parentId);

if (parentId && parentExists) {
if (!childrenOf.has(parentId)) {
childrenOf.set(parentId, []);
}
childrenOf.get(parentId).push(item);

const parent = itemsMap.get(parentId);
if (parent) {
parent.nodes = childrenOf.get(parentId);
}
} else {
tree.push(item);
}
});

return tree;
}

export default toHierarchy;
6 changes: 6 additions & 0 deletions tests/App.test.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<script lang="ts">
import { TreeView as TreeViewNav } from "carbon-components-svelte";
import TreeView from "./TreeView/TreeView.test.svelte";
import TreeViewHierarchy from "./TreeView/TreeView.hierarchy.test.svelte";
import { onMount } from "svelte";

const routes = [
Expand All @@ -9,6 +10,11 @@
name: "TreeView",
component: TreeView,
},
{
path: "/treeview-hierarchy",
name: "TreeViewHierarchy",
component: TreeViewHierarchy,
},
] as const;

let currentPath = window.location.pathname;
Expand Down
24 changes: 24 additions & 0 deletions tests/RecursiveList/RecursiveList.hierarchy.test.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<script lang="ts">
import { RecursiveList } from "carbon-components-svelte";
import toHierarchy from "../../src/utils/toHierarchy";

let nodes = toHierarchy(
[
{ id: 1, text: "Item 1" },
{ id: 2, text: "Item 1a", pid: 1 },
{ id: 3, html: "<h5>HTML content</h5>", pid: 2 },
{ id: 4, text: "Item 2" },
{ id: 5, href: "https://svelte.dev/", pid: 4 },
{
id: 6,
href: "https://svelte.dev/",
text: "Link with custom text",
pid: 4,
},
{ id: 7, text: "Item 3" },
],
(node) => node.pid,
);
</script>

<RecursiveList type="ordered" {nodes} />
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,14 @@
{
text: "Item 2",
nodes: [
{
href: "https://svelte.dev/",
},
{ href: "https://svelte.dev/" },
{
href: "https://svelte.dev/",
text: "Link with custom text",
},
],
},
{
text: "Item 3",
},
{ text: "Item 3" },
];
</script>

Expand Down
47 changes: 47 additions & 0 deletions tests/RecursiveList/RecursiveList.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { render, screen } from "@testing-library/svelte";
import RecursiveListHierarchyTest from "./RecursiveList.hierarchy.test.svelte";
import RecursiveListTest from "./RecursiveList.test.svelte";

const testCases = [
{ name: "RecursiveList", component: RecursiveListTest },
{ name: "RecursiveList hierarchy", component: RecursiveListHierarchyTest },
];

describe.each(testCases)("$name", ({ component }) => {
it("renders all top-level items", () => {
render(component);

expect(screen.getByText("Item 1")).toBeInTheDocument();
expect(screen.getByText("Item 2")).toBeInTheDocument();
expect(screen.getByText("Item 3")).toBeInTheDocument();

expect(screen.getAllByRole("list")).toHaveLength(4);

// Nested items
expect(screen.getByText("Item 1a")).toBeInTheDocument();
});

it("renders HTML content", () => {
render(component);

const htmlContent = screen.getByText("HTML content");
expect(htmlContent.tagName).toBe("H5");
});

it("renders links correctly", () => {
render(component);

const links = screen.getAllByRole("link");
expect(links).toHaveLength(2);

// Link with custom text
const customLink = screen.getByText("Link with custom text");
expect(customLink).toHaveAttribute("href", "https://svelte.dev/");

// Plain link
const plainLink = links.find(
(link) => link.textContent === "https://svelte.dev/",
);
expect(plainLink).toHaveAttribute("href", "https://svelte.dev/");
});
});
61 changes: 61 additions & 0 deletions tests/TreeView/TreeView.hierarchy.test.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<script lang="ts">
import { Button, TreeView } from "carbon-components-svelte";
import { toHierarchy } from "../../src/utils/toHierarchy";
import type { TreeNodeId } from "carbon-components-svelte/TreeView/TreeView.svelte";
import Analytics from "carbon-icons-svelte/lib/Analytics.svelte";

let treeview: TreeView;
let activeId: TreeNodeId = "";
let selectedIds: TreeNodeId[] = [];
let expandedIds: TreeNodeId[] = [];
let nodes = toHierarchy(
[
{ id: 0, text: "AI / Machine learning", icon: Analytics },
{ id: 1, text: "Analytics" },
{ id: 2, text: "IBM Analytics Engine", pid: 1 },
{ id: 3, text: "Apache Spark", pid: 2 },
{ id: 4, text: "Hadoop", pid: 2 },
{ id: 5, text: "IBM Cloud SQL Query", pid: 1 },
{ id: 6, text: "IBM Db2 Warehouse on Cloud", pid: 1 },
{ id: 7, text: "Blockchain" },
{ id: 8, text: "IBM Blockchain Platform", pid: 7 },
{ id: 9, text: "Databases" },
{ id: 10, text: "IBM Cloud Databases for Elasticsearch", pid: 9 },
{ id: 11, text: "IBM Cloud Databases for Enterprise DB", pid: 9 },
{ id: 12, text: "IBM Cloud Databases for MongoDB", pid: 9 },
{ id: 13, text: "IBM Cloud Databases for PostgreSQL", pid: 9 },
{ id: 14, text: "Integration", disabled: true },
{ id: 15, text: "IBM API Connect", disabled: true, pid: 14 },
],
(node) => node.pid,
);

$: console.log("selectedIds", selectedIds);
</script>

<TreeView
bind:this={treeview}
size="compact"
labelText="Cloud Products"
{nodes}
bind:activeId
bind:selectedIds
bind:expandedIds
on:select={({ detail }) => console.log("select", detail)}
on:toggle={({ detail }) => console.log("toggle", detail)}
on:focus={({ detail }) => console.log("focus", detail)}
let:node
>
{node.text}
</TreeView>

<Button on:click={treeview.expandAll}>Expand all</Button>
<Button
on:click={() => {
treeview.expandNodes((node) => {
return /^IBM/.test(node.text);
});
}}
>
Expand some nodes
</Button>
12 changes: 0 additions & 12 deletions tests/TreeView/TreeView.test.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -50,18 +50,6 @@
];

$: console.log("selectedIds", selectedIds);

/* $: if (treeview) {
treeview.expandAll();
treeview.expandNodes((node) => {
return +node.id > 0;
});
treeview.collapseAll();
treeview.collapseNodes((node) => {
return node.disabled === true;
});
treeview.showNode(1);
} */
</script>

<TreeView
Expand Down
14 changes: 10 additions & 4 deletions tests/TreeView/TreeView.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import { render, screen } from "@testing-library/svelte";
import { user } from "../setup-tests";
import TreeViewHierarchy from "./TreeView.hierarchy.test.svelte";
import TreeView from "./TreeView.test.svelte";

describe("TreeView", () => {
const testCases = [
{ name: "TreeView", component: TreeView },
{ name: "TreeView hierarchy", component: TreeViewHierarchy },
];

describe.each(testCases)("$name", ({ component }) => {
const getItemByName = (name: RegExp) => {
return screen.getByRole("treeitem", {
name,
Expand Down Expand Up @@ -30,7 +36,7 @@ describe("TreeView", () => {
it("can select a node", async () => {
const consoleLog = vi.spyOn(console, "log");

render(TreeView);
render(component);

const firstItem = getItemByName(/AI \/ Machine learning/);
expect(firstItem).toBeInTheDocument();
Expand All @@ -49,7 +55,7 @@ describe("TreeView", () => {
});

it("can expand all nodes", async () => {
render(TreeView);
render(component);

noExpandedItems();

Expand All @@ -60,7 +66,7 @@ describe("TreeView", () => {
});

it("can expand some nodes", async () => {
render(TreeView);
render(component);

noExpandedItems();

Expand Down
Loading
Loading