Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
feat(notes): spaces sidebar tree — private/team sections, DnD, menus, keyboard nav
Gabriel Steinc18db7c514ac
diff --git a/preload.js b/preload.jsindex b34f3593f..f3eff0c2e 100644--- a/preload.js+++ b/preload.js@@ -135,6 +135,7 @@ contextBridge.exposeInMainWorld("electronAPI", {createFolder: (name, spaceId) => ipcRenderer.invoke("db-create-folder", name, spaceId),deleteFolder: (id) => ipcRenderer.invoke("db-delete-folder", id),renameFolder: (id, name) => ipcRenderer.invoke("db-rename-folder", id, name),+ moveFolderToSpace: (id, spaceId) => ipcRenderer.invoke("db-move-folder-to-space", id, spaceId),getFolderNoteCounts: () => ipcRenderer.invoke("db-get-folder-note-counts"),// Space functionsdiff --git a/src/components/CommandSearch.tsx b/src/components/CommandSearch.tsxindex 8765d494f..cf6233151 100644--- a/src/components/CommandSearch.tsx+++ b/src/components/CommandSearch.tsx@@ -1,9 +1,9 @@import { useState, useEffect, useCallback, useMemo, useRef } from "react";import { useTranslation } from "react-i18next";import * as DialogPrimitive from "@radix-ui/react-dialog";-import { Search, FileText, Mic, Folder, Users, Upload, MessageSquare } from "lucide-react";+import { Search, FileText, Mic, Folder, Lock, Users, Upload, MessageSquare } from "lucide-react";import { cn } from "./lib/utils";-import type { NoteItem, FolderItem, TranscriptionItem } from "../types/electron.js";+import type { NoteItem, FolderItem, SpaceItem, TranscriptionItem } from "../types/electron.js";import { normalizeDbDate } from "../utils/dateFormatting";interface ConversationResult {@@ -13,17 +13,27 @@ interface ConversationResult {updated_at: string;}+interface JumpTarget {+ key: string;+ spaceId: number;+ folderId: number | null;+ label: string;+ space: SpaceItem | undefined;+}+export interface CommandSearchProps {open: boolean;onOpenChange: (open: boolean) => void;mode?: "all" | "conversations";transcriptions?: TranscriptionItem[];- onNoteSelect?: (noteId: number, folderId: number | null) => void;+ onNoteSelect?: (noteId: number, folderId: number | null, spaceId?: number) => void;+ onContainerSelect?: (spaceId: number, folderId: number | null) => void;onTranscriptSelect?: (transcriptId: number) => void;onConversationSelect?: (conversationId: number) => void;}type FlatItem =+ | { kind: "container"; target: JumpTarget }| { kind: "note"; note: NoteItem }| { kind: "transcript"; transcript: TranscriptionItem }| { kind: "conversation"; conversation: ConversationResult };@@ -60,6 +70,7 @@ export default function CommandSearch({mode = "all",transcriptions = [],onNoteSelect,+ onContainerSelect,onTranscriptSelect,onConversationSelect,}: CommandSearchProps) {@@ -67,6 +78,7 @@ export default function CommandSearch({const [query, setQuery] = useState("");const [notes, setNotes] = useState<NoteItem[]>([]);const [folders, setFolders] = useState<FolderItem[]>([]);+ const [spaces, setSpaces] = useState<SpaceItem[]>([]);const [conversations, setConversations] = useState<ConversationResult[]>([]);const [selectedIndex, setSelectedIndex] = useState(0);const inputRef = useRef<HTMLInputElement>(null);@@ -84,6 +96,10 @@ export default function CommandSearch({.getFolders().then(setFolders).catch(() => {});+ window.electronAPI+ .getSpaces?.()+ .then((items) => setSpaces(items ?? []))+ .catch(() => {});}, [isConversationsMode]);if (open && !prevOpen) {@@ -183,29 +199,49 @@ export default function CommandSearch({}const folderMap = useMemo(() => new Map(folders.map((f) => [f.id, f])), [folders]);+ const spaceMap = useMemo(() => new Map(spaces.map((s) => [s.id, s])), [spaces]);++ const spaceLabel = useCallback(+ (space: SpaceItem) =>+ space.kind === "private"+ ? t("notes.spaces.personal")+ : `${space.emoji ? `${space.emoji} ` : ""}${space.name}`,+ [t]+ );++ const noteBreadcrumb = useCallback(+ (note: NoteItem) => {+ const space = spaceMap.get(note.space_id);+ const folder = note.folder_id != null ? folderMap.get(note.folder_id) : undefined;+ if (!space) return folder?.name ?? "";+ return folder ? `${spaceLabel(space)} / ${folder.name}` : spaceLabel(space);+ },+ [spaceMap, folderMap, spaceLabel]+ );- const noteGroups = useMemo(() => {- const groups = new Map<number | null, NoteItem[]>();- for (const note of notes) {- const fid = note.folder_id ?? null;- if (!groups.has(fid)) groups.set(fid, []);- groups.get(fid)!.push(note);+ const jumpTargets = useMemo<JumpTarget[]>(() => {+ const q = query.trim().toLowerCase();+ if (!q || isConversationsMode) return [];+ const targets: JumpTarget[] = [];+ for (const space of spaces) {+ const label = spaceLabel(space);+ if (label.toLowerCase().includes(q)) {+ targets.push({ key: `s:${space.id}`, spaceId: space.id, folderId: null, label, space });+ }+ }+ for (const folder of folders) {+ if (folder.name.toLowerCase().includes(q)) {+ targets.push({+ key: `f:${folder.id}`,+ spaceId: folder.space_id,+ folderId: folder.id,+ label: folder.name,+ space: spaceMap.get(folder.space_id),+ });+ }}- return [...groups.entries()]- .sort(([a], [b]) => {- if (a === null) return -1;- if (b === null) return 1;- const fa = folderMap.get(a);- const fb = folderMap.get(b);- if (fa?.is_default) return -1;- if (fb?.is_default) return 1;- return (fa?.sort_order ?? 0) - (fb?.sort_order ?? 0);- })- .map(([fid, items]) => ({- folder: fid !== null ? (folderMap.get(fid) ?? null) : null,- items,- }));- }, [notes, folderMap]);+ return targets.slice(0, 5);+ }, [query, spaces, folders, spaceMap, spaceLabel, isConversationsMode]);const filteredTranscripts = useMemo(() => {const slice = query.trim()@@ -219,21 +255,22 @@ export default function CommandSearch({return conversations.map((c) => ({ kind: "conversation" as const, conversation: c }));}const items: FlatItem[] = [];- for (const group of noteGroups) {- for (const note of group.items) items.push({ kind: "note", note });- }+ for (const target of jumpTargets) items.push({ kind: "container", target });+ for (const note of notes) items.push({ kind: "note", note });for (const transcript of filteredTranscripts) items.push({ kind: "transcript", transcript });return items;- }, [noteGroups, filteredTranscripts, conversations, isConversationsMode]);+ }, [jumpTargets, notes, filteredTranscripts, conversations, isConversationsMode]);const selectItem = useCallback((item: FlatItem) => {- if (item.kind === "note") onNoteSelect?.(item.note.id, item.note.folder_id ?? null);+ if (item.kind === "container") onContainerSelect?.(item.target.spaceId, item.target.folderId);+ else if (item.kind === "note")+ onNoteSelect?.(item.note.id, item.note.folder_id ?? null, item.note.space_id);else if (item.kind === "transcript") onTranscriptSelect?.(item.transcript.id);else if (item.kind === "conversation") onConversationSelect?.(item.conversation.id);onOpenChange(false);},- [onNoteSelect, onTranscriptSelect, onConversationSelect, onOpenChange]+ [onNoteSelect, onContainerSelect, onTranscriptSelect, onConversationSelect, onOpenChange]);const handleKeyDown = useCallback(@@ -361,38 +398,60 @@ export default function CommandSearch({))) : (<>- {noteGroups.length > 0 && (+ {jumpTargets.length > 0 && (<div>- {noteGroups.map((group) => {- const label = group.folder?.name ?? t("commandSearch.sections.notes");- const Icon = group.folder ? Folder : FileText;+ <SectionHeader+ icon={<Folder size={11} />}+ label={t("commandSearch.sections.jumpTo")}+ />+ {jumpTargets.map((target) => {+ const idx = flatItems.findIndex(+ (fi) => fi.kind === "container" && fi.target.key === target.key+ );return (- <div key={group.folder?.id ?? "null-folder"}>- <SectionHeader icon={<Icon size={11} />} label={label} />- {group.items.map((note) => {- const idx = flatItems.findIndex(- (fi) => fi.kind === "note" && fi.note.id === note.id- );- return (- <NoteRow- key={note.id}- note={note}- idx={idx}- isSelected={selectedIndex === idx}- onSelect={() => selectItem({ kind: "note", note })}- onHover={() => setSelectedIndex(idx)}- t={t}- />- );- })}- </div>+ <ContainerRow+ key={target.key}+ target={target}+ showSpaceHint={target.folderId != null && spaces.length > 1}+ spaceLabel={spaceLabel}+ idx={idx}+ isSelected={selectedIndex === idx}+ onSelect={() => selectItem({ kind: "container", target })}+ onHover={() => setSelectedIndex(idx)}+ />+ );+ })}+ </div>+ )}++ {notes.length > 0 && (+ <div className={jumpTargets.length > 0 ? "mt-0.5" : ""}>+ <SectionHeader+ icon={<FileText size={11} />}+ label={t("commandSearch.sections.notes")}+ />+ {notes.map((note) => {+ const idx = flatItems.findIndex(+ (fi) => fi.kind === "note" && fi.note.id === note.id+ );+ return (+ <NoteRow+ key={note.id}+ note={note}+ breadcrumb={noteBreadcrumb(note)}+ idx={idx}+ isSelected={selectedIndex === idx}+ onSelect={() => selectItem({ kind: "note", note })}+ onHover={() => setSelectedIndex(idx)}+ t={t}+ />);})}</div>)}{filteredTranscripts.length > 0 && (- <div className={noteGroups.length > 0 ? "mt-0.5" : ""}>+ <div className={jumpTargets.length > 0 || notes.length > 0 ? "mt-0.5" : ""}><SectionHeadericon={<Mic size={11} />}label={t("commandSearch.sections.transcripts")}@@ -442,8 +501,65 @@ function SectionHeader({ icon, label }: { icon: React.ReactNode; label: string });}+function ContainerRow({+ target,+ showSpaceHint,+ spaceLabel,+ idx,+ isSelected,+ onSelect,+ onHover,+}: {+ target: JumpTarget;+ showSpaceHint: boolean;+ spaceLabel: (space: SpaceItem) => string;+ idx: number;+ isSelected: boolean;+ onSelect: () => void;+ onHover: () => void;+}) {+ const { space } = target;+ const iconClass = cn(+ "shrink-0 transition-colors",+ isSelected ? "text-primary" : "text-muted-foreground/40"+ );+ return (+ <button+ type="button"+ data-idx={idx}+ onClick={onSelect}+ onMouseEnter={onHover}+ className={cn(+ "group flex items-center gap-2.5 w-full px-2.5 py-2 rounded-lg text-left transition-colors duration-100 outline-none",+ isSelected+ ? "bg-primary/8 dark:bg-primary/10"+ : "hover:bg-foreground/4 dark:hover:bg-white/4"+ )}+ >+ {target.folderId != null ? (+ <Folder size={13} className={iconClass} />+ ) : space?.kind === "private" ? (+ <Lock size={13} className={iconClass} />+ ) : space?.emoji ? (+ <span className="text-[13px] leading-none shrink-0" aria-hidden="true">+ {space.emoji}+ </span>+ ) : (+ <Users size={13} className={iconClass} />+ )}+ <p className="flex-1 text-xs font-medium text-foreground truncate min-w-0">{target.label}</p>+ {showSpaceHint && space && (+ <span className="text-[10px] text-muted-foreground/45 truncate shrink-0 max-w-32">+ {spaceLabel(space)}+ </span>+ )}+ </button>+ );+}+function NoteRow({note,+ breadcrumb,idx,isSelected,onSelect,@@ -451,6 +567,7 @@ function NoteRow({t,}: {note: NoteItem;+ breadcrumb: string;idx: number;isSelected: boolean;onSelect: () => void;@@ -489,8 +606,12 @@ function NoteRow({>{note.title || t("notes.list.untitled")}</p>- {preview && (- <p className="text-[11px] text-muted-foreground/55 truncate mt-px">{preview}</p>+ {(breadcrumb || preview) && (+ <p className="text-[10px] truncate mt-px">+ {breadcrumb && <span className="text-muted-foreground/45">{breadcrumb}</span>}+ {breadcrumb && preview && <span className="text-muted-foreground/35"> · </span>}+ {preview && <span className="text-muted-foreground/55">{preview}</span>}+ </p>)}</div><span className="text-[10px] text-muted-foreground/35 tabular-nums shrink-0">diff --git a/src/components/ControlPanel.tsx b/src/components/ControlPanel.tsxindex a9b638e76..c979ce20b 100644--- a/src/components/ControlPanel.tsx+++ b/src/components/ControlPanel.tsx@@ -36,6 +36,7 @@ import { isAccessibilitySkipped } from "../utils/permissions";import {setActiveNoteId,setActiveFolderId,+ navigateToContainer,useActiveNoteId,initializeNotes,} from "../stores/noteStore";@@ -715,11 +716,16 @@ export default function ControlPanel({ initialSettingsSection }: ControlPanelProopen={showSearch}onOpenChange={setShowSearch}transcriptions={history}- onNoteSelect={(id, folderId) => {- if (folderId) setActiveFolderId(folderId);+ onNoteSelect={(id, folderId, spaceId) => {+ if (folderId != null) setActiveFolderId(folderId);+ else if (spaceId != null) navigateToContainer(spaceId, null);setActiveNoteId(id);setActiveView("personal-notes");}}+ onContainerSelect={(spaceId, folderId) => {+ navigateToContainer(spaceId, folderId);+ setActiveView("personal-notes");+ }}onTranscriptSelect={() => {setActiveView("home");}}diff --git a/src/components/notes/CreateSpaceDialog.tsx b/src/components/notes/CreateSpaceDialog.tsxnew file mode 100644index 000000000..df5981515--- /dev/null+++ b/src/components/notes/CreateSpaceDialog.tsx@@ -0,0 +1,94 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "../ui/dialog";+import { Button } from "../ui/button";+import { Input } from "../ui/input";+import { useToast } from "../ui/useToast";+import { createSpace } from "../../stores/noteStore";++interface CreateSpaceDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+}++export default function CreateSpaceDialog({ open, onOpenChange }: CreateSpaceDialogProps) {+ const { t } = useTranslation();+ const { toast } = useToast();+ const [name, setName] = useState("");+ const [emoji, setEmoji] = useState("");+ const [isCreating, setIsCreating] = useState(false);++ const handleOpenChange = (nextOpen: boolean) => {+ onOpenChange(nextOpen);+ if (!nextOpen) {+ setName("");+ setEmoji("");+ }+ };++ const handleCreate = async () => {+ const trimmed = name.trim();+ if (!trimmed || isCreating) return;+ setIsCreating(true);+ try {+ const result = await createSpace(trimmed, emoji.trim() || null);+ if (result.success) {+ handleOpenChange(false);+ } else if (result.error) {+ toast({+ title: t("notes.spaces.couldNotCreate"),+ description: result.error,+ variant: "destructive",+ });+ }+ } finally {+ setIsCreating(false);+ }+ };++ return (+ <Dialog open={open} onOpenChange={handleOpenChange}>+ <DialogContent className="sm:max-w-95 p-6 gap-5">+ <DialogHeader>+ <DialogTitle>{t("notes.spaces.createTitle")}</DialogTitle>+ </DialogHeader>++ <div className="flex gap-3">+ <div className="space-y-1.5 w-14 shrink-0">+ <label className="text-xs font-medium text-foreground/50">+ {t("notes.spaces.emojiLabel")}+ </label>+ <Input+ value={emoji}+ onChange={(e) => setEmoji(e.target.value)}+ maxLength={4}+ className="text-center"+ />+ </div>+ <div className="space-y-1.5 flex-1">+ <label className="text-xs font-medium text-foreground/50">+ {t("notes.spaces.nameLabel")}+ </label>+ <Input+ value={name}+ autoFocus+ onChange={(e) => setName(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") handleCreate();+ }}+ />+ </div>+ </div>++ <DialogFooter>+ <Button variant="ghost" onClick={() => handleOpenChange(false)}>+ {t("notes.upload.cancel")}+ </Button>+ <Button onClick={handleCreate} disabled={!name.trim() || isCreating}>+ {t("notes.spaces.create")}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/src/components/notes/NoteListItem.tsx b/src/components/notes/NoteListItem.tsxdeleted file mode 100644index 6d0d74478..000000000--- a/src/components/notes/NoteListItem.tsx+++ /dev/null@@ -1,301 +0,0 @@-import { useState, useMemo } from "react";-import { useTranslation } from "react-i18next";-import {- MoreHorizontal,- FolderOpen,- Trash2,- Check,- Plus,- Search,- ExternalLink,- Share2,-} from "lucide-react";-import { Button } from "../ui/button";-import {- DropdownMenu,- DropdownMenuTrigger,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSub,- DropdownMenuSubTrigger,- DropdownMenuSubContent,- DropdownMenuSeparator,-} from "../ui/dropdown-menu";-import { cn } from "../lib/utils";-import type { NoteItem, FolderItem } from "../../types/electron";-import { normalizeDbDate } from "../../utils/dateFormatting";--const RE_HEADING = /#{1,6}\s+/g;-const RE_EMPHASIS = /[*_~`]+/g;-const RE_LINK = /\[([^\]]+)\]\([^)]+\)/g;-const RE_IMAGE = /!\[([^\]]*)\]\([^)]+\)/g;-const RE_BLOCKQUOTE = />\s+/g;-const RE_NEWLINES = /\n+/g;--interface NoteListItemProps {- note: NoteItem;- isActive: boolean;- onClick: () => void;- onDelete: (id: number) => void;- folders: FolderItem[];- currentFolderId: number | null;- onMoveToFolder: (noteId: number, folderId: number) => void;- onCreateFolderAndMove: (noteId: number, folderName: string) => void;- dragHandlers?: {- draggable: true;- onDragStart: (e: React.DragEvent) => void;- onDragEnd: () => void;- };- isDragging?: boolean;- noteFilesEnabled?: boolean;-}--function stripMarkdown(text: string): string {- return text- .replace(RE_HEADING, "")- .replace(RE_EMPHASIS, "")- .replace(RE_LINK, "$1")- .replace(RE_IMAGE, "$1")- .replace(RE_BLOCKQUOTE, "")- .replace(RE_NEWLINES, " ")- .trim();-}--function relativeTime(- dateStr: string,- t: (key: string, options?: Record<string, unknown>) => string-): string {- const date = normalizeDbDate(dateStr);- if (Number.isNaN(date.getTime())) return dateStr;-- const diff = Date.now() - date.getTime();- const minutes = Math.floor(diff / 60000);- const hours = Math.floor(diff / 3600000);- const days = Math.floor(diff / 86400000);-- if (minutes < 1) return t("notes.list.timeNow");- if (minutes < 60) return t("notes.list.minutesAgo", { count: minutes });- if (hours < 24) return t("notes.list.hoursAgo", { count: hours });- if (days < 7) return t("notes.list.daysAgo", { count: days });- return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });-}--export default function NoteListItem({- note,- isActive,- onClick,- onDelete,- folders,- currentFolderId,- onMoveToFolder,- onCreateFolderAndMove,- dragHandlers,- isDragging,- noteFilesEnabled,-}: NoteListItemProps) {- const { t } = useTranslation();- const preview = stripMarkdown(note.content);- const [folderSearch, setFolderSearch] = useState("");- const [newFolderName, setNewFolderName] = useState("");- const [isCreating, setIsCreating] = useState(false);-- const fileManagerName = navigator.platform.startsWith("Mac")- ? "Finder"- : navigator.platform.startsWith("Win")- ? "Explorer"- : "Files";-- const filteredFolders = useMemo(- () =>- folderSearch- ? folders.filter((f) => f.name.toLowerCase().includes(folderSearch.toLowerCase()))- : folders,- [folders, folderSearch]- );-- return (- <button- type="button"- onClick={onClick}- {...dragHandlers}- className={cn(- "group relative w-full text-left px-3 py-2 cursor-pointer transition-all duration-150",- "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/30",- isActive ? "bg-primary/6 dark:bg-primary/8" : "hover:bg-foreground/3 dark:hover:bg-white/3",- isDragging && "opacity-40 scale-[0.97]"- )}- >- <div className="flex-1 min-w-0">- <div className="flex items-center justify-between gap-2">- <p- className={cn(- "text-xs truncate transition-colors duration-150 text-foreground",- isActive && "font-medium"- )}- >- {note.title || t("notes.list.untitled")}- </p>- <div className="flex items-center gap-0.5 shrink-0">- {Boolean(note.is_shared) && (- <Share2- size={11}- className="text-foreground/40 mr-1 group-hover:opacity-0 transition-opacity"- aria-label={t("notes.list.shared")}- />- )}- <span className="text-xs text-muted-foreground dark:text-muted-foreground/30 tabular-nums group-hover:opacity-0 transition-opacity">- {relativeTime(note.updated_at, t)}- </span>- <DropdownMenu- onOpenChange={(open) => {- if (!open) {- setFolderSearch("");- setIsCreating(false);- setNewFolderName("");- }- }}- >- <DropdownMenuTrigger asChild>- <Button- size="icon"- variant="ghost"- onClick={(e) => e.stopPropagation()}- className="h-5 w-5 rounded-sm opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100 transition-opacity absolute right-2 text-muted-foreground/60 dark:text-muted-foreground/40 hover:text-foreground/60 hover:bg-foreground/5 active:bg-foreground/8"- >- <MoreHorizontal size={12} />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" sideOffset={4} className="min-w-40">- {noteFilesEnabled && (- <>- <DropdownMenuItem- onClick={(e) => {- e.stopPropagation();- window.electronAPI?.showNoteFile?.(note.id);- }}- className="text-xs gap-2 rounded-lg px-2.5 py-1.5 cursor-pointer focus:bg-foreground/5"- >- <ExternalLink- size={12}- className="text-muted-foreground/80 dark:text-muted-foreground/60"- />- {t("notes.context.showInFileManager", { manager: fileManagerName })}- </DropdownMenuItem>- <DropdownMenuSeparator />- </>- )}- <DropdownMenuSub>- <DropdownMenuSubTrigger className="text-xs gap-2 rounded-lg px-2.5 py-1.5 cursor-pointer focus:bg-foreground/5 data-[state=open]:bg-foreground/5">- <FolderOpen- size={12}- className="text-muted-foreground/80 dark:text-muted-foreground/60"- />- {t("notes.context.moveToFolder")}- </DropdownMenuSubTrigger>- <DropdownMenuSubContent- sideOffset={4}- className="min-w-36 rounded-xl border border-border p-1"- >- {folders.length > 5 && (- <>- <div className="relative px-1.5 py-0.5">- <Search- size={9}- className="absolute left-3.5 top-1/2 -translate-y-1/2 text-foreground/15 pointer-events-none"- />- <input- value={folderSearch}- onChange={(e) => setFolderSearch(e.target.value)}- onKeyDown={(e) => e.stopPropagation()}- placeholder={t("notes.context.searchFolders")}- className="input-inline w-full pl-4.5 pr-1 py-0.5 text-xs text-foreground placeholder:text-foreground/15 outline-none border-none appearance-none"- />- </div>- <DropdownMenuSeparator />- </>- )}- <div className="overflow-y-auto max-h-40">- {filteredFolders.map((folder) => {- const isCurrent = folder.id === currentFolderId;- return (- <DropdownMenuItem- key={folder.id}- disabled={isCurrent}- onClick={(e) => {- e.stopPropagation();- onMoveToFolder(note.id, folder.id);- }}- className="text-xs gap-2 rounded-md px-2 py-1"- >- <span className="truncate flex-1">{folder.name}</span>- {isCurrent && <Check size={9} className="text-primary shrink-0" />}- </DropdownMenuItem>- );- })}- {folderSearch && filteredFolders.length === 0 && (- <p className="text-xs text-foreground/20 text-center py-1.5">- {t("notes.context.noResults")}- </p>- )}- </div>- <DropdownMenuSeparator />- {isCreating ? (- <div className="px-1">- <input- autoFocus- value={newFolderName}- onChange={(e) => setNewFolderName(e.target.value)}- onKeyDown={(e) => {- e.stopPropagation();- if (e.key === "Enter" && newFolderName.trim()) {- onCreateFolderAndMove(note.id, newFolderName.trim());- setNewFolderName("");- setIsCreating(false);- }- if (e.key === "Escape") {- setIsCreating(false);- setNewFolderName("");- }- }}- placeholder={t("notes.folders.folderName")}- className="input-inline w-full px-2 py-1.5 rounded-md bg-transparent text-xs text-foreground placeholder:text-foreground/20 outline-none border-none appearance-none"- />- </div>- ) : (- <DropdownMenuItem- onSelect={(e) => {- e.preventDefault();- setIsCreating(true);- }}- className="text-xs gap-2 rounded-md px-2 py-1 text-foreground/40"- >- <Plus size={10} />- {t("notes.context.newFolder")}- </DropdownMenuItem>- )}- </DropdownMenuSubContent>- </DropdownMenuSub>- <DropdownMenuSeparator />- <DropdownMenuItem- onClick={(e) => {- e.stopPropagation();- onDelete(note.id);- }}- className="text-xs gap-2 rounded-lg px-2.5 py-1.5 text-destructive focus:text-destructive focus:bg-destructive/10"- >- <Trash2 size={12} />- {t("notes.context.delete")}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </div>- </div>- {preview && (- <p className="text-xs text-muted-foreground/80 dark:text-muted-foreground/40 line-clamp-1 mt-0.5">- {preview}- </p>- )}- </div>- </button>- );-}diff --git a/src/components/notes/PersonalNotesView.tsx b/src/components/notes/PersonalNotesView.tsxindex caf874e1c..7e629e037 100644--- a/src/components/notes/PersonalNotesView.tsx+++ b/src/components/notes/PersonalNotesView.tsx@@ -1,72 +1,54 @@import { useState, useEffect, useRef, useCallback, useMemo } from "react";import { useTranslation } from "react-i18next";-import {- Plus,- Loader2,- FolderOpen,- MoreHorizontal,- Pencil,- Trash2,- Check,- SquarePen,- Search,- Sparkles,- ExternalLink,-} from "lucide-react";+import { Plus, SquarePen, Search, Sparkles } from "lucide-react";import { Button } from "../ui/button";-import {- DropdownMenu,- DropdownMenuTrigger,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,-} from "../ui/dropdown-menu";-import {- ConfirmDialog,- Dialog,- DialogContent,- DialogHeader,- DialogTitle,- DialogFooter,-} from "../ui/dialog";-import { useDialogs } from "../../hooks/useDialogs";+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "../ui/dialog";import {Select,SelectTrigger,SelectValue,SelectContent,+ SelectGroup,+ SelectLabel,SelectItem,SelectSeparator,} from "../ui/select";import { Input } from "../ui/input";import { useToast } from "../ui/useToast";-import NoteListItem from "./NoteListItem";import NoteEditor from "./NoteEditor";+import SpacesTree from "./SpacesTree";import ActionPicker from "./ActionPicker";import ActionManagerDialog from "./ActionManagerDialog";import AddNotesToFolderDialog from "./AddNotesToFolderDialog";import { useActionProcessing } from "../../hooks/useActionProcessing";+import type { NoteMoveTarget } from "../../hooks/useNoteDragAndDrop";import {useSettingsStore,selectIsCloudNoteFormattingMode,selectResolvedNoteFormatting,} from "../../stores/settingsStore";-import { useFolderManagement } from "../../hooks/useFolderManagement";-import { useNoteDragAndDrop } from "../../hooks/useNoteDragAndDrop";import { cn } from "../lib/utils";-import { MEETINGS_FOLDER_NAME, findDefaultFolder } from "./shared";+import { findDefaultFolder } from "./shared";import logger from "../../utils/logger";import { parseTranscriptSegments } from "../../utils/parseTranscriptSegments";import { serializeTranscriptSegments } from "../../utils/transcriptSpeakerState";import { resolveExpectedSpeakerCount } from "../../utils/participants";import {useNotes,+ useSpaces,+ useFolders,+ useActiveNote,useActiveNoteId,useActiveFolderId,+ useActiveContext,initializeNotes,+ initializeNotesTree,+ loadFolders,setActiveNoteId,- setActiveFolderId,- removeNote,+ setActiveContext,+ revealContainer,+ createFolder,+ getNoteFromStore,} from "../../stores/noteStore";import {useMeetingRecordingStore,@@ -81,9 +63,6 @@ import {import { useNotesOnboarding } from "../../hooks/useNotesOnboarding";import NotesOnboarding from "./NotesOnboarding";-const FOLDER_INPUT_CLASS =- "w-full h-6 bg-foreground/5 dark:bg-white/5 rounded px-2 text-xs text-foreground outline-none border border-primary/30 focus:border-primary/50";-function makeContentHash(content: string): string {return String(content.length) + "-" + content.slice(0, 50);}@@ -118,7 +97,8 @@ export default function PersonalNotesView({const [localEnhancedContent, setLocalEnhancedContent] = useState<string | null>(null);const [showActionManager, setShowActionManager] = useState(false);const [showNewNoteDialog, setShowNewNoteDialog] = useState(false);- const [newNoteFolderId, setNewNoteFolderId] = useState<string>("");+ const [showAddNotesDialog, setShowAddNotesDialog] = useState(false);+ const [newNoteTarget, setNewNoteTarget] = useState<string>("");const [isCreatingNewNoteFolder, setIsCreatingNewNoteFolder] = useState(false);const [newNoteFolderName, setNewNoteFolderName] = useState("");const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);@@ -142,12 +122,6 @@ export default function PersonalNotesView({const { toast } = useToast();const isCloudMode = useSettingsStore(selectIsCloudNoteFormattingMode);const effectiveModelId = useSettingsStore((s) => selectResolvedNoteFormatting(s).model);- const noteFilesEnabled = useSettingsStore((s) => s.noteFilesEnabled);- const fileManagerName = navigator.platform.startsWith("Mac")- ? "Finder"- : navigator.platform.startsWith("Win")- ? "Explorer"- : "Files";const { isComplete: isOnboardingComplete, complete: completeOnboarding } = useNotesOnboarding();const isTranscribing = useMeetingRecordingStore((s) => s.isRecording);@@ -163,48 +137,15 @@ export default function PersonalNotesView({const userTouchedStepper = useMeetingRecordingStore((s) => s.userTouchedStepper);const recordingNoteId = useMeetingRecordingStore((s) => s.recordingNoteId);- const {- folders,- folderCounts,- isLoading,- isCreatingFolder,- newFolderName,- renamingFolderId,- renameValue,- showAddNotesDialog,- newFolderInputRef,- renameInputRef,- setIsCreatingFolder,- setNewFolderName,- setRenamingFolderId,- setRenameValue,- setShowAddNotesDialog,- loadFolders,- handleCreateFolder,- handleConfirmRename,- handleDeleteFolder,- } = useFolderManagement();-- const { confirmDialog, showConfirmDialog, hideConfirmDialog } = useDialogs();+ const spaces = useSpaces();+ const folders = useFolders();+ const activeContext = useActiveContext();- const requestDeleteFolder = useCallback(- (folder: { id: number; name: string }) => {- const count = folderCounts[folder.id] ?? 0;- showConfirmDialog({- title: t("notes.folders.deleteTitle"),- description:- count > 0- ? t("notes.folders.deleteDescription", { name: folder.name, count })- : t("notes.folders.deleteDescriptionEmpty", { name: folder.name }),- confirmText: t("notes.folders.deleteConfirm"),- variant: "destructive",- onConfirm: () => handleDeleteFolder(folder.id),- });- },- [folderCounts, handleDeleteFolder, showConfirmDialog, t]- );+ useEffect(() => {+ initializeNotesTree();+ }, []);- const activeNote = notes.find((n) => n.id === activeNoteId) ?? null;+ const activeNote = useActiveNote();// Derive folder name and calendar event name for the metadata chipsconst activeFolderName = useMemo(() => {@@ -212,6 +153,13 @@ export default function PersonalNotesView({return folders.find((f) => f.id === activeNote.folder_id)?.name ?? null;}, [activeNote?.folder_id, folders]);+ // The editor's move-to-folder chip only offers folders in the note's own+ // space; cross-space moves change the audience and need an explicit confirm.+ const editorFolders = useMemo(+ () => (activeNote ? folders.filter((f) => f.space_id === activeNote.space_id) : folders),+ [activeNote, folders]+ );+const [calendarEventName, setCalendarEventName] = useState<string | null>(null);useEffect(() => {if (!activeNote?.calendar_event_id) {@@ -225,7 +173,7 @@ export default function PersonalNotesView({const startRecording = useCallback(async () => {const noteId = activeNoteRef.current;- const note = notes.find((n) => n.id === noteId);+ const note = activeNote?.id === noteId ? activeNote : null;const seedSegments = note?.transcript ? parseTranscriptSegments(note.transcript) : [];await storeStartRecording({noteId,@@ -235,7 +183,7 @@ export default function PersonalNotesView({diarizationEnabled: note?.diarization_enabled == null ? null : note.diarization_enabled === 1,expectedCount: resolveExpectedSpeakerCount(note),});- }, [notes]);+ }, [activeNote]);const stopRecording = useCallback(async () => {await storeStopRecording();@@ -360,110 +308,142 @@ export default function PersonalNotesView({}, 1000);}, []);- const handleNewNote = useCallback(async () => {- if (!activeFolderId) return;- const result = await window.electronAPI.saveNote(- t("notes.list.untitledNote"),- "",- "personal",- null,- null,- activeFolderId- );- if (result.success && result.note) {- setActiveNoteId(result.note.id);- loadFolders();- }- }, [activeFolderId, loadFolders, t]);+ const handleNewNoteIn = useCallback(+ async (spaceId: number, folderId: number | null) => {+ const result = await window.electronAPI.saveNote(+ t("notes.list.untitledNote"),+ "",+ "personal",+ null,+ null,+ folderId,+ spaceId+ );+ if (result.success && result.note) {+ setActiveContext(result.note.space_id, result.note.folder_id);+ revealContainer(result.note.space_id, result.note.folder_id);+ setActiveNoteId(result.note.id);+ }+ },+ [t]+ );++ const handleNewNote = useCallback(() => {+ if (!activeContext) return;+ handleNewNoteIn(activeContext.spaceId, activeContext.folderId);+ }, [activeContext, handleNewNoteIn]);++ const privateSpaceId = useMemo(+ () => spaces.find((s) => s.kind === "private")?.id ?? null,+ [spaces]+ );++ const spaceIdForTarget = useCallback(+ (target: string): number | null => {+ if (target.startsWith("f:")) {+ return folders.find((f) => f.id === Number(target.slice(2)))?.space_id ?? null;+ }+ if (target.startsWith("s:")) return Number(target.slice(2));+ return null;+ },+ [folders]+ );const handleOpenNewNoteDialog = useCallback(() => {- const personal = findDefaultFolder(folders);- setNewNoteFolderId(personal ? String(personal.id) : folders[0] ? String(folders[0].id) : "");+ let target = "";+ if (activeContext?.folderId != null) {+ target = `f:${activeContext.folderId}`;+ } else if (activeContext && activeContext.spaceId !== privateSpaceId) {+ target = `s:${activeContext.spaceId}`;+ }+ if (!target) {+ const personal = findDefaultFolder(folders) ?? folders[0];+ target = personal ? `f:${personal.id}` : "";+ }+ setNewNoteTarget(target);setShowNewNoteDialog(true);- }, [folders]);+ }, [activeContext, privateSpaceId, folders]);- const handleNewNoteFolderChange = useCallback((val: string) => {+ const handleNewNoteTargetChange = useCallback((val: string) => {if (val === "__create_new__") {setIsCreatingNewNoteFolder(true);return;}- setNewNoteFolderId(val);+ setNewNoteTarget(val);}, []);const handleCreateNewNoteFolder = useCallback(async () => {const trimmed = newNoteFolderName.trim();if (!trimmed) return;- const res = await window.electronAPI.createFolder(trimmed);+ const spaceId = spaceIdForTarget(newNoteTarget) ?? privateSpaceId;+ if (spaceId == null) return;+ const res = await createFolder(trimmed, spaceId);if (res.success && res.folder) {- await loadFolders();- setNewNoteFolderId(String(res.folder.id));+ setNewNoteTarget(`f:${res.folder.id}`);+ } else if (res.error) {+ toast({+ title: t("notes.folders.couldNotCreate"),+ description: res.error,+ variant: "destructive",+ });}setNewNoteFolderName("");setIsCreatingNewNoteFolder(false);- }, [newNoteFolderName, loadFolders]);+ }, [newNoteFolderName, newNoteTarget, spaceIdForTarget, privateSpaceId, toast, t]);const handleConfirmNewNote = useCallback(async () => {- const folderId = Number(newNoteFolderId);- if (!folderId) return;- const result = await window.electronAPI.saveNote(- t("notes.list.untitledNote"),- "",- "personal",- null,- null,- folderId- );- if (result.success && result.note) {- setActiveFolderId(folderId);- setActiveNoteId(result.note.id);- loadFolders();- }+ const spaceId = spaceIdForTarget(newNoteTarget);+ if (spaceId == null) return;+ const folderId = newNoteTarget.startsWith("f:") ? Number(newNoteTarget.slice(2)) : null;+ await handleNewNoteIn(spaceId, folderId);setShowNewNoteDialog(false);- }, [newNoteFolderId, loadFolders, t]);+ }, [newNoteTarget, spaceIdForTarget, handleNewNoteIn]);const handleNotesAdded = useCallback(async () => {if (activeFolderId) {await initializeNotes(null, 50, activeFolderId);}loadFolders();- }, [activeFolderId, loadFolders]);+ }, [activeFolderId]);- const handleDelete = useCallback(- async (id: number) => {- if (saveTimeoutRef.current) {- clearTimeout(saveTimeoutRef.current);- saveTimeoutRef.current = null;+ const handleDelete = useCallback(async (id: number) => {+ if (saveTimeoutRef.current) {+ clearTimeout(saveTimeoutRef.current);+ saveTimeoutRef.current = null;+ }+ await window.electronAPI.deleteNote(id);+ }, []);++ const handleMoveNote = useCallback(+ async (noteId: number, target: NoteMoveTarget) => {+ await window.electronAPI.updateNote(noteId, {+ folder_id: target.folderId,+ space_id: target.spaceId,+ });+ if (noteId === activeNoteId) {+ setActiveContext(target.spaceId, target.folderId);+ revealContainer(target.spaceId, target.folderId);}- await window.electronAPI.deleteNote(id);- loadFolders();},- [loadFolders]+ [activeNoteId]);const handleMoveToFolder = useCallback(async (noteId: number, folderId: number) => {- await window.electronAPI.updateNote(noteId, { folder_id: folderId });- if (noteId === activeNoteId) {- setActiveFolderId(folderId);- } else {- removeNote(noteId);- }- loadFolders();+ const folder = folders.find((f) => f.id === folderId);+ if (!folder) return;+ await handleMoveNote(noteId, { spaceId: folder.space_id, folderId });},- [activeNoteId, loadFolders]+ [folders, handleMoveNote]);- const { dragState, noteDragHandlers, folderDropHandlers } = useNoteDragAndDrop({- onMoveToFolder: handleMoveToFolder,- currentFolderId: activeFolderId,- });-const handleCreateFolderAndMove = useCallback(async (noteId: number, folderName: string) => {- const result = await window.electronAPI.createFolder(folderName);+ const spaceId = getNoteFromStore(noteId)?.space_id ?? privateSpaceId;+ if (spaceId == null) return;+ const result = await createFolder(folderName, spaceId);if (result.success && result.folder) {- await window.electronAPI.updateNote(noteId, { folder_id: result.folder.id });- await loadFolders();+ await handleMoveToFolder(noteId, result.folder.id);} else if (result.error) {toast({title: t("notes.folders.couldNotCreate"),@@ -472,7 +452,7 @@ export default function PersonalNotesView({});}},- [loadFolders, toast, t]+ [privateSpaceId, handleMoveToFolder, toast, t]);const {@@ -514,7 +494,7 @@ export default function PersonalNotesView({useEffect(() => {if (!meetingRecordingRequest || activeNoteId !== meetingRecordingRequest.noteId) return;- const note = notes.find((n) => n.id === meetingRecordingRequest.noteId);+ const note = activeNote?.id === meetingRecordingRequest.noteId ? activeNote : null;const seedSegments = note?.transcript ? parseTranscriptSegments(note.transcript) : [];storeStartRecording({noteId: meetingRecordingRequest.noteId,@@ -525,7 +505,7 @@ export default function PersonalNotesView({expectedCount: resolveExpectedSpeakerCount(note),});onMeetingRecordingRequestHandled?.();- }, [meetingRecordingRequest, activeNoteId, notes, onMeetingRecordingRequestHandled]);+ }, [meetingRecordingRequest, activeNoteId, activeNote, onMeetingRecordingRequestHandled]);const prevTranscribingRef = useRef(false);@@ -622,309 +602,12 @@ export default function PersonalNotesView({</button></div>- {/* Folders */}- <div className="flex items-center justify-between px-3 py-2">- <span className="text-xs font-medium uppercase tracking-wider text-foreground/50 dark:text-foreground/25">- {t("notes.folders.title")}- </span>- <Button- variant="ghost"- size="icon"- onClick={() => setIsCreatingFolder(true)}- aria-label={t("notes.context.newFolder")}- className="h-5 w-5 rounded-md text-muted-foreground/50 dark:text-muted-foreground/30 hover:text-foreground/60 hover:bg-foreground/5"- >- <Plus size={13} />- </Button>- </div>-- <div className="px-1.5 space-y-px">- {folders.map((folder) => {- const isActive = folder.id === activeFolderId;- const isMeetings = folder.name === MEETINGS_FOLDER_NAME;- const count = folderCounts[folder.id] || 0;- const isRenaming = renamingFolderId === folder.id;-- if (isRenaming) {- return (- <div key={folder.id} className="px-2">- <input- ref={renameInputRef}- value={renameValue}- onChange={(e) => setRenameValue(e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter") handleConfirmRename();- if (e.key === "Escape") {- setRenamingFolderId(null);- setRenameValue("");- }- }}- onBlur={handleConfirmRename}- className={FOLDER_INPUT_CLASS}- />- </div>- );- }-- const isDragOver = dragState.dragOverFolderId === folder.id;- const isDropSuccess = dragState.dropSuccessFolderId === folder.id;-- return (- <button- key={folder.id}- onClick={() => setActiveFolderId(folder.id)}- {...folderDropHandlers(folder.id, folder.name)}- className={cn(- "group relative flex items-center gap-2 w-full h-7 px-2 rounded-md cursor-pointer text-left transition-all duration-150",- "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/30",- isActive- ? "bg-primary/8 dark:bg-primary/10"- : "hover:bg-foreground/4 dark:hover:bg-white/4",- isDragOver &&- !isMeetings &&- "bg-primary/12 dark:bg-primary/15 ring-1 ring-primary/25 scale-[1.02]",- isDropSuccess &&- "bg-emerald-500/10 dark:bg-emerald-400/10 ring-1 ring-emerald-500/20"- )}- >- <FolderOpen- size={13}- className={cn(- "shrink-0 transition-colors duration-150",- isDragOver || isActive- ? "text-primary"- : "text-foreground/35 dark:text-foreground/20 group-hover:text-foreground/50 dark:group-hover:text-foreground/35"- )}- />- <span- className={cn(- "text-xs truncate flex-1 transition-colors duration-150",- isDragOver || isActive- ? "text-foreground font-medium"- : "text-foreground/50 group-hover:text-foreground/70"- )}- >- {folder.name}- </span>-- {isDropSuccess ? (- <Check- size={10}- className="text-emerald-500 dark:text-emerald-400 shrink-0 animate-[scale-in_200ms_ease-out]"- />- ) : (- <span- className={cn(- "text-xs tabular-nums shrink-0 transition-colors group-hover:opacity-0",- isActive- ? "text-foreground/50 dark:text-foreground/30"- : "text-foreground/35 dark:text-foreground/15"- )}- >- {count > 0 ? count : ""}- </span>- )}- {(!folder.is_default || noteFilesEnabled) && (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <span- role="button"- tabIndex={-1}- onClick={(e) => e.stopPropagation()}- className="h-4 w-4 flex items-center justify-center rounded-sm opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100 transition-opacity absolute right-1.5 text-foreground/25 hover:text-foreground/50 cursor-pointer"- >- <MoreHorizontal size={11} />- </span>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" sideOffset={4} className="min-w-32">- {noteFilesEnabled && (- <DropdownMenuItem- onClick={(e) => {- e.stopPropagation();- window.electronAPI?.showFolderInExplorer?.(folder.name);- }}- className="text-xs gap-2 rounded-md px-2 py-1"- >- <ExternalLink size={11} className="text-muted-foreground/60" />- {t("notes.context.showInFileManager", { manager: fileManagerName })}- </DropdownMenuItem>- )}- {!folder.is_default && (- <>- {noteFilesEnabled && <DropdownMenuSeparator />}- <DropdownMenuItem- onClick={(e) => {- e.stopPropagation();- setRenamingFolderId(folder.id);- setRenameValue(folder.name);- }}- className="text-xs gap-2 rounded-md px-2 py-1"- >- <Pencil size={11} className="text-muted-foreground/60" />- {t("notes.context.rename")}- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem- onClick={(e) => {- e.stopPropagation();- requestDeleteFolder(folder);- }}- className="text-xs gap-2 rounded-md px-2 py-1 text-destructive focus:text-destructive focus:bg-destructive/10"- >- <Trash2 size={11} />- {t("notes.context.delete")}- </DropdownMenuItem>- </>- )}- </DropdownMenuContent>- </DropdownMenu>- )}- </button>- );- })}-- {isCreatingFolder && (- <div className="px-2">- <input- ref={newFolderInputRef}- value={newFolderName}- onChange={(e) => setNewFolderName(e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter") handleCreateFolder();- if (e.key === "Escape") {- setIsCreatingFolder(false);- setNewFolderName("");- }- }}- onBlur={handleCreateFolder}- placeholder={t("notes.folders.folderName")}- className={cn(FOLDER_INPUT_CLASS, "placeholder:text-foreground/20")}- />- </div>- )}- </div>-- <div className="mx-3 h-px bg-border/10 dark:bg-white/4 my-2" />-- {/* Notes list */}- <div className="flex items-center justify-between px-3 py-1">- <span className="text-xs font-medium uppercase tracking-wider text-foreground/50 dark:text-foreground/25">- {t("notes.list.title")}- </span>- <Button- variant="ghost"- size="icon"- onClick={handleNewNote}- aria-label={t("notes.list.newNote")}- className="h-5 w-5 rounded-md text-muted-foreground/50 dark:text-muted-foreground/30 hover:text-foreground/60 hover:bg-foreground/5"- >- <Plus size={13} />- </Button>- </div>-- <div className="flex-1 overflow-y-auto">- {isLoading ? (- <div className="flex items-center justify-center py-8">- <Loader2 size={12} className="animate-spin text-foreground/15" />- </div>- ) : notes.length === 0 ? (- <div className="flex flex-col items-center justify-center py-8 px-4">- <svg- className="text-foreground dark:text-white mb-3"- width="40"- height="36"- viewBox="0 0 40 36"- fill="none"- >- <rect- x="12"- y="1"- width="20"- height="26"- rx="2"- transform="rotate(5 22 14)"- fill="currentColor"- fillOpacity={0.025}- stroke="currentColor"- strokeOpacity={0.06}- />- <rect- x="8"- y="3"- width="20"- height="26"- rx="2"- fill="currentColor"- fillOpacity={0.04}- stroke="currentColor"- strokeOpacity={0.08}- />- <rect- x="12"- y="9"- width="10"- height="1.5"- rx="0.75"- fill="currentColor"- fillOpacity={0.07}- />- <rect- x="12"- y="13"- width="12"- height="1.5"- rx="0.75"- fill="currentColor"- fillOpacity={0.05}- />- <rect- x="12"- y="17"- width="8"- height="1.5"- rx="0.75"- fill="currentColor"- fillOpacity={0.04}- />- </svg>- <p className="text-xs text-foreground/50 dark:text-foreground/25 mb-3">- {t("notes.empty.emptyFolder")}- </p>- <div className="flex flex-col gap-1.5 w-full max-w-36">- <button- onClick={handleNewNote}- className="flex items-center justify-center gap-1.5 h-6 rounded-md bg-primary/8 dark:bg-primary/10 border border-primary/12 dark:border-primary/15 text-xs font-medium text-primary/70 hover:bg-primary/12 hover:text-primary hover:border-primary/20 transition-colors"- >- <Plus size={10} />- {t("notes.empty.createNote")}- </button>- <button- onClick={() => setShowAddNotesDialog(true)}- className="flex items-center justify-center gap-1.5 h-6 rounded-md border border-foreground/8 dark:border-white/8 text-xs text-foreground/40 hover:text-foreground/60 hover:border-foreground/15 hover:bg-foreground/3 dark:hover:bg-white/3 transition-colors"- >- {t("notes.addToFolder.addExisting")}- </button>- </div>- </div>- ) : (- notes.map((note) => (- <NoteListItem- key={note.id}- note={note}- isActive={note.id === activeNoteId}- onClick={() => setActiveNoteId(note.id)}- onDelete={handleDelete}- folders={folders}- currentFolderId={activeFolderId}- onMoveToFolder={handleMoveToFolder}- onCreateFolderAndMove={handleCreateFolderAndMove}- dragHandlers={noteDragHandlers(note.id, note.title)}- isDragging={dragState.draggingNoteId === note.id}- noteFilesEnabled={noteFilesEnabled}- />- ))- )}- </div>+ <SpacesTree+ onDeleteNote={handleDelete}+ onMoveNote={handleMoveNote}+ onCreateFolderAndMove={handleCreateFolderAndMove}+ onNewNote={handleNewNoteIn}+ /></div></div>@@ -972,7 +655,7 @@ export default function PersonalNotesView({onSetSessionExpectedCount={setSessionExpectedCount}folderName={activeFolderName}calendarEventName={calendarEventName}- folders={folders}+ folders={editorFolders}onMoveToFolder={handleMoveToFolder}onCreateFolderAndMove={handleCreateFolderAndMove}actionProcessingState={actionProcessingState}@@ -1218,16 +901,37 @@ export default function PersonalNotesView({<label className="text-xs font-medium text-foreground/50">{t("notes.folders.title")}</label>- <Select value={newNoteFolderId} onValueChange={handleNewNoteFolderChange}>+ <Select value={newNoteTarget} onValueChange={handleNewNoteTargetChange}><SelectTrigger><SelectValue placeholder={t("notes.upload.selectFolder")} /></SelectTrigger><SelectContent>- {folders.map((f) => (- <SelectItem key={f.id} value={String(f.id)}>- {f.name}- </SelectItem>- ))}+ {spaces.map((space) => {+ const spaceFolders = folders.filter((f) => f.space_id === space.id);+ const isTeam = space.kind === "team";+ if (!isTeam && spaceFolders.length === 0) return null;+ return (+ <SelectGroup key={space.id}>+ {spaces.length > 1 && (+ <SelectLabel>+ {isTeam+ ? `${space.emoji ? `${space.emoji} ` : ""}${space.name}`+ : t("notes.spaces.personal")}+ </SelectLabel>+ )}+ {isTeam && (+ <SelectItem value={`s:${space.id}`}>+ {t("notes.spaces.spaceRoot")}+ </SelectItem>+ )}+ {spaceFolders.map((f) => (+ <SelectItem key={f.id} value={`f:${f.id}`}>+ {f.name}+ </SelectItem>+ ))}+ </SelectGroup>+ );+ })}<SelectSeparator /><SelectItem value="__create_new__"><span className="flex items-center gap-1.5 text-primary/60">@@ -1262,7 +966,7 @@ export default function PersonalNotesView({<Button variant="ghost" onClick={() => setShowNewNoteDialog(false)}>{t("notes.upload.cancel")}</Button>- <Button onClick={handleConfirmNewNote} disabled={!newNoteFolderId}>+ <Button onClick={handleConfirmNewNote} disabled={!newNoteTarget}>{t("notes.upload.create")}</Button></>@@ -1270,17 +974,6 @@ export default function PersonalNotesView({</DialogFooter></DialogContent></Dialog>-- <ConfirmDialog- open={confirmDialog.open}- onOpenChange={(open) => !open && hideConfirmDialog()}- title={confirmDialog.title}- description={confirmDialog.description}- confirmText={confirmDialog.confirmText}- cancelText={confirmDialog.cancelText}- onConfirm={confirmDialog.onConfirm}- variant={confirmDialog.variant}- /></div>);}diff --git a/src/components/notes/SpacesTree.tsx b/src/components/notes/SpacesTree.tsxnew file mode 100644index 000000000..1318d9448--- /dev/null+++ b/src/components/notes/SpacesTree.tsx@@ -0,0 +1,1701 @@+import { useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ Check,+ ChevronRight,+ ExternalLink,+ FileText,+ Folder,+ FolderOpen,+ Loader2,+ Lock,+ MoreHorizontal,+ Pencil,+ Plus,+ Search,+ Share2,+ Smile,+ Trash2,+ Users,+} from "lucide-react";+import { Button } from "../ui/button";+import {+ DropdownMenu,+ DropdownMenuTrigger,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSub,+ DropdownMenuSubTrigger,+ DropdownMenuSubContent,+ DropdownMenuSeparator,+} from "../ui/dropdown-menu";+import { ConfirmDialog } from "../ui/dialog";+import { useDialogs } from "../../hooks/useDialogs";+import { useToast } from "../ui/useToast";+import {+ useNoteDragAndDrop,+ type DraggedNoteInfo,+ type NoteMoveTarget,+} from "../../hooks/useNoteDragAndDrop";+import {+ useTeamSpacesCapability,+ hasTeamSpacesDevOverride,+} from "../../hooks/useTeamSpacesCapability";+import { useSettingsStore } from "../../stores/settingsStore";+import { cn } from "../lib/utils";+import { normalizeDbDate } from "../../utils/dateFormatting";+import CreateSpaceDialog from "./CreateSpaceDialog";+import type { FolderItem, NoteItem, SpaceItem } from "../../types/electron";+import {+ folderContainerKey,+ spaceContainerKey,+ useSpaces,+ useFolders,+ useFolderCounts,+ useNotesByContainer,+ useExpandedContainers,+ useActiveContext,+ useActiveNoteId,+ useIsTreeLoading,+ setActiveContext,+ setActiveNoteId,+ setContainerExpanded,+ toggleContainerExpanded,+ revealContainer,+ createFolder,+ renameFolder,+ deleteFolder,+ moveFolderToSpace,+ updateSpaceMeta,+ purgeSpace,+ getNoteFromStore,+} from "../../stores/noteStore";++const FOLDER_INPUT_CLASS =+ "w-full h-6 bg-foreground/5 dark:bg-white/5 rounded px-2 text-xs text-foreground outline-none border border-primary/30 focus:border-primary/50";++const ROW_BASE_CLASS =+ "group relative flex items-center gap-1.5 rounded-md cursor-pointer select-none " ++ "transition-colors duration-150 outline-none focus-visible:ring-1 focus-visible:ring-ring/30";++const KEBAB_BUTTON_CLASS =+ "h-5 w-5 rounded-sm opacity-0 group-hover:opacity-100 focus-visible:opacity-100 data-[state=open]:opacity-100 " ++ "transition-opacity text-muted-foreground/60 dark:text-muted-foreground/40 " ++ "hover:text-foreground/60 hover:bg-foreground/5 active:bg-foreground/8";++const KEBAB_TRIGGER_CLASS = cn(KEBAB_BUTTON_CLASS, "absolute right-1.5");++const MENU_ITEM_CLASS = "text-xs gap-2 rounded-md px-2 py-1";++const SUB_CONTENT_CLASS = "min-w-36 rounded-xl border border-border p-1";++type TFn = (key: string, options?: Record<string, unknown>) => string;++type TreeRow =+ | { type: "space"; key: string; space: SpaceItem; parentKey?: undefined }+ | { type: "folder"; key: string; folder: FolderItem; parentKey: string }+ | { type: "note"; key: string; note: NoteItem; parentKey: string; level: 2 | 3 };++interface DropHandlers {+ onDragOver: (e: React.DragEvent) => void;+ onDragEnter: (e: React.DragEvent) => void;+ onDragLeave: () => void;+ onDrop: (e: React.DragEvent) => void;+}++interface RowA11yProps {+ tabIndex: number;+ rowRef: (el: HTMLDivElement | null) => void;+ onKeyDown: (e: React.KeyboardEvent<HTMLDivElement>) => void;+ onFocus: () => void;+}++interface SpacesTreeProps {+ onDeleteNote: (id: number) => void;+ onMoveNote: (noteId: number, target: NoteMoveTarget) => Promise<void>;+ onCreateFolderAndMove: (noteId: number, folderName: string) => void;+ onNewNote: (spaceId: number, folderId: number | null) => void;+}++function spaceDisplayName(space: SpaceItem, t: TFn): string {+ return space.kind === "private" ? t("notes.spaces.personal") : space.name;+}++function relativeTime(dateStr: string, t: TFn): string {+ const date = normalizeDbDate(dateStr);+ if (Number.isNaN(date.getTime())) return dateStr;++ const diff = Date.now() - date.getTime();+ const minutes = Math.floor(diff / 60000);+ const hours = Math.floor(diff / 3600000);+ const days = Math.floor(diff / 86400000);++ if (minutes < 1) return t("notes.list.timeNow");+ if (minutes < 60) return t("notes.list.minutesAgo", { count: minutes });+ if (hours < 24) return t("notes.list.hoursAgo", { count: hours });+ if (days < 7) return t("notes.list.daysAgo", { count: days });+ return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });+}++function useFileManagerName(): string {+ return navigator.platform.startsWith("Mac")+ ? "Finder"+ : navigator.platform.startsWith("Win")+ ? "Explorer"+ : "Files";+}++function SectionHeader({+ label,+ action,+ className,+}: {+ label: string;+ action?: React.ReactNode;+ className?: string;+}) {+ return (+ <div role="none" className={cn("flex items-center justify-between h-6 px-2 mt-1", className)}>+ <span className="text-[10px] font-semibold uppercase tracking-wide text-foreground/50 select-none">+ {label}+ </span>+ {action}+ </div>+ );+}++function TreeChildren({ open, children }: { open: boolean; children: React.ReactNode }) {+ return (+ <div+ role="none"+ className={cn(+ "grid transition-[grid-template-rows] duration-[160ms] ease-out",+ open ? "grid-rows-[1fr]" : "grid-rows-[0fr]"+ )}+ >+ <div+ role="group"+ className={cn(+ "min-h-0 overflow-hidden transition-opacity duration-[80ms]",+ open ? "opacity-100" : "opacity-0"+ )}+ >+ {children}+ </div>+ </div>+ );+}++function Chevron({ isExpanded, onToggle }: { isExpanded: boolean; onToggle: () => void }) {+ return (+ <span+ aria-hidden="true"+ onClick={(e) => {+ e.stopPropagation();+ onToggle();+ }}+ className="h-4 w-4 flex items-center justify-center shrink-0 rounded-sm text-foreground/30 hover:text-foreground/60 transition-colors duration-150"+ >+ <ChevronRight+ size={12}+ className={cn("transition-transform duration-150", isExpanded && "rotate-90")}+ />+ </span>+ );+}++function SpaceMenuIcon({ space }: { space: SpaceItem }) {+ if (space.kind === "private") {+ return <Lock size={11} className="text-muted-foreground/60 shrink-0" />;+ }+ if (space.emoji) {+ return (+ <span className="text-[11px] leading-none shrink-0" aria-hidden="true">+ {space.emoji}+ </span>+ );+ }+ return <Users size={11} className="text-muted-foreground/60 shrink-0" />;+}++function SpaceRow({+ space,+ displayName,+ isExpanded,+ isActive,+ count,+ isDragOver,+ isDropSuccess,+ dropHandlers,+ canDeleteSpace,+ onActivate,+ onToggle,+ onNewFolder,+ onRename,+ onDelete,+ a11y,+ t,+}: {+ space: SpaceItem;+ displayName: string;+ isExpanded: boolean;+ isActive: boolean;+ count: number;+ isDragOver: boolean;+ isDropSuccess: boolean;+ dropHandlers: DropHandlers;+ canDeleteSpace: boolean;+ onActivate: () => void;+ onToggle: () => void;+ onNewFolder: () => void;+ onRename: (focus: "name" | "emoji") => void;+ onDelete: () => void;+ a11y: RowA11yProps;+ t: TFn;+}) {+ const isPrivate = space.kind === "private";+ return (+ <div+ role="treeitem"+ aria-level={1}+ aria-expanded={isExpanded}+ aria-selected={isActive}+ aria-label={+ count > 0 ? `${displayName}, ${t("notes.spaces.noteCount", { count })}` : displayName+ }+ tabIndex={a11y.tabIndex}+ ref={a11y.rowRef}+ onKeyDown={a11y.onKeyDown}+ onFocus={a11y.onFocus}+ onClick={onActivate}+ title={displayName}+ {...dropHandlers}+ className={cn(+ ROW_BASE_CLASS,+ "h-[30px] px-2",+ isActive+ ? "bg-primary/8 dark:bg-primary/10"+ : "hover:bg-foreground/4 dark:hover:bg-white/4",+ isDragOver && "bg-primary/12 dark:bg-primary/15 ring-1 ring-primary/25",+ isDropSuccess && "bg-emerald-500/10 dark:bg-emerald-400/10 ring-1 ring-emerald-500/20"+ )}+ >+ <Chevron isExpanded={isExpanded} onToggle={onToggle} />+ {isPrivate ? (+ <span title={t("notes.spaces.privateTooltip")} className="flex shrink-0">+ <Lock+ size={14}+ role="img"+ aria-label={t("notes.spaces.privateTooltip")}+ className={cn(+ "transition-colors duration-150",+ isActive ? "text-primary" : "text-foreground/35 dark:text-foreground/20"+ )}+ />+ </span>+ ) : space.emoji ? (+ <span className="text-[13px] leading-none shrink-0" aria-hidden="true">+ {space.emoji}+ </span>+ ) : (+ <Users+ size={14}+ className={cn(+ "shrink-0 transition-colors duration-150",+ isDragOver || isActive ? "text-primary" : "text-foreground/35 dark:text-foreground/20"+ )}+ />+ )}+ <span+ className={cn(+ "text-xs truncate flex-1 transition-colors duration-150",+ isDragOver || isActive ? "text-foreground font-medium" : "text-foreground/70"+ )}+ >+ {displayName}+ </span>+ {isDropSuccess ? (+ <Check+ size={10}+ className="text-emerald-500 dark:text-emerald-400 shrink-0 animate-[scale-in_200ms_ease-out]"+ />+ ) : (+ <span+ aria-hidden="true"+ className={cn(+ "text-xs tabular-nums shrink-0 transition-opacity group-hover:opacity-0",+ isActive+ ? "text-foreground/50 dark:text-foreground/30"+ : "text-foreground/35 dark:text-foreground/15"+ )}+ >+ {count > 0 ? count : ""}+ </span>+ )}+ <span className="absolute right-1.5 flex items-center gap-px">+ <Button+ variant="ghost"+ size="icon"+ aria-label={t("notes.context.newFolder")}+ onClick={(e) => {+ e.stopPropagation();+ onNewFolder();+ }}+ className={KEBAB_BUTTON_CLASS}+ >+ <Plus size={12} />+ </Button>+ {!isPrivate && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ aria-label={t("common.actions")}+ onClick={(e) => e.stopPropagation()}+ className={KEBAB_BUTTON_CLASS}+ >+ <MoreHorizontal size={12} />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" sideOffset={4} className="min-w-36">+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation();+ onRename("name");+ }}+ className={MENU_ITEM_CLASS}+ >+ <Pencil size={11} className="text-muted-foreground/60" />+ {t("notes.spaces.rename")}+ </DropdownMenuItem>+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation();+ onRename("emoji");+ }}+ className={MENU_ITEM_CLASS}+ >+ <Smile size={11} className="text-muted-foreground/60" />+ {t("notes.spaces.changeEmoji")}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ disabled={!canDeleteSpace}+ onClick={(e) => {+ e.stopPropagation();+ onDelete();+ }}+ className={cn(+ MENU_ITEM_CLASS,+ "text-destructive focus:text-destructive focus:bg-destructive/10"+ )}+ >+ <Trash2 size={11} />+ {t("notes.spaces.deleteSpace")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </span>+ </div>+ );+}++function FolderRow({+ folder,+ spaces,+ isExpanded,+ isActive,+ count,+ isDragOver,+ isDropSuccess,+ dropHandlers,+ noteFilesEnabled,+ fileManagerName,+ onActivate,+ onToggle,+ onRename,+ onMoveToSpace,+ onDelete,+ a11y,+ t,+}: {+ folder: FolderItem;+ spaces: SpaceItem[];+ isExpanded: boolean;+ isActive: boolean;+ count: number;+ isDragOver: boolean;+ isDropSuccess: boolean;+ dropHandlers: DropHandlers;+ noteFilesEnabled: boolean;+ fileManagerName: string;+ onActivate: () => void;+ onToggle: () => void;+ onRename: () => void;+ onMoveToSpace: (space: SpaceItem) => void;+ onDelete: () => void;+ a11y: RowA11yProps;+ t: TFn;+}) {+ const [spaceSearch, setSpaceSearch] = useState("");+ const canMoveToSpace = !folder.is_default && spaces.length > 1;+ const filteredSpaces = useMemo(+ () =>+ spaceSearch+ ? spaces.filter((s) =>+ spaceDisplayName(s, t).toLowerCase().includes(spaceSearch.toLowerCase())+ )+ : spaces,+ [spaces, spaceSearch, t]+ );++ return (+ <div+ role="treeitem"+ aria-level={2}+ aria-expanded={isExpanded}+ aria-selected={isActive}+ aria-label={+ count > 0 ? `${folder.name}, ${t("notes.spaces.noteCount", { count })}` : folder.name+ }+ tabIndex={a11y.tabIndex}+ ref={a11y.rowRef}+ onKeyDown={a11y.onKeyDown}+ onFocus={a11y.onFocus}+ onClick={onActivate}+ title={folder.name}+ {...dropHandlers}+ className={cn(+ ROW_BASE_CLASS,+ "h-7 pl-[14px] pr-2",+ isActive+ ? "bg-primary/8 dark:bg-primary/10"+ : "hover:bg-foreground/4 dark:hover:bg-white/4",+ isDragOver && "bg-primary/12 dark:bg-primary/15 ring-1 ring-primary/25",+ isDropSuccess && "bg-emerald-500/10 dark:bg-emerald-400/10 ring-1 ring-emerald-500/20"+ )}+ >+ <Chevron isExpanded={isExpanded} onToggle={onToggle} />+ <Folder+ size={14}+ className={cn(+ "shrink-0 transition-colors duration-150",+ isDragOver || isActive+ ? "text-primary"+ : "text-foreground/35 dark:text-foreground/20 group-hover:text-foreground/50 dark:group-hover:text-foreground/35"+ )}+ />+ <span+ className={cn(+ "text-xs truncate flex-1 transition-colors duration-150",+ isDragOver || isActive+ ? "text-foreground font-medium"+ : "text-foreground/50 group-hover:text-foreground/70"+ )}+ >+ {folder.name}+ </span>+ {isDropSuccess ? (+ <Check+ size={10}+ className="text-emerald-500 dark:text-emerald-400 shrink-0 animate-[scale-in_200ms_ease-out]"+ />+ ) : (+ <span+ aria-hidden="true"+ className={cn(+ "text-xs tabular-nums shrink-0 transition-opacity group-hover:opacity-0",+ isActive+ ? "text-foreground/50 dark:text-foreground/30"+ : "text-foreground/35 dark:text-foreground/15"+ )}+ >+ {count > 0 ? count : ""}+ </span>+ )}+ {(!folder.is_default || noteFilesEnabled) && (+ <DropdownMenu onOpenChange={(open) => !open && setSpaceSearch("")}>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ aria-label={t("common.actions")}+ onClick={(e) => e.stopPropagation()}+ className={KEBAB_TRIGGER_CLASS}+ >+ <MoreHorizontal size={12} />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" sideOffset={4} className="min-w-32">+ {noteFilesEnabled && (+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation();+ window.electronAPI?.showFolderInExplorer?.(folder.name);+ }}+ className={MENU_ITEM_CLASS}+ >+ <ExternalLink size={11} className="text-muted-foreground/60" />+ {t("notes.context.showInFileManager", { manager: fileManagerName })}+ </DropdownMenuItem>+ )}+ {!folder.is_default && (+ <>+ {noteFilesEnabled && <DropdownMenuSeparator />}+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation();+ onRename();+ }}+ className={MENU_ITEM_CLASS}+ >+ <Pencil size={11} className="text-muted-foreground/60" />+ {t("notes.context.rename")}+ </DropdownMenuItem>+ {canMoveToSpace && (+ <DropdownMenuSub>+ <DropdownMenuSubTrigger+ className={cn(+ MENU_ITEM_CLASS,+ "cursor-pointer focus:bg-foreground/5 data-[state=open]:bg-foreground/5"+ )}+ >+ <Users size={11} className="text-muted-foreground/60" />+ {t("notes.spaces.moveToSpace")}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent sideOffset={4} className={SUB_CONTENT_CLASS}>+ {spaces.length > 5 && (+ <>+ <div className="relative px-1.5 py-0.5">+ <Search+ size={9}+ className="absolute left-3.5 top-1/2 -translate-y-1/2 text-foreground/15 pointer-events-none"+ />+ <input+ value={spaceSearch}+ onChange={(e) => setSpaceSearch(e.target.value)}+ onKeyDown={(e) => e.stopPropagation()}+ placeholder={t("notes.spaces.searchSpaces")}+ className="input-inline w-full pl-4.5 pr-1 py-0.5 text-xs text-foreground placeholder:text-foreground/15 outline-none border-none appearance-none"+ />+ </div>+ <DropdownMenuSeparator />+ </>+ )}+ <div className="overflow-y-auto max-h-40">+ {filteredSpaces.map((space) => {+ const isCurrent = space.id === folder.space_id;+ return (+ <DropdownMenuItem+ key={space.id}+ disabled={isCurrent}+ onClick={(e) => {+ e.stopPropagation();+ onMoveToSpace(space);+ }}+ className={MENU_ITEM_CLASS}+ >+ <SpaceMenuIcon space={space} />+ <span className="truncate flex-1">{spaceDisplayName(space, t)}</span>+ {isCurrent && <Check size={9} className="text-primary shrink-0" />}+ </DropdownMenuItem>+ );+ })}+ {spaceSearch && filteredSpaces.length === 0 && (+ <p className="text-xs text-foreground/20 text-center py-1.5">+ {t("notes.spaces.noSpacesFound")}+ </p>+ )}+ </div>+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ )}+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation();+ onDelete();+ }}+ className={cn(+ MENU_ITEM_CLASS,+ "text-destructive focus:text-destructive focus:bg-destructive/10"+ )}+ >+ <Trash2 size={11} />+ {t("notes.context.delete")}+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </div>+ );+}++interface MoveOption {+ key: string;+ label: string;+ space: SpaceItem;+ target: NoteMoveTarget;+ isCurrent: boolean;+}++function NoteLeaf({+ note,+ level,+ isActive,+ isDragging,+ dragHandlers,+ spaces,+ folders,+ noteFilesEnabled,+ fileManagerName,+ onOpen,+ onMove,+ onCreateFolderAndMove,+ onDelete,+ a11y,+ t,+}: {+ note: NoteItem;+ level: 2 | 3;+ isActive: boolean;+ isDragging: boolean;+ dragHandlers: {+ draggable: true;+ onDragStart: (e: React.DragEvent) => void;+ onDragEnd: () => void;+ };+ spaces: SpaceItem[];+ folders: FolderItem[];+ noteFilesEnabled: boolean;+ fileManagerName: string;+ onOpen: () => void;+ onMove: (target: NoteMoveTarget) => void;+ onCreateFolderAndMove: (noteId: number, folderName: string) => void;+ onDelete: (id: number) => void;+ a11y: RowA11yProps;+ t: TFn;+}) {+ const [moveSearch, setMoveSearch] = useState("");+ const [newFolderName, setNewFolderName] = useState("");+ const [isCreating, setIsCreating] = useState(false);++ const multiSpace = spaces.length > 1;++ const moveOptions = useMemo<MoveOption[]>(() => {+ const options: MoveOption[] = [];+ for (const space of spaces) {+ if (space.kind === "team") {+ options.push({+ key: spaceContainerKey(space.id),+ label: spaceDisplayName(space, t),+ space,+ target: { spaceId: space.id, folderId: null },+ isCurrent: note.folder_id == null && note.space_id === space.id,+ });+ }+ for (const folder of folders.filter((f) => f.space_id === space.id)) {+ options.push({+ key: folderContainerKey(folder.id),+ label: folder.name,+ space,+ target: { spaceId: space.id, folderId: folder.id },+ isCurrent: note.folder_id === folder.id,+ });+ }+ }+ return options;+ }, [spaces, folders, note.folder_id, note.space_id, t]);++ const filteredOptions = useMemo(() => {+ if (!moveSearch) return moveOptions;+ const query = moveSearch.toLowerCase();+ return moveOptions.filter(+ (option) =>+ option.label.toLowerCase().includes(query) ||+ spaceDisplayName(option.space, t).toLowerCase().includes(query)+ );+ }, [moveOptions, moveSearch, t]);++ const renderOption = (option: MoveOption, label: string) => (+ <DropdownMenuItem+ key={option.key}+ disabled={option.isCurrent}+ onClick={(e) => {+ e.stopPropagation();+ onMove(option.target);+ }}+ className={MENU_ITEM_CLASS}+ >+ <span className="truncate flex-1">{label}</span>+ {option.isCurrent && <Check size={9} className="text-primary shrink-0" />}+ </DropdownMenuItem>+ );++ const title = note.title || t("notes.list.untitled");++ return (+ <div+ role="treeitem"+ aria-level={level}+ aria-selected={isActive}+ tabIndex={a11y.tabIndex}+ ref={a11y.rowRef}+ onKeyDown={a11y.onKeyDown}+ onFocus={a11y.onFocus}+ onClick={onOpen}+ title={title}+ {...dragHandlers}+ className={cn(+ ROW_BASE_CLASS,+ "h-7 pr-2",+ level === 3 ? "pl-7" : "pl-[14px]",+ isActive+ ? "bg-primary/8 dark:bg-primary/10"+ : "hover:bg-foreground/4 dark:hover:bg-white/4",+ isDragging && "opacity-40"+ )}+ >+ <FileText+ size={13}+ className={cn(+ "shrink-0 transition-colors duration-150",+ isActive+ ? "text-primary"+ : "text-foreground/30 dark:text-foreground/20 group-hover:text-foreground/45 dark:group-hover:text-foreground/30"+ )}+ />+ <span+ className={cn(+ "text-xs truncate flex-1 transition-colors duration-150",+ isActive+ ? "text-foreground font-medium"+ : "text-foreground/60 group-hover:text-foreground/80"+ )}+ >+ {title}+ </span>+ {Boolean(note.is_shared) && (+ <Share2+ size={11}+ role="img"+ aria-label={t("notes.list.shared")}+ className="text-foreground/40 shrink-0 transition-opacity group-hover:opacity-0"+ />+ )}+ <span+ aria-hidden="true"+ className="text-[10px] tabular-nums shrink-0 text-foreground/35 dark:text-foreground/15 transition-opacity group-hover:opacity-0"+ >+ {relativeTime(note.updated_at, t)}+ </span>+ <DropdownMenu+ onOpenChange={(open) => {+ if (!open) {+ setMoveSearch("");+ setIsCreating(false);+ setNewFolderName("");+ }+ }}+ >+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ aria-label={t("common.actions")}+ onClick={(e) => e.stopPropagation()}+ className={KEBAB_TRIGGER_CLASS}+ >+ <MoreHorizontal size={12} />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" sideOffset={4} className="min-w-40">+ {noteFilesEnabled && (+ <>+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation();+ window.electronAPI?.showNoteFile?.(note.id);+ }}+ className={MENU_ITEM_CLASS}+ >+ <ExternalLink size={11} className="text-muted-foreground/60" />+ {t("notes.context.showInFileManager", { manager: fileManagerName })}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ </>+ )}+ <DropdownMenuSub>+ <DropdownMenuSubTrigger+ className={cn(+ MENU_ITEM_CLASS,+ "cursor-pointer focus:bg-foreground/5 data-[state=open]:bg-foreground/5"+ )}+ >+ <FolderOpen size={11} className="text-muted-foreground/60" />+ {multiSpace ? t("notes.spaces.moveTo") : t("notes.context.moveToFolder")}+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent sideOffset={4} className={SUB_CONTENT_CLASS}>+ {moveOptions.length > 5 && (+ <>+ <div className="relative px-1.5 py-0.5">+ <Search+ size={9}+ className="absolute left-3.5 top-1/2 -translate-y-1/2 text-foreground/15 pointer-events-none"+ />+ <input+ value={moveSearch}+ onChange={(e) => setMoveSearch(e.target.value)}+ onKeyDown={(e) => e.stopPropagation()}+ placeholder={t("notes.context.searchFolders")}+ className="input-inline w-full pl-4.5 pr-1 py-0.5 text-xs text-foreground placeholder:text-foreground/15 outline-none border-none appearance-none"+ />+ </div>+ <DropdownMenuSeparator />+ </>+ )}+ <div className="overflow-y-auto max-h-40">+ {moveSearch ? (+ <>+ {filteredOptions.map((option) =>+ renderOption(+ option,+ multiSpace && option.target.folderId != null+ ? `${spaceDisplayName(option.space, t)} / ${option.label}`+ : option.label+ )+ )}+ {filteredOptions.length === 0 && (+ <p className="text-xs text-foreground/20 text-center py-1.5">+ {t("notes.context.noResults")}+ </p>+ )}+ </>+ ) : multiSpace ? (+ spaces.map((space) => {+ const spaceOptions = moveOptions.filter(+ (option) => option.space.id === space.id+ );+ if (spaceOptions.length === 0) return null;+ return (+ <DropdownMenuSub key={space.id}>+ <DropdownMenuSubTrigger+ className={cn(+ MENU_ITEM_CLASS,+ "cursor-pointer focus:bg-foreground/5 data-[state=open]:bg-foreground/5"+ )}+ >+ <SpaceMenuIcon space={space} />+ <span className="truncate flex-1">{spaceDisplayName(space, t)}</span>+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent+ sideOffset={4}+ className={cn(SUB_CONTENT_CLASS, "max-h-40 overflow-y-auto")}+ >+ {spaceOptions.map((option) =>+ renderOption(+ option,+ option.target.folderId == null+ ? t("notes.spaces.spaceRoot")+ : option.label+ )+ )}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ );+ })+ ) : (+ moveOptions.map((option) => renderOption(option, option.label))+ )}+ </div>+ <DropdownMenuSeparator />+ {isCreating ? (+ <div className="px-1">+ <input+ autoFocus+ value={newFolderName}+ onChange={(e) => setNewFolderName(e.target.value)}+ onKeyDown={(e) => {+ e.stopPropagation();+ if (e.key === "Enter" && newFolderName.trim()) {+ onCreateFolderAndMove(note.id, newFolderName.trim());+ setNewFolderName("");+ setIsCreating(false);+ }+ if (e.key === "Escape") {+ setIsCreating(false);+ setNewFolderName("");+ }+ }}+ placeholder={t("notes.folders.folderName")}+ className="input-inline w-full px-2 py-1.5 rounded-md bg-transparent text-xs text-foreground placeholder:text-foreground/20 outline-none border-none appearance-none"+ />+ </div>+ ) : (+ <DropdownMenuItem+ onSelect={(e) => {+ e.preventDefault();+ setIsCreating(true);+ }}+ className={cn(MENU_ITEM_CLASS, "text-foreground/40")}+ >+ <Plus size={10} />+ {t("notes.context.newFolder")}+ </DropdownMenuItem>+ )}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation();+ onDelete(note.id);+ }}+ className={cn(+ MENU_ITEM_CLASS,+ "text-destructive focus:text-destructive focus:bg-destructive/10"+ )}+ >+ <Trash2 size={11} />+ {t("notes.context.delete")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+}++function SkeletonRows() {+ return (+ <div className="space-y-px" aria-hidden="true">+ {["w-3/5", "w-2/5", "w-1/2"].map((width) => (+ <div key={width} className="flex items-center h-7 pl-[18px] pr-2">+ <div+ className={cn(+ "h-2.5 rounded-full bg-foreground/6 dark:bg-white/6 animate-pulse",+ width+ )}+ />+ </div>+ ))}+ </div>+ );+}++export default function SpacesTree({+ onDeleteNote,+ onMoveNote,+ onCreateFolderAndMove,+ onNewNote,+}: SpacesTreeProps) {+ const { t } = useTranslation();+ const { toast, dismiss } = useToast();+ const fileManagerName = useFileManagerName();++ const spaces = useSpaces();+ const folders = useFolders();+ const folderCounts = useFolderCounts();+ const notesByContainer = useNotesByContainer();+ const expanded = useExpandedContainers();+ const activeContext = useActiveContext();+ const activeNoteId = useActiveNoteId();+ const isTreeLoading = useIsTreeLoading();+ const teamCapability = useTeamSpacesCapability();+ const devOverride = hasTeamSpacesDevOverride();+ const noteFilesEnabled = useSettingsStore((s) => s.noteFilesEnabled);++ const [creatingFolderSpaceId, setCreatingFolderSpaceId] = useState<number | null>(null);+ const [newFolderName, setNewFolderName] = useState("");+ const [renamingFolderId, setRenamingFolderId] = useState<number | null>(null);+ const [renameValue, setRenameValue] = useState("");+ const [renamingSpaceId, setRenamingSpaceId] = useState<number | null>(null);+ const [renameSpaceName, setRenameSpaceName] = useState("");+ const [renameSpaceEmoji, setRenameSpaceEmoji] = useState("");+ const [spaceRenameFocus, setSpaceRenameFocus] = useState<"name" | "emoji">("name");+ const [showCreateSpace, setShowCreateSpace] = useState(false);+ const [focusedKey, setFocusedKey] = useState<string | null>(null);+ const rowRefs = useRef(new Map<string, HTMLDivElement>());+ const undoToastIdRef = useRef<string | null>(null);++ const { confirmDialog, showConfirmDialog, hideConfirmDialog } = useDialogs();++ const privateSpaces = useMemo(() => spaces.filter((s) => s.kind === "private"), [spaces]);+ const teamSpaces = useMemo(() => spaces.filter((s) => s.kind === "team"), [spaces]);+ const visibleSpaces = teamCapability ? spaces : privateSpaces;++ const targetLabel = (target: NoteMoveTarget): string => {+ if (target.folderId != null) {+ return folders.find((f) => f.id === target.folderId)?.name ?? "";+ }+ const space = spaces.find((s) => s.id === target.spaceId);+ return space ? spaceDisplayName(space, t) : "";+ };++ const showUndoToast = (title: string, target: string, onUndo: () => void) => {+ if (undoToastIdRef.current) dismiss(undoToastIdRef.current);+ undoToastIdRef.current = toast({+ title: t("notes.spaces.moved", { title, target }),+ duration: 8000,+ action: (+ <Button+ variant="ghost"+ size="sm"+ onClick={() => {+ if (undoToastIdRef.current) dismiss(undoToastIdRef.current);+ undoToastIdRef.current = null;+ onUndo();+ }}+ className="h-6 px-2 text-xs text-white/70 hover:text-white hover:bg-white/10"+ >+ {t("notes.spaces.undo")}+ </Button>+ ),+ });+ };++ const confirmCrossSpaceMove = (+ fromSpaceId: number,+ toSpaceId: number,+ isFolder: boolean,+ onConfirm: () => void+ ) => {+ const intoSpace = spaces.find((s) => s.id === toSpaceId);+ const fromSpace = spaces.find((s) => s.id === fromSpaceId);+ if (!intoSpace || !fromSpace) return;+ const movingIntoTeam = intoSpace.kind === "team";+ showConfirmDialog({+ title: movingIntoTeam+ ? t("notes.spaces.confirmMoveInTitle", { space: intoSpace.name })+ : t("notes.spaces.confirmMoveOutTitle", { space: fromSpace.name }),+ description: movingIntoTeam+ ? t(isFolder ? "notes.spaces.confirmMoveInFolder" : "notes.spaces.confirmMoveIn", {+ space: intoSpace.name,+ })+ : t(isFolder ? "notes.spaces.confirmMoveOutFolder" : "notes.spaces.confirmMoveOut", {+ space: fromSpace.name,+ }),+ confirmText: t("notes.spaces.moveConfirm"),+ onConfirm,+ });+ };++ const moveNoteSafely = async (noteId: number, target: NoteMoveTarget): Promise<boolean> => {+ try {+ await onMoveNote(noteId, target);+ return true;+ } catch {+ toast({ title: t("notes.spaces.couldNotMoveNote"), variant: "destructive" });+ return false;+ }+ };++ const commitMoveNote = async (noteId: number, target: NoteMoveTarget) => {+ const note = getNoteFromStore(noteId);+ const prev: NoteMoveTarget | null = note+ ? { spaceId: note.space_id, folderId: note.folder_id }+ : null;+ const moved = await moveNoteSafely(noteId, target);+ if (moved && prev) {+ const title = note?.title || t("notes.list.untitled");+ // Undo silently restores the previous space/folder — no confirm, no new toast.+ showUndoToast(title, targetLabel(target), () => void moveNoteSafely(noteId, prev));+ }+ };++ const requestMoveNote = (noteId: number, target: NoteMoveTarget) => {+ const note = getNoteFromStore(noteId);+ if (!note) return;+ if (note.space_id !== target.spaceId) {+ confirmCrossSpaceMove(+ note.space_id,+ target.spaceId,+ false,+ () => void commitMoveNote(noteId, target)+ );+ } else {+ void commitMoveNote(noteId, target);+ }+ };++ const moveFolderSafely = async (+ folderId: number,+ spaceId: number+ ): Promise<{ success: boolean; error?: string }> => {+ const result = await moveFolderToSpace(folderId, spaceId).catch((err: unknown) => ({+ success: false,+ error: (err as Error).message,+ }));+ if (!result.success) {+ toast({+ title: t("notes.spaces.couldNotMove"),+ description: result.error,+ variant: "destructive",+ });+ }+ return result;+ };++ const commitMoveFolder = async (folder: FolderItem, space: SpaceItem) => {+ const prevSpaceId = folder.space_id;+ const result = await moveFolderSafely(folder.id, space.id);+ if (!result.success) return;+ revealContainer(space.id, null);+ showUndoToast(+ folder.name,+ spaceDisplayName(space, t),+ () => void moveFolderSafely(folder.id, prevSpaceId)+ );+ };++ const requestMoveFolder = (folder: FolderItem, space: SpaceItem) => {+ if (space.id === folder.space_id) return;+ confirmCrossSpaceMove(+ folder.space_id,+ space.id,+ true,+ () => void commitMoveFolder(folder, space)+ );+ };++ const { dragState, noteDragHandlers, dropTargetHandlers } = useNoteDragAndDrop({+ onMoveToTarget: commitMoveNote,+ onCrossSpaceDrop: (note: DraggedNoteInfo, target, commit) =>+ confirmCrossSpaceMove(note.spaceId, target.spaceId, false, commit),+ onHoverTarget: (key) => setContainerExpanded(key, true),+ });++ const visibleRows = useMemo<TreeRow[]>(() => {+ const rows: TreeRow[] = [];+ const pushSpace = (space: SpaceItem) => {+ const spaceKey = spaceContainerKey(space.id);+ rows.push({ type: "space", key: spaceKey, space });+ if (!expanded.has(spaceKey)) return;+ folders+ .filter((f) => f.space_id === space.id)+ .forEach((folder) => {+ const folderKey = folderContainerKey(folder.id);+ rows.push({ type: "folder", key: folderKey, folder, parentKey: spaceKey });+ if (expanded.has(folderKey)) {+ (notesByContainer[folderKey] ?? []).forEach((note) => {+ rows.push({+ type: "note",+ key: `n:${note.id}`,+ note,+ parentKey: folderKey,+ level: 3,+ });+ });+ }+ });+ (notesByContainer[spaceKey] ?? []).forEach((note) => {+ rows.push({ type: "note", key: `n:${note.id}`, note, parentKey: spaceKey, level: 2 });+ });+ };+ privateSpaces.forEach(pushSpace);+ if (teamCapability) teamSpaces.forEach(pushSpace);+ return rows;+ }, [privateSpaces, teamSpaces, folders, notesByContainer, expanded, teamCapability]);++ const effectiveFocusKey =+ focusedKey && visibleRows.some((r) => r.key === focusedKey)+ ? focusedKey+ : (visibleRows[0]?.key ?? null);++ const focusRow = (key: string | undefined) => {+ if (!key) return;+ setFocusedKey(key);+ rowRefs.current.get(key)?.focus();+ };++ /** Restore focus to a row after an inline input closes (keyboard paths only). */+ const focusRowSoon = (key: string) => {+ setFocusedKey(key);+ requestAnimationFrame(() => rowRefs.current.get(key)?.focus());+ };++ const activateRow = (row: TreeRow) => {+ if (row.type === "space") {+ setActiveContext(row.space.id, null);+ toggleContainerExpanded(row.key);+ } else if (row.type === "folder") {+ setActiveContext(row.folder.space_id, row.folder.id);+ toggleContainerExpanded(row.key);+ } else {+ setActiveNoteId(row.note.id);+ }+ };++ const startRenameFolder = (folder: FolderItem) => {+ setRenamingFolderId(folder.id);+ setRenameValue(folder.name);+ };++ const startRenameSpace = (space: SpaceItem, focus: "name" | "emoji") => {+ setRenamingSpaceId(space.id);+ setRenameSpaceName(space.name);+ setRenameSpaceEmoji(space.emoji ?? "");+ setSpaceRenameFocus(focus);+ };++ const requestDeleteFolder = (folder: FolderItem) => {+ const count = folderCounts[folder.id] ?? 0;+ showConfirmDialog({+ title: t("notes.folders.deleteTitle"),+ description:+ count > 0+ ? t("notes.folders.deleteDescription", { name: folder.name, count })+ : t("notes.folders.deleteDescriptionEmpty", { name: folder.name }),+ confirmText: t("notes.folders.deleteConfirm"),+ variant: "destructive",+ onConfirm: async () => {+ const result = await deleteFolder(folder.id);+ if (!result.success && result.error) {+ toast({+ title: t("notes.folders.couldNotDelete"),+ description: result.error,+ variant: "destructive",+ });+ }+ },+ });+ };++ const requestDeleteSpace = (space: SpaceItem) => {+ showConfirmDialog({+ title: t("notes.spaces.deleteConfirmTitle"),+ description: t("notes.spaces.deleteConfirmDescription", { space: space.name }),+ confirmText: t("notes.spaces.deleteSpace"),+ variant: "destructive",+ onConfirm: async () => {+ const result = await purgeSpace(space.id);+ if (!result.success && result.error) {+ toast({+ title: t("notes.spaces.couldNotDelete"),+ description: result.error,+ variant: "destructive",+ });+ }+ },+ });+ };++ const handleRowKeyDown = (e: React.KeyboardEvent<HTMLDivElement>, row: TreeRow) => {+ if (e.target !== e.currentTarget) return;+ const idx = visibleRows.findIndex((r) => r.key === row.key);+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "n") {+ e.preventDefault();+ if (activeContext) onNewNote(activeContext.spaceId, activeContext.folderId);+ return;+ }+ switch (e.key) {+ case "ArrowDown":+ e.preventDefault();+ focusRow(visibleRows[idx + 1]?.key);+ break;+ case "ArrowUp":+ e.preventDefault();+ focusRow(visibleRows[idx - 1]?.key);+ break;+ case "ArrowRight":+ e.preventDefault();+ if (row.type === "note") break;+ if (!expanded.has(row.key)) {+ setContainerExpanded(row.key, true);+ } else if (visibleRows[idx + 1]?.parentKey === row.key) {+ focusRow(visibleRows[idx + 1]?.key);+ }+ break;+ case "ArrowLeft":+ e.preventDefault();+ if (row.type !== "note" && expanded.has(row.key)) {+ setContainerExpanded(row.key, false);+ } else if (row.parentKey) {+ focusRow(row.parentKey);+ }+ break;+ case "F2":+ e.preventDefault();+ if (row.type === "folder" && !row.folder.is_default) {+ startRenameFolder(row.folder);+ } else if (row.type === "space" && row.space.kind === "team") {+ startRenameSpace(row.space, "name");+ }+ break;+ case "Delete":+ case "Backspace":+ // Bare Backspace stays inert; Cmd/Ctrl+Backspace matches the native delete gesture.+ if (e.key === "Backspace" && !(e.metaKey || e.ctrlKey)) break;+ e.preventDefault();+ if (row.type === "note") {+ focusRow(visibleRows[idx + 1]?.key ?? visibleRows[idx - 1]?.key);+ onDeleteNote(row.note.id);+ } else if (row.type === "folder" && !row.folder.is_default) {+ requestDeleteFolder(row.folder);+ } else if (row.type === "space" && row.space.kind === "team" && devOverride) {+ requestDeleteSpace(row.space);+ }+ break;+ case "Enter":+ case " ":+ e.preventDefault();+ activateRow(row);+ break;+ }+ };++ const a11yFor = (key: string): RowA11yProps => ({+ tabIndex: key === effectiveFocusKey ? 0 : -1,+ rowRef: (el) => {+ if (el) rowRefs.current.set(key, el);+ else rowRefs.current.delete(key);+ },+ onKeyDown: (e) => {+ const row = visibleRows.find((r) => r.key === key);+ if (row) handleRowKeyDown(e, row);+ },+ onFocus: () => setFocusedKey(key),+ });++ const startCreateFolder = (space: SpaceItem) => {+ setContainerExpanded(spaceContainerKey(space.id), true);+ setCreatingFolderSpaceId(space.id);+ setNewFolderName("");+ };++ const confirmCreateFolder = async (): Promise<string | null> => {+ const spaceId = creatingFolderSpaceId;+ const trimmed = newFolderName.trim();+ setCreatingFolderSpaceId(null);+ setNewFolderName("");+ if (spaceId == null || !trimmed) return null;+ const result = await createFolder(trimmed, spaceId);+ if (result.success && result.folder) {+ setActiveContext(spaceId, result.folder.id);+ return folderContainerKey(result.folder.id);+ }+ if (result.error) {+ toast({+ title: t("notes.folders.couldNotCreate"),+ description: result.error,+ variant: "destructive",+ });+ }+ return null;+ };++ const confirmRename = async () => {+ const folderId = renamingFolderId;+ const trimmed = renameValue.trim();+ setRenamingFolderId(null);+ setRenameValue("");+ if (folderId == null || !trimmed) return;+ const result = await renameFolder(folderId, trimmed);+ if (!result.success && result.error) {+ toast({+ title: t("notes.folders.couldNotRename"),+ description: result.error,+ variant: "destructive",+ });+ }+ };++ const confirmSpaceRename = async () => {+ const spaceId = renamingSpaceId;+ if (spaceId == null) return;+ const space = spaces.find((s) => s.id === spaceId);+ const name = renameSpaceName.trim();+ const emoji = renameSpaceEmoji.trim() || null;+ setRenamingSpaceId(null);+ if (!space || !name) return;+ if (name === space.name && emoji === (space.emoji ?? null)) return;+ const result = await updateSpaceMeta(spaceId, { name, emoji });+ if (!result.success && result.error) {+ toast({+ title: t("notes.spaces.couldNotRename"),+ description: result.error,+ variant: "destructive",+ });+ }+ };++ const renderNote = (note: NoteItem, level: 2 | 3, parentKey: string) => (+ <NoteLeaf+ key={note.id}+ note={note}+ level={level}+ isActive={note.id === activeNoteId}+ isDragging={dragState.draggingNoteId === note.id}+ dragHandlers={noteDragHandlers({+ id: note.id,+ title: note.title,+ folderId: note.folder_id,+ spaceId: note.space_id,+ })}+ spaces={visibleSpaces}+ folders={folders}+ noteFilesEnabled={noteFilesEnabled}+ fileManagerName={fileManagerName}+ onOpen={() => activateRow({ type: "note", key: `n:${note.id}`, note, parentKey, level })}+ onMove={(target) => requestMoveNote(note.id, target)}+ onCreateFolderAndMove={onCreateFolderAndMove}+ onDelete={onDeleteNote}+ a11y={a11yFor(`n:${note.id}`)}+ t={t}+ />+ );++ const renderFolder = (folder: FolderItem, parentKey: string) => {+ const folderKey = folderContainerKey(folder.id);+ const isExpanded = expanded.has(folderKey);+ const isRenaming = renamingFolderId === folder.id;++ if (isRenaming) {+ return (+ <div key={folder.id} role="none" className="pl-[14px] pr-2">+ <input+ autoFocus+ value={renameValue}+ onChange={(e) => setRenameValue(e.target.value)}+ onFocus={(e) => e.currentTarget.select()}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ confirmRename();+ focusRowSoon(folderKey);+ }+ if (e.key === "Escape") {+ setRenamingFolderId(null);+ setRenameValue("");+ focusRowSoon(folderKey);+ }+ }}+ onBlur={confirmRename}+ className={FOLDER_INPUT_CLASS}+ />+ </div>+ );+ }++ return (+ <div key={folder.id} role="none">+ <FolderRow+ folder={folder}+ spaces={visibleSpaces}+ isExpanded={isExpanded}+ isActive={activeContext?.folderId === folder.id}+ count={folderCounts[folder.id] ?? 0}+ isDragOver={dragState.dragOverKey === folderKey}+ isDropSuccess={dragState.dropSuccessKey === folderKey}+ dropHandlers={dropTargetHandlers({+ spaceId: folder.space_id,+ folderId: folder.id,+ folderName: folder.name,+ isDefaultFolder: Boolean(folder.is_default),+ })}+ noteFilesEnabled={noteFilesEnabled}+ fileManagerName={fileManagerName}+ onActivate={() => activateRow({ type: "folder", key: folderKey, folder, parentKey })}+ onToggle={() => toggleContainerExpanded(folderKey)}+ onRename={() => startRenameFolder(folder)}+ onMoveToSpace={(space) => requestMoveFolder(folder, space)}+ onDelete={() => requestDeleteFolder(folder)}+ a11y={a11yFor(folderKey)}+ t={t}+ />+ <TreeChildren open={isExpanded}>+ <div className="space-y-px">+ {(notesByContainer[folderKey] ?? []).map((note) => renderNote(note, 3, folderKey))}+ </div>+ </TreeChildren>+ </div>+ );+ };++ const renderSpace = (space: SpaceItem) => {+ const spaceKey = spaceContainerKey(space.id);+ const isExpanded = expanded.has(spaceKey);+ const spaceFolders = folders.filter((f) => f.space_id === space.id);+ const rootNotes = notesByContainer[spaceKey];+ const displayName = spaceDisplayName(space, t);+ const noteCount =+ spaceFolders.reduce((sum, f) => sum + (folderCounts[f.id] ?? 0), 0) ++ (rootNotes?.length ?? 0);+ const showSkeletons =+ space.kind === "team" &&+ space.sync_status === "pending" &&+ spaceFolders.length === 0 &&+ rootNotes === undefined;+ const showEmptySpace =+ space.kind === "team" && spaceFolders.length === 0 && rootNotes?.length === 0;++ return (+ <div key={space.id} role="none">+ {renamingSpaceId === space.id ? (+ <div+ role="none"+ className="flex items-center gap-1 h-[30px] px-2"+ onBlur={(e) => {+ if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {+ confirmSpaceRename();+ }+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ confirmSpaceRename();+ focusRowSoon(spaceKey);+ }+ if (e.key === "Escape") {+ setRenamingSpaceId(null);+ focusRowSoon(spaceKey);+ }+ }}+ >+ <input+ autoFocus={spaceRenameFocus === "emoji"}+ value={renameSpaceEmoji}+ onChange={(e) => setRenameSpaceEmoji(e.target.value)}+ maxLength={4}+ aria-label={t("notes.spaces.changeEmoji")}+ className={cn(FOLDER_INPUT_CLASS, "w-8 shrink-0 px-0 text-center")}+ />+ <input+ autoFocus={spaceRenameFocus === "name"}+ value={renameSpaceName}+ onChange={(e) => setRenameSpaceName(e.target.value)}+ onFocus={(e) => e.currentTarget.select()}+ aria-label={t("notes.spaces.rename")}+ className={FOLDER_INPUT_CLASS}+ />+ </div>+ ) : (+ <SpaceRow+ space={space}+ displayName={displayName}+ isExpanded={isExpanded}+ isActive={activeContext?.spaceId === space.id && activeContext.folderId == null}+ count={noteCount}+ isDragOver={dragState.dragOverKey === spaceKey}+ isDropSuccess={dragState.dropSuccessKey === spaceKey}+ dropHandlers={dropTargetHandlers({ spaceId: space.id, folderId: null })}+ canDeleteSpace={devOverride}+ onActivate={() => activateRow({ type: "space", key: spaceKey, space })}+ onToggle={() => toggleContainerExpanded(spaceKey)}+ onNewFolder={() => startCreateFolder(space)}+ onRename={(focus) => startRenameSpace(space, focus)}+ onDelete={() => requestDeleteSpace(space)}+ a11y={a11yFor(spaceKey)}+ t={t}+ />+ )}+ <TreeChildren open={isExpanded}>+ <div className="space-y-px">+ {spaceFolders.map((folder) => renderFolder(folder, spaceKey))}+ {creatingFolderSpaceId === space.id && (+ <div className="pl-[14px] pr-2">+ <input+ autoFocus+ value={newFolderName}+ onChange={(e) => setNewFolderName(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ void confirmCreateFolder().then((key) => key && focusRowSoon(key));+ }+ if (e.key === "Escape") {+ setCreatingFolderSpaceId(null);+ setNewFolderName("");+ focusRowSoon(spaceKey);+ }+ }}+ onBlur={confirmCreateFolder}+ placeholder={t("notes.folders.folderName")}+ className={cn(FOLDER_INPUT_CLASS, "placeholder:text-foreground/20")}+ />+ </div>+ )}+ {(rootNotes ?? []).map((note) => renderNote(note, 2, spaceKey))}+ {showSkeletons && <SkeletonRows />}+ {showEmptySpace && (+ <div className="pl-[18px] pr-2 py-1">+ <p className="text-xs text-foreground/40 leading-relaxed mb-1.5">+ {t("notes.spaces.emptySpace", { space: space.name })}+ </p>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => onNewNote(space.id, null)}+ className="h-6 px-2 text-xs gap-1 text-primary/70 hover:text-primary hover:bg-primary/8"+ >+ <Plus size={11} />+ {t("notes.list.newNote")}+ </Button>+ </div>+ )}+ </div>+ </TreeChildren>+ </div>+ );+ };++ if (isTreeLoading && spaces.length === 0) {+ return (+ <div className="flex-1 flex items-start justify-center py-8">+ <Loader2 size={12} className="animate-spin text-foreground/15" />+ </div>+ );+ }++ return (+ <>+ <div+ role="tree"+ aria-label={t("notes.list.title")}+ className="flex-1 overflow-y-auto px-1.5 pb-2 space-y-px"+ >+ <SectionHeader label={t("notes.spaces.privateSpaces")} />+ {privateSpaces.map(renderSpace)}+ {teamCapability && (+ <div role="none" className="group/section">+ <SectionHeader+ label={t("notes.spaces.teamSpaces")}+ className="mt-3"+ action={+ devOverride ? (+ <Button+ variant="ghost"+ size="icon"+ aria-label={t("notes.spaces.newSpace")}+ onClick={() => setShowCreateSpace(true)}+ className={cn(+ "h-5 w-5 rounded-sm opacity-0 group-hover/section:opacity-100 focus-visible:opacity-100",+ "transition-opacity text-muted-foreground/60 dark:text-muted-foreground/40",+ "hover:text-foreground/60 hover:bg-foreground/5 active:bg-foreground/8"+ )}+ >+ <Plus size={12} />+ </Button>+ ) : undefined+ }+ />+ {teamSpaces.map(renderSpace)}+ </div>+ )}+ </div>++ <CreateSpaceDialog open={showCreateSpace} onOpenChange={setShowCreateSpace} />++ <ConfirmDialog+ open={confirmDialog.open}+ onOpenChange={(open) => !open && hideConfirmDialog()}+ title={confirmDialog.title}+ description={confirmDialog.description}+ confirmText={confirmDialog.confirmText}+ cancelText={confirmDialog.cancelText}+ onConfirm={confirmDialog.onConfirm}+ variant={confirmDialog.variant}+ />+ </>+ );+}diff --git a/src/helpers/database.js b/src/helpers/database.jsindex 08d4d5a80..b7a031619 100644--- a/src/helpers/database.js+++ b/src/helpers/database.js@@ -1571,6 +1571,9 @@ class DatabaseManager {if (folderId != null) {conditions.push("folder_id = ?");params.push(folderId);+ } else if (spaceId != null) {+ // spaceId without folderId lists a space's root: folderless notes only.+ conditions.push("folder_id IS NULL");}if (spaceId != null) {conditions.push("space_id = ?");@@ -1746,6 +1749,46 @@ class DatabaseManager {}}+ moveFolderToSpace(id, spaceId) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ const folder = this.db.prepare("SELECT * FROM folders WHERE id = ?").get(id);+ if (!folder) return { success: false, error: "Folder not found" };+ if (folder.is_default) return { success: false, error: "Cannot move default folders" };+ const space = this.db+ .prepare("SELECT id FROM spaces WHERE id = ? AND deleted_at IS NULL")+ .get(spaceId);+ if (!space) return { success: false, error: "Space not found" };+ if (folder.space_id === spaceId) return { success: true, folder, notes: [] };+ const existing = this.db+ .prepare(+ "SELECT id FROM folders WHERE name = ? AND space_id = ? AND deleted_at IS NULL AND id != ?"+ )+ .get(folder.name, spaceId, id);+ if (existing) return { success: false, error: "A folder with that name already exists" };+ const notes = this.db.transaction(() => {+ this.db+ .prepare(+ "UPDATE folders SET space_id = ?, sync_status = 'pending', updated_at = datetime('now') WHERE id = ?"+ )+ .run(spaceId, id);+ this.db+ .prepare(+ "UPDATE notes SET space_id = ?, sync_status = 'pending', updated_at = datetime('now') WHERE folder_id = ? AND deleted_at IS NULL"+ )+ .run(spaceId, id);+ return this.db+ .prepare("SELECT * FROM notes WHERE folder_id = ? AND deleted_at IS NULL")+ .all(id);+ })();+ const updated = this.db.prepare("SELECT * FROM folders WHERE id = ?").get(id);+ return { success: true, folder: updated, notes };+ } catch (error) {+ debugLogger.error("Error moving folder to space", { error: error.message }, "spaces");+ throw error;+ }+ }+getFolderNoteCounts() {try {if (!this.db) throw new Error("Database not initialized");diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 83a76ef9f..56d35ae24 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -1276,6 +1276,17 @@ class IPCHandlers {return result;});+ ipcMain.handle("db-move-folder-to-space", async (event, id, spaceId) => {+ const result = this.databaseManager.moveFolderToSpace(id, spaceId);+ if (result?.success) {+ // Qdrant payloads carry space_id — refresh the moved notes' vectors.+ for (const note of result.notes ?? []) {+ this._asyncVectorUpsert(note);+ }+ }+ return result;+ });+ipcMain.handle("db-get-folder-note-counts", async () => {return this.databaseManager.getFolderNoteCounts();});diff --git a/src/hooks/useFolderManagement.ts b/src/hooks/useFolderManagement.tsdeleted file mode 100644index a16ed109a..000000000--- a/src/hooks/useFolderManagement.ts+++ /dev/null@@ -1,244 +0,0 @@-import { useState, useEffect, useRef, useCallback } from "react";-import { useTranslation } from "react-i18next";-import { useToast } from "../components/ui/useToast";-import logger from "../utils/logger";-import type { FolderItem } from "../types/electron";-import { findDefaultFolder } from "../components/notes/shared";-import { syncService } from "../services/SyncService.js";-import {- useActiveFolderId,- setActiveFolderId,- setActiveNoteId,- getActiveFolderIdValue,- getActiveNoteIdValue,- initializeNotes,-} from "../stores/noteStore";--export interface UseFolderManagementReturn {- folders: FolderItem[];- folderCounts: Record<number, number>;- isLoading: boolean;- isCreatingFolder: boolean;- newFolderName: string;- renamingFolderId: number | null;- renameValue: string;- showAddNotesDialog: boolean;- newFolderInputRef: React.RefObject<HTMLInputElement>;- renameInputRef: React.RefObject<HTMLInputElement>;- setIsCreatingFolder: (v: boolean) => void;- setNewFolderName: (v: string) => void;- setRenamingFolderId: (id: number | null) => void;- setRenameValue: (v: string) => void;- setShowAddNotesDialog: (v: boolean) => void;- loadFolders: () => Promise<FolderItem[]>;- handleCreateFolder: () => Promise<void>;- handleConfirmRename: () => Promise<void>;- handleDeleteFolder: (id: number) => Promise<void>;-}--export function useFolderManagement(): UseFolderManagementReturn {- const { t } = useTranslation();- const { toast } = useToast();- const activeFolderId = useActiveFolderId();-- const [folders, setFolders] = useState<FolderItem[]>([]);- const [folderCounts, setFolderCounts] = useState<Record<number, number>>({});- const [isLoading, setIsLoading] = useState(true);- const [isCreatingFolder, setIsCreatingFolder] = useState(false);- const [newFolderName, setNewFolderName] = useState("");- const [renamingFolderId, setRenamingFolderId] = useState<number | null>(null);- const [renameValue, setRenameValue] = useState("");- const [showAddNotesDialog, setShowAddNotesDialog] = useState(false);-- const newFolderInputRef = useRef<HTMLInputElement>(null);- const renameInputRef = useRef<HTMLInputElement>(null);- const prevFolderIdRef = useRef<number | null>(null);- const isMountedRef = useRef(true);-- const loadFolders = useCallback(async () => {- try {- const [items, counts] = await Promise.all([- window.electronAPI.getFolders(),- window.electronAPI.getFolderNoteCounts(),- ]);- if (!isMountedRef.current) return items;- setFolders(items);- const countMap: Record<number, number> = {};- counts.forEach((c) => {- countMap[c.folder_id] = c.count;- });- setFolderCounts(countMap);- return items;- } catch (err) {- logger.warn("Failed to load folders", { error: (err as Error).message }, "notes");- return [];- }- }, []);-- // Load folders on mount, determine initial active folder- useEffect(() => {- isMountedRef.current = true;- const load = async () => {- try {- setIsLoading(true);- const items = await loadFolders();- if (!isMountedRef.current) return;-- // Respect pre-set activeFolderId (e.g., navigating from "Open Note")- const presetFolderId = getActiveFolderIdValue();- const isPresetValid = presetFolderId != null && items.some((f) => f.id === presetFolderId);-- const initialFolderId = isPresetValid- ? presetFolderId- : (findDefaultFolder(items)?.id ?? items[0]?.id ?? null);-- if (initialFolderId !== presetFolderId) {- setActiveFolderId(initialFolderId);- }- if (initialFolderId) {- const notes = await initializeNotes(null, 50, initialFolderId);- if (!isMountedRef.current) return;- const presetNoteId = getActiveNoteIdValue();- if (!presetNoteId && notes.length > 0) {- setActiveNoteId(notes[0].id);- }- }- prevFolderIdRef.current = initialFolderId;- } finally {- if (isMountedRef.current) setIsLoading(false);- }- };- load();- return () => {- isMountedRef.current = false;- };- }, [loadFolders]);-- // Re-initialize notes when active folder changes- useEffect(() => {- if (!activeFolderId || isLoading) return;- if (prevFolderIdRef.current === activeFolderId) return;- prevFolderIdRef.current = activeFolderId;- const loadForFolder = async () => {- try {- const notes = await initializeNotes(null, 50, activeFolderId);- if (getActiveFolderIdValue() !== activeFolderId) return;- const presetNoteId = getActiveNoteIdValue();- if (!presetNoteId || !notes.some((n) => n.id === presetNoteId)) {- setActiveNoteId(notes.length > 0 ? notes[0].id : null);- }- } catch (err) {- logger.warn(- "Failed to load notes for folder",- { folderId: activeFolderId, error: (err as Error).message },- "notes"- );- }- };- loadForFolder();- }, [activeFolderId, isLoading]);-- // Focus new folder input when creating- useEffect(() => {- if (isCreatingFolder && newFolderInputRef.current) {- newFolderInputRef.current.focus();- }- }, [isCreatingFolder]);-- // Focus rename input when renaming- useEffect(() => {- if (renamingFolderId && renameInputRef.current) {- renameInputRef.current.focus();- renameInputRef.current.select();- }- }, [renamingFolderId]);-- const handleCreateFolder = useCallback(async () => {- const trimmed = newFolderName.trim();- if (!trimmed) {- setIsCreatingFolder(false);- setNewFolderName("");- return;- }- const result = await window.electronAPI.createFolder(trimmed);- if (result.success && result.folder) {- await loadFolders();- setActiveFolderId(result.folder.id);- syncService.debouncedPush("folder", result.folder.id);- } else if (result.error) {- toast({- title: t("notes.folders.couldNotCreate"),- description: result.error,- variant: "destructive",- });- }- setIsCreatingFolder(false);- setNewFolderName("");- }, [newFolderName, loadFolders, toast, t]);-- const handleConfirmRename = useCallback(async () => {- if (!renamingFolderId) return;- const trimmed = renameValue.trim();- if (!trimmed) {- setRenamingFolderId(null);- setRenameValue("");- return;- }- const result = await window.electronAPI.renameFolder(renamingFolderId, trimmed);- if (result.success) {- await loadFolders();- syncService.debouncedPush("folder", renamingFolderId);- } else if (result.error) {- toast({- title: t("notes.folders.couldNotRename"),- description: result.error,- variant: "destructive",- });- }- setRenamingFolderId(null);- setRenameValue("");- }, [renamingFolderId, renameValue, loadFolders, toast, t]);-- const handleDeleteFolder = useCallback(- async (folderId: number) => {- const result = await window.electronAPI.deleteFolder(folderId);- if (result.success) {- const items = await loadFolders();- if (getActiveFolderIdValue() === folderId) {- const personalFolder = findDefaultFolder(items);- if (personalFolder) setActiveFolderId(personalFolder.id);- }- syncService.requestSyncAll("manual");- } else if (result.error) {- toast({- title: t("notes.folders.couldNotDelete"),- description: result.error,- variant: "destructive",- });- }- },- [loadFolders, toast, t]- );-- return {- folders,- folderCounts,- isLoading,- isCreatingFolder,- newFolderName,- renamingFolderId,- renameValue,- showAddNotesDialog,- newFolderInputRef,- renameInputRef,- setIsCreatingFolder,- setNewFolderName,- setRenamingFolderId,- setRenameValue,- setShowAddNotesDialog,- loadFolders,- handleCreateFolder,- handleConfirmRename,- handleDeleteFolder,- };-}diff --git a/src/hooks/useNoteDragAndDrop.ts b/src/hooks/useNoteDragAndDrop.tsindex 667247c5e..281fd3bac 100644--- a/src/hooks/useNoteDragAndDrop.ts+++ b/src/hooks/useNoteDragAndDrop.ts@@ -1,42 +1,85 @@import { useState, useCallback, useRef, useEffect } from "react";import { MEETINGS_FOLDER_NAME } from "../components/notes/shared";+import { folderContainerKey, spaceContainerKey } from "../stores/noteStore";++export interface NoteMoveTarget {+ spaceId: number;+ folderId: number | null;+}++export interface DraggedNoteInfo {+ id: number;+ title: string;+ folderId: number | null;+ spaceId: number;+}++interface DropTargetInfo extends NoteMoveTarget {+ folderName?: string;+ isDefaultFolder?: boolean;+}interface DragState {draggingNoteId: number | null;- dragOverFolderId: number | null;- dropSuccessFolderId: number | null;+ dragOverKey: string | null;+ dropSuccessKey: string | null;}interface UseNoteDragAndDropOptions {- onMoveToFolder: (noteId: number, folderId: number) => Promise<void>;- currentFolderId: number | null;+ onMoveToTarget: (noteId: number, target: NoteMoveTarget) => void | Promise<void>;+ /** Cross-space drops change the note's audience — the caller confirms, then calls commit(). */+ onCrossSpaceDrop: (note: DraggedNoteInfo, target: NoteMoveTarget, commit: () => void) => void;+ /** Fired after hovering a target for 500ms mid-drag (auto-expand collapsed containers). */+ onHoverTarget?: (key: string) => void;}-export function useNoteDragAndDrop({ onMoveToFolder, currentFolderId }: UseNoteDragAndDropOptions) {+const HOVER_EXPAND_DELAY_MS = 500;++function targetKey(target: NoteMoveTarget): string {+ return target.folderId != null+ ? folderContainerKey(target.folderId)+ : spaceContainerKey(target.spaceId);+}++export function useNoteDragAndDrop({+ onMoveToTarget,+ onCrossSpaceDrop,+ onHoverTarget,+}: UseNoteDragAndDropOptions) {const [dragState, setDragState] = useState<DragState>({draggingNoteId: null,- dragOverFolderId: null,- dropSuccessFolderId: null,+ dragOverKey: null,+ dropSuccessKey: null,});const successTimeoutRef = useRef<NodeJS.Timeout | null>(null);- const enterCounterRef = useRef<Map<number, number>>(new Map());+ const hoverTimeoutRef = useRef<NodeJS.Timeout | null>(null);+ const hoverKeyRef = useRef<string | null>(null);+ const enterCounterRef = useRef<Map<string, number>>(new Map());+ const draggedNoteRef = useRef<DraggedNoteInfo | null>(null);++ const clearHoverTimeout = useCallback(() => {+ if (hoverTimeoutRef.current) clearTimeout(hoverTimeoutRef.current);+ hoverTimeoutRef.current = null;+ hoverKeyRef.current = null;+ }, []);useEffect(() => {return () => {if (successTimeoutRef.current) clearTimeout(successTimeoutRef.current);+ if (hoverTimeoutRef.current) clearTimeout(hoverTimeoutRef.current);};}, []);const noteDragHandlers = useCallback(- (noteId: number, noteTitle: string) => ({+ (note: DraggedNoteInfo) => ({draggable: true as const,onDragStart: (e: React.DragEvent) => {e.dataTransfer.effectAllowed = "move";- e.dataTransfer.setData("application/x-note-id", String(noteId));+ e.dataTransfer.setData("application/x-note-id", String(note.id));const ghost = document.createElement("div");- const label = noteTitle || "Untitled";+ const label = note.title || "Untitled";ghost.textContent = label.length > 24 ? label.slice(0, 24) + "…" : label;ghost.style.cssText = `position: fixed; top: -200px; left: -200px;@@ -54,82 +97,117 @@ export function useNoteDragAndDrop({ onMoveToFolder, currentFolderId }: UseNoteDe.dataTransfer.setDragImage(ghost, 0, 0);requestAnimationFrame(() => ghost.remove());- setDragState((prev) => ({ ...prev, draggingNoteId: noteId }));+ draggedNoteRef.current = note;+ setDragState((prev) => ({ ...prev, draggingNoteId: note.id }));enterCounterRef.current.clear();},onDragEnd: () => {+ draggedNoteRef.current = null;+ clearHoverTimeout();setDragState((prev) => ({...prev,draggingNoteId: null,- dragOverFolderId: null,+ dragOverKey: null,}));enterCounterRef.current.clear();},}),- []+ [clearHoverTimeout]+ );++ const commitDrop = useCallback(+ (noteId: number, target: NoteMoveTarget, key: string) => {+ setDragState((prev) => ({ ...prev, dropSuccessKey: key }));+ if (successTimeoutRef.current) clearTimeout(successTimeoutRef.current);+ successTimeoutRef.current = setTimeout(() => {+ setDragState((prev) =>+ prev.dropSuccessKey === key ? { ...prev, dropSuccessKey: null } : prev+ );+ }, 800);+ void onMoveToTarget(noteId, target);+ },+ [onMoveToTarget]);- const folderDropHandlers = useCallback(- (folderId: number, folderName: string) => {- const isMeetings = folderName === MEETINGS_FOLDER_NAME;- const isSameFolder = folderId === currentFolderId;- const canDrop = !isMeetings && !isSameFolder;+ const dropTargetHandlers = useCallback(+ (targetInfo: DropTargetInfo) => {+ const target: NoteMoveTarget = { spaceId: targetInfo.spaceId, folderId: targetInfo.folderId };+ const key = targetKey(target);+ const canDrop = () => {+ const note = draggedNoteRef.current;+ if (!note) return false;+ const isSameContainer =+ target.folderId != null+ ? note.folderId === target.folderId+ : note.folderId == null && note.spaceId === target.spaceId;+ if (isSameContainer) return false;+ // The default Meetings folder of the note's own space stays a non-target.+ const isOwnMeetings =+ !!targetInfo.isDefaultFolder &&+ targetInfo.folderName === MEETINGS_FOLDER_NAME &&+ targetInfo.spaceId === note.spaceId;+ return !isOwnMeetings;+ };return {onDragOver: (e: React.DragEvent) => {- if (!canDrop) return;+ if (!canDrop()) return;e.preventDefault();e.dataTransfer.dropEffect = "move";},onDragEnter: (e: React.DragEvent) => {e.preventDefault();- if (!canDrop) return;- const count = (enterCounterRef.current.get(folderId) ?? 0) + 1;- enterCounterRef.current.set(folderId, count);+ if (!canDrop()) return;+ const count = (enterCounterRef.current.get(key) ?? 0) + 1;+ enterCounterRef.current.set(key, count);if (count === 1) {- setDragState((prev) => ({ ...prev, dragOverFolderId: folderId }));+ setDragState((prev) => ({ ...prev, dragOverKey: key }));+ if (onHoverTarget) {+ clearHoverTimeout();+ hoverKeyRef.current = key;+ hoverTimeoutRef.current = setTimeout(() => onHoverTarget(key), HOVER_EXPAND_DELAY_MS);+ }}},onDragLeave: () => {- if (!canDrop) return;- const count = (enterCounterRef.current.get(folderId) ?? 0) - 1;- enterCounterRef.current.set(folderId, Math.max(0, count));+ if (!canDrop()) return;+ const count = (enterCounterRef.current.get(key) ?? 0) - 1;+ enterCounterRef.current.set(key, Math.max(0, count));if (count <= 0) {- enterCounterRef.current.set(folderId, 0);+ enterCounterRef.current.set(key, 0);+ if (hoverKeyRef.current === key) clearHoverTimeout();setDragState((prev) =>- prev.dragOverFolderId === folderId ? { ...prev, dragOverFolderId: null } : prev+ prev.dragOverKey === key ? { ...prev, dragOverKey: null } : prev);}},- onDrop: async (e: React.DragEvent) => {+ onDrop: (e: React.DragEvent) => {e.preventDefault();- if (!canDrop) return;+ if (!canDrop()) return;- const noteIdStr = e.dataTransfer.getData("application/x-note-id");- const noteId = parseInt(noteIdStr, 10);- if (isNaN(noteId)) return;+ const note = draggedNoteRef.current;+ const noteId = parseInt(e.dataTransfer.getData("application/x-note-id"), 10);+ if (!note || isNaN(noteId) || noteId !== note.id) return;+ clearHoverTimeout();enterCounterRef.current.clear();+ draggedNoteRef.current = null;setDragState((prev) => ({...prev,draggingNoteId: null,- dragOverFolderId: null,- dropSuccessFolderId: folderId,+ dragOverKey: null,}));- if (successTimeoutRef.current) clearTimeout(successTimeoutRef.current);- successTimeoutRef.current = setTimeout(() => {- setDragState((prev) =>- prev.dropSuccessFolderId === folderId ? { ...prev, dropSuccessFolderId: null } : prev- );- }, 800);-- await onMoveToFolder(noteId, folderId);+ if (note.spaceId !== target.spaceId) {+ onCrossSpaceDrop(note, target, () => commitDrop(noteId, target, key));+ } else {+ commitDrop(noteId, target, key);+ }},};},- [currentFolderId, onMoveToFolder]+ [onCrossSpaceDrop, onHoverTarget, commitDrop, clearHoverTimeout]);- return { dragState, noteDragHandlers, folderDropHandlers };+ return { dragState, noteDragHandlers, dropTargetHandlers };}diff --git a/src/hooks/useTeamSpacesCapability.ts b/src/hooks/useTeamSpacesCapability.tsnew file mode 100644index 000000000..340a068f9--- /dev/null+++ b/src/hooks/useTeamSpacesCapability.ts@@ -0,0 +1,15 @@+import { useSpaces } from "../stores/noteStore";++/** Phase-2 gate for local-only team-space mutations (create/delete). */+export function hasTeamSpacesDevOverride(): boolean {+ return localStorage.getItem("teamSpacesDevOverride") === "true";+}++/**+ * Whether the TEAM SPACES section should render. Phase 2: dev override or+ * locally known team spaces; Phase 3 swaps in the server capability probe.+ */+export function useTeamSpacesCapability(): boolean {+ const spaces = useSpaces();+ return hasTeamSpacesDevOverride() || spaces.some((space) => space.kind === "team");+}diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 1f16f7ab3..55911d1da 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -2367,6 +2367,44 @@"searchNotes": "Notizen suchen","actions": "Aktionen"},+ "spaces": {+ "privateSpaces": "Private Bereiche",+ "teamSpaces": "Team-Bereiche",+ "personal": "Persönlich",+ "privateTooltip": "Nur du kannst deinen persönlichen Bereich sehen",+ "newSpace": "Neuer Bereich",+ "createTitle": "Bereich erstellen",+ "nameLabel": "Name",+ "emojiLabel": "Emoji",+ "create": "Erstellen",+ "couldNotCreate": "Bereich konnte nicht erstellt werden",+ "rename": "Umbenennen",+ "changeEmoji": "Emoji ändern",+ "couldNotRename": "Bereich konnte nicht umbenannt werden",+ "deleteSpace": "Bereich löschen",+ "deleteConfirmTitle": "Bereich löschen?",+ "deleteConfirmDescription": "Dadurch werden {{space}} und alle zugehörigen Ordner und Notizen auf diesem Gerät endgültig gelöscht.",+ "couldNotDelete": "Bereich konnte nicht gelöscht werden",+ "moveTo": "Verschieben nach",+ "moveToSpace": "In Bereich verschieben…",+ "searchSpaces": "Bereiche suchen...",+ "noSpacesFound": "Keine Bereiche gefunden",+ "spaceRoot": "Oberste Ebene",+ "moveConfirm": "Verschieben",+ "confirmMoveInTitle": "Nach {{space}} verschieben?",+ "confirmMoveIn": "Alle in {{space}} können diese Notiz sehen und bearbeiten.",+ "confirmMoveInFolder": "Alle in {{space}} können diesen Ordner und seine Notizen sehen und bearbeiten.",+ "confirmMoveOutTitle": "Aus {{space}} verschieben?",+ "confirmMoveOut": "Mitglieder von {{space}} verlieren den Zugriff auf diese Notiz.",+ "confirmMoveOutFolder": "Mitglieder von {{space}} verlieren den Zugriff auf diesen Ordner und seine Notizen.",+ "moved": "„{{title}}“ nach {{target}} verschoben",+ "couldNotMove": "Ordner konnte nicht verschoben werden",+ "couldNotMoveNote": "Notiz konnte nicht verschoben werden",+ "undo": "Rückgängig",+ "emptySpace": "Noch keine Notizen. Notizen hier sind für alle in {{space}} sichtbar.",+ "noteCount_one": "{{count}} Notiz",+ "noteCount_other": "{{count}} Notizen"+ },"folders": {"title": "Ordner","soon": "Demnächst",@@ -2974,7 +3012,8 @@"placeholder": "Notizen und Transkripte durchsuchen…","sections": {"notes": "Notizen",- "transcripts": "Transkripte"+ "transcripts": "Transkripte",+ "jumpTo": "Gehe zu"},"noResults": "Keine Ergebnisse","emptyState": "Tippen, um zu suchen",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 49657d022..e2ac95db7 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -2367,6 +2367,44 @@"searchNotes": "Search notes","actions": "Actions"},+ "spaces": {+ "privateSpaces": "Private spaces",+ "teamSpaces": "Team spaces",+ "personal": "Personal",+ "privateTooltip": "Only you can see your Personal space",+ "newSpace": "New space",+ "createTitle": "Create space",+ "nameLabel": "Name",+ "emojiLabel": "Emoji",+ "create": "Create",+ "couldNotCreate": "Couldn't create space",+ "rename": "Rename",+ "changeEmoji": "Change emoji",+ "couldNotRename": "Couldn't rename space",+ "deleteSpace": "Delete space",+ "deleteConfirmTitle": "Delete space?",+ "deleteConfirmDescription": "This permanently deletes {{space}} with all of its folders and notes on this device.",+ "couldNotDelete": "Couldn't delete space",+ "moveTo": "Move to",+ "moveToSpace": "Move to space…",+ "searchSpaces": "Search spaces...",+ "noSpacesFound": "No spaces found",+ "spaceRoot": "Space root",+ "moveConfirm": "Move",+ "confirmMoveInTitle": "Move to {{space}}?",+ "confirmMoveIn": "Everyone in {{space}} will be able to view and edit this note.",+ "confirmMoveInFolder": "Everyone in {{space}} will be able to view and edit this folder and its notes.",+ "confirmMoveOutTitle": "Move out of {{space}}?",+ "confirmMoveOut": "Members of {{space}} will lose access to this note.",+ "confirmMoveOutFolder": "Members of {{space}} will lose access to this folder and its notes.",+ "moved": "Moved “{{title}}” to {{target}}",+ "couldNotMove": "Couldn't move folder",+ "couldNotMoveNote": "Couldn't move note",+ "undo": "Undo",+ "emptySpace": "No notes yet. Notes here are visible to everyone in {{space}}.",+ "noteCount_one": "{{count}} note",+ "noteCount_other": "{{count}} notes"+ },"folders": {"title": "Folders","soon": "Soon",@@ -2974,7 +3012,8 @@"placeholder": "Search notes and transcripts…","sections": {"notes": "Notes",- "transcripts": "Transcripts"+ "transcripts": "Transcripts",+ "jumpTo": "Jump to"},"noResults": "No results","emptyState": "Start typing to search",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex da24feb19..d25e8b603 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -2209,6 +2209,44 @@"searchNotes": "Buscar notas","actions": "Acciones"},+ "spaces": {+ "privateSpaces": "Espacios privados",+ "teamSpaces": "Espacios de equipo",+ "personal": "Personal",+ "privateTooltip": "Solo tú puedes ver tu espacio personal",+ "newSpace": "Nuevo espacio",+ "createTitle": "Crear espacio",+ "nameLabel": "Nombre",+ "emojiLabel": "Emoji",+ "create": "Crear",+ "couldNotCreate": "No se pudo crear el espacio",+ "rename": "Renombrar",+ "changeEmoji": "Cambiar emoji",+ "couldNotRename": "No se pudo renombrar el espacio",+ "deleteSpace": "Eliminar espacio",+ "deleteConfirmTitle": "¿Eliminar espacio?",+ "deleteConfirmDescription": "Esto elimina permanentemente {{space}} con todas sus carpetas y notas en este dispositivo.",+ "couldNotDelete": "No se pudo eliminar el espacio",+ "moveTo": "Mover a",+ "moveToSpace": "Mover a espacio…",+ "searchSpaces": "Buscar espacios...",+ "noSpacesFound": "No se encontraron espacios",+ "spaceRoot": "Raíz del espacio",+ "moveConfirm": "Mover",+ "confirmMoveInTitle": "¿Mover a {{space}}?",+ "confirmMoveIn": "Todos en {{space}} podrán ver y editar esta nota.",+ "confirmMoveInFolder": "Todos en {{space}} podrán ver y editar esta carpeta y sus notas.",+ "confirmMoveOutTitle": "¿Sacar de {{space}}?",+ "confirmMoveOut": "Los miembros de {{space}} perderán el acceso a esta nota.",+ "confirmMoveOutFolder": "Los miembros de {{space}} perderán el acceso a esta carpeta y sus notas.",+ "moved": "«{{title}}» se movió a {{target}}",+ "couldNotMove": "No se pudo mover la carpeta",+ "couldNotMoveNote": "No se pudo mover la nota",+ "undo": "Deshacer",+ "emptySpace": "Aún no hay notas. Las notas aquí son visibles para todos en {{space}}.",+ "noteCount_one": "{{count}} nota",+ "noteCount_other": "{{count}} notas"+ },"folders": {"title": "Carpetas","soon": "Próximamente",@@ -2917,7 +2955,8 @@"placeholder": "Buscar notas y transcripciones…","sections": {"notes": "Notas",- "transcripts": "Transcripciones"+ "transcripts": "Transcripciones",+ "jumpTo": "Ir a"},"noResults": "Sin resultados","emptyState": "Escribe para buscar",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 414053a82..265550a4b 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -2367,6 +2367,44 @@"searchNotes": "Rechercher des notes","actions": "Actions"},+ "spaces": {+ "privateSpaces": "Espaces privés",+ "teamSpaces": "Espaces d'équipe",+ "personal": "Personnel",+ "privateTooltip": "Vous seul pouvez voir votre espace personnel",+ "newSpace": "Nouvel espace",+ "createTitle": "Créer un espace",+ "nameLabel": "Nom",+ "emojiLabel": "Émoji",+ "create": "Créer",+ "couldNotCreate": "Impossible de créer l'espace",+ "rename": "Renommer",+ "changeEmoji": "Changer l'émoji",+ "couldNotRename": "Impossible de renommer l'espace",+ "deleteSpace": "Supprimer l'espace",+ "deleteConfirmTitle": "Supprimer l'espace ?",+ "deleteConfirmDescription": "Cela supprime définitivement {{space}} ainsi que tous ses dossiers et notes sur cet appareil.",+ "couldNotDelete": "Impossible de supprimer l'espace",+ "moveTo": "Déplacer vers",+ "moveToSpace": "Déplacer vers un espace…",+ "searchSpaces": "Rechercher des espaces...",+ "noSpacesFound": "Aucun espace trouvé",+ "spaceRoot": "Racine de l'espace",+ "moveConfirm": "Déplacer",+ "confirmMoveInTitle": "Déplacer vers {{space}} ?",+ "confirmMoveIn": "Tous les membres de {{space}} pourront voir et modifier cette note.",+ "confirmMoveInFolder": "Tous les membres de {{space}} pourront voir et modifier ce dossier et ses notes.",+ "confirmMoveOutTitle": "Retirer de {{space}} ?",+ "confirmMoveOut": "Les membres de {{space}} perdront l'accès à cette note.",+ "confirmMoveOutFolder": "Les membres de {{space}} perdront l'accès à ce dossier et à ses notes.",+ "moved": "« {{title}} » déplacée vers {{target}}",+ "couldNotMove": "Impossible de déplacer le dossier",+ "couldNotMoveNote": "Impossible de déplacer la note",+ "undo": "Annuler",+ "emptySpace": "Aucune note pour le moment. Les notes ici sont visibles par tous les membres de {{space}}.",+ "noteCount_one": "{{count}} note",+ "noteCount_other": "{{count}} notes"+ },"folders": {"title": "Dossiers","soon": "Bientôt",@@ -2974,7 +3012,8 @@"placeholder": "Rechercher notes et transcriptions…","sections": {"notes": "Notes",- "transcripts": "Transcriptions"+ "transcripts": "Transcriptions",+ "jumpTo": "Aller à"},"noResults": "Aucun résultat","emptyState": "Commencez à taper pour rechercher",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex b5abea66a..fd4f6f211 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -2161,6 +2161,44 @@"searchNotes": "Cerca note","actions": "Azioni"},+ "spaces": {+ "privateSpaces": "Spazi privati",+ "teamSpaces": "Spazi del team",+ "personal": "Personale",+ "privateTooltip": "Solo tu puoi vedere il tuo spazio personale",+ "newSpace": "Nuovo spazio",+ "createTitle": "Crea spazio",+ "nameLabel": "Nome",+ "emojiLabel": "Emoji",+ "create": "Crea",+ "couldNotCreate": "Impossibile creare lo spazio",+ "rename": "Rinomina",+ "changeEmoji": "Cambia emoji",+ "couldNotRename": "Impossibile rinominare lo spazio",+ "deleteSpace": "Elimina spazio",+ "deleteConfirmTitle": "Eliminare lo spazio?",+ "deleteConfirmDescription": "Questo elimina definitivamente {{space}} con tutte le sue cartelle e note su questo dispositivo.",+ "couldNotDelete": "Impossibile eliminare lo spazio",+ "moveTo": "Sposta in",+ "moveToSpace": "Sposta in uno spazio…",+ "searchSpaces": "Cerca spazi...",+ "noSpacesFound": "Nessuno spazio trovato",+ "spaceRoot": "Radice dello spazio",+ "moveConfirm": "Sposta",+ "confirmMoveInTitle": "Spostare in {{space}}?",+ "confirmMoveIn": "Tutti in {{space}} potranno vedere e modificare questa nota.",+ "confirmMoveInFolder": "Tutti in {{space}} potranno vedere e modificare questa cartella e le sue note.",+ "confirmMoveOutTitle": "Spostare fuori da {{space}}?",+ "confirmMoveOut": "I membri di {{space}} perderanno l'accesso a questa nota.",+ "confirmMoveOutFolder": "I membri di {{space}} perderanno l'accesso a questa cartella e alle sue note.",+ "moved": "“{{title}}” spostata in {{target}}",+ "couldNotMove": "Impossibile spostare la cartella",+ "couldNotMoveNote": "Impossibile spostare la nota",+ "undo": "Annulla",+ "emptySpace": "Ancora nessuna nota. Le note qui sono visibili a tutti in {{space}}.",+ "noteCount_one": "{{count}} nota",+ "noteCount_other": "{{count}} note"+ },"folders": {"title": "Cartelle","soon": "Presto",@@ -2869,7 +2907,8 @@"placeholder": "Cerca note e trascrizioni…","sections": {"notes": "Note",- "transcripts": "Trascrizioni"+ "transcripts": "Trascrizioni",+ "jumpTo": "Vai a"},"noResults": "Nessun risultato","emptyState": "Inizia a digitare per cercare",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex 90dce91a9..dfa5d7361 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -2089,6 +2089,44 @@"searchNotes": "ノートを検索","actions": "アクション"},+ "spaces": {+ "privateSpaces": "プライベートスペース",+ "teamSpaces": "チームスペース",+ "personal": "個人",+ "privateTooltip": "パーソナルスペースはあなただけが見られます",+ "newSpace": "新しいスペース",+ "createTitle": "スペースを作成",+ "nameLabel": "名前",+ "emojiLabel": "絵文字",+ "create": "作成",+ "couldNotCreate": "スペースを作成できませんでした",+ "rename": "名前を変更",+ "changeEmoji": "絵文字を変更",+ "couldNotRename": "スペースの名前を変更できませんでした",+ "deleteSpace": "スペースを削除",+ "deleteConfirmTitle": "スペースを削除しますか?",+ "deleteConfirmDescription": "{{space}}とそのすべてのフォルダとノートがこのデバイスから完全に削除されます。",+ "couldNotDelete": "スペースを削除できませんでした",+ "moveTo": "移動",+ "moveToSpace": "スペースに移動…",+ "searchSpaces": "スペースを検索...",+ "noSpacesFound": "スペースが見つかりません",+ "spaceRoot": "スペースのルート",+ "moveConfirm": "移動",+ "confirmMoveInTitle": "{{space}}に移動しますか?",+ "confirmMoveIn": "{{space}}の全員がこのノートを表示・編集できるようになります。",+ "confirmMoveInFolder": "{{space}}の全員がこのフォルダとそのノートを表示・編集できるようになります。",+ "confirmMoveOutTitle": "{{space}}から移動しますか?",+ "confirmMoveOut": "{{space}}のメンバーはこのノートにアクセスできなくなります。",+ "confirmMoveOutFolder": "{{space}}のメンバーはこのフォルダとそのノートにアクセスできなくなります。",+ "moved": "「{{title}}」を{{target}}に移動しました",+ "couldNotMove": "フォルダを移動できませんでした",+ "couldNotMoveNote": "ノートを移動できませんでした",+ "undo": "元に戻す",+ "emptySpace": "まだノートがありません。ここのノートは{{space}}の全員に表示されます。",+ "noteCount_one": "{{count}} 件のノート",+ "noteCount_other": "{{count}} 件のノート"+ },"editor": {"transcribe": "文字起こし","staleIndicator": "強化後にコンテンツが変更されました",@@ -2869,7 +2907,8 @@"placeholder": "ノートと文字起こしを検索…","sections": {"notes": "ノート",- "transcripts": "文字起こし"+ "transcripts": "文字起こし",+ "jumpTo": "移動"},"noResults": "結果なし","emptyState": "入力して検索",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex 4c6244f02..d1e476bbf 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -2161,6 +2161,44 @@"searchNotes": "Pesquisar notas","actions": "Ações"},+ "spaces": {+ "privateSpaces": "Espaços privados",+ "teamSpaces": "Espaços de equipe",+ "personal": "Pessoal",+ "privateTooltip": "Somente você pode ver seu espaço pessoal",+ "newSpace": "Novo espaço",+ "createTitle": "Criar espaço",+ "nameLabel": "Nome",+ "emojiLabel": "Emoji",+ "create": "Criar",+ "couldNotCreate": "Não foi possível criar o espaço",+ "rename": "Renomear",+ "changeEmoji": "Alterar emoji",+ "couldNotRename": "Não foi possível renomear o espaço",+ "deleteSpace": "Excluir espaço",+ "deleteConfirmTitle": "Excluir espaço?",+ "deleteConfirmDescription": "Isso exclui permanentemente {{space}} com todas as suas pastas e notas neste dispositivo.",+ "couldNotDelete": "Não foi possível excluir o espaço",+ "moveTo": "Mover para",+ "moveToSpace": "Mover para espaço…",+ "searchSpaces": "Pesquisar espaços...",+ "noSpacesFound": "Nenhum espaço encontrado",+ "spaceRoot": "Raiz do espaço",+ "moveConfirm": "Mover",+ "confirmMoveInTitle": "Mover para {{space}}?",+ "confirmMoveIn": "Todos em {{space}} poderão ver e editar esta nota.",+ "confirmMoveInFolder": "Todos em {{space}} poderão ver e editar esta pasta e suas notas.",+ "confirmMoveOutTitle": "Mover para fora de {{space}}?",+ "confirmMoveOut": "Os membros de {{space}} perderão o acesso a esta nota.",+ "confirmMoveOutFolder": "Os membros de {{space}} perderão o acesso a esta pasta e suas notas.",+ "moved": "“{{title}}” movida para {{target}}",+ "couldNotMove": "Não foi possível mover a pasta",+ "couldNotMoveNote": "Não foi possível mover a nota",+ "undo": "Desfazer",+ "emptySpace": "Nenhuma nota ainda. As notas aqui são visíveis para todos em {{space}}.",+ "noteCount_one": "{{count}} nota",+ "noteCount_other": "{{count}} notas"+ },"folders": {"title": "Pastas","soon": "Em breve",@@ -2869,7 +2907,8 @@"placeholder": "Pesquisar notas e transcrições…","sections": {"notes": "Notas",- "transcripts": "Transcrições"+ "transcripts": "Transcrições",+ "jumpTo": "Ir para"},"noResults": "Sem resultados","emptyState": "Comece a digitar para pesquisar",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 6f8c8b737..e05dbf7ce 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -2163,6 +2163,46 @@"searchNotes": "Поиск заметок","actions": "Действия"},+ "spaces": {+ "privateSpaces": "Личные пространства",+ "teamSpaces": "Командные пространства",+ "personal": "Личное",+ "privateTooltip": "Только вы видите своё личное пространство",+ "newSpace": "Новое пространство",+ "createTitle": "Создать пространство",+ "nameLabel": "Название",+ "emojiLabel": "Эмодзи",+ "create": "Создать",+ "couldNotCreate": "Не удалось создать пространство",+ "rename": "Переименовать",+ "changeEmoji": "Изменить эмодзи",+ "couldNotRename": "Не удалось переименовать пространство",+ "deleteSpace": "Удалить пространство",+ "deleteConfirmTitle": "Удалить пространство?",+ "deleteConfirmDescription": "Пространство {{space}} со всеми его папками и заметками будет безвозвратно удалено с этого устройства.",+ "couldNotDelete": "Не удалось удалить пространство",+ "moveTo": "Переместить в",+ "moveToSpace": "Переместить в пространство…",+ "searchSpaces": "Поиск пространств...",+ "noSpacesFound": "Пространства не найдены",+ "spaceRoot": "Корень пространства",+ "moveConfirm": "Переместить",+ "confirmMoveInTitle": "Переместить в {{space}}?",+ "confirmMoveIn": "Все в {{space}} смогут просматривать и редактировать эту заметку.",+ "confirmMoveInFolder": "Все в {{space}} смогут просматривать и редактировать эту папку и её заметки.",+ "confirmMoveOutTitle": "Переместить из {{space}}?",+ "confirmMoveOut": "Участники {{space}} потеряют доступ к этой заметке.",+ "confirmMoveOutFolder": "Участники {{space}} потеряют доступ к этой папке и её заметкам.",+ "moved": "«{{title}}» перемещено в {{target}}",+ "couldNotMove": "Не удалось переместить папку",+ "couldNotMoveNote": "Не удалось переместить заметку",+ "undo": "Отменить",+ "emptySpace": "Пока нет заметок. Заметки здесь видны всем в {{space}}.",+ "noteCount_one": "{{count}} заметка",+ "noteCount_few": "{{count}} заметки",+ "noteCount_many": "{{count}} заметок",+ "noteCount_other": "{{count}} заметки"+ },"folders": {"title": "Папки","soon": "Скоро",@@ -2875,7 +2915,8 @@"placeholder": "Поиск по заметкам и транскрипциям…","sections": {"notes": "Заметки",- "transcripts": "Транскрипции"+ "transcripts": "Транскрипции",+ "jumpTo": "Перейти к"},"noResults": "Нет результатов","emptyState": "Начните ввод для поиска",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 549593dad..4100f3376 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -2161,6 +2161,44 @@"searchNotes": "搜索笔记","actions": "操作"},+ "spaces": {+ "privateSpaces": "私人空间",+ "teamSpaces": "团队空间",+ "personal": "个人",+ "privateTooltip": "只有你可以看到你的个人空间",+ "newSpace": "新建空间",+ "createTitle": "创建空间",+ "nameLabel": "名称",+ "emojiLabel": "表情符号",+ "create": "创建",+ "couldNotCreate": "无法创建空间",+ "rename": "重命名",+ "changeEmoji": "更改表情符号",+ "couldNotRename": "无法重命名空间",+ "deleteSpace": "删除空间",+ "deleteConfirmTitle": "删除空间?",+ "deleteConfirmDescription": "这将从此设备永久删除 {{space}} 及其所有文件夹和笔记。",+ "couldNotDelete": "无法删除空间",+ "moveTo": "移动到",+ "moveToSpace": "移动到空间…",+ "searchSpaces": "搜索空间...",+ "noSpacesFound": "未找到空间",+ "spaceRoot": "空间根目录",+ "moveConfirm": "移动",+ "confirmMoveInTitle": "移动到 {{space}}?",+ "confirmMoveIn": "{{space}} 中的所有人都将能查看和编辑此笔记。",+ "confirmMoveInFolder": "{{space}} 中的所有人都将能查看和编辑此文件夹及其笔记。",+ "confirmMoveOutTitle": "移出 {{space}}?",+ "confirmMoveOut": "{{space}} 的成员将无法再访问此笔记。",+ "confirmMoveOutFolder": "{{space}} 的成员将无法再访问此文件夹及其笔记。",+ "moved": "已将“{{title}}”移动到 {{target}}",+ "couldNotMove": "无法移动文件夹",+ "couldNotMoveNote": "无法移动笔记",+ "undo": "撤销",+ "emptySpace": "还没有笔记。这里的笔记对 {{space}} 中的所有人可见。",+ "noteCount_one": "{{count}} 条笔记",+ "noteCount_other": "{{count}} 条笔记"+ },"folders": {"title": "文件夹","soon": "即将推出",@@ -2869,7 +2907,8 @@"placeholder": "搜索笔记和转录…","sections": {"notes": "笔记",- "transcripts": "转录"+ "transcripts": "转录",+ "jumpTo": "跳转到"},"noResults": "无结果","emptyState": "输入内容开始搜索",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 4ce9a3c85..e74bf88d0 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -2161,6 +2161,44 @@"searchNotes": "搜尋筆記","actions": "動作"},+ "spaces": {+ "privateSpaces": "私人空間",+ "teamSpaces": "團隊空間",+ "personal": "個人",+ "privateTooltip": "只有你可以看到你的個人空間",+ "newSpace": "新增空間",+ "createTitle": "建立空間",+ "nameLabel": "名稱",+ "emojiLabel": "表情符號",+ "create": "建立",+ "couldNotCreate": "無法建立空間",+ "rename": "重新命名",+ "changeEmoji": "變更表情符號",+ "couldNotRename": "無法重新命名空間",+ "deleteSpace": "刪除空間",+ "deleteConfirmTitle": "刪除空間?",+ "deleteConfirmDescription": "這會從此裝置永久刪除 {{space}} 及其所有資料夾和筆記。",+ "couldNotDelete": "無法刪除空間",+ "moveTo": "移動到",+ "moveToSpace": "移動到空間…",+ "searchSpaces": "搜尋空間...",+ "noSpacesFound": "找不到空間",+ "spaceRoot": "空間根目錄",+ "moveConfirm": "移動",+ "confirmMoveInTitle": "移動到 {{space}}?",+ "confirmMoveIn": "{{space}} 中的所有人都將能檢視和編輯這則筆記。",+ "confirmMoveInFolder": "{{space}} 中的所有人都將能檢視和編輯這個資料夾及其筆記。",+ "confirmMoveOutTitle": "移出 {{space}}?",+ "confirmMoveOut": "{{space}} 的成員將無法再存取這則筆記。",+ "confirmMoveOutFolder": "{{space}} 的成員將無法再存取這個資料夾及其筆記。",+ "moved": "已將「{{title}}」移動到 {{target}}",+ "couldNotMove": "無法移動資料夾",+ "couldNotMoveNote": "無法移動筆記",+ "undo": "復原",+ "emptySpace": "還沒有筆記。這裡的筆記對 {{space}} 中的所有人可見。",+ "noteCount_one": "{{count}} 則筆記",+ "noteCount_other": "{{count}} 則筆記"+ },"folders": {"title": "資料夾","soon": "即將推出",@@ -2869,7 +2907,8 @@"placeholder": "搜尋筆記與轉錄…","sections": {"notes": "筆記",- "transcripts": "轉錄"+ "transcripts": "轉錄",+ "jumpTo": "跳至"},"noResults": "無結果","emptyState": "輸入內容開始搜尋",diff --git a/src/stores/noteStore.ts b/src/stores/noteStore.tsindex fedb1e9ce..87effbbb6 100644--- a/src/stores/noteStore.ts+++ b/src/stores/noteStore.ts@@ -1,6 +1,13 @@import { create } from "zustand";import { syncService } from "../services/SyncService.js";-import type { NoteItem, NoteShareInvitation, ShareSettings } from "../types/electron";+import { findDefaultFolder } from "../components/notes/shared";+import type {+ FolderItem,+ NoteItem,+ NoteShareInvitation,+ ShareSettings,+ SpaceItem,+} from "../types/electron";export interface NoteShareCacheEntry {share: ShareSettings;@@ -10,18 +17,56 @@ export interface NoteShareCacheEntry {rawToken: string | null;}+export interface ActiveContext {+ spaceId: number;+ folderId: number | null;+}+interface NoteState {notes: NoteItem[];+ spaces: SpaceItem[];+ folders: FolderItem[];+ folderCounts: Record<number, number>;+ notesByContainer: Record<string, NoteItem[]>;+ expandedContainers: Set<string>;+ activeContext: ActiveContext | null;activeNoteId: number | null;activeFolderId: number | null;+ isTreeLoading: boolean;migration: { total: number; done: number } | null;shareByCloudId: Map<string, NoteShareCacheEntry>;}+const EXPANDED_STORAGE_KEY = "notesTree.expanded";++function readExpandedContainers(): Set<string> {+ try {+ const raw = localStorage.getItem(EXPANDED_STORAGE_KEY);+ return new Set(raw ? (JSON.parse(raw) as string[]) : []);+ } catch {+ return new Set();+ }+}++function persistExpandedContainers(expanded: Set<string>): void {+ try {+ localStorage.setItem(EXPANDED_STORAGE_KEY, JSON.stringify([...expanded]));+ } catch {+ // localStorage unavailable — expansion just won't persist+ }+}+const useNoteStore = create<NoteState>()(() => ({notes: [],+ spaces: [],+ folders: [],+ folderCounts: {},+ notesByContainer: {},+ expandedContainers: readExpandedContainers(),+ activeContext: null,activeNoteId: null,activeFolderId: null,+ isTreeLoading: true,migration: null,shareByCloudId: new Map<string, NoteShareCacheEntry>(),}));@@ -30,6 +75,54 @@ let hasBoundIpcListeners = false;const DEFAULT_LIMIT = 50;let currentLimit = DEFAULT_LIMIT;let loadGeneration = 0;+let treeLoadGeneration = 0;++export function folderContainerKey(folderId: number): string {+ return `f:${folderId}`;+}++export function spaceContainerKey(spaceId: number): string {+ return `s:${spaceId}`;+}++export function contextContainerKey(context: ActiveContext): string {+ return context.folderId != null+ ? folderContainerKey(context.folderId)+ : spaceContainerKey(context.spaceId);+}++function noteContainerKey(note: NoteItem): string {+ return note.folder_id != null+ ? folderContainerKey(note.folder_id)+ : spaceContainerKey(note.space_id);+}++function activeContainerKey(state: NoteState): string | null {+ return state.activeContext ? contextContainerKey(state.activeContext) : null;+}++function findNoteInState(state: NoteState, id: number): NoteItem | null {+ for (const items of Object.values(state.notesByContainer)) {+ const note = items.find((n) => n.id === id);+ if (note) return note;+ }+ return state.notes.find((n) => n.id === id) ?? null;+}++/** Apply a notesByContainer replacement, mirroring the active container into the flat `notes` list. */+function applyContainers(+ notesByContainer: Record<string, NoteItem[]>,+ extra: Partial<NoteState> = {}+): void {+ const state = useNoteStore.getState();+ const context = (extra.activeContext ?? state.activeContext) as ActiveContext | null;+ const activeKey = context ? contextContainerKey(context) : null;+ const update: Partial<NoteState> = { notesByContainer, ...extra };+ if (activeKey && notesByContainer[activeKey] && notesByContainer[activeKey] !== state.notes) {+ update.notes = notesByContainer[activeKey];+ }+ useNoteStore.setState(update);+}function ensureIpcListeners() {if (hasBoundIpcListeners || typeof window === "undefined") {@@ -42,6 +135,7 @@ function ensureIpcListeners() {const dispose = window.electronAPI.onNoteAdded((note) => {if (note) {addNote(note);+ loadFolders();}});if (typeof dispose === "function") {@@ -52,7 +146,11 @@ function ensureIpcListeners() {if (window.electronAPI?.onNoteUpdated) {const dispose = window.electronAPI.onNoteUpdated((note) => {if (note) {+ const previous = findNoteInState(useNoteStore.getState(), note.id);updateNoteInStore(note);+ if (previous && noteContainerKey(previous) !== noteContainerKey(note)) {+ loadFolders();+ }// Sharing is per-note consent: edits to a shared note must reach the// cloud even when the global backup toggle is off.if (note.is_shared) {@@ -68,6 +166,7 @@ function ensureIpcListeners() {if (window.electronAPI?.onNoteDeleted) {const dispose = window.electronAPI.onNoteDeleted(({ id }) => {removeNote(id);+ loadFolders();// Push the tombstone right away so a shared link stops serving now,// not at the next ambient pass ("manual" bypasses the throttle).syncService.requestSyncAll("manual");@@ -77,6 +176,15 @@ function ensureIpcListeners() {}}+ if (window.electronAPI?.onSpacePurged) {+ const dispose = window.electronAPI.onSpacePurged(({ spaceId }) => {+ handleSpacePurged(spaceId);+ });+ if (typeof dispose === "function") {+ disposers.push(dispose);+ }+ }+hasBoundIpcListeners = true;window.addEventListener("beforeunload", () => {@@ -84,6 +192,133 @@ function ensureIpcListeners() {});}+export async function loadSpaces(): Promise<SpaceItem[]> {+ const items = (await window.electronAPI?.getSpaces?.()) ?? [];+ useNoteStore.setState({ spaces: items });+ return items;+}++export async function loadFolders(): Promise<FolderItem[]> {+ const [items, counts] = await Promise.all([+ window.electronAPI.getFolders(),+ window.electronAPI.getFolderNoteCounts(),+ ]);+ const folderCounts: Record<number, number> = {};+ counts.forEach((c) => {+ if (c.folder_id != null) folderCounts[c.folder_id] = c.count;+ });+ useNoteStore.setState({ folders: items, folderCounts });+ return items;+}++export async function loadContainerNotes(key: string): Promise<NoteItem[]> {+ const [kind, idStr] = key.split(":");+ const id = Number(idStr);+ const items =+ kind === "f"+ ? ((await window.electronAPI?.getNotes(null, DEFAULT_LIMIT, id)) ?? [])+ : ((await window.electronAPI?.getNotes(null, DEFAULT_LIMIT, null, id)) ?? []);+ applyContainers({ ...useNoteStore.getState().notesByContainer, [key]: items });+ return items;+}++export async function ensureContainerLoaded(key: string): Promise<NoteItem[]> {+ const cached = useNoteStore.getState().notesByContainer[key];+ if (cached) return cached;+ return loadContainerNotes(key);+}++export function setContainerExpanded(key: string, expanded: boolean): void {+ const current = useNoteStore.getState().expandedContainers;+ if (current.has(key) !== expanded) {+ const next = new Set(current);+ if (expanded) next.add(key);+ else next.delete(key);+ useNoteStore.setState({ expandedContainers: next });+ persistExpandedContainers(next);+ }+ if (expanded) void ensureContainerLoaded(key);+}++export function toggleContainerExpanded(key: string): void {+ setContainerExpanded(key, !useNoteStore.getState().expandedContainers.has(key));+}++/** Expand the containers that make a space/folder (and its notes) visible in the tree. */+export function revealContainer(spaceId: number, folderId: number | null): void {+ setContainerExpanded(spaceContainerKey(spaceId), true);+ if (folderId != null) setContainerExpanded(folderContainerKey(folderId), true);+}++export function setActiveContext(spaceId: number, folderId: number | null): void {+ const state = useNoteStore.getState();+ const key = folderId != null ? folderContainerKey(folderId) : spaceContainerKey(spaceId);+ useNoteStore.setState({+ activeContext: { spaceId, folderId },+ activeFolderId: folderId,+ notes: state.notesByContainer[key] ?? [],+ });+ void ensureContainerLoaded(key);+}++/**+ * Loads spaces, folders and counts, resolves the initial active context+ * (honoring a pre-set activeFolderId or activeContext, e.g. navigating from+ * search), loads the active container and auto-selects its first note when+ * none is pre-set.+ */+export async function initializeNotesTree(): Promise<void> {+ const gen = ++treeLoadGeneration;+ ensureIpcListeners();+ useNoteStore.setState({ isTreeLoading: true });+ try {+ const [spaces, folders] = await Promise.all([loadSpaces(), loadFolders()]);+ if (gen !== treeLoadGeneration) return;++ const presetFolderId = getActiveFolderIdValue();+ const presetFolder =+ presetFolderId != null ? folders.find((f) => f.id === presetFolderId) : undefined;+ const preset = useNoteStore.getState().activeContext;+ const presetContext =+ preset &&+ spaces.some((s) => s.id === preset.spaceId) &&+ (preset.folderId == null || folders.some((f) => f.id === preset.folderId))+ ? preset+ : null;+ const privateSpace = spaces.find((s) => s.kind === "private") ?? spaces[0];+ let context: ActiveContext | null = null;+ if (presetFolder) {+ context = { spaceId: presetFolder.space_id, folderId: presetFolder.id };+ } else if (presetContext) {+ context = presetContext;+ } else if (privateSpace) {+ const privateFolders = folders.filter((f) => f.space_id === privateSpace.id);+ const initialFolder = findDefaultFolder(privateFolders) ?? privateFolders[0];+ context = { spaceId: privateSpace.id, folderId: initialFolder?.id ?? null };+ }+ if (!context) return;++ revealContainer(context.spaceId, context.folderId);+ useNoteStore.setState({ activeContext: context, activeFolderId: context.folderId });+ const notes = await loadContainerNotes(contextContainerKey(context));+ if (gen !== treeLoadGeneration) return;+ // Containers restored as expanded from a previous session must load their+ // notes too, or they render expanded-but-empty until re-toggled.+ const validKeys = new Set<string>([+ ...spaces.map((s) => spaceContainerKey(s.id)),+ ...folders.map((f) => folderContainerKey(f.id)),+ ]);+ useNoteStore.getState().expandedContainers.forEach((key) => {+ if (validKeys.has(key)) void ensureContainerLoaded(key);+ });+ if (getActiveNoteIdValue() == null && notes.length > 0) {+ setActiveNoteId(notes[0].id);+ }+ } finally {+ if (gen === treeLoadGeneration) useNoteStore.setState({ isTreeLoading: false });+ }+}+export async function initializeNotes(noteType?: string | null,limit = DEFAULT_LIMIT,@@ -94,38 +329,236 @@ export async function initializeNotes(ensureIpcListeners();const items = (await window.electronAPI?.getNotes(noteType, limit, folderId)) ?? [];if (gen !== loadGeneration) return items;- useNoteStore.setState({ notes: items });+ if (folderId != null) {+ applyContainers({+ ...useNoteStore.getState().notesByContainer,+ [folderContainerKey(folderId)]: items,+ });+ } else {+ useNoteStore.setState({ notes: items });+ }return items;}export function addNote(note: NoteItem): void {if (!note) return;- const { notes, activeFolderId } = useNoteStore.getState();- if (activeFolderId && note.folder_id !== activeFolderId) return;- const withoutDuplicate = notes.filter((existing) => existing.id !== note.id);- useNoteStore.setState({ notes: [note, ...withoutDuplicate].slice(0, currentLimit) });+ const state = useNoteStore.getState();+ const key = noteContainerKey(note);+ const items = state.notesByContainer[key];+ // Not-yet-loaded containers pick the note up on their lazy load.+ if (!items) return;+ const next = [note, ...items.filter((existing) => existing.id !== note.id)].slice(+ 0,+ currentLimit+ );+ applyContainers({ ...state.notesByContainer, [key]: next });}export function updateNoteInStore(note: NoteItem): void {if (!note) return;- const { notes } = useNoteStore.getState();- useNoteStore.setState({- notes: notes.map((existing) => (existing.id === note.id ? note : existing)),- });+ const state = useNoteStore.getState();+ const targetKey = noteContainerKey(note);+ const notesByContainer = { ...state.notesByContainer };+ let changed = false;+ for (const [key, items] of Object.entries(state.notesByContainer)) {+ const idx = items.findIndex((existing) => existing.id === note.id);+ if (idx === -1) continue;+ changed = true;+ if (key === targetKey) {+ const next = items.slice();+ next[idx] = note;+ notesByContainer[key] = next;+ } else {+ // The note moved container (folder/space change) — relocate it.+ notesByContainer[key] = items.filter((existing) => existing.id !== note.id);+ }+ }+ const target = notesByContainer[targetKey];+ if (target && !target.some((existing) => existing.id === note.id)) {+ notesByContainer[targetKey] = [note, ...target].slice(0, currentLimit);+ changed = true;+ }+ if (changed) applyContainers(notesByContainer);}export function removeNote(id: number): void {if (id == null) return;- const { notes, activeNoteId } = useNoteStore.getState();- const next = notes.filter((item) => item.id !== id);- if (next.length === notes.length) return;- const update: Partial<NoteState> = { notes: next };- if (activeNoteId === id) {- const idx = notes.findIndex((item) => item.id === id);- const neighbor = next[Math.min(idx, next.length - 1)] ?? null;- update.activeNoteId = neighbor?.id ?? null;+ const state = useNoteStore.getState();+ const notesByContainer = { ...state.notesByContainer };+ let sourceItems: NoteItem[] | null = null;+ let sourceKey: string | null = null;+ let changed = false;+ for (const [key, items] of Object.entries(state.notesByContainer)) {+ if (!items.some((n) => n.id === id)) continue;+ sourceItems = items;+ sourceKey = key;+ notesByContainer[key] = items.filter((n) => n.id !== id);+ changed = true;}- useNoteStore.setState(update);+ if (!changed) return;+ const extra: Partial<NoteState> = {};+ if (state.activeNoteId === id && sourceItems && sourceKey) {+ const idx = sourceItems.findIndex((n) => n.id === id);+ const next = notesByContainer[sourceKey];+ extra.activeNoteId = next[Math.min(idx, next.length - 1)]?.id ?? null;+ }+ applyContainers(notesByContainer, extra);+}++function handleSpacePurged(spaceId: number): void {+ const state = useNoteStore.getState();+ const removedKeys = new Set<string>([spaceContainerKey(spaceId)]);+ state.folders.forEach((f) => {+ if (f.space_id === spaceId) removedKeys.add(folderContainerKey(f.id));+ });++ const notesByContainer: Record<string, NoteItem[]> = {};+ for (const [key, items] of Object.entries(state.notesByContainer)) {+ if (!removedKeys.has(key)) notesByContainer[key] = items;+ }+ const folderCounts = { ...state.folderCounts };+ state.folders.forEach((f) => {+ if (f.space_id === spaceId) delete folderCounts[f.id];+ });+ const expanded = new Set([...state.expandedContainers].filter((key) => !removedKeys.has(key)));+ persistExpandedContainers(expanded);++ const extra: Partial<NoteState> = {+ spaces: state.spaces.filter((s) => s.id !== spaceId),+ folders: state.folders.filter((f) => f.space_id !== spaceId),+ folderCounts,+ expandedContainers: expanded,+ };+ const activeNote = state.activeNoteId != null ? findNoteInState(state, state.activeNoteId) : null;+ if (activeNote?.space_id === spaceId) {+ extra.activeNoteId = null;+ }++ let fallbackContext: ActiveContext | null = null;+ if (state.activeContext?.spaceId === spaceId) {+ const privateSpace = extra.spaces?.find((s) => s.kind === "private");+ if (privateSpace) {+ const privateFolders = state.folders.filter((f) => f.space_id === privateSpace.id);+ const fallbackFolder = findDefaultFolder(privateFolders) ?? privateFolders[0];+ fallbackContext = { spaceId: privateSpace.id, folderId: fallbackFolder?.id ?? null };+ extra.activeContext = fallbackContext;+ extra.activeFolderId = fallbackContext.folderId;+ extra.notes = notesByContainer[contextContainerKey(fallbackContext)] ?? [];+ }+ }+ useNoteStore.setState({ notesByContainer, ...extra });+ if (fallbackContext) void ensureContainerLoaded(contextContainerKey(fallbackContext));+}++export async function createFolder(+ name: string,+ spaceId: number+): Promise<{ success: boolean; folder?: FolderItem; error?: string }> {+ const result = await window.electronAPI.createFolder(name, spaceId);+ if (result.success && result.folder) {+ await loadFolders();+ syncService.debouncedPush("folder", result.folder.id);+ }+ return result;+}++export async function renameFolder(+ id: number,+ name: string+): Promise<{ success: boolean; folder?: FolderItem; error?: string }> {+ const result = await window.electronAPI.renameFolder(id, name);+ if (result.success) {+ await loadFolders();+ syncService.debouncedPush("folder", id);+ }+ return result;+}++export async function deleteFolder(id: number): Promise<{ success: boolean; error?: string }> {+ const result = await window.electronAPI.deleteFolder(id);+ if (!result.success) return result;++ const state = useNoteStore.getState();+ const folder = state.folders.find((f) => f.id === id);+ const key = folderContainerKey(id);+ const deletedNotes = state.notesByContainer[key];+ const notesByContainer = { ...state.notesByContainer };+ delete notesByContainer[key];+ const expanded = new Set(state.expandedContainers);+ if (expanded.delete(key)) persistExpandedContainers(expanded);+ const extra: Partial<NoteState> = { expandedContainers: expanded };+ if (state.activeNoteId != null && deletedNotes?.some((n) => n.id === state.activeNoteId)) {+ extra.activeNoteId = null;+ }+ useNoteStore.setState({ notesByContainer, ...extra });++ await loadFolders();+ if (getActiveFolderIdValue() === id && folder) {+ const { folders } = useNoteStore.getState();+ const spaceFolders = folders.filter((f) => f.space_id === folder.space_id);+ const fallback = findDefaultFolder(spaceFolders) ?? spaceFolders[0];+ setActiveContext(folder.space_id, fallback?.id ?? null);+ if (getActiveNoteIdValue() == null) {+ const notes = await ensureContainerLoaded(+ fallback ? folderContainerKey(fallback.id) : spaceContainerKey(folder.space_id)+ );+ if (notes.length > 0) setActiveNoteId(notes[0].id);+ }+ }+ syncService.requestSyncAll("manual");+ return result;+}++export async function moveFolderToSpace(+ folderId: number,+ spaceId: number+): Promise<{ success: boolean; folder?: FolderItem; error?: string }> {+ const result = await window.electronAPI.moveFolderToSpace(folderId, spaceId);+ if (!result.success) return result;++ await loadFolders();+ const key = folderContainerKey(folderId);+ if (useNoteStore.getState().notesByContainer[key]) {+ // Refresh the container so its notes carry the new space_id.+ await loadContainerNotes(key);+ }+ const { activeContext } = useNoteStore.getState();+ if (activeContext?.folderId === folderId && activeContext.spaceId !== spaceId) {+ useNoteStore.setState({ activeContext: { spaceId, folderId } });+ }+ syncService.requestSyncAll("manual");+ return result;+}++export async function createSpace(+ name: string,+ emoji: string | null+): Promise<{ success: boolean; space?: SpaceItem; error?: string }> {+ const result = (await window.electronAPI.createSpace?.({ name, emoji })) ?? { success: false };+ if (result.success && result.space) {+ await loadSpaces();+ setActiveContext(result.space.id, null);+ setContainerExpanded(spaceContainerKey(result.space.id), true);+ }+ return result;+}++export async function updateSpaceMeta(+ id: number,+ updates: { name?: string; emoji?: string | null }+): Promise<{ success: boolean; space?: SpaceItem; error?: string }> {+ const result = (await window.electronAPI.updateSpace?.(id, updates)) ?? { success: false };+ if (result.success && result.space) {+ const updated = result.space;+ const { spaces } = useNoteStore.getState();+ useNoteStore.setState({ spaces: spaces.map((s) => (s.id === id ? updated : s)) });+ }+ return result;+}++/** Local purge (dev override); store cleanup happens via the space-purged broadcast. */+export async function purgeSpace(id: number): Promise<{ success: boolean; error?: string }> {+ return (await window.electronAPI.purgeSpace?.(id)) ?? { success: false };}export function setActiveNoteId(id: number | null): void {@@ -133,8 +566,31 @@ export function setActiveNoteId(id: number | null): void {useNoteStore.setState({ activeNoteId: id });}+/**+ * Jump navigation (CommandSearch/ControlPanel): activate and reveal a+ * space/folder. Works both with a mounted tree and as a preset that+ * initializeNotesTree resolves on mount.+ */+export function navigateToContainer(spaceId: number, folderId: number | null): void {+ if (folderId != null) {+ setActiveFolderId(folderId);+ return;+ }+ setActiveContext(spaceId, null);+ revealContainer(spaceId, null);+}+export function setActiveFolderId(id: number | null): void {- if (useNoteStore.getState().activeFolderId === id) return;+ const state = useNoteStore.getState();+ const folder = id != null ? state.folders.find((f) => f.id === id) : undefined;+ if (folder) {+ setActiveContext(folder.space_id, folder.id);+ revealContainer(folder.space_id, folder.id);+ return;+ }+ // Folders not loaded yet (or id cleared): keep as a preset that+ // initializeNotesTree resolves on mount.+ if (state.activeFolderId === id) return;useNoteStore.setState({ activeFolderId: id });}@@ -142,6 +598,10 @@ export function getActiveNoteIdValue(): number | null {return useNoteStore.getState().activeNoteId;}+export function getNoteFromStore(id: number): NoteItem | null {+ return findNoteInState(useNoteStore.getState(), id);+}+export function getActiveFolderIdValue(): number | null {return useNoteStore.getState().activeFolderId;}@@ -150,6 +610,34 @@ export function useNotes(): NoteItem[] {return useNoteStore((state) => state.notes);}+export function useSpaces(): SpaceItem[] {+ return useNoteStore((state) => state.spaces);+}++export function useFolders(): FolderItem[] {+ return useNoteStore((state) => state.folders);+}++export function useFolderCounts(): Record<number, number> {+ return useNoteStore((state) => state.folderCounts);+}++export function useNotesByContainer(): Record<string, NoteItem[]> {+ return useNoteStore((state) => state.notesByContainer);+}++export function useExpandedContainers(): Set<string> {+ return useNoteStore((state) => state.expandedContainers);+}++export function useActiveContext(): ActiveContext | null {+ return useNoteStore((state) => state.activeContext);+}++export function useIsTreeLoading(): boolean {+ return useNoteStore((state) => state.isTreeLoading);+}+export function useActiveNoteId(): number | null {return useNoteStore((state) => state.activeNoteId);}@@ -158,6 +646,12 @@ export function useActiveFolderId(): number | null {return useNoteStore((state) => state.activeFolderId);}+export function useActiveNote(): NoteItem | null {+ return useNoteStore((state) =>+ state.activeNoteId != null ? findNoteInState(state, state.activeNoteId) : null+ );+}+export function useMigration(): { total: number; done: number } | null {return useNoteStore((state) => state.migration);}diff --git a/src/types/electron.ts b/src/types/electron.tsindex 00a3442ce..3b55e656e 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -690,6 +690,10 @@ declare global {id: number,name: string) => Promise<{ success: boolean; folder?: FolderItem; error?: string }>;+ moveFolderToSpace: (+ id: number,+ spaceId: number+ ) => Promise<{ success: boolean; folder?: FolderItem; notes?: NoteItem[]; error?: string }>;getFolderNoteCounts: () => Promise<Array<{ folder_id: number; count: number }>>;// Space operationsdiff --git a/test/helpers/spacesDatabase.test.js b/test/helpers/spacesDatabase.test.jsindex e8879edcd..d6f067d37 100644--- a/test/helpers/spacesDatabase.test.js+++ b/test/helpers/spacesDatabase.test.js@@ -273,3 +273,57 @@ test("saveNote resolves default folders within the target space", (t) => {assert.equal(teamDoc.folder_id, null);assert.equal(teamDoc.space_id, team.id);});++test("moveFolderToSpace moves the folder and its live notes in one transaction", (t) => {+ const db = createDb(t);+ if (!db) return;+ const privateId = db.getPrivateSpaceId();+ const team = db.createSpace({ name: "Growth" }).space;+ const folder = db.createFolder("Campaigns").folder;+ const filed = db.saveNote("Plan", "body", "personal", null, null, folder.id).note;+ const loose = db.saveNote("Loose", "body").note;++ const moved = db.moveFolderToSpace(folder.id, team.id);+ assert.ok(moved.success);+ assert.equal(moved.folder.space_id, team.id);+ assert.equal(moved.folder.sync_status, "pending");+ assert.deepEqual(+ moved.notes.map((n) => n.id),+ [filed.id]+ );++ const movedNote = db.getNote(filed.id);+ assert.equal(movedNote.space_id, team.id);+ assert.equal(movedNote.folder_id, folder.id, "notes keep their folder link");+ assert.equal(movedNote.sync_status, "pending");+ assert.equal(db.getNote(loose.id).space_id, privateId, "notes outside the folder stay put");++ const duplicate = db.createFolder("Campaigns").folder;+ assert.equal(+ db.moveFolderToSpace(duplicate.id, team.id).success,+ false,+ "a same-named folder in the target space blocks the move"+ );++ const meetings = db.getMeetingsFolder();+ assert.equal(db.moveFolderToSpace(meetings.id, team.id).success, false);+});++test("getNotes with spaceId and no folderId lists only the space's root notes", (t) => {+ const db = createDb(t);+ if (!db) return;+ const team = db.createSpace({ name: "Ops" }).space;+ const folder = db.createFolder("Docs", team.id).folder;+ const rootNote = db.saveNote("Root", "body", "personal", null, null, null, team.id).note;+ db.saveNote("Filed", "body", "personal", null, null, folder.id);++ const rootNotes = db.getNotes(null, 50, null, team.id);+ assert.deepEqual(+ rootNotes.map((n) => n.id),+ [rootNote.id]+ );++ const folderNotes = db.getNotes(null, 50, folder.id);+ assert.equal(folderNotes.length, 1);+ assert.equal(folderNotes[0].title, "Filed");+});