From 4f0ce196c697b90c6e4e3a5ad5d6adef83ebc988 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sun, 4 Oct 2026 10:06:56 +0000 Subject: [PATCH] feat(notes): notes tree in the navigation, note pages and the BlockSuite editor Free notes show as a tree in the left navigation (add inside, drag to move). A note page has its title, one-line summary, date and PARA place, and AFFiNE's BlockSuite editor, where @ and # open a menu of what to link. Recordings and entities open their own page. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01XZQXJtCvJgbG1Z2H312KcS --- nextjs-frontend/__tests__/notes-links.test.ts | 21 + nextjs-frontend/app/(app)/notes/[id]/page.tsx | 11 + .../(app)/notes/about/[kind]/[key]/page.tsx | 11 + nextjs-frontend/app/(app)/notes/page.tsx | 10 + .../components/app-shell/nav-config.ts | 2 + nextjs-frontend/components/app-shell/nav.tsx | 9 +- .../components/entities/entity-drawer.tsx | 13 +- .../components/notes/block-editor.tsx | 198 ++ nextjs-frontend/components/notes/links.ts | 33 + .../components/notes/note-page.tsx | 297 +++ .../components/notes/notes-home.tsx | 92 + .../components/notes/notes-tree.tsx | 280 +++ .../components/recording/header.tsx | 8 +- nextjs-frontend/package.json | 6 + nextjs-frontend/pnpm-lock.yaml | 1674 ++++++++++++++++- nextjs-frontend/pnpm-workspace.yaml | 2 + 16 files changed, 2656 insertions(+), 11 deletions(-) create mode 100644 nextjs-frontend/__tests__/notes-links.test.ts create mode 100644 nextjs-frontend/app/(app)/notes/[id]/page.tsx create mode 100644 nextjs-frontend/app/(app)/notes/about/[kind]/[key]/page.tsx create mode 100644 nextjs-frontend/app/(app)/notes/page.tsx create mode 100644 nextjs-frontend/components/notes/block-editor.tsx create mode 100644 nextjs-frontend/components/notes/links.ts create mode 100644 nextjs-frontend/components/notes/note-page.tsx create mode 100644 nextjs-frontend/components/notes/notes-home.tsx create mode 100644 nextjs-frontend/components/notes/notes-tree.tsx diff --git a/nextjs-frontend/__tests__/notes-links.test.ts b/nextjs-frontend/__tests__/notes-links.test.ts new file mode 100644 index 000000000..5db7b8f33 --- /dev/null +++ b/nextjs-frontend/__tests__/notes-links.test.ts @@ -0,0 +1,21 @@ +import { hrefFor, pageOf } from "@/components/notes/links"; + +describe("links in notes", () => { + it("open the thing in the app", () => { + expect(hrefFor("page:3")).toBe("/notes/3"); + expect(hrefFor("recording:12")).toBe("/resources/12"); + expect(hrefFor("entity:5", "pods")).toBe("/entities?entity=5&ns=pods"); + expect(hrefFor("speaker:7")).toBe("/speakers/7"); + expect(hrefFor("collection:4", "pods")).toBe("/library?namespace=pods&collection=4"); + }); + + it("ignore what isn't a link to Lens", () => { + expect(hrefFor("https://example.com")).toBeNull(); + expect(hrefFor("entity:x")).toBeNull(); + expect(hrefFor("thing:3")).toBeNull(); + }); + + it("find a thing's page", () => { + expect(pageOf("entity:5")).toBe("/notes/about/entity/5"); + }); +}); diff --git a/nextjs-frontend/app/(app)/notes/[id]/page.tsx b/nextjs-frontend/app/(app)/notes/[id]/page.tsx new file mode 100644 index 000000000..a33b3eec4 --- /dev/null +++ b/nextjs-frontend/app/(app)/notes/[id]/page.tsx @@ -0,0 +1,11 @@ +import type { Metadata } from "next"; + +import { NotePage } from "@/components/notes/note-page"; + +export const metadata: Metadata = { title: "Note" }; + +/** A free note, opened from the tree in the left navigation or from a link in another note. */ +export default async function Page({ params }: { params: Promise<{ id: string }> }) { + const { id } = await params; + return ; +} diff --git a/nextjs-frontend/app/(app)/notes/about/[kind]/[key]/page.tsx b/nextjs-frontend/app/(app)/notes/about/[kind]/[key]/page.tsx new file mode 100644 index 000000000..c5530f6c2 --- /dev/null +++ b/nextjs-frontend/app/(app)/notes/about/[kind]/[key]/page.tsx @@ -0,0 +1,11 @@ +import type { Metadata } from "next"; + +import { NotePage } from "@/components/notes/note-page"; + +export const metadata: Metadata = { title: "Note" }; + +/** The page of a recording, entity, collection or speaker: a draft until someone writes on it. */ +export default async function Page({ params }: { params: Promise<{ kind: string; key: string }> }) { + const { kind, key } = await params; + return ; +} diff --git a/nextjs-frontend/app/(app)/notes/page.tsx b/nextjs-frontend/app/(app)/notes/page.tsx new file mode 100644 index 000000000..7c3cc4e20 --- /dev/null +++ b/nextjs-frontend/app/(app)/notes/page.tsx @@ -0,0 +1,10 @@ +import type { Metadata } from "next"; + +import { NotesHome } from "@/components/notes/notes-home"; + +export const metadata: Metadata = { title: "Notes" }; + +/** Notes: free notes of the namespace in view, newest first; the tree is in the left navigation. */ +export default function Page() { + return ; +} diff --git a/nextjs-frontend/components/app-shell/nav-config.ts b/nextjs-frontend/components/app-shell/nav-config.ts index e7ff695b3..925e72c79 100644 --- a/nextjs-frontend/components/app-shell/nav-config.ts +++ b/nextjs-frontend/components/app-shell/nav-config.ts @@ -7,6 +7,7 @@ import { LibraryBig, type LucideIcon, MessagesSquare, + NotebookPen, RadioTower, Search, Settings, @@ -41,6 +42,7 @@ export const NAV: NavItem[] = [ }, { label: "Search", href: "/search", icon: Search }, { label: "Chat", href: "/chat", icon: MessagesSquare }, + { label: "Notes", href: "/notes", icon: NotebookPen }, { label: "Entities", href: "/entities", icon: Shapes }, { label: "Graph", href: "/graph", icon: Waypoints }, { diff --git a/nextjs-frontend/components/app-shell/nav.tsx b/nextjs-frontend/components/app-shell/nav.tsx index 62d0a838b..c1c9a6e1a 100644 --- a/nextjs-frontend/components/app-shell/nav.tsx +++ b/nextjs-frontend/components/app-shell/nav.tsx @@ -5,6 +5,7 @@ import Link from "next/link"; import { usePathname } from "next/navigation"; import { isActive, navFor } from "@/components/app-shell/nav-config"; +import { NotesTree } from "@/components/notes/notes-tree"; import { Brand } from "@/components/brand"; import { Tooltip } from "@/components/ui/tooltip"; import { count } from "@/lib/format"; @@ -77,7 +78,13 @@ export function Nav({ ); })} -
+ {collapsed ? ( +
+ ) : ( +
+ +
+ )} {onToggle && ( + <> + + + ) } > diff --git a/nextjs-frontend/components/notes/block-editor.tsx b/nextjs-frontend/components/notes/block-editor.tsx new file mode 100644 index 000000000..8f4e312bc --- /dev/null +++ b/nextjs-frontend/components/notes/block-editor.tsx @@ -0,0 +1,198 @@ +"use client"; + +import "@toeverything/theme/style.css"; + +import { useEffect, useRef } from "react"; + +import { cn } from "@/lib/utils"; + +export type LinkTarget = { target: string; label: string; kind: string }; +export type EditorChange = { markdown: string; doc: string }; + +type Props = { + /** The page's Markdown: read when there is no `doc` (a new page, or one the assistant last wrote). */ + markdown: string; + /** The editor's own state (a Yjs update, base64) from the last save, when there is one. */ + doc: string | null; + readOnly?: boolean; + onChange: (change: EditorChange) => void; + /** What @ (resources, people, pages) and # (topics) offer for what was typed after them. */ + search: (sign: "@" | "#", query: string) => Promise; + /** A click on a link to something in Lens ("entity:5", "page:3"). */ + onOpenLink: (target: string) => void; + className?: string; +}; + +const LENS_LINK = /^(recording|entity|collection|speaker|page):\d+$/; + +function toBase64(bytes: Uint8Array): string { + let s = ""; + for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); + return btoa(s); +} + +function fromBase64(text: string): Uint8Array { + const s = atob(text); + const out = new Uint8Array(s.length); + for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i); + return out; +} + +/** AFFiNE's BlockSuite editor on one page. Its documents are Yjs CRDTs (what OctoBase stores and syncs). It keeps the + * Markdown and its own state in step: @ and # open a menu of what to link, written as @[label](kind:id) in the + * Markdown. Loaded in the browser only. */ +export default function BlockEditor({ markdown, doc, readOnly, onChange, search, onOpenLink, className }: Props) { + const host = useRef(null); + const latest = useRef({ onChange, search, onOpenLink }); + latest.current = { onChange, search, onOpenLink }; + // The page is read once per mount: the parent remounts the editor (key) for another page. + const initial = useRef({ markdown, doc, readOnly }); + + useEffect(() => { + let disposed = false; + let cleanup = () => {}; + (async () => { + const [blockEffects, presetEffects, presets, blocks, store, std, Y] = await Promise.all([ + import("@blocksuite/blocks/effects"), + import("@blocksuite/presets/effects"), + import("@blocksuite/presets"), + import("@blocksuite/blocks"), + import("@blocksuite/store"), + import("@blocksuite/block-std"), + import("yjs"), + ]); + if (!customElements.get("affine-editor-container")) { + blockEffects.effects(); + presetEffects.effects(); + } + if (disposed || !host.current) return; + const { markdown, doc: state, readOnly } = initial.current; + const schema = new store.Schema().register(blocks.AffineSchemas); + const collection = new store.DocCollection({ schema }); + collection.meta.initialize(); + + let id = "page"; + if (state) { + const d = collection.createDoc({ id }); + d.load(); + Y.applyUpdate(d.spaceDoc, fromBase64(state)); + } else { + const job = new store.Job({ collection }); + const made = markdown.trim() + ? await new blocks.MarkdownAdapter(job).toDoc({ file: markdown, assets: job.assetsManager }) + : undefined; + if (made) id = made.id; + else { + const d = collection.createDoc({ id }); + d.load(() => { + const root = d.addBlock("affine:page", {}); + d.addBlock("affine:surface", {}, root); + d.addBlock("affine:paragraph", {}, d.addBlock("affine:note", {}, root)); + }); + } + } + const page = collection.getDoc(id, { readonly: Boolean(readOnly) }); + if (!page || disposed || !host.current) return; + page.load(); + + const linkedWidget = { + triggerKeys: ["@", "#"], + convertTriggerKey: false, + ignoreBlockTypes: ["affine:code"], + getMenus: async ( + query: string, + abort: () => void, + _host: unknown, + inline: { + yTextString: string; + getInlineRange: () => { index: number; length: number } | null; + deleteText: (r: { index: number; length: number }) => void; + insertText: (r: { index: number; length: number }, text: string, attrs?: Record) => void; + setInlineRange: (r: { index: number; length: number }) => void; + }, + ) => { + const range = inline.getInlineRange(); + const at = range ? range.index - query.length - 1 : -1; + const sign = inline.yTextString[at] === "#" ? "#" : "@"; + const hits = await latest.current.search(sign, query).catch(() => [] as LinkTarget[]); + return [ + { + name: sign === "#" ? "Topics" : "Link to", + maxDisplay: 8, + overflowText: "more", + items: hits.map((h) => ({ + key: h.target, + name: h.label, + icon: sign === "#" ? blocks.TagsIcon : blocks.LinkedDocIcon, + suffix: h.kind, + action: () => { + abort(); // takes away what was typed: the sign and the query + inline.insertText({ index: at, length: 0 }, sign); + inline.insertText({ index: at + 1, length: 0 }, h.label, { link: h.target }); + inline.insertText({ index: at + 1 + h.label.length, length: 0 }, " "); + inline.setInlineRange({ index: at + 2 + h.label.length, length: 0 }); + }, + })), + }, + ]; + }, + }; + + const editor = new presets.AffineEditorContainer(); + editor.pageSpecs = [...blocks.PageEditorBlockSpecs, std.ConfigExtension("affine:page", { linkedWidget })]; + editor.doc = page; + editor.mode = "page"; + host.current.replaceChildren(editor); + + // Links to things in Lens open in the app, not as web addresses. + const onClick = (e: MouseEvent) => { + const a = (e.composedPath().find((n) => n instanceof HTMLAnchorElement) ?? null) as HTMLAnchorElement | null; + const href = a?.getAttribute("href") ?? ""; + if (!LENS_LINK.test(href)) return; + e.preventDefault(); + e.stopPropagation(); + latest.current.onOpenLink(href); + }; + host.current.addEventListener("click", onClick, true); + + let timer: ReturnType | undefined; + const save = async (flush = false) => { + const job = new store.Job({ collection }); + const snapshot = job.docToSnapshot(page); + if (!snapshot) return; + const out = await new blocks.MarkdownAdapter(job).fromDocSnapshot({ snapshot, assets: job.assetsManager }); + if (disposed && !flush) return; + const title = String((page.root as { title?: { toString(): string } } | null)?.title ?? ""); + let md = out.file.trim(); + if (title && md.startsWith(`# ${title}`)) md = md.slice(title.length + 2).trimStart(); + latest.current.onChange({ + markdown: md, + doc: toBase64(Y.encodeStateAsUpdate(page.spaceDoc)), + }); + }; + const changed = page.slots.blockUpdated.on(() => { + clearTimeout(timer); + timer = setTimeout(() => { + timer = undefined; + void save(); + }, 600); + }); + const el = host.current; + cleanup = () => { + if (timer) void save(true); // what was typed in the last moment before leaving the page + clearTimeout(timer); + changed.dispose(); + el.removeEventListener("click", onClick, true); + el.replaceChildren(); + collection.dispose(); + }; + })().catch((err) => console.error("The editor didn't load", err)); + return () => { + disposed = true; + cleanup(); + }; + }, []); + + // The page's title is Lens's own field above the editor, so the editor's title line is hidden. + return
; +} diff --git a/nextjs-frontend/components/notes/links.ts b/nextjs-frontend/components/notes/links.ts new file mode 100644 index 000000000..ecd47a14b --- /dev/null +++ b/nextjs-frontend/components/notes/links.ts @@ -0,0 +1,33 @@ +/** Where a link in a note goes in the app: "recording:12", "entity:5", "page:3", "collection:4", "speaker:7". */ +export function hrefFor(target: string, ns?: string | null): string | null { + const [kind, id] = target.split(":"); + if (!id || !/^\d+$/.test(id)) return null; + const q = ns ? `&ns=${encodeURIComponent(ns)}` : ""; + switch (kind) { + case "page": + return `/notes/${id}`; + case "recording": + return `/resources/${id}`; + case "entity": + return `/entities?entity=${id}${q}`; + case "speaker": + return `/speakers/${id}`; + case "collection": + return ns ? `/library?namespace=${encodeURIComponent(ns)}&collection=${id}` : "/library"; + default: + return null; + } +} + +/** The page of a thing: /notes/about/entity/5. */ +export function pageOf(target: string): string { + const [kind, id] = target.split(":"); + return `/notes/about/${kind}/${id}`; +} + +export const PLACES = [ + { value: "project", label: "Project" }, + { value: "area", label: "Area" }, + { value: "resource", label: "Resource" }, + { value: "archive", label: "Archive" }, +] as const; diff --git a/nextjs-frontend/components/notes/note-page.tsx b/nextjs-frontend/components/notes/note-page.tsx new file mode 100644 index 000000000..486d8a82f --- /dev/null +++ b/nextjs-frontend/components/notes/note-page.tsx @@ -0,0 +1,297 @@ +"use client"; + +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { ArrowUpRight, FileText, Link2, Sparkles, Trash2 } from "lucide-react"; +import dynamic from "next/dynamic"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useCallback, useEffect, useRef, useState } from "react"; + +import { Notes } from "@/app/openapi-client"; +import type { NotePage as Page, NotePageDraft as PageDraft } from "@/app/openapi-client/types.gen"; +import type { EditorChange, LinkTarget } from "@/components/notes/block-editor"; +import { PLACES, hrefFor } from "@/components/notes/links"; +import { Button } from "@/components/ui/button"; +import { EmptyState, Skeleton } from "@/components/ui/states"; +import { useToast } from "@/components/ui/toast"; +import { ApiError, data, useApiClient } from "@/lib/api/browser"; +import { shortDate } from "@/lib/format"; +import { cn } from "@/lib/utils"; + +const BlockEditor = dynamic(() => import("@/components/notes/block-editor"), { + ssr: false, + loading: () => , +}); + +type Changes = { title?: string; summary?: string; date?: string; place?: string; body?: string; doc?: string }; + +/** A note: a free note (`id`), or the page of a thing (`about`, like "entity:5"), which is a draft until someone writes + * on it. Everything saves as you type. */ +export function NotePage({ id, about }: { id?: number; about?: string }) { + const client = useApiClient(); + const qc = useQueryClient(); + const router = useRouter(); + const toast = useToast(); + const key = id ? ["note", id] : ["note-about", about]; + const q = useQuery({ + queryKey: key, + queryFn: () => { + if (id) return data(Notes.getPage({ client, path: { pid: id } })); + const [kind, k] = (about ?? "").split(":"); + return data(Notes.pageAbout({ client, path: { kind, key: Number(k) } })); + }, + }); + const page = q.data as (Page | PageDraft) | undefined; + const saved = page && page.id != null ? (page as Page) : null; + + const [title, setTitle] = useState(""); + const [summary, setSummary] = useState(""); + const [date, setDate] = useState(""); + const [place, setPlace] = useState(""); + const loadedFor = useRef(null); + useEffect(() => { + if (!page) return; + const k = `${page.id ?? "draft"}:${page.about ?? ""}`; + if (loadedFor.current === k) return; + loadedFor.current = k; + setTitle(page.title); + setSummary(saved?.summary ?? ""); + setDate(saved?.date ?? ""); + setPlace(saved?.place ?? ""); + }, [page, saved]); + + // Saving: changes gather for a moment, then go in one request. A thing's draft becomes its page on the first one. + const pending = useRef({}); + const timer = useRef>(undefined); + const savedId = useRef(null); + savedId.current = saved?.id ?? savedId.current; + const [state, setState] = useState<"saved" | "saving" | "error">("saved"); + const now = useRef({ page, title, key }); + now.current = { page, title, key }; + + const flush = useCallback(async () => { + clearTimeout(timer.current); + const c = pending.current; + pending.current = {}; + const { page, title, key } = now.current; + if (!page || !Object.keys(c).length) return; + setState("saving"); + try { + let out: Page; + if (savedId.current == null) { + out = await data( + Notes.createPage({ + client, + body: { + ns: page.namespace, + about: page.about ?? undefined, + title: (c.title ?? title).trim() || page.title, + body: c.body ?? "", + doc: c.doc ?? null, + summary: c.summary || null, + date: c.date || null, + place: (c.place || null) as Page["place"], + }, + }), + ); + savedId.current = out.id; + } else { + const body: Record = {}; + if (c.title !== undefined && c.title.trim()) body.title = c.title.trim(); + if (c.summary !== undefined) body.summary = c.summary; + if (c.date !== undefined && c.date) body.date = c.date; + if (c.place !== undefined) body.place = c.place; + if (c.body !== undefined) { + body.body = c.body; + body.doc = c.doc ?? null; + } + out = await data(Notes.updatePage({ client, path: { pid: savedId.current }, body })); + } + qc.setQueryData(key, out); + qc.invalidateQueries({ queryKey: ["notes-tree"] }); + setState("saved"); + } catch (err) { + setState("error"); + toast({ + title: "Couldn’t save the note", + body: err instanceof ApiError ? err.message : "Please try again.", + tone: "red", + }); + } + }, [client, qc, toast]); + + const change = useCallback( + (c: Changes) => { + pending.current = { ...pending.current, ...c }; + clearTimeout(timer.current); + timer.current = setTimeout(() => void flush(), 800); + }, + [flush], + ); + const flushRef = useRef(flush); + flushRef.current = flush; + useEffect(() => () => void flushRef.current(), []); + + const search = useCallback( + async (sign: "@" | "#", query: string): Promise => + page ? data(Notes.linkTargets({ client, query: { ns: page.namespace, sign, q: query, limit: 20 } })) : [], + [client, page], + ); + const openLink = useCallback( + (target: string) => { + const href = hrefFor(target, page?.namespace); + if (href) router.push(href); + }, + [router, page?.namespace], + ); + + const remove = async () => { + if (savedId.current == null) return; + if (!window.confirm("Delete this note? The notes inside it move up a level.")) return; + try { + await data(Notes.deletePage({ client, path: { pid: savedId.current } })); + qc.invalidateQueries({ queryKey: ["notes-tree"] }); + router.push("/notes"); + } catch (err) { + toast({ + title: "Couldn’t delete it", + body: err instanceof ApiError ? err.message : "Please try again.", + tone: "red", + }); + } + }; + + if (q.isError) + return ( + } title="This note isn’t here" tone="error"> + It was deleted, or you don’t have access to it. + + ); + if (!page) + return ( +
+ + + +
+ ); + + const canEdit = page.can_edit; + const aboutHref = page.about ? hrefFor(page.about, page.namespace) : null; + return ( +
+
+ {page.namespace} + {aboutHref && ( + + Open {page.about?.split(":")[0]} + + )} + {saved?.author === "assistant" && ( + + Written by the assistant + + )} + + {canEdit && ( + + {state === "saving" ? "Saving…" : state === "error" ? "Not saved" : saved ? "Saved" : "Draft"} + + )} + {canEdit && saved && ( + + )} +
+ { + setTitle(e.target.value); + change({ title: e.target.value }); + }} + placeholder="Untitled" + className="w-full bg-transparent text-[30px] font-bold leading-tight tracking-[-.015em] text-fg outline-none placeholder:text-fg-muted" + /> + { + setSummary(e.target.value); + change({ summary: e.target.value }); + }} + placeholder={canEdit ? "One line on what this note holds (the assistant reads it first)" : ""} + className="w-full bg-transparent text-[15px] text-fg-secondary outline-none placeholder:text-fg-muted" + /> +
+ + + {saved?.updated_at && Changed {shortDate(saved.updated_at)}} +
+ change({ body: c.markdown, doc: c.doc })} + search={search} + onOpenLink={openLink} + /> + +
+ ); +} + +function Backlinks({ items }: { items: { page: number; title: string; about?: string | null }[] }) { + if (!items.length) return null; + return ( +
+

+ Linked from {items.length} {items.length === 1 ? "note" : "notes"} +

+
    + {items.map((b) => ( +
  • + + {b.title} + +
  • + ))} +
+
+ ); +} diff --git a/nextjs-frontend/components/notes/notes-home.tsx b/nextjs-frontend/components/notes/notes-home.tsx new file mode 100644 index 000000000..f46c1c15c --- /dev/null +++ b/nextjs-frontend/components/notes/notes-home.tsx @@ -0,0 +1,92 @@ +"use client"; + +import { useMutation, useQueries, useQueryClient } from "@tanstack/react-query"; +import { FileText, NotebookPen, Plus, Sparkles } from "lucide-react"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; + +import { Notes } from "@/app/openapi-client"; +import { PLACES } from "@/components/notes/links"; +import { Button } from "@/components/ui/button"; +import { EmptyState, PageHeader, SkeletonRows } from "@/components/ui/states"; +import { useToast } from "@/components/ui/toast"; +import { ApiError, data, useApiClient } from "@/lib/api/browser"; +import { shortDate } from "@/lib/format"; +import { useArchive } from "@/lib/hooks/session"; + +/** Every free note in view, the latest changed first, with where it's filed. */ +export function NotesHome() { + const client = useApiClient(); + const qc = useQueryClient(); + const router = useRouter(); + const toast = useToast(); + const { namespace, namespaces, can } = useArchive(); + const names = namespace ? [namespace] : namespaces.map((n) => n.name); + const trees = useQueries({ + queries: names.map((ns) => ({ + queryKey: ["notes-tree", ns], + queryFn: () => data(Notes.listPages({ client, query: { ns } })), + })), + }); + const pages = trees + .flatMap((t) => (t.data ? t.data.pages.map((p) => ({ ...p, ns: t.data.namespace })) : [])) + .sort((a, b) => (b.updated_at ?? "").localeCompare(a.updated_at ?? "")); + const target = namespace ?? names.find((n) => can("editor", n)) ?? null; + const create = useMutation({ + mutationFn: () => data(Notes.createPage({ client, body: { ns: target!, title: "Untitled" } })), + onSuccess: (p) => { + qc.invalidateQueries({ queryKey: ["notes-tree"] }); + router.push(`/notes/${p.id}`); + }, + onError: (err) => + toast({ + title: "Couldn’t add a note", + body: err instanceof ApiError ? err.message : "Please try again.", + tone: "red", + }), + }); + const newNote = + target && can("editor", target) ? ( + + ) : null; + const place = (v?: string | null) => PLACES.find((p) => p.value === v)?.label; + + return ( +
+ + {trees.some((t) => t.isPending) ? ( + + ) : !pages.length ? ( + } title="No notes yet" actions={newNote}> + The assistant writes notes as it learns, and you can write your own. Type @ in a note to link a recording, + person or another note, and # for a topic. Every recording and entity also has a page of its own. + + ) : ( +
    + {pages.map((p) => ( +
  • + + {p.author === "assistant" ? ( + + ) : ( + + )} + + {p.title} + {p.summary && {p.summary}} + + + {[place(p.place), !namespace ? p.ns : null, p.updated_at ? shortDate(p.updated_at) : null] + .filter(Boolean) + .join(" · ")} + + +
  • + ))} +
+ )} +
+ ); +} diff --git a/nextjs-frontend/components/notes/notes-tree.tsx b/nextjs-frontend/components/notes/notes-tree.tsx new file mode 100644 index 000000000..7173b3f8e --- /dev/null +++ b/nextjs-frontend/components/notes/notes-tree.tsx @@ -0,0 +1,280 @@ +"use client"; + +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { ChevronRight, FileText, Plus, Sparkles } from "lucide-react"; +import Link from "next/link"; +import { usePathname, useRouter } from "next/navigation"; +import { useEffect, useMemo, useState, type DragEvent } from "react"; + +import { Notes } from "@/app/openapi-client"; +import type { NotePageItem as PageItem } from "@/app/openapi-client/types.gen"; +import { useToast } from "@/components/ui/toast"; +import { ApiError, data, useApiClient } from "@/lib/api/browser"; +import { useArchive } from "@/lib/hooks/session"; +import { cn } from "@/lib/utils"; + +const OPEN_KEY = "lens.notes.open"; + +function readOpen(): Set { + try { + return new Set(JSON.parse(localStorage.getItem(OPEN_KEY) ?? "[]") as number[]); + } catch { + return new Set(); + } +} + +/** The free notes of the namespaces in view, as a tree in the left navigation (like Notion): open a note, add one + * inside another, drag one onto another to move it there, or onto a namespace's name to move it to the top. Pages of + * resources and entities aren't here: they open from those things. */ +export function NotesTree({ onNavigate }: { onNavigate?: () => void }) { + const { namespace, namespaces } = useArchive(); + const names = namespace ? [namespace] : namespaces.map((n) => n.name); + const [open, setOpen] = useState>(() => new Set()); + useEffect(() => setOpen(readOpen()), []); + const toggle = (id: number) => + setOpen((s) => { + const next = new Set(s); + if (next.has(id)) next.delete(id); + else next.add(id); + try { + localStorage.setItem(OPEN_KEY, JSON.stringify([...next])); + } catch { + /* the tree just forgets what was open */ + } + return next; + }); + if (!names.length) return null; + return ( +
+ {names.map((ns) => ( + + ))} +
+ ); +} + +function NamespaceNotes({ + ns, + showName, + open, + toggle, + onNavigate, +}: { + ns: string; + showName: boolean; + open: Set; + toggle: (id: number) => void; + onNavigate?: () => void; +}) { + const client = useApiClient(); + const qc = useQueryClient(); + const router = useRouter(); + const toast = useToast(); + const { can } = useArchive(); + const canEdit = can("editor", ns); + const tree = useQuery({ + queryKey: ["notes-tree", ns], + queryFn: () => data(Notes.listPages({ client, query: { ns } })), + }); + const kids = useMemo(() => { + const m = new Map(); + for (const p of tree.data?.pages ?? []) { + const k = p.parent ?? null; + m.set(k, [...(m.get(k) ?? []), p]); + } + return m; + }, [tree.data]); + const fail = (title: string) => (err: unknown) => + toast({ title, body: err instanceof ApiError ? err.message : "Please try again.", tone: "red" }); + const create = useMutation({ + mutationFn: (parent: number | null) => data(Notes.createPage({ client, body: { ns, title: "Untitled", parent } })), + onSuccess: (p, parent) => { + if (parent != null && !open.has(parent)) toggle(parent); + qc.invalidateQueries({ queryKey: ["notes-tree", ns] }); + router.push(`/notes/${p.id}`); + onNavigate?.(); + }, + onError: fail("Couldn’t add a note"), + }); + const move = useMutation({ + mutationFn: ({ id, parent }: { id: number; parent: number | null }) => + data(Notes.movePage({ client, path: { pid: id }, body: { parent } })), + onSuccess: () => qc.invalidateQueries({ queryKey: ["notes-tree", ns] }), + onError: fail("Couldn’t move the note"), + }); + const [over, setOver] = useState(null); + const drop = (parent: number | null) => (e: DragEvent) => { + e.preventDefault(); + setOver(null); + const id = Number(e.dataTransfer.getData("application/x-lens-note")); + const from = e.dataTransfer.getData("application/x-lens-ns"); + if (!id || from !== ns || id === parent) return; + move.mutate({ id, parent }); + if (parent != null && !open.has(parent)) toggle(parent); + }; + const allow = (target: number | "top") => (e: DragEvent) => { + if (!canEdit || !e.dataTransfer.types.includes("application/x-lens-note")) return; + e.preventDefault(); + setOver(target); + }; + + const top = kids.get(null) ?? []; + return ( +
+
setOver(null)} + onDrop={drop(null)} + > + + {showName ? `Notes · ${ns}` : "Notes"} + + {canEdit && ( + + )} +
+ {tree.isSuccess && !top.length &&

No notes yet.

} + {top.map((p) => ( + setOver(null)} + onAdd={(parent) => create.mutate(parent)} + onNavigate={onNavigate} + /> + ))} +
+ ); +} + +function Node({ + page, + depth, + ns, + kids, + open, + toggle, + canEdit, + over, + allow, + drop, + onLeave, + onAdd, + onNavigate, +}: { + page: PageItem; + depth: number; + ns: string; + kids: Map; + open: Set; + toggle: (id: number) => void; + canEdit: boolean; + over: number | "top" | null; + allow: (target: number) => (e: DragEvent) => void; + drop: (parent: number) => (e: DragEvent) => void; + onLeave: () => void; + onAdd: (parent: number) => void; + onNavigate?: () => void; +}) { + const pathname = usePathname(); + const children = kids.get(page.id) ?? []; + const expanded = open.has(page.id); + const on = pathname === `/notes/${page.id}`; + return ( +
+
{ + e.dataTransfer.setData("application/x-lens-note", String(page.id)); + e.dataTransfer.setData("application/x-lens-ns", ns); + e.dataTransfer.effectAllowed = "move"; + }} + onDragOver={allow(page.id)} + onDragLeave={onLeave} + onDrop={drop(page.id)} + > + + + {page.author === "assistant" ? ( + + ) : ( + + )} + {page.title} + + {canEdit && ( + + )} +
+ {expanded && + children.map((c) => ( + + ))} +
+ ); +} diff --git a/nextjs-frontend/components/recording/header.tsx b/nextjs-frontend/components/recording/header.tsx index a2d727fac..ce46f1e98 100644 --- a/nextjs-frontend/components/recording/header.tsx +++ b/nextjs-frontend/components/recording/header.tsx @@ -18,6 +18,7 @@ import { Keyboard, Link2, ListChecks, + NotebookPen, Paperclip, Pencil, RefreshCw, @@ -190,9 +191,14 @@ function Meta({ icon, children }: { icon: ReactNode; children: ReactNode }) { export function HeaderActions({ compact }: { compact?: boolean }) { const r = useRec(); const api = usePlayerApi(); - const { canEdit, ns, openShare, paged } = r; + const { canEdit, ns, openShare, paged, id } = r; return (
+ {!compact && ( + + )} {!compact && !paged && (