A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
web: get rid of react-complex-tree
Abdullah Atta4c77c8e22c7d
diff --git a/apps/web/package.json b/apps/web/package.jsonindex bedc4251d..900df8911 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -66,8 +66,6 @@"qclone": "^1.2.0","react": "18.2.0","react-avatar-editor": "^13.0.2",- "react-complex-tree": "^2.2.4",- "react-day-picker": "^8.9.1","react-dom": "18.2.0","react-dropzone": "^14.2.3","react-error-boundary": "^4.0.12",diff --git a/apps/web/src/components/list-container/index.tsx b/apps/web/src/components/list-container/index.tsxindex 291baf573..8ea97d84b 100644--- a/apps/web/src/components/list-container/index.tsx+++ b/apps/web/src/components/list-container/index.tsx@@ -413,7 +413,7 @@ function ListHeader({ context }: { context?: ListContext }) {* attempts have been made. Each attempt is separated by a* 50ms interval.*/-function waitForElement(+export function waitForElement(list: VirtuosoHandle,index: number,elementId: string,diff --git a/apps/web/src/components/sub-notebook/index.tsx b/apps/web/src/components/sub-notebook/index.tsxindex 828bccac2..1fca89115 100644--- a/apps/web/src/components/sub-notebook/index.tsx+++ b/apps/web/src/components/sub-notebook/index.tsx@@ -40,7 +40,6 @@ type SubNotebookProps = {isExpanded: boolean;expand: () => void;collapse: () => void;- focus: () => void;refresh?: () => void;depth: number;rootId: string;@@ -53,7 +52,6 @@ function SubNotebook(props: SubNotebookProps) {isExpanded,expand,collapse,- focus,refresh,depth,rootId@@ -104,6 +102,7 @@ function SubNotebook(props: SubNotebookProps) {}}onKeyPress={async (e) => {if (e.code === "Space") {+ e.stopPropagation();if (isExpandable) isExpanded ? collapse() : expand();else if (!isOpened) {focus();@@ -116,7 +115,7 @@ function SubNotebook(props: SubNotebookProps) {navigate(`/notebooks/${rootId}/${item.id}`);}} else if (e.code === "Delete") {- console.log("Delete", useSelectionStore.getState().selectedItems);+ e.stopPropagation();await Multiselect.moveNotebooksToTrash(useSelectionStore.getState().selectedItems);diff --git a/apps/web/src/components/virtualized-tree/index.tsx b/apps/web/src/components/virtualized-tree/index.tsxnew file mode 100644index 000000000..f909abc16--- /dev/null+++ b/apps/web/src/components/virtualized-tree/index.tsx@@ -0,0 +1,274 @@+/*+This file is part of the Notesnook project (https://notesnook.com/)++Copyright (C) 2023 Streetwriters (Private) Limited++This program is free software: you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation, either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++import { useEffect, useImperativeHandle, useRef, useState } from "react";+import { usePersistentState } from "../../hooks/use-persistent-state";+import { ItemProps, Virtuoso, VirtuosoHandle } from "react-virtuoso";+import { useKeyboardListNavigation } from "../../hooks/use-keyboard-list-navigation";+import { CustomScrollbarsVirtualList, waitForElement } from "../list-container";++export type VirtualizedTreeHandle<T> = {+ refresh: () => void;+ refreshItem: (index: number, item?: T) => void;+};+export type TreeNode<T = any> = {+ id: string;+ parentId: string;+ depth: number;+ hasChildren: boolean;+ data: T;+};+type ExpandedIds = Record<string, boolean>;+type TreeViewProps<T> = {+ treeRef?: React.Ref<VirtualizedTreeHandle<T>> | null;+ rootId: string;+ itemHeight: number;+ getChildNodes: (id: string, depth: number) => Promise<TreeNode<T>[]>;+ renderItem: (props: {+ item: TreeNode<T>;+ index: number;+ expanded: boolean;+ expand: () => void;+ collapse: () => void;+ }) => React.ReactNode;+ saveKey?: string;++ onSelect?: (id: string) => void;+ onDeselect?: (id: string) => void;+ bulkSelect?: (ids: string[]) => void;+ deselectAll?: () => void;+ isSelected?: (id: string) => boolean;+};+export function VirtualizedTree<T>(props: TreeViewProps<T>) {+ const {+ rootId,+ itemHeight,+ renderItem: Node,+ getChildNodes,+ treeRef,+ saveKey,++ isSelected,+ onDeselect,+ onSelect,+ deselectAll,+ bulkSelect+ } = props;+ const [nodes, setNodes] = useState<TreeNode<T>[]>([]);+ const [expandedIds, setExpandedIds] = usePersistentState<ExpandedIds>(+ saveKey,+ {}+ );+ const list = useRef<VirtuosoHandle>(null);++ useImperativeHandle(+ treeRef,+ () => ({+ async refresh() {+ const children = await getChildNodes(rootId, -1);+ setNodes(children);+ },+ async refreshItem(index, item) {+ const node = nodes[index];+ const removeIds: string[] = [node.id];+ for (const treeNode of nodes) {+ if (removeIds.includes(treeNode.parentId)) {+ removeIds.push(treeNode.id);+ }+ }++ const filtered = nodes.filter((n) => !removeIds.includes(n.id));+ if (!item) {+ setNodes(filtered);+ return;+ }++ const children = await fetchChildren(+ node.id,+ node.depth,+ expandedIds,+ getChildNodes+ );+ filtered.splice(+ index,+ 0,+ {+ id: node.id,+ data: item,+ depth: node.depth,+ hasChildren: children.length > 0,+ parentId: node.parentId+ },+ ...children+ );+ setNodes(filtered);+ }+ }),+ [expandedIds, getChildNodes, nodes, rootId]+ );++ const { onMouseUp, onKeyDown } = useKeyboardListNavigation({+ length: nodes.length,+ reset: () => deselectAll?.(),+ deselect: (index) => {+ const id = nodes[index].id;+ if (!id) return;+ onDeselect?.(id);+ },+ select: (index, toggleable) => {+ const id = nodes[index].id;+ if (!id) return;+ if (toggleable && isSelected?.(id)) onDeselect?.(id);+ else onSelect?.(id);+ },+ bulkSelect: (indices) => {+ const ids =+ indices.length === nodes.length+ ? nodes.map((c) => c.id)+ : (indices.map((i) => nodes[i].id).filter(Boolean) as string[]);+ bulkSelect?.(ids);+ },+ focusItemAt: (index) => {+ const id = nodes[index].id;+ if (!id || !list.current) return;++ waitForElement(list.current, index, `id_${id}`, (element) =>+ element.focus()+ );+ },+ skip: () => false,+ open: (index) => {+ const id = nodes[index].id;+ if (!id || !list.current) return;++ waitForElement(list.current, index, `id_${id}`, (element) =>+ element.click()+ );+ }+ });++ useEffect(() => {+ fetchChildren(rootId, -1, expandedIds, getChildNodes).then(setNodes);+ }, [rootId]);++ return (+ <Virtuoso+ ref={list}+ data={nodes}+ computeItemKey={(i, item) => item.id}+ fixedItemHeight={itemHeight}+ onKeyDown={(e) => onKeyDown(e.nativeEvent)}+ context={{+ onMouseUp+ }}+ components={{+ Scroller: CustomScrollbarsVirtualList,+ Item: VirtuosoItem+ }}+ itemContent={(index, node) => (+ <Node+ item={node}+ index={index}+ expanded={expandedIds[node.id]}+ collapse={() => {+ if (!expandedIds[node.id]) return;++ const expanded = { ...expandedIds, [node.id]: false };+ setNodes((tree) => {+ const removeIds: string[] = [];+ for (const treeNode of tree) {+ if (+ treeNode.parentId === node.id ||+ removeIds.includes(treeNode.parentId)+ ) {+ expanded[treeNode.id] = false;+ removeIds.push(treeNode.id);+ }+ }+ return tree.filter((n) => !removeIds.includes(n.id));+ });+ setExpandedIds(expanded);+ }}+ expand={async () => {+ if (expandedIds[node.id]) return;++ setExpandedIds({ ...expandedIds, [node.id]: true });++ const children = await fetchChildren(+ node.id,+ node.depth,+ expandedIds,+ getChildNodes+ );+ setNodes((tree) => {+ const copy = tree.slice();+ copy.splice(index + 1, 0, ...children);+ return copy;+ });+ }}+ />+ )}+ />+ );+}++type ListContext = {+ onMouseUp: (e: MouseEvent, index: number) => void;+};+function VirtuosoItem({+ item: _item,+ context,+ ...props+}: ItemProps<TreeNode> & {+ context?: ListContext;+}) {+ return (+ <div+ {...props}+ onMouseUp={(e) =>+ context?.onMouseUp(e.nativeEvent, props["data-item-index"])+ }+ >+ {props.children}+ </div>+ );+}++async function fetchChildren<T>(+ id: string,+ depth: number,+ expandedIds: ExpandedIds,+ getChildNodes: (id: string, depth: number) => Promise<TreeNode<T>[]>+) {+ const children = await getChildNodes(id, depth);+ for (let i = 0; i < children.length; i++) {+ const childNode = children[i];+ if (expandedIds[childNode.id]) {+ const nodes = await fetchChildren(+ childNode.id,+ childNode.depth,+ expandedIds,+ getChildNodes+ );+ children.splice(i + 1, 0, ...nodes);+ i += nodes.length;+ }+ }+ return children;+}diff --git a/apps/web/src/dialogs/move-note-dialog.tsx b/apps/web/src/dialogs/move-note-dialog.tsxindex 743ab7b0d..31fabc669 100644--- a/apps/web/src/dialogs/move-note-dialog.tsx+++ b/apps/web/src/dialogs/move-note-dialog.tsx@@ -38,17 +38,15 @@ import { showToast } from "../utils/toast";import { isMac } from "../utils/platform";import { create } from "zustand";import { Notebook } from "@notesnook/core";-import {- UncontrolledTreeEnvironment,- Tree,- TreeItemIndex,- TreeEnvironmentRef-} from "react-complex-tree";-import { FlexScrollContainer } from "../components/scroll-container";import Field from "../components/field";import { AddNotebookDialog } from "./add-notebook-dialog";import { BaseDialogProps, DialogManager } from "../common/dialog-manager";import { strings } from "@notesnook/intl";+import {+ TreeNode,+ VirtualizedTree,+ VirtualizedTreeHandle+} from "../components/virtualized-tree";type MoveNoteDialogProps = BaseDialogProps<boolean> & { noteIds: string[] };type NotebookReference = {@@ -78,8 +76,7 @@ export const MoveNoteDialog = DialogManager.register(function MoveNoteDialog({const setIsMultiselect = useSelectionStore((store) => store.setIsMultiselect);const isMultiselect = useSelectionStore((store) => store.isMultiselect);const refreshNotebooks = useStore((store) => store.refresh);- const reloadItem = useRef<(changedItemIds: TreeItemIndex[]) => void>();- const treeRef = useRef<TreeEnvironmentRef>(null);+ const treeRef = useRef<VirtualizedTreeHandle<Notebook>>(null);const [notebooks, setNotebooks] = useState<string[]>([]);useEffect(() => {@@ -115,6 +112,10 @@ export const MoveNoteDialog = DialogManager.register(function MoveNoteDialog({})();}, [noteIds, refreshNotebooks, setSelected, setIsMultiselect]);+ useEffect(() => {+ treeRef.current?.refresh();+ }, [notebooks]);+const _onClose = useCallback((result: boolean) => {setSelected([]);@@ -131,7 +132,8 @@ export const MoveNoteDialog = DialogManager.register(function MoveNoteDialog({title={strings.selectNotebooks()}description={strings.selectNotebooksDesktopDesc(isMac() ? "Cmd" : "Ctrl")}onClose={() => _onClose(false)}- width={450}+ width={500}+ noScrollpositiveButton={{text: strings.done(),onClick: async () => {@@ -170,170 +172,134 @@ export const MoveNoteDialog = DialogManager.register(function MoveNoteDialog({onClick: () => _onClose(false)}}>- <Field- autoFocus- sx={{ m: 0, mb: 2 }}- styles={{- input: { p: "7.5px" }+ <Flex+ id="subnotebooks"+ variant="columnFill"+ sx={{+ height: "80vh",+ px: 4}}- placeholder={strings.searchNotebooks()}- onChange={async (e) => {- const query = e.target.value.trim();- const ids = await (query- ? db.lookup.notebooks(query).ids()- : db.notebooks.roots.ids(db.settings.getGroupOptions("notebooks")));- setNotebooks(ids);- reloadItem.current?.(["root"]);- }}- />- {isMultiselect && (- <Button- variant="anchor"- onClick={() => {- const originalSelection: NotebookReference[] = useSelectionStore- .getState()- .selected.filter((a) => !a.new)- .map((s) => ({ ...s, op: "add" }));- setSelected(originalSelection);- setIsMultiselect(originalSelection.length > 1);+ >+ <Field+ autoFocus+ sx={{ m: 0, mb: 2 }}+ styles={{+ input: { p: "7.5px" }}}- sx={{ textDecoration: "none", mb: 2 }}- >- {strings.resetSelection()}- </Button>- )}- {notebooks.length > 0 ? (- <FlexScrollContainer>- <UncontrolledTreeEnvironment- ref={treeRef}- dataProvider={{- onDidChangeTreeData(listener) {- reloadItem.current = listener;- return {- dispose() {- reloadItem.current = undefined;+ placeholder={strings.searchNotebooks()}+ onChange={async (e) => {+ const query = e.target.value.trim();+ const ids = await (query+ ? db.lookup.notebooks(query).ids()+ : db.notebooks.roots.ids(+ db.settings.getGroupOptions("notebooks")+ ));+ setNotebooks(ids);+ }}+ />+ {isMultiselect && (+ <Button+ variant="anchor"+ onClick={() => {+ const originalSelection: NotebookReference[] = useSelectionStore+ .getState()+ .selected.filter((a) => !a.new)+ .map((s) => ({ ...s, op: "add" }));+ setSelected(originalSelection);+ setIsMultiselect(originalSelection.length > 1);+ }}+ sx={{ textDecoration: "none", mb: 2 }}+ >+ {strings.resetSelection()}+ </Button>+ )}+ {notebooks.length > 0 ? (+ <>+ <VirtualizedTree+ rootId={"root"}+ itemHeight={30}+ treeRef={treeRef}+ getChildNodes={async (id, depth) => {+ const nodes: TreeNode<Notebook>[] = [];+ if (id === "root") {+ for (const id of notebooks) {+ const notebook = (await db.notebooks.notebook(id))!;+ const children = await db.relations+ .from(notebook, "notebook")+ .count();+ nodes.push({+ data: notebook,+ depth: depth + 1,+ hasChildren: children > 0,+ id,+ parentId: id+ });}- };- },- async getTreeItem(itemId) {- if (itemId === "root") {- return {- data: { title: "Root" },- index: itemId,- isFolder: true,- canMove: false,- canRename: false,- children: notebooks- };+ return nodes;}- const notebook = (await db.notebooks.notebook(- itemId as string- ))!;- const children = await db.relations- .from({ type: "notebook", id: itemId as string }, "notebook")- .get();- return {- index: itemId,- data: notebook,- children: children.map((i) => i.toId),- isFolder: children.length > 0- };- },- async getTreeItems(itemIds) {- const records = await db.notebooks.all.records(- itemIds as string[],- db.settings.getGroupOptions("notebooks")- );- const children = await db.relations- .from(- { type: "notebook", ids: itemIds as string[] },- "notebook"- )- .get();- return itemIds.filter(Boolean).map((id) => {- if (id === "root") {- return {- data: { title: "Root" },- index: id,- isFolder: true,- canMove: false,- canRename: false,- children: notebooks- };- }+ const subNotebooks = await db.relations+ .from({ type: "notebook", id }, "notebook")+ .resolve();- const notebook = records[id];- const subNotebooks = children- .filter((r) => r.fromId === id)- .map((r) => r.toId);- // const totalNotes = allChildren.filter(- // (r) => r.fromId === id && r.toType === "note"- // ).length;- return {- index: id,+ for (const notebook of subNotebooks) {+ const hasChildren =+ (await db.relations.from(notebook, "notebook").count()) > 0;+ nodes.push({+ parentId: id,+ id: notebook.id,data: notebook,- children: subNotebooks,- isFolder: subNotebooks.length > 0- };- });- }- }}- renderItem={(props) => (- <>+ depth: depth + 1,+ hasChildren+ });+ }++ return nodes;+ }}+ renderItem={({ item, expanded, index, collapse, expand }) => (<NotebookItem- notebook={props.item.data as any}- depth={props.depth}- isExpandable={props.item.isFolder || false}- isExpanded={props.context.isExpanded || false}- toggle={props.context.toggleExpandedState}+ notebook={item.data}+ depth={item.depth}+ isExpandable={item.hasChildren}+ isExpanded={expanded}+ toggle={expanded ? collapse : expand}onCreateItem={() => {- console.log([props.item.index]);- reloadItem.current?.([props.item.index]);- treeRef.current?.expandItem(- props.item.index,- props.info.treeId- );+ treeRef.current?.refreshItem(index, item.data);+ expand();}}/>-- {props.children}- </>- )}- getItemTitle={(item) => item.data.title}- viewState={{}}- >- <Tree treeId={"root"} rootItem="root" treeLabel="Tree Example" />- </UncontrolledTreeEnvironment>- </FlexScrollContainer>- ) : (- <Flex- sx={{- my: 2,- flexDirection: "column",- justifyContent: "center",- alignItems: "center"- }}- >- <Text variant="body">{strings.notebooksEmpty()}</Text>- <Button- data-test-id="add-new-notebook"- variant="secondary"- sx={{ mt: 2 }}- onClick={() =>- AddNotebookDialog.show({}).then((res) =>- res- ? db.notebooks.roots- .ids(db.settings.getGroupOptions("notebooks"))- .then((ids) => setNotebooks(ids))- : null- )- }+ )}+ />+ </>+ ) : (+ <Flex+ sx={{+ my: 2,+ flexDirection: "column",+ justifyContent: "center",+ alignItems: "center"+ }}>- {strings.addNotebook()}- </Button>- </Flex>- )}+ <Text variant="body">{strings.notebooksEmpty()}</Text>+ <Button+ data-test-id="add-new-notebook"+ variant="secondary"+ sx={{ mt: 2 }}+ onClick={() =>+ AddNotebookDialog.show({}).then((res) =>+ res+ ? db.notebooks.roots+ .ids(db.settings.getGroupOptions("notebooks"))+ .then((ids) => setNotebooks(ids))+ : null+ )+ }+ >+ {strings.addNotebook()}+ </Button>+ </Flex>+ )}+ </Flex></Dialog>);});diff --git a/apps/web/src/views/notebook.tsx b/apps/web/src/views/notebook.tsxindex 2ee069dd6..19b42ef03 100644--- a/apps/web/src/views/notebook.tsx+++ b/apps/web/src/views/notebook.tsx@@ -17,13 +17,7 @@ You should have received a copy of the GNU General Public Licensealong with this program. If not, see <http://www.gnu.org/licenses/>.*/-import {- useCallback,- useEffect,- useLayoutEffect,- useRef,- useState-} from "react";+import { useEffect, useLayoutEffect, useRef, useState } from "react";import { useStore as useAppStore } from "../stores/app-store";import { hashNavigate, navigate } from "../navigation";import { Button, Flex, Text } from "@theme-ui/components";@@ -36,25 +30,14 @@ import {RemoveShortcutLink,ShortcutLink} from "../components/icons";-import { pluralize } from "@notesnook/common";import { Plus } from "../components/icons";import { useStore as useNotesStore } from "../stores/note-store";import { useStore as useNotebookStore } from "../stores/notebook-store";import { db } from "../common/db";import { getFormattedDate } from "@notesnook/common";-import {- UncontrolledTreeEnvironment,- Tree,- TreeItemIndex,- TreeEnvironmentRef,- TreeItem-} from "react-complex-tree";-// import "react-complex-tree/lib/style-modern.css";import SubNotebook from "../components/sub-notebook";import { NotebookContext } from "../components/list-container/types";-import { FlexScrollContainer } from "../components/scroll-container";import { Menu } from "../hooks/use-menu";-import Config from "../utils/config";import Notes from "./notes";import {PanelGroup,@@ -64,6 +47,13 @@ import {} from "react-resizable-panels";import { AddNotebookDialog } from "../dialogs/add-notebook-dialog";import { strings } from "@notesnook/intl";+import { Notebook as NotebookType } from "@notesnook/core";+import { useStore as useSelectionStore } from "../stores/selection-store";+import {+ TreeNode,+ VirtualizedTree,+ VirtualizedTreeHandle+} from "../components/virtualized-tree";type NotebookProps = {rootId: string;@@ -128,8 +118,6 @@ function Notebook(props: NotebookProps) {onResize={(size) => setIsCollapsed(size <= 7)}><SubNotebooks- key={rootId}- notebookId={notebookId}isCollapsed={isCollapsed}rootId={rootId}onClick={() => {@@ -144,60 +132,23 @@ function Notebook(props: NotebookProps) {export default Notebook;type SubNotebooksProps = {- notebookId?: string;rootId: string;isCollapsed: boolean;onClick: () => void;};-function SubNotebooks({- notebookId,- rootId,- isCollapsed,- onClick-}: SubNotebooksProps) {+function SubNotebooks({ rootId, isCollapsed, onClick }: SubNotebooksProps) {// sometimes the onClick event is triggered on dragEnd// which shouldn't happen. To prevent that we make sure// that onMouseDown & onMouseUp events got called.const mouseEventCounter = useRef(0);- const treeRef = useRef<TreeEnvironmentRef>(null);- const reloadItem = useRef<(changedItemIds: TreeItemIndex[]) => void>();- const notebooks = useNotebookStore((store) => store.notebooks);- const contextNotes = useNotesStore((store) => store.contextNotes);- const context = useNotesStore((store) => store.context);-- const saveViewState = useCallback((id: string) => {- if (!treeRef.current?.viewState) return;- Config.set(`${id}:viewState`, treeRef.current.viewState[id]);- }, []);-- useEffect(() => {- const items: TreeItemIndex[] = [];- for (const item in treeRef.current?.items) {- if (item === "root") continue;- items.push(item);- }- reloadItem.current?.(items);- }, [notebooks, notebookId]);-- useEffect(() => {- if (- !context ||- context?.type !== "notebook" ||- !context.id ||- !treeRef.current?.items[context.id]- )- return;- db.notebooks.exists(context.id).then((exists) => {- if (!exists) {- return navigate(- rootId && rootId !== context.id- ? `/notebooks/${rootId}`- : `/notebooks/`- );- }- reloadItem.current?.([context.id]);- });- }, [contextNotes, context]);+ const treeRef = useRef<VirtualizedTreeHandle<SubNotebookTreeItem>>(null);+ const setSelectedItems = useSelectionStore((store) => store.setSelectedItems);+ const isSelected = useSelectionStore((store) => store.isSelected);+ const selectItem = useSelectionStore((store) => store.selectItem);+ const deselectItem = useSelectionStore((store) => store.deselectItem);+ const toggleSelection = useSelectionStore(+ (store) => store.toggleSelectionMode+ );if (!rootId) return null;@@ -261,6 +212,7 @@ function SubNotebooks({}}onClick={async (e) => {e.stopPropagation();+ const context = useNotesStore.getState().context;await AddNotebookDialog.show({parentId: context?.type === "notebook" ? context.id : rootId});@@ -271,142 +223,40 @@ function SubNotebooks({</Flex></Flex>- <FlexScrollContainer>- <UncontrolledTreeEnvironment- ref={treeRef}- onFocusItem={(item) => {- const element = document.getElementById(`id_${item.index}`);- if (!element) return;- setTimeout(() => {- element.focus();- element.scrollIntoView();- });- }}- onPrimaryAction={(item) => {- const element = document.getElementById(`id_${item.index}`);- if (!element) return;- element.click();- }}- dataProvider={{- onDidChangeTreeData(listener) {- reloadItem.current = listener;- return {- dispose() {- reloadItem.current = undefined;- }- };- },- async getTreeItem(itemId) {- if (itemId === "root") {- return {- data: { notebook: { title: "Root" } },- index: itemId,- isFolder: true,- canMove: false,- canRename: false,- children: [rootId]- };- }-- const notebook = (await db.notebooks.notebook(itemId as string))!;- const children = await db.relations- .from({ type: "notebook", id: itemId as string }, "notebook")- .get();- return {- index: itemId,- data: { notebook },- children: children.map((i) => i.toId),- isFolder: children.length > 0- };- },- async getTreeItems(itemIds) {- const notebooks = await db.notebooks.all.records(- itemIds as string[],- db.settings.getGroupOptions("notebooks")+ <VirtualizedTree+ itemHeight={28}+ getChildNodes={fetchChildren}+ rootId={rootId}+ deselectAll={() => toggleSelection(false)}+ bulkSelect={setSelectedItems}+ isSelected={isSelected}+ onDeselect={deselectItem}+ onSelect={selectItem}+ treeRef={treeRef}+ saveKey={`${rootId}-subnotebooks`}+ renderItem={({ collapse, expand, expanded, index, item: node }) => (+ <SubNotebook+ depth={node.depth}+ isExpandable={node.hasChildren}+ item={node.data.notebook}+ isExpanded={expanded}+ rootId={rootId}+ totalNotes={node.data.totalNotes}+ refresh={async () => {+ const notebook = await db.notebooks.notebook(node.id);+ const totalNotes = await db.relations+ .from(node.data.notebook, "note")+ .count();+ treeRef.current?.refreshItem(+ index,+ notebook ? { notebook, totalNotes } : undefined);- const allChildren = await db.relations- .from({ type: "notebook", ids: itemIds as string[] }, [- "notebook",- "note"- ])- .get();-- return itemIds.reduce((prev, id) => {- if (id === "root") {- prev.push({- data: { notebook: { title: "Root" } },- index: id,- isFolder: true,- canMove: false,- canRename: false,- children: [rootId]- });- return prev;- }-- const notebook = notebooks[id];- if (!notebook) return prev;-- const children = allChildren- .filter((r) => r.fromId === id && r.toType === "notebook")- .map((r) => r.toId);- const totalNotes = allChildren.filter(- (r) => r.fromId === id && r.toType === "note"- ).length;-- prev.push({- index: id,- data: { notebook, totalNotes },- children: children,- isFolder: children.length > 0- });-- return prev;- }, [] as TreeItem[]);- }- }}- renderItem={(props) => (- <>- <SubNotebook- item={props.item.data.notebook}- totalNotes={props.item.data.totalNotes}- depth={props.depth}- isExpandable={props.item.isFolder || false}- isExpanded={props.context.isExpanded || false}- collapse={props.context.collapseItem}- expand={props.context.expandItem}- focus={props.context.focusItem}- rootId={rootId}- refresh={() => {- reloadItem.current && reloadItem.current([props.item.index]);- setTimeout(() => props.context.expandItem());- }}- />- {props.children}- </>- )}- getItemTitle={(item) => item.data.notebook.title}- viewState={{- [rootId]: Config.get(`${rootId}:viewState`, {- expandedItems: [notebookId || rootId],- focusedItem: notebookId || rootId- })- }}- onExpandItem={(_, id) => saveViewState(id)}- onCollapseItem={(_, id) => saveViewState(id)}- >- <Tree- treeId={rootId}- renderTreeContainer={({ children, containerProps }) => (- <div data-test-id="subnotebooks-list" {...containerProps}>- {children}- </div>- )}- rootItem="root"- treeLabel="Tree Example"+ }}+ collapse={collapse}+ expand={expand}/>- </UncontrolledTreeEnvironment>- </FlexScrollContainer>+ )}+ /></Flex>);}@@ -608,3 +458,32 @@ function navigateCrumb(notebookId: string, rootId?: string) {navigate(`/notebooks/${rootId}/${notebookId}`);}}++type SubNotebookTreeItem = {+ notebook: NotebookType;+ totalNotes: number;+};+async function fetchChildren(+ id: string,+ depth: number+): Promise<TreeNode<SubNotebookTreeItem>[]> {+ const subNotebooks = await db.relations+ .from({ type: "notebook", id }, "notebook")+ .resolve();++ const nodes: TreeNode<SubNotebookTreeItem>[] = [];+ for (const notebook of subNotebooks) {+ const hasChildren =+ (await db.relations.from(notebook, "notebook").count()) > 0;+ const totalNotes = await db.relations.from(notebook, "note").count();+ nodes.push({+ parentId: id,+ id: notebook.id,+ data: { notebook, totalNotes },+ depth: depth + 1,+ hasChildren+ });+ }++ return nodes;+}