diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a1ed26e6..ca028370c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version ## Unreleased +- **Pin notes.** A note's ⋯ menu in the tree has Pin: pinned notes show at the top of the tree and first on the + Notes page, for the person who pinned them only ([Pinned notes](docs/notes.md#pinned-notes)). - **Notes tree menu.** Each note in the tree in the left navigation has a ⋯ menu to add a note inside, rename it in place, move it (find the note to put it in by name, or move it to the top) and delete it with Undo, so nothing needs dragging and it works on a phone. The navigation links and the tree now scroll together, so a long tree has room diff --git a/docs/api.md b/docs/api.md index facdaaff5..5663f17d8 100644 --- a/docs/api.md +++ b/docs/api.md @@ -636,6 +636,8 @@ GET /api/v1/notes/{pid} PATCH /api/v1/notes/{pid} DELETE /api/v1/notes/{pid} POST /api/v1/notes/{pid}/move +PUT /api/v1/notes/{pid}/pin +DELETE /api/v1/notes/{pid}/pin GET /api/v1/notes/{pid}/history GET /api/v1/notes/{pid}/history/{vid} POST /api/v1/notes/{pid}/history/{vid}/restore @@ -649,8 +651,10 @@ Note pages ([Notes](notes.md)), apart from the notes on an asset above. `GET /no (`all=true` adds the pages of things). `search?q=` finds pages by the words in their title, summary or text, title matches first, each with the words around the match ([Finding notes](notes.md#finding-notes)). `DELETE /notes/{pid}` moves a page to recently deleted for 30 days: `deleted` lists them, `restore` puts one back where it was and -`DELETE /notes/deleted/{pid}` deletes one for good ([Deleting](notes.md#deleting-and-putting-back)). `move` puts a free note inside `parent` before `before`, `history` lists what the -page was before each change, and `restore` puts an earlier version back (what it was becomes a version too). `files` +`DELETE /notes/deleted/{pid}` deletes one for good ([Deleting](notes.md#deleting-and-putting-back)). `move` puts a +free note inside `parent` before `before`. `PUT …/pin` pins a page for you (`pinned` on each page says whether you +did) and `DELETE …/pin` unpins it ([Pinned notes](notes.md#pinned-notes)). `history` lists what the page was before +each change, and `restore` puts an earlier version back (what it was becomes a version too). `files` lists the files and images attached to a page; `blobs` uploads (in chunks) and reads them, and `DELETE …/files?key=` removes one. diff --git a/docs/notes.md b/docs/notes.md index fce3f2a56..64632be63 100644 --- a/docs/notes.md +++ b/docs/notes.md @@ -128,13 +128,21 @@ Free notes sit in a tree in the left navigation, under the main links. The links long tree has the whole height. A row opens its note, its arrow shows the notes inside it (the tree remembers which are open) and **+** adds a note inside. Each row's **⋯** menu, which always shows on a touch screen, adds a note inside, renames the note in place (Enter saves, Escape leaves it as it was), moves it (**Move to…** finds the note to put it in -by name, Enter picks the first; **Move to the top**) and deletes it with Undo. Dragging a note onto another puts it -inside, and onto the Notes heading moves it to the top. The pages of recordings and entities aren't in the tree: they -open from those things. +by name, Enter picks the first; **Move to the top**), pins it ([below](#pinned-notes)) and deletes it with Undo. +Dragging a note onto another puts it inside, and onto the Notes heading moves it to the top. The pages of recordings +and entities aren't in the tree: they open from those things. `POST /api/v1/notes/{pid}/move` with `{parent}` moves a note (`null` for the top); `PATCH /api/v1/notes/{pid}` with `{title}` renames it. +## Pinned notes + +**Pin** in a note's ⋯ menu in the tree pins it for you: it shows at the top of the tree, under **Pinned**, and first +on the Notes page with a pin. Pins are each person's own, so pinning changes nothing for anyone else and needs only +read access; up to 50 per namespace. **Unpin** (in the menu, or the button on its row under Pinned) takes it off. +`PUT /api/v1/notes/{pid}/pin` pins and `DELETE` unpins; each page in `GET /api/v1/notes` says whether you pinned it +(`pinned`). + ## Deleting and putting back **Delete** on a page deletes it at once, with no question first: the notice has **Undo**, which puts it back and opens diff --git a/fastapi_backend/app/api/v1/routes/notebook.py b/fastapi_backend/app/api/v1/routes/notebook.py index f33bccde7..1401a332e 100644 --- a/fastapi_backend/app/api/v1/routes/notebook.py +++ b/fastapi_backend/app/api/v1/routes/notebook.py @@ -58,6 +58,12 @@ def _backlinks(acl: Access, db: DB, sid: int, targets: list[str]) -> list[dict[s return notebook.backlinks(db, sid, targets) if targets else [] +def _mine(p: dict[str, Any], user: Principal) -> dict[str, Any]: + """The page's fields as this person sees them: whether they pinned it, not who else did.""" + out = {k: v for k, v in p.items() if k not in ("space", "created_by", "updated_by", "pinned_by")} + return {**out, "pinned": user.id in (p.get("pinned_by") or [])} + + def _out(acl: Access, db: DB, p: dict[str, Any], user: Principal) -> NotePage: names = store.space_names(db) links = notebook.links(db, p["id"]) @@ -71,7 +77,7 @@ def _out(acl: Access, db: DB, p: dict[str, Any], user: Principal) -> NotePage: writer = db.one("SELECT email FROM $r", r=store.R("account", p["created_by"])) if p.get("created_by") else None targets = [f"page:{p['id']}"] + ([p["about"]] if p.get("about") else []) return NotePage( - **{k: v for k, v in p.items() if k not in ("space", "created_by", "updated_by")}, + **_mine(p, user), namespace=names.get(p["space"], ""), created_by=(writer or {}).get("email"), links=out_links, @@ -84,7 +90,7 @@ def _out(acl: Access, db: DB, p: dict[str, Any], user: Principal) -> NotePage: def list_pages(ns: str, user: CurrentUser, acl: Acl, db: Db, everything: bool = Query(False, alias="all")) -> NoteTree: """The namespace's free notes for the tree (no bodies), in order; `all=true` adds the pages of things.""" sid = acl.namespace(ns) - return NoteTree(namespace=ns, pages=[NotePageItem(**p) for p in notebook.tree(db, sid, everything)]) + return NoteTree(namespace=ns, pages=[NotePageItem(**_mine(p, user)) for p in notebook.tree(db, sid, everything)]) @router.post("") @@ -299,6 +305,24 @@ def move_page(pid: int, body: NotePageMove, user: Writer, acl: Acl, db: Db) -> N return _out(acl, db, notebook.get(db, pid), user) +@router.put("/{pid}/pin") +def pin_page(pid: int, user: CurrentUser, acl: Acl, db: Db) -> NotePage: + """Pin the page for you: it shows first on your Notes page and in your tree. Pins are each person's own; anyone + who can read the page can pin it.""" + _page(acl, db, pid) + with domain_errors(): + notebook.pin(db, pid, user.id) + return _out(acl, db, notebook.get(db, pid), user) + + +@router.delete("/{pid}/pin") +def unpin_page(pid: int, user: CurrentUser, acl: Acl, db: Db) -> NotePage: + """Unpin the page for you.""" + _page(acl, db, pid) + notebook.pin(db, pid, user.id, on=False) + return _out(acl, db, notebook.get(db, pid), user) + + @router.delete("/{pid}") def delete_page(pid: int, user: Writer, acl: Acl, db: Db) -> Ok: """Delete a page; the pages inside it move up a level. It can be put back from recently deleted for diff --git a/fastapi_backend/app/domain/notebook.py b/fastapi_backend/app/domain/notebook.py index 8557c880e..cb5ab1e93 100644 --- a/fastapi_backend/app/domain/notebook.py +++ b/fastapi_backend/app/domain/notebook.py @@ -47,7 +47,7 @@ MENTION = re.compile(r"([@#])\[([^\]\n]{1,200})\]\(([a-z]+):(\d{1,18})\)") FIELDS = ( "record::id(id) AS id, space, title, summary, summary_by, date, place, place_by, place_suggestion, parent, position, " - "about, author, view, doc_stale, created_by, updated_by, created_at, updated_at" + "about, author, view, doc_stale, created_by, updated_by, created_at, updated_at, pinned_by" ) @@ -413,6 +413,21 @@ def move(db, pid, parent=None, before=None): db.q("UPDATE $r SET parent = $p, position = $pos, updated_at = $t", r=R("note_page", int(pid)), p=parent, pos=position, t=store.now()) +PINS_MAX = 50 # a person's pinned notes, per namespace + + +def pin(db, pid, account, on=True): + """Pin the page for this person (on top of their Notes page and tree), or unpin it. Pins are each person's own: + pinning a page doesn't change it for anyone else, and needs only to see it. ValueError past PINS_MAX.""" + p = get(db, pid) + if on and account not in (p.get("pinned_by") or []): + mine = db.values("SELECT VALUE id FROM note_page WHERE space = $s AND pinned_by CONTAINS $a", s=p["space"], a=account) + if len(mine) >= PINS_MAX: + raise ValueError(f"Up to {PINS_MAX} notes can be pinned in a namespace: unpin one first.") + op = "array::union(pinned_by ?? [], [$a])" if on else "array::complement(pinned_by ?? [], [$a])" + db.q(f"UPDATE $r SET pinned_by = {op}", r=R("note_page", int(pid)), a=account) + + TRASH_DAYS = 30 # a deleted page can be put back for this long, then it's gone with its files and history diff --git a/fastapi_backend/app/schemas/notebook.py b/fastapi_backend/app/schemas/notebook.py index a674675d7..62e83a504 100644 --- a/fastapi_backend/app/schemas/notebook.py +++ b/fastapi_backend/app/schemas/notebook.py @@ -32,6 +32,7 @@ class NotePageItem(ResponseModel): about: str | None = Field(None, description='what this is the page of, like "recording:12"; null for a free note') author: Literal["person", "assistant"] = Field("person", description="who wrote it") view: Literal["page", "edgeless"] | None = Field(None, description="how the editor shows it (default: page)") + pinned: bool = Field(False, description="you pinned it: it shows first on your Notes page and in your tree") created_at: str | None = None updated_at: str | None = None diff --git a/fastapi_backend/tests/api/test_notebook.py b/fastapi_backend/tests/api/test_notebook.py index 08e9419c1..4e7e87a55 100644 --- a/fastapi_backend/tests/api/test_notebook.py +++ b/fastapi_backend/tests/api/test_notebook.py @@ -536,3 +536,34 @@ def test_deleted_pages_go_after_a_while(client, env, db, cfg): assert notebook.purge_due(db, cfg) == 1 assert [d["title"] for d in client.get("/api/v1/notes/deleted?ns=pods", headers=he).json()] == ["New"] assert not db.rows("SELECT id FROM note_version WHERE page = $p", p=old["id"]) + + +def test_pins(client, env, db): + he, hv, hx = env["he"], env["hv"], env["hx"] + a = _new(client, he, title="Plans") + b = _new(client, he, title="Hiring", parent=a["id"]) + # a viewer pins a note for themselves; nobody else sees it pinned, and the page itself doesn't change + r = client.put(f"/api/v1/notes/{b['id']}/pin", headers=hv) + assert r.status_code == 200 and r.json()["pinned"] is True + assert "pinned_by" not in r.json() + assert r.json()["updated_at"] == b["updated_at"] + assert client.put(f"/api/v1/notes/{b['id']}/pin", headers=hv).status_code == 200 # twice is once + mine = {p["id"]: p["pinned"] for p in client.get("/api/v1/notes?ns=pods", headers=hv).json()["pages"]} + theirs = {p["id"]: p["pinned"] for p in client.get("/api/v1/notes?ns=pods", headers=he).json()["pages"]} + assert mine == {a["id"]: False, b["id"]: True} and theirs == {a["id"]: False, b["id"]: False} + assert client.get(f"/api/v1/notes/{b['id']}", headers=hv).json()["pinned"] is True + assert len(db.values("SELECT VALUE pinned_by FROM $r", r=R("note_page", b["id"]))[0]) == 1 + # outside the namespace it isn't there to pin + assert client.put(f"/api/v1/notes/{b['id']}/pin", headers=hx).status_code == 404 + r = client.delete(f"/api/v1/notes/{b['id']}/pin", headers=hv) + assert r.status_code == 200 and r.json()["pinned"] is False + # there's a limit, per person and namespace + old = notebook.PINS_MAX + notebook.PINS_MAX = 1 + try: + assert client.put(f"/api/v1/notes/{a['id']}/pin", headers=hv).status_code == 200 + r = client.put(f"/api/v1/notes/{b['id']}/pin", headers=hv) + assert r.status_code == 400 and "unpin one first" in r.json()["detail"] + assert client.put(f"/api/v1/notes/{b['id']}/pin", headers=he).status_code == 200 + finally: + notebook.PINS_MAX = old diff --git a/nextjs-frontend/__tests__/notes-find.test.tsx b/nextjs-frontend/__tests__/notes-find.test.tsx index 0be9beb22..d690a693d 100644 --- a/nextjs-frontend/__tests__/notes-find.test.tsx +++ b/nextjs-frontend/__tests__/notes-find.test.tsx @@ -100,6 +100,18 @@ describe("the Notes page", () => { expect(push).toHaveBeenCalledWith("/entities/5"); }); + it("lists the notes this person pinned first", async () => { + m(Notes.listPages).mockImplementation(() => + ok({ namespace: "home", pages: [page(1, "Fresh"), page(2, "Pinned plan", { pinned: true }), page(3, "Newest")] }), + ); + show(); + await screen.findByRole("link", { name: /Pinned plan/ }); + const rows = screen.getAllByRole("listitem").map((li) => li.textContent); + expect(rows[0]).toContain("Pinned plan"); + expect(rows.slice(1)).toEqual([expect.stringContaining("Newest"), expect.stringContaining("Fresh")]); + expect(screen.getByLabelText("Pinned")).toBeInTheDocument(); + }); + it("says when no note has the words", async () => { m(Notes.searchPages).mockImplementation(() => ok({ total: 0, pages: [] })); show(); diff --git a/nextjs-frontend/__tests__/notes-tree.test.tsx b/nextjs-frontend/__tests__/notes-tree.test.tsx index 33b5bcfd4..ae23fab09 100644 --- a/nextjs-frontend/__tests__/notes-tree.test.tsx +++ b/nextjs-frontend/__tests__/notes-tree.test.tsx @@ -13,6 +13,8 @@ jest.mock("@/app/openapi-client", () => ({ updatePage: jest.fn(), deletePage: jest.fn(), restoreDeleted: jest.fn(), + pinPage: jest.fn(), + unpinPage: jest.fn(), }, })); jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: "t" } }) })); @@ -21,8 +23,9 @@ let pathname = "/notes"; jest.mock("next/navigation", () => ({ usePathname: () => pathname, useRouter: () => ({ push }) })); const toast = jest.fn(); jest.mock("@/components/ui/toast", () => ({ useToast: () => toast })); +let editor = true; jest.mock("@/lib/hooks/session", () => ({ - useArchive: () => ({ namespaces: [{ name: "home" }], namespace: "home", can: () => true }), + useArchive: () => ({ namespaces: [{ name: "home" }], namespace: "home", can: () => editor }), })); const ok = (data: unknown) => Promise.resolve({ data, response: { ok: true, status: 200 } }); @@ -54,6 +57,7 @@ beforeEach(() => { jest.clearAllMocks(); localStorage.clear(); pathname = "/notes"; + editor = true; m(Notes.listPages).mockImplementation(() => ok({ namespace: "home", pages: PAGES })); }); @@ -119,4 +123,38 @@ describe("the notes tree", () => { expect(m(Notes.deletePage).mock.calls[0][0].path).toEqual({ pid: 4 }); expect(toast.mock.calls[0][0]).toMatchObject({ title: "Deleted “Trips”", action: { label: "Undo" } }); }); + + it("pins a note, which then shows at the top, and unpins it there", async () => { + m(Notes.pinPage).mockImplementation(() => ok({ id: 4, title: "Trips", pinned: true })); + m(Notes.unpinPage).mockImplementation(() => ok({ id: 4, title: "Trips", pinned: false })); + show(); + await choose("Trips", "Pin"); + const pinned = await screen.findByRole("group", { name: "Pinned notes" }); + expect(within(pinned).getByRole("link", { name: "Trips" })).toHaveAttribute("href", "/notes/4"); + await waitFor(() => expect(Notes.pinPage).toHaveBeenCalled()); + expect(m(Notes.pinPage).mock.calls[0][0].path).toEqual({ pid: 4 }); + fireEvent.click(within(pinned).getByRole("button", { name: "Unpin Trips" })); + await waitFor(() => expect(screen.queryByRole("group", { name: "Pinned notes" })).not.toBeInTheDocument()); + expect(m(Notes.unpinPage).mock.calls[0][0].path).toEqual({ pid: 4 }); + }); + + it("lets someone who can only read pin, and nothing else", async () => { + editor = false; + show(); + fireEvent.keyDown(await screen.findByRole("button", { name: "More for Trips" }), { key: "Enter" }); + const items = await screen.findAllByRole("menuitem"); + expect(items.map((i) => i.textContent)).toEqual(["Pin"]); + expect(screen.queryByRole("button", { name: "New note inside Trips" })).not.toBeInTheDocument(); + }); + + it("takes a pin back when the server says no", async () => { + m(Notes.pinPage).mockImplementation(() => + Promise.resolve({ error: { detail: "Up to 50 notes can be pinned" }, response: { ok: false, status: 400 } }), + ); + show(); + await choose("Trips", "Pin"); + await waitFor(() => expect(toast).toHaveBeenCalled()); + expect(toast.mock.calls[0][0].title).toBe("Couldn’t pin it"); + expect(screen.queryByRole("group", { name: "Pinned notes" })).not.toBeInTheDocument(); + }); }); diff --git a/nextjs-frontend/app/openapi-client/index.ts b/nextjs-frontend/app/openapi-client/index.ts index c2f07c530..48b2a5a15 100644 --- a/nextjs-frontend/app/openapi-client/index.ts +++ b/nextjs-frontend/app/openapi-client/index.ts @@ -2147,6 +2147,11 @@ export type { PhotoHit, PhotoResults, PickedLine, + PinPageData, + PinPageError, + PinPageErrors, + PinPageResponse, + PinPageResponses, Pipeline, PipelineCatalog, PipelineCreate, @@ -3094,6 +3099,11 @@ export type { UnlockVaultErrors, UnlockVaultResponse, UnlockVaultResponses, + UnpinPageData, + UnpinPageError, + UnpinPageErrors, + UnpinPageResponse, + UnpinPageResponses, UnsealVaultData, UnsealVaultError, UnsealVaultErrors, diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index cfdb7fdb0..dd0931a61 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -1060,6 +1060,9 @@ import type { PasskeySetupOptionsErrors, PasskeySetupOptionsResponses, PasskeySetupResponses, + PinPageData, + PinPageErrors, + PinPageResponses, PlaceRecordingsData, PlaceRecordingsErrors, PlaceRecordingsResponses, @@ -1492,6 +1495,9 @@ import type { UnlockVaultData, UnlockVaultErrors, UnlockVaultResponses, + UnpinPageData, + UnpinPageErrors, + UnpinPageResponses, UnsealVaultData, UnsealVaultErrors, UnsealVaultResponses, @@ -5390,6 +5396,35 @@ export class Notes { }); } + /** + * Unpin Page + * + * Unpin the page for you. + */ + public static unpinPage( + options: Options, + ): RequestResult { + return (options.client ?? client).delete({ + url: "/api/v1/notes/{pid}/pin", + ...options, + }); + } + + /** + * Pin Page + * + * Pin the page for you: it shows first on your Notes page and in your tree. Pins are each person's own; anyone + * who can read the page can pin it. + */ + public static pinPage( + options: Options, + ): RequestResult { + return (options.client ?? client).put({ + url: "/api/v1/notes/{pid}/pin", + ...options, + }); + } + /** * Delete Page File * diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index cd6ec1799..4f021cbea 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -10136,6 +10136,12 @@ export type NotePage = { * how the editor shows it (default: page) */ view?: "page" | "edgeless" | null; + /** + * Pinned + * + * you pinned it: it shows first on your Notes page and in your tree + */ + pinned?: boolean; /** * Created At */ @@ -10352,6 +10358,12 @@ export type NotePageItem = { * how the editor shows it (default: page) */ view?: "page" | "edgeless" | null; + /** + * Pinned + * + * you pinned it: it shows first on your Notes page and in your tree + */ + pinned?: boolean; /** * Created At */ @@ -27417,6 +27429,66 @@ export type MovePageResponses = { export type MovePageResponse = MovePageResponses[keyof MovePageResponses]; +export type UnpinPageData = { + body?: never; + path: { + /** + * Pid + */ + pid: number; + }; + query?: never; + url: "/api/v1/notes/{pid}/pin"; +}; + +export type UnpinPageErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type UnpinPageError = UnpinPageErrors[keyof UnpinPageErrors]; + +export type UnpinPageResponses = { + /** + * Successful Response + */ + 200: NotePage; +}; + +export type UnpinPageResponse = UnpinPageResponses[keyof UnpinPageResponses]; + +export type PinPageData = { + body?: never; + path: { + /** + * Pid + */ + pid: number; + }; + query?: never; + url: "/api/v1/notes/{pid}/pin"; +}; + +export type PinPageErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type PinPageError = PinPageErrors[keyof PinPageErrors]; + +export type PinPageResponses = { + /** + * Successful Response + */ + 200: NotePage; +}; + +export type PinPageResponse = PinPageResponses[keyof PinPageResponses]; + export type DeletePageFileData = { body?: never; path: { diff --git a/nextjs-frontend/components/notes/notes-home.tsx b/nextjs-frontend/components/notes/notes-home.tsx index 6098fe0ae..80b7c778e 100644 --- a/nextjs-frontend/components/notes/notes-home.tsx +++ b/nextjs-frontend/components/notes/notes-home.tsx @@ -1,7 +1,7 @@ "use client"; import { keepPreviousData, useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query"; -import { FileText, NotebookPen, Plus, Search, Sparkles } from "lucide-react"; +import { FileText, NotebookPen, Pin, Plus, Search, Sparkles } from "lucide-react"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { useMemo, useState } from "react"; @@ -32,9 +32,11 @@ type Row = { about?: string | null; author?: string | null; updated_at?: string | null; + pinned?: boolean; }; -/** Every free note in view, the latest changed first, with where it sits in the tree and where it's filed. Words in +/** Every free note in view, the ones this person pinned first, then the latest changed, with where each sits in the + * tree and where it's filed. Words in * the search box find notes by their title, summary or text (the pages of things too); the filter shows one PARA * place. */ export function NotesHome() { @@ -68,7 +70,7 @@ export function NotesHome() { }, [trees]); const all: Row[] = 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 ?? "")); + .sort((a, b) => Number(!!b.pinned) - Number(!!a.pinned) || (b.updated_at ?? "").localeCompare(a.updated_at ?? "")); const rows: Row[] = words ? (search.data?.pages ?? []).map((p) => ({ ...p, ns: p.namespace })) : all.filter((p) => !place || p.place === place); @@ -190,8 +192,11 @@ export function NotesHome() { {p.about ? `Page of ${p.about.split(":")[0]}` : `In ${inside}`} )} - - + + + + + {p.pinned && } {line && ( diff --git a/nextjs-frontend/components/notes/notes-tree.tsx b/nextjs-frontend/components/notes/notes-tree.tsx index dbf8de98c..23dbdc235 100644 --- a/nextjs-frontend/components/notes/notes-tree.tsx +++ b/nextjs-frontend/components/notes/notes-tree.tsx @@ -1,6 +1,6 @@ "use client"; -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query"; import { ArrowUpToLine, ChevronRight, @@ -8,6 +8,8 @@ import { FileText, FolderInput, Pencil, + Pin, + PinOff, Plus, Sparkles, Trash2, @@ -19,6 +21,7 @@ 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 { useDeleteNote } from "@/components/notes/delete"; +import { usePin } from "@/components/notes/pin"; import { Dialog } from "@/components/ui/dialog"; import { FindBox } from "@/components/ui/find-box"; import { Menu, MenuContent, MenuItem, MenuSeparator, MenuTrigger } from "@/components/ui/menu"; @@ -40,7 +43,8 @@ function readOpen(): 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. Each row's * menu (⋯, always showing on a touch screen) adds a note inside, renames, moves (no dragging needed) and deletes, with - * Undo. Pages of resources and entities aren't here: they open from those things. */ + * Undo, and pins it: pinned notes (each person's own) also show at 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); @@ -61,6 +65,7 @@ export function NotesTree({ onNavigate }: { onNavigate?: () => void }) { if (!names.length) return null; return (
+ {names.map((ns) => ( ))} @@ -68,6 +73,61 @@ export function NotesTree({ onNavigate }: { onNavigate?: () => void }) { ); } +/** The notes this person pinned, in every namespace in view, above the tree: one click to open, one to unpin. */ +function Pinned({ names, showName, onNavigate }: { names: string[]; showName: boolean; onNavigate?: () => void }) { + const client = useApiClient(); + const pathname = usePathname(); + const pin = usePin(); + const trees = useQueries({ + queries: names.map((ns) => ({ + queryKey: ["notes-tree", ns], + queryFn: () => data(Notes.listPages({ client, query: { ns } })), + })), + }); + const pinned = trees.flatMap((t) => + t.data ? t.data.pages.filter((p) => p.pinned).map((p) => ({ ...p, ns: t.data.namespace })) : [], + ); + if (!pinned.length) return null; + return ( +
+
+ Pinned +
+ {pinned.map((p) => { + const on = pathname === `/notes/${p.id}`; + return ( +
+ + + {p.title} + + +
+ ); + })} +
+ ); +} + function NamespaceNotes({ ns, showName, @@ -127,6 +187,7 @@ function NamespaceNotes({ onError: fail("Couldn’t rename the note"), }); const deleteNote = useDeleteNote(); + const pin = usePin(); const pathname = usePathname(); const [renaming, setRenaming] = useState(null); const [moving, setMoving] = useState(null); @@ -143,6 +204,7 @@ function NamespaceNotes({ if (parent != null && !open.has(parent)) toggle(parent); }, startMove: setMoving, + pin: (p, on) => void pin(ns, p.id, on), remove: async (p) => { // deleting the note that's open leaves it for the Notes page if ((await deleteNote(p.id, p.title)) && pathname === `/notes/${p.id}`) router.push("/notes"); @@ -233,6 +295,7 @@ type RowActions = { rename: (id: number, title: string) => void; moveTo: (id: number, parent: number | null) => void; startMove: (page: PageItem) => void; + pin: (page: PageItem, on: boolean) => void; remove: (page: PageItem) => void; }; @@ -393,7 +456,7 @@ function Node({ {page.title} )} - {canEdit && renaming !== page.id && ( + {renaming !== page.id && ( <> @@ -402,34 +465,48 @@ function Node({ - } onSelect={() => actions.add(page.id)}> - Add a note inside - - } onSelect={() => actions.startRename(page.id)}> - Rename - - } onSelect={() => actions.startMove(page)}> - Move to… - - {page.parent != null && ( - } onSelect={() => actions.moveTo(page.id, null)}> - Move to the top - + {canEdit && ( + <> + } onSelect={() => actions.add(page.id)}> + Add a note inside + + } onSelect={() => actions.startRename(page.id)}> + Rename + + } onSelect={() => actions.startMove(page)}> + Move to… + + {page.parent != null && ( + } onSelect={() => actions.moveTo(page.id, null)}> + Move to the top + + )} + )} - - } danger onSelect={() => actions.remove(page)}> - Delete + {/* pins are each person's own, so viewers pin too */} + : } onSelect={() => actions.pin(page, !page.pinned)}> + {page.pinned ? "Unpin" : "Pin"} + {canEdit && ( + <> + + } danger onSelect={() => actions.remove(page)}> + Delete + + + )} - + {canEdit && ( + + )} )}
diff --git a/nextjs-frontend/components/notes/pin.ts b/nextjs-frontend/components/notes/pin.ts new file mode 100644 index 000000000..a66124893 --- /dev/null +++ b/nextjs-frontend/components/notes/pin.ts @@ -0,0 +1,39 @@ +"use client"; + +import { useQueryClient } from "@tanstack/react-query"; +import { useCallback } from "react"; + +import { Notes } from "@/app/openapi-client"; +import type { NoteTree } from "@/app/openapi-client/types.gen"; +import { useToast } from "@/components/ui/toast"; +import { ApiError, data, useApiClient } from "@/lib/api/browser"; + +/** Pins a note for this person, or unpins it: pinned notes show first on their Notes page and at the top of their + * tree. It shows at once, and goes back if the server says no. */ +export function usePin() { + const client = useApiClient(); + const qc = useQueryClient(); + const toast = useToast(); + return useCallback( + async (ns: string, pid: number, on: boolean) => { + const key = ["notes-tree", ns]; + const set = (pinned: boolean) => + qc.setQueryData(key, (t) => + t ? { ...t, pages: t.pages.map((p) => (p.id === pid ? { ...p, pinned } : p)) } : t, + ); + set(on); + try { + await data((on ? Notes.pinPage : Notes.unpinPage)({ client, path: { pid } })); + } catch (err) { + set(!on); + toast({ + title: on ? "Couldn’t pin it" : "Couldn’t unpin it", + body: err instanceof ApiError ? err.message : "Please try again.", + tone: "red", + }); + } + qc.invalidateQueries({ queryKey: ["note", pid] }); + }, + [client, qc, toast], + ); +} diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index 54b7b741a..d0d09fa5a 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -10573,6 +10573,90 @@ } } }, + "/api/v1/notes/{pid}/pin": { + "put": { + "tags": [ + "notes" + ], + "summary": "Pin Page", + "description": "Pin the page for you: it shows first on your Notes page and in your tree. Pins are each person's own; anyone\nwho can read the page can pin it.", + "operationId": "pin_page", + "parameters": [ + { + "name": "pid", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "title": "Pid" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NotePage" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "delete": { + "tags": [ + "notes" + ], + "summary": "Unpin Page", + "description": "Unpin the page for you.", + "operationId": "unpin_page", + "parameters": [ + { + "name": "pid", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "title": "Pid" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NotePage" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, "/api/v1/notes/{pid}/files": { "get": { "tags": [ @@ -45303,6 +45387,12 @@ "title": "View", "description": "how the editor shows it (default: page)" }, + "pinned": { + "type": "boolean", + "title": "Pinned", + "description": "you pinned it: it shows first on your Notes page and in your tree", + "default": false + }, "created_at": { "anyOf": [ { @@ -45724,6 +45814,12 @@ "title": "View", "description": "how the editor shows it (default: page)" }, + "pinned": { + "type": "boolean", + "title": "Pinned", + "description": "you pinned it: it shows first on your Notes page and in your tree", + "default": false + }, "created_at": { "anyOf": [ {