import { ArrowLeft, Edit2, Expand, FileText, Folder, FolderPlus, MoreHorizontal, Minimize2, Plus, Search, X, } from "lucide-react"; import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useI18n } from "../../application/i18n/I18nProvider"; import { useApplicationBackend } from "../../application/state/useApplicationBackend"; import { useStoredNumber } from "../../application/state/useStoredNumber"; import { ancestorNoteGroupPaths, cleanNoteGroupPath, getNoteGroupParentPath, isNoteGroupInside, joinNoteGroupPath, matchesVaultNoteSearch, normalizeNoteGroups, normalizeVaultNotes, remapExpandedNoteGroupPaths, replaceNoteGroupPrefix, resolveMovedNoteGroupPath, } from "../../domain/notes"; import { getNextVaultOrder, reorderVaultItems, reorderVaultStrings, sortByVaultOrder } from "../../domain/vaultOrder"; import { STORAGE_KEY_VAULT_NOTES_TREE_WIDTH } from "../../infrastructure/config/storageKeys"; import { cn } from "../../lib/utils"; import type { Host, VaultNote } from "../../types"; import { Button } from "../ui/button"; import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger, } from "../ui/context-menu"; import { Dropdown, DropdownContent, DropdownTrigger } from "../ui/dropdown"; import { Input } from "../ui/input"; import { ScrollArea } from "../ui/scroll-area"; import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip"; import { VaultTreeGroupRow, VaultTreeInlineRenameInput, VaultTreeItemRow, } from "../vault/VaultTreeRow"; import { clearVaultDropIndicator, getVaultDropIntent, getVaultDropPosition, type VaultDropPosition, hasVaultDragType, markVaultDropIndicator, markVaultInsideDropIndicator, } from "../vault/vaultReorderDrag"; import { InlineMarkdownEditor } from "./InlineMarkdownEditor"; interface NoteFolderNode { name: string; path: string; children: NoteFolderNode[]; notes: VaultNote[]; } type NotesToolbarPanel = "search" | null; const toolbarIconButtonClass = "netcatty-tab h-7 w-7 shrink-0 rounded-md p-0 hover:bg-transparent"; const menuItemClass = "flex h-8 w-full items-center rounded-md px-3 text-left text-sm hover:bg-secondary"; const NOTES_TREE_DEFAULT_WIDTH = 300; const NOTES_TREE_MIN_WIDTH = 220; const NOTES_TREE_MAX_WIDTH = 520; const NOTE_DRAG_TYPE = "application/x-netcatty-note-id"; const NOTE_GROUP_DRAG_TYPE = "application/x-netcatty-note-group-path"; export interface NotesManagerProps { notes: VaultNote[]; noteGroups: string[]; hosts: Host[]; onUpdateNotes: (notes: VaultNote[]) => void; onUpdateNoteGroups: (groups: string[]) => void; onOpenHost?: (host: Host, source?: { noteId: string }) => void; displayMode?: "full" | "sidebar"; openNoteId?: string | null; } type HoverActionMenuProps = { children: React.ReactNode; className?: string; }; const HoverActionMenu: React.FC = ({ children, className }) => { const [open, setOpen] = useState(false); const closeTimerRef = useRef(null); const cancelClose = () => { if (closeTimerRef.current !== null) { window.clearTimeout(closeTimerRef.current); closeTimerRef.current = null; } }; const scheduleClose = () => { cancelClose(); closeTimerRef.current = window.setTimeout(() => setOpen(false), 140); }; useEffect(() => () => cancelClose(), []); return ( {children} ); }; const createNote = (group: string | null, order: number): VaultNote => { const now = Date.now(); return { id: crypto.randomUUID(), title: "Untitled note", content: "", group: group || undefined, createdAt: now, updatedAt: now, order, }; }; const sortNoteItems = (items: VaultNote[]): VaultNote[] => sortByVaultOrder(items); const sortFolderNodes = ( items: NoteFolderNode[], groupOrderByPath: ReadonlyMap, ): NoteFolderNode[] => [...items] .sort((a, b) => { const orderA = groupOrderByPath.get(a.path); const orderB = groupOrderByPath.get(b.path); if (typeof orderA === "number" && typeof orderB === "number" && orderA !== orderB) { return orderA - orderB; } if (typeof orderA === "number") return -1; if (typeof orderB === "number") return 1; return a.name.localeCompare(b.name); }) .map((node) => ({ ...node, children: sortFolderNodes(node.children, groupOrderByPath), notes: sortNoteItems(node.notes), })); const buildNoteTree = (groups: string[], notes: VaultNote[]): { children: NoteFolderNode[]; rootNotes: VaultNote[] } => { const nodes = new Map(); const ensureNode = (path: string): NoteFolderNode => { const cleanPath = cleanNoteGroupPath(path); const existing = nodes.get(cleanPath); if (existing) return existing; const name = cleanPath.split("/").pop() || cleanPath; const node: NoteFolderNode = { name, path: cleanPath, children: [], notes: [] }; nodes.set(cleanPath, node); const parentPath = cleanPath.split("/").slice(0, -1).join("/"); if (parentPath) { ensureNode(parentPath).children.push(node); } return node; }; const allGroups = normalizeNoteGroups([ ...groups, ...notes.map((note) => note.group).filter((group): group is string => Boolean(group)), ]); allGroups.flatMap(ancestorNoteGroupPaths).forEach(ensureNode); const rootNotes: VaultNote[] = []; notes.forEach((note) => { const group = note.group ? cleanNoteGroupPath(note.group) : ""; if (!group) { rootNotes.push(note); return; } ensureNode(group).notes.push(note); }); return { children: Array.from(nodes.values()).filter((node) => !node.path.includes("/")), rootNotes, }; }; export const getSelectedVaultNote = (notes: VaultNote[], selectedNoteId: string | null): VaultNote | null => selectedNoteId ? notes.find((note) => note.id === selectedNoteId) ?? null : null; export const isNoteFolderTreeSelected = ( selectedGroup: string | null, selectedNoteId: string | null, groupPath: string, ): boolean => selectedNoteId === null && selectedGroup === groupPath; export const getNoteActionTargetGroup = ( selectedNote: VaultNote | null, selectedGroup: string | null, ): string | null => selectedNote?.group || selectedGroup || null; export const getNoteSelectionState = ( note: VaultNote, isSidebarMode: boolean, ): { selectedNoteId: string; selectedGroup: null; overlayNoteId: string | null } => ({ selectedNoteId: note.id, selectedGroup: null, overlayNoteId: isSidebarMode ? note.id : null, }); export const getNoteGroupSelectionState = ( groupPath: string, ): { selectedNoteId: null; selectedGroup: string; overlayNoteId: null } => ({ selectedNoteId: null, selectedGroup: groupPath, overlayNoteId: null, }); export const getFallbackNoteSelectionState = ( remainingNotes: VaultNote[], isSidebarMode: boolean, ): { selectedNoteId: string | null; selectedGroup: null; overlayNoteId: null } => ({ selectedNoteId: isSidebarMode ? null : remainingNotes[0]?.id ?? null, selectedGroup: null, overlayNoteId: null, }); export const getNotesGroupDropAction = ( sourceGroup: string | null, targetGroup: string, intent: VaultDropPosition | "inside", ): "ignore" | "inside" | "reorder" => { if (!sourceGroup || sourceGroup === targetGroup || targetGroup.startsWith(`${sourceGroup}/`)) { return "ignore"; } return intent === "inside" ? "inside" : "reorder"; }; export const NotesManager: React.FC = ({ notes, noteGroups, hosts, onUpdateNotes, onUpdateNoteGroups, onOpenHost, displayMode = "full", openNoteId = null, }) => { const { t } = useI18n(); const { openExternal } = useApplicationBackend(); const isSidebarMode = displayMode === "sidebar"; const initialOpenNoteId = isSidebarMode && openNoteId && notes.some((note) => note.id === openNoteId) ? openNoteId : null; const [query, setQuery] = useState(""); const [selectedGroup, setSelectedGroup] = useState(null); const [selectedNoteId, setSelectedNoteId] = useState(() => initialOpenNoteId ?? (isSidebarMode ? null : notes[0]?.id ?? null)); const [overlayNoteId, setOverlayNoteId] = useState(() => initialOpenNoteId); const [expandedGroups, setExpandedGroups] = useState>( () => new Set(notes.flatMap((note) => note.group ? ancestorNoteGroupPaths(note.group) : [])), ); const [expandedPanel, setExpandedPanel] = useState(null); const [creatingGroupParent, setCreatingGroupParent] = useState(undefined); const [editingGroupPath, setEditingGroupPath] = useState(null); const [editingNoteId, setEditingNoteId] = useState(null); const [isTreeResizing, setIsTreeResizing] = useState(false); const [draggingNoteId, setDraggingNoteId] = useState(null); const [draggingGroupPath, setDraggingGroupPath] = useState(null); const [treeWidth, setTreeWidth, persistTreeWidth] = useStoredNumber( STORAGE_KEY_VAULT_NOTES_TREE_WIDTH, NOTES_TREE_DEFAULT_WIDTH, { min: NOTES_TREE_MIN_WIDTH, max: NOTES_TREE_MAX_WIDTH }, ); const searchInputRef = useRef(null); const groups = useMemo(() => normalizeNoteGroups(noteGroups), [noteGroups]); const groupOrderByPath = useMemo( () => new Map(groups.map((group, index) => [group, index])), [groups], ); const sortedNotes = useMemo(() => sortNoteItems(normalizeVaultNotes(notes)), [notes]); const noteTree = useMemo(() => { const tree = buildNoteTree(groups, sortedNotes); return { children: sortFolderNodes(tree.children, groupOrderByPath), rootNotes: sortNoteItems(tree.rootNotes), }; }, [groupOrderByPath, groups, sortedNotes]); const selectedNote = getSelectedVaultNote(sortedNotes, selectedNoteId); const overlayNote = sortedNotes.find((note) => note.id === overlayNoteId) ?? null; const queryText = query.trim(); const queryLower = queryText.toLowerCase(); const noteMatches = (note: VaultNote) => matchesVaultNoteSearch(note, queryText, hosts); const groupMatches = (node: NoteFolderNode) => !queryLower || node.name.toLowerCase().includes(queryLower) || node.path.toLowerCase().includes(queryLower); useEffect(() => { if (!selectedNoteId || sortedNotes.some((note) => note.id === selectedNoteId)) return; const nextSelection = getFallbackNoteSelectionState(sortedNotes, isSidebarMode); setSelectedNoteId(nextSelection.selectedNoteId); setSelectedGroup(nextSelection.selectedGroup); setOverlayNoteId(nextSelection.overlayNoteId); }, [isSidebarMode, selectedNoteId, sortedNotes]); useEffect(() => { if (!overlayNoteId || sortedNotes.some((note) => note.id === overlayNoteId)) return; setOverlayNoteId(null); }, [overlayNoteId, sortedNotes]); useEffect(() => { if (!selectedNote?.group) return; setExpandedGroups((current) => new Set([...current, ...ancestorNoteGroupPaths(selectedNote.group || "")])); }, [selectedNote?.group]); useEffect(() => { if (!isSidebarMode || !openNoteId) return; const note = sortedNotes.find((item) => item.id === openNoteId); if (!note) return; const nextSelection = getNoteSelectionState(note, true); setSelectedNoteId(nextSelection.selectedNoteId); setSelectedGroup(nextSelection.selectedGroup); setOverlayNoteId(nextSelection.overlayNoteId); if (note.group) { setExpandedGroups((current) => new Set([...current, ...ancestorNoteGroupPaths(note.group || "")])); } }, [isSidebarMode, openNoteId, sortedNotes]); useEffect(() => { if (expandedPanel !== "search") return; const frame = requestAnimationFrame(() => { searchInputRef.current?.focus(); }); return () => cancelAnimationFrame(frame); }, [expandedPanel]); const expandPath = (path: string) => { setExpandedGroups((current) => new Set([...current, ...ancestorNoteGroupPaths(path)])); }; const toggleGroup = (path: string) => { setExpandedGroups((current) => { const next = new Set(current); if (next.has(path)) { next.delete(path); } else { next.add(path); } return next; }); }; const allGroupPaths = useMemo(() => { const paths: string[] = []; const visit = (nodes: NoteFolderNode[]) => { nodes.forEach((node) => { paths.push(node.path); visit(node.children); }); }; visit(noteTree.children); return paths; }, [noteTree.children]); const expandAllGroups = () => setExpandedGroups(new Set(allGroupPaths)); const collapseAllGroups = () => setExpandedGroups(new Set()); const saveNote = (nextNote: VaultNote) => { const cleaned = normalizeVaultNotes( sortedNotes.map((note) => (note.id === nextNote.id ? nextNote : note)), ); onUpdateNotes(cleaned); }; const handleOpenHostFromNote = useCallback((host: Host, noteId: string) => { onOpenHost?.(host, { noteId }); }, [onOpenHost]); const addNoteToGroup = (group: string | null) => { const note = createNote(group, getNextVaultOrder(sortedNotes)); onUpdateNotes(normalizeVaultNotes([...sortedNotes, note])); if (group) expandPath(group); const nextSelection = getNoteSelectionState(note, isSidebarMode); setSelectedNoteId(nextSelection.selectedNoteId); setSelectedGroup(nextSelection.selectedGroup); setOverlayNoteId(nextSelection.overlayNoteId); }; const addNote = () => { addNoteToGroup(getNoteActionTargetGroup(selectedNote, selectedGroup)); }; const duplicateNoteById = (noteId: string) => { const source = sortedNotes.find((note) => note.id === noteId); if (!source) return; const now = Date.now(); const copy: VaultNote = { ...source, id: crypto.randomUUID(), title: `${source.title} (${t("action.copy")})`, createdAt: now, updatedAt: now, order: getNextVaultOrder(sortedNotes), }; onUpdateNotes(normalizeVaultNotes([...sortedNotes, copy])); if (copy.group) expandPath(copy.group); const nextSelection = getNoteSelectionState(copy, isSidebarMode); setSelectedNoteId(nextSelection.selectedNoteId); setSelectedGroup(nextSelection.selectedGroup); setOverlayNoteId(nextSelection.overlayNoteId); }; const deleteNoteById = (noteId: string) => { const next = sortedNotes.filter((note) => note.id !== noteId); onUpdateNotes(next); if (selectedNoteId === noteId) { const nextSelection = getFallbackNoteSelectionState(next, isSidebarMode); setSelectedNoteId(nextSelection.selectedNoteId); setSelectedGroup(nextSelection.selectedGroup); setOverlayNoteId(nextSelection.overlayNoteId); setEditingNoteId(null); } if (overlayNoteId === noteId) setOverlayNoteId(null); }; const startCreateGroup = () => { const targetGroup = getNoteActionTargetGroup(selectedNote, selectedGroup); setCreatingGroupParent(targetGroup); if (targetGroup) expandPath(targetGroup); }; const commitCreateGroup = (name: string) => { const nextPath = joinNoteGroupPath(creatingGroupParent ?? null, name); setCreatingGroupParent(undefined); if (!nextPath) return; const next = normalizeNoteGroups([...groups, ...ancestorNoteGroupPaths(nextPath)]); onUpdateNoteGroups(next); expandPath(nextPath); const nextSelection = getNoteGroupSelectionState(nextPath); setSelectedNoteId(nextSelection.selectedNoteId); setSelectedGroup(nextSelection.selectedGroup); setOverlayNoteId(nextSelection.overlayNoteId); }; const renameGroup = (group: string, nextName: string) => { setEditingGroupPath(null); const nextPath = joinNoteGroupPath(getNoteGroupParentPath(group), nextName); if (!nextPath || nextPath === group) return; const nextGroups = normalizeNoteGroups( groups.map((item) => replaceNoteGroupPrefix(item, group, nextPath) || ""), ); const nextNotes = sortedNotes.map((note) => ({ ...note, group: replaceNoteGroupPrefix(note.group, group, nextPath), })); onUpdateNoteGroups(nextGroups); onUpdateNotes(normalizeVaultNotes(nextNotes)); setExpandedGroups((current) => { const next = new Set(); current.forEach((item) => { const renamed = replaceNoteGroupPrefix(item, group, nextPath); if (renamed) next.add(renamed); }); ancestorNoteGroupPaths(nextPath).forEach((path) => next.add(path)); return next; }); if (selectedGroup && isNoteGroupInside(selectedGroup, group)) { setSelectedGroup(replaceNoteGroupPrefix(selectedGroup, group, nextPath) ?? null); } }; const deleteGroup = (group: string) => { onUpdateNoteGroups(groups.filter((item) => !isNoteGroupInside(item, group))); onUpdateNotes(sortedNotes.map((note) => isNoteGroupInside(note.group, group) ? { ...note, group: undefined } : note)); if (selectedGroup && isNoteGroupInside(selectedGroup, group)) setSelectedGroup(null); setEditingGroupPath(null); }; const resetTreeDragState = () => { setDraggingNoteId(null); setDraggingGroupPath(null); clearVaultDropIndicator(); }; const getDraggedNoteId = (dataTransfer: DataTransfer) => dataTransfer.getData(NOTE_DRAG_TYPE) || dataTransfer.getData("note-id"); const getDraggedGroupPath = (dataTransfer: DataTransfer) => dataTransfer.getData(NOTE_GROUP_DRAG_TYPE) || dataTransfer.getData("note-group-path"); const hasNotesTreeDrag = (dataTransfer: DataTransfer) => draggingNoteId || draggingGroupPath || hasVaultDragType(dataTransfer, NOTE_DRAG_TYPE) || hasVaultDragType(dataTransfer, NOTE_GROUP_DRAG_TYPE) || hasVaultDragType(dataTransfer, "note-id") || hasVaultDragType(dataTransfer, "note-group-path"); const handleTreeRowDragLeave = (event: React.DragEvent) => { const relatedTarget = event.relatedTarget; if (relatedTarget instanceof Node && event.currentTarget.contains(relatedTarget)) return; clearVaultDropIndicator(); }; const moveNoteToGroup = (noteId: string, group: string | null) => { const source = sortedNotes.find((note) => note.id === noteId); if (!source) return; const nextGroup = group || undefined; if ((source.group || undefined) === nextGroup) return; onUpdateNotes(normalizeVaultNotes(sortedNotes.map((note) => ( note.id === noteId ? { ...note, group: nextGroup, updatedAt: Date.now() } : note )))); if (group) expandPath(group); }; const reorderNoteToNote = (sourceId: string, targetNote: VaultNote, event: React.DragEvent) => { if (!sourceId || sourceId === targetNote.id) return; const position = getVaultDropPosition(event.currentTarget, event.clientX, event.clientY); const movedNotes = sortedNotes.map((note) => ( note.id === sourceId ? { ...note, group: targetNote.group, updatedAt: Date.now() } : note )); onUpdateNotes(normalizeVaultNotes(reorderVaultItems(movedNotes, sourceId, targetNote.id, position))); if (targetNote.group) expandPath(targetNote.group); }; const moveGroupToParent = (group: string, parent: string | null) => { const knownGroups = normalizeNoteGroups([ ...groups, ...sortedNotes.map((note) => note.group).filter((item): item is string => Boolean(item)), ]); const nextPath = resolveMovedNoteGroupPath(group, parent, knownGroups); if (!nextPath) return; const nextGroups = normalizeNoteGroups(groups.map((item) => replaceNoteGroupPrefix(item, group, nextPath) || "")); const nextNotes = sortedNotes.map((note) => ({ ...note, group: replaceNoteGroupPrefix(note.group, group, nextPath), })); onUpdateNoteGroups(nextGroups); onUpdateNotes(normalizeVaultNotes(nextNotes)); setExpandedGroups((current) => remapExpandedNoteGroupPaths(current, group, nextPath)); if (selectedGroup && isNoteGroupInside(selectedGroup, group)) { setSelectedGroup(replaceNoteGroupPrefix(selectedGroup, group, nextPath) ?? null); } }; const reorderGroupToGroup = ( sourceGroup: string, targetGroup: string, position: VaultDropPosition, ) => { if (!sourceGroup || !targetGroup || sourceGroup === targetGroup) return; if (targetGroup.startsWith(`${sourceGroup}/`)) return; const targetParent = getNoteGroupParentPath(targetGroup); const knownGroups = normalizeNoteGroups([ ...groups, ...sortedNotes.map((note) => note.group).filter((item): item is string => Boolean(item)), ]); const nextSourceGroup = getNoteGroupParentPath(sourceGroup) === targetParent ? cleanNoteGroupPath(sourceGroup) : resolveMovedNoteGroupPath(sourceGroup, targetParent, knownGroups); if (!nextSourceGroup) return; const nextGroupsBeforeReorder = normalizeNoteGroups([ ...groups.map((item) => replaceNoteGroupPrefix(item, sourceGroup, nextSourceGroup) || ""), ...ancestorNoteGroupPaths(nextSourceGroup), ...ancestorNoteGroupPaths(targetGroup), ]); const nextGroups = reorderVaultStrings( nextGroupsBeforeReorder, nextSourceGroup, targetGroup, position, ); const nextNotes = nextSourceGroup === sourceGroup ? sortedNotes : sortedNotes.map((note) => ({ ...note, group: replaceNoteGroupPrefix(note.group, sourceGroup, nextSourceGroup), })); onUpdateNoteGroups(nextGroups); if (nextSourceGroup !== sourceGroup) { onUpdateNotes(normalizeVaultNotes(nextNotes)); setExpandedGroups((current) => remapExpandedNoteGroupPaths(current, sourceGroup, nextSourceGroup)); if (selectedGroup && isNoteGroupInside(selectedGroup, sourceGroup)) { setSelectedGroup(replaceNoteGroupPrefix(selectedGroup, sourceGroup, nextSourceGroup) ?? null); } } }; const handleGroupDrop = (targetGroup: string | null, event: React.DragEvent) => { event.preventDefault(); event.stopPropagation(); const noteId = getDraggedNoteId(event.dataTransfer); const groupPath = getDraggedGroupPath(event.dataTransfer); if (noteId) moveNoteToGroup(noteId, targetGroup); if (groupPath) moveGroupToParent(groupPath, targetGroup); resetTreeDragState(); }; const renderNoteActions = (note: VaultNote, mode: "dropdown" | "context") => { const actions = [ { label: t("common.rename"), action: () => setEditingNoteId(note.id), }, { label: t("action.copy"), action: () => duplicateNoteById(note.id), }, { label: t("action.delete"), action: () => deleteNoteById(note.id), destructive: true, }, ]; if (mode === "context") { return actions.map((action) => ( { action.action(); }} > {action.label} )); } return actions.map((action) => ( )); }; const renderGroupActions = (groupPath: string, mode: "dropdown" | "context") => { const actions = [ { label: t("notes.action.newNote"), action: () => addNoteToGroup(groupPath), }, { label: t("notes.action.newGroup"), action: () => { setCreatingGroupParent(groupPath); expandPath(groupPath); }, }, { label: t("common.rename"), action: () => setEditingGroupPath(groupPath), }, { label: t("action.delete"), action: () => deleteGroup(groupPath), destructive: true, }, ]; if (mode === "context") { return actions.map((action) => ( { action.action(); }} > {action.label} )); } return actions.map((action) => ( )); }; const renderCreateGroupRow = (parent: string | null, depth: number) => { if (creatingGroupParent !== parent) return null; return (
setCreatingGroupParent(undefined)} />
); }; const renderNoteRow = (note: VaultNote, depth: number) => { if (!noteMatches(note)) return null; return ( { setEditingNoteId(null); const title = name.trim(); if (!title) return; saveNote({ ...note, title, updatedAt: Date.now() }); }} onRenameCancel={() => setEditingNoteId(null)} icon={} data-note-id={note.id} data-notes-drag-kind="note" data-notes-context-menu="note" data-vault-reorder-dragging={draggingNoteId === note.id ? "true" : undefined} draggable={editingNoteId !== note.id} onDragStart={(event) => { event.dataTransfer.setData(NOTE_DRAG_TYPE, note.id); event.dataTransfer.setData("note-id", note.id); event.dataTransfer.effectAllowed = "move"; setDraggingNoteId(note.id); }} onDragOver={(event) => { const sourceNoteId = draggingNoteId || getDraggedNoteId(event.dataTransfer); if (!sourceNoteId || sourceNoteId === note.id) { clearVaultDropIndicator(); return; } event.preventDefault(); event.stopPropagation(); event.dataTransfer.dropEffect = "move"; markVaultDropIndicator( event.currentTarget, getVaultDropPosition(event.currentTarget, event.clientX, event.clientY), ); }} onDragLeave={handleTreeRowDragLeave} onDrop={(event) => { event.preventDefault(); event.stopPropagation(); reorderNoteToNote(draggingNoteId || getDraggedNoteId(event.dataTransfer), note, event); resetTreeDragState(); }} onDragEnd={resetTreeDragState} onClick={() => { const nextSelection = getNoteSelectionState(note, isSidebarMode); setSelectedNoteId(nextSelection.selectedNoteId); setSelectedGroup(nextSelection.selectedGroup); setOverlayNoteId(nextSelection.overlayNoteId); }} actions={( {renderNoteActions(note, "dropdown")} )} /> {renderNoteActions(note, "context")} ); }; const renderFolderRow = (node: NoteFolderNode, depth: number): React.ReactNode => { const folderMatchesQuery = groupMatches(node); const visibleNotes = folderMatchesQuery ? node.notes : node.notes.filter(noteMatches); const visibleChildren = node.children .map((child) => renderFolderRow(child, depth + 1)) .filter(Boolean); if (queryText && !folderMatchesQuery && visibleNotes.length === 0 && visibleChildren.length === 0) { return null; } const expanded = queryText ? true : expandedGroups.has(node.path); const hasChildren = node.children.length > 0 || node.notes.length > 0; return ( renameGroup(node.path, name)} onRenameCancel={() => setEditingGroupPath(null)} data-note-group-path={node.path} data-notes-drag-kind="group" data-notes-context-menu="group" data-vault-reorder-dragging={draggingGroupPath === node.path ? "true" : undefined} draggable={editingGroupPath !== node.path} onDragStart={(event) => { event.dataTransfer.setData(NOTE_GROUP_DRAG_TYPE, node.path); event.dataTransfer.setData("note-group-path", node.path); event.dataTransfer.effectAllowed = "move"; setDraggingGroupPath(node.path); }} onDragOver={(event) => { const sourceNoteId = draggingNoteId || getDraggedNoteId(event.dataTransfer); const sourceGroupPath = draggingGroupPath || getDraggedGroupPath(event.dataTransfer); if (!sourceNoteId && !sourceGroupPath) { clearVaultDropIndicator(); return; } if (sourceGroupPath && (sourceGroupPath === node.path || node.path.startsWith(`${sourceGroupPath}/`))) { clearVaultDropIndicator(); return; } event.preventDefault(); event.stopPropagation(); event.dataTransfer.dropEffect = "move"; if (sourceGroupPath) { const intent = getVaultDropIntent(event.currentTarget, event.clientX, event.clientY, false); if (intent === "inside") { markVaultInsideDropIndicator(event.currentTarget); } else { markVaultDropIndicator(event.currentTarget, intent); } return; } markVaultInsideDropIndicator(event.currentTarget); }} onDragLeave={handleTreeRowDragLeave} onDrop={(event) => { const sourceGroupPath = draggingGroupPath || getDraggedGroupPath(event.dataTransfer); if (sourceGroupPath) { const intent = getVaultDropIntent(event.currentTarget, event.clientX, event.clientY, false); const dropAction = getNotesGroupDropAction(sourceGroupPath, node.path, intent); if (dropAction === "reorder" && intent !== "inside") { event.preventDefault(); event.stopPropagation(); reorderGroupToGroup(sourceGroupPath, node.path, intent); resetTreeDragState(); return; } if (dropAction === "ignore") return; } handleGroupDrop(node.path, event); }} onDragEnd={resetTreeDragState} onClick={() => { const nextSelection = getNoteGroupSelectionState(node.path); setSelectedNoteId(nextSelection.selectedNoteId); setSelectedGroup(nextSelection.selectedGroup); setOverlayNoteId(nextSelection.overlayNoteId); if (hasChildren) toggleGroup(node.path); }} actions={( {renderGroupActions(node.path, "dropdown")} )} /> {renderGroupActions(node.path, "context")} {expanded && ( <> {renderCreateGroupRow(node.path, depth + 1)} {visibleChildren} {visibleNotes.map((note) => renderNoteRow(note, depth + 1))} )} ); }; const visibleRootNotes = noteTree.rootNotes.filter(noteMatches); const visibleTree = noteTree.children .map((child) => renderFolderRow(child, 0)) .filter(Boolean); const treeIsEmpty = visibleRootNotes.length === 0 && visibleTree.length === 0; const hasSearch = query.trim().length > 0; const canExpandCollapse = allGroupPaths.length > 0 && !hasSearch; const handleTreeResizeStart = useCallback((event: React.PointerEvent) => { event.preventDefault(); event.stopPropagation(); const startX = event.clientX; const startWidth = treeWidth; const previousCursor = document.body.style.cursor; const previousUserSelect = document.body.style.userSelect; setIsTreeResizing(true); document.body.style.cursor = "col-resize"; document.body.style.userSelect = "none"; const clampWidth = (value: number) => Math.max(NOTES_TREE_MIN_WIDTH, Math.min(NOTES_TREE_MAX_WIDTH, value)); const handlePointerMove = (moveEvent: PointerEvent) => { setTreeWidth(clampWidth(startWidth + moveEvent.clientX - startX)); }; const handlePointerUp = (upEvent: PointerEvent) => { const nextWidth = clampWidth(startWidth + upEvent.clientX - startX); setTreeWidth(nextWidth); persistTreeWidth(nextWidth); setIsTreeResizing(false); document.body.style.cursor = previousCursor; document.body.style.userSelect = previousUserSelect; window.removeEventListener("pointermove", handlePointerMove); window.removeEventListener("pointerup", handlePointerUp); window.removeEventListener("pointercancel", handlePointerUp); }; window.addEventListener("pointermove", handlePointerMove); window.addEventListener("pointerup", handlePointerUp); window.addEventListener("pointercancel", handlePointerUp); }, [persistTreeWidth, setTreeWidth, treeWidth]); return (
{!isSidebarMode && (
{selectedNote ? ( <>
saveNote({ ...selectedNote, title: event.target.value, updatedAt: Date.now(), })} />
saveNote({ ...selectedNote, content, updatedAt: Date.now(), })} hosts={hosts} onOpenHost={(host) => handleOpenHostFromNote(host, selectedNote.id)} onOpenExternalLink={openExternal} />
) : (

{t("notes.empty.title")}

{t("notes.empty.desc")}

)}
)}
{isSidebarMode && overlayNote && (
{t("common.back")}
{overlayNote.title || t("notes.title.placeholder")}
saveNote({ ...overlayNote, title: event.target.value, updatedAt: Date.now(), })} />
saveNote({ ...overlayNote, content, updatedAt: Date.now(), })} hosts={hosts} onOpenHost={(host) => handleOpenHostFromNote(host, overlayNote.id)} onOpenExternalLink={openExternal} />
)}
); };