feat: add toHierarchy utility for TreeView, RecursiveList (#2072)

Co-authored-by: Bram <bramhavers@gmail.com>
This commit is contained in:
Eric Liu 2024-12-09 12:22:36 -08:00 committed by GitHub
commit 48afd18e5e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
19 changed files with 413 additions and 23 deletions

1
types/TreeView/index.d.ts vendored Normal file
View file

@ -0,0 +1 @@
export { default as TreeView } from "./TreeView.svelte";

1
types/index.d.ts vendored
View file

@ -166,3 +166,4 @@ export { default as SkipToContent } from "./UIShell/SkipToContent.svelte";
export { default as HeaderGlobalAction } from "./UIShell/HeaderGlobalAction.svelte";
export { default as HeaderSearch } from "./UIShell/HeaderSearch.svelte";
export { default as UnorderedList } from "./UnorderedList/UnorderedList.svelte";
export { default as toHierarchy } from "./utils/toHierarchy";

21
types/utils/toHierarchy.d.ts vendored Normal file
View file

@ -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;