From 60560c3eb6b42b9b7627b8d8fcf19372aa5b3635 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Thu, 15 Oct 2026 12:45:16 +0000 Subject: [PATCH] feat(notes): templates, and a copy of any note MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Notes inside a namespace's Templates note are templates. New note from a template… on the Notes page and in Jump to lists them (type to find, Enter takes the first) and starts a note with the template's title, text, drawings, files, filing and view; with none yet it makes the Templates note. The tree's menu makes a copy of any note beside it. GET/POST /notes/templates and POST /notes/{pid}/copy. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01RrY2byt5BHVeBXJUyfwWpb --- CHANGELOG.md | 3 + README.md | 9 +- docs/api.md | 7 +- docs/notes.md | 14 +- docs/requirements.md | 2 + fastapi_backend/app/api/v1/routes/notebook.py | 34 +++ fastapi_backend/app/domain/notebook.py | 59 +++++ fastapi_backend/app/schemas/notebook.py | 21 ++ fastapi_backend/tests/api/test_notebook.py | 40 +++ nextjs-frontend/__tests__/notes-find.test.tsx | 27 +- .../__tests__/notes-templates.test.tsx | 74 ++++++ .../__tests__/notes-today.test.tsx | 5 +- nextjs-frontend/__tests__/notes-tree.test.tsx | 13 + nextjs-frontend/app/openapi-client/index.ts | 19 ++ nextjs-frontend/app/openapi-client/sdk.gen.ts | 68 ++++- .../app/openapi-client/types.gen.ts | 161 +++++++++++- .../components/app-shell/command-palette.tsx | 6 + .../components/notes/notes-home.tsx | 37 ++- .../components/notes/notes-tree.tsx | 11 + .../components/notes/templates.tsx | 128 +++++++++ nextjs-frontend/openapi.json | 248 ++++++++++++++++++ 21 files changed, 968 insertions(+), 18 deletions(-) create mode 100644 nextjs-frontend/__tests__/notes-templates.test.tsx create mode 100644 nextjs-frontend/components/notes/templates.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index d3db1d498..494f7de8c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,9 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version - **Download notes as Markdown.** A note's ⋯ menu in the tree downloads it as a Markdown file, and the Notes page's ⋯ menu downloads all of a namespace's notes as a zip in folders that follow the tree, for Obsidian and other notes apps ([Downloading as Markdown](docs/notes.md#downloading-as-markdown)). +- **Templates.** Notes inside a namespace's Templates note are templates: **New note from a template…** on the Notes + page and in Jump to starts a note from one, with its text, drawings, files and filing. Any note's menu in the tree can + also **Make a copy** ([Templates](docs/notes.md#templates)). - **Automations for agents.** Agents list, save, try and run automations through the MCP tools `automations`, `automation_actions`, `save_automation`, `test_automation` and `run_automation`, with problems in plain words. The assistant saves them switched off and asks before switching one on or running it diff --git a/README.md b/README.md index 83d7342d1..393694908 100644 --- a/README.md +++ b/README.md @@ -123,9 +123,10 @@ listed under [In progress](#in-progress), and what comes next under [Planned](#p [long recordings](docs/speech-providers.md#long-recordings); [checks](docs/requirements.md#understand-it)) - **Learn from it.** Make a two-host podcast episode about what you pick, every claim cited and checked against its source, read aloud in two voices. Keep notes beside every asset, entity and topic, written by you or the assistant, in - a tree where notes are renamed, moved and pinned (pins are your own), with today's note one click away, a search by - their words, and Undo and Recently deleted instead of a confirm. Export an asset or a collection as an evidence PDF - with everything Lens found about it, or the parts you pick. ([Podcasts](docs/podcasts.md), [notes](docs/notes.md), + a tree where notes are renamed, moved, copied and pinned (pins are your own), with today's note one click away, + templates to start from, a search by their words, a download as Markdown, and Undo and Recently deleted instead of a + confirm. Export an asset or a collection as an evidence PDF with everything Lens found about it, or the parts you + pick. ([Podcasts](docs/podcasts.md), [notes](docs/notes.md), [evidence PDFs](docs/api.md#evidence-pdfs); [checks](docs/requirements.md#learn-from-it)) - **Automate it.** Pipelines and workflows on a canvas, routines on a schedule, batch runs over a collection, and notifications to webhooks, Slack, Discord and Matterbridge. Everything that happens in Lens (new assets, emails, @@ -201,8 +202,6 @@ These are open pull requests, not yet part of Lens: - **The assistant** answering questions about Lens itself, from its docs and this server ([#400](https://github.com/adeelahmad/lense/pull/400)). - **Chat:** a conversation exported as Markdown, PDF or JSON ([#474](https://github.com/adeelahmad/lense/pull/474)). -- **Notes:** download a note, or all of a namespace's notes, as Markdown - ([#419](https://github.com/adeelahmad/lense/pull/419)). - **Sources:** RSS and Atom news feeds ([#453](https://github.com/adeelahmad/lense/pull/453)). - **Pictures:** described on this machine with Florence-2 ([#477](https://github.com/adeelahmad/lense/pull/477)), and low-quality images enhanced before they're read ([#479](https://github.com/adeelahmad/lense/pull/479)). diff --git a/docs/api.md b/docs/api.md index 24bd6f4b8..51ce8d292 100644 --- a/docs/api.md +++ b/docs/api.md @@ -817,6 +817,8 @@ deleted. GET /api/v1/notes POST /api/v1/notes POST /api/v1/notes/today +GET /api/v1/notes/templates +POST /api/v1/notes/templates GET /api/v1/notes/search GET /api/v1/notes/export GET /api/v1/notes/deleted @@ -826,6 +828,7 @@ GET /api/v1/notes/{pid} PATCH /api/v1/notes/{pid} DELETE /api/v1/notes/{pid} POST /api/v1/notes/{pid}/move +POST /api/v1/notes/{pid}/copy PUT /api/v1/notes/{pid}/pin DELETE /api/v1/notes/{pid}/pin GET /api/v1/notes/{pid}/markdown @@ -840,7 +843,9 @@ DELETE /api/v1/notes/{pid}/files Note pages ([Notes](notes.md)), apart from the notes on an asset above. `GET /notes?ns=` is a namespace's page tree (`all=true` adds the pages of things). `today` gives the namespace's note for `date`, made the first time it's asked -for ([Today's note](notes.md#todays-note)). `search?q=` finds pages by the words in their title, summary or text, title +for ([Today's note](notes.md#todays-note)). `templates` lists the notes inside the namespace's Templates note, and +`POST /notes/templates` makes that note the first time; `copy` makes a new note from a page, with its text, drawings, +files and filing ([Templates](notes.md#templates)). `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 diff --git a/docs/notes.md b/docs/notes.md index fa672d27a..9a8dd6fe4 100644 --- a/docs/notes.md +++ b/docs/notes.md @@ -128,7 +128,8 @@ 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**), pins it ([below](#pinned-notes)), downloads it as Markdown and +by name, Enter picks the first; **Move to the top**), makes a copy beside it ("Copy of …", with its text, drawings +and files), pins it ([below](#pinned-notes)), downloads it as Markdown 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. @@ -143,6 +144,17 @@ day in the namespace in view, made the first time it's asked for: titled with th everyone there shares; rename or move it like any note. `POST /api/v1/notes/today` with `{ns, date}` (editors) gives the same note to agents. +## Templates + +Each note inside a namespace's **Templates** note is a template. **New note from a template…** in the Notes page's +**⋯** menu, or the same action in Jump to (⌘K), lists them: type to find one, Enter takes the first. The new note has the +template's title (selected, to type over), text, drawings, files, filing and view, and goes at the top of the tree. +With no templates yet, the same place makes the Templates note. + +`GET /api/v1/notes/templates?ns=` lists a namespace's templates; `POST /api/v1/notes/templates` with `{ns}` gives its +Templates note, made the first time; `POST /api/v1/notes/{pid}/copy` with optional `{title, parent}` makes a new note +from any page (editors). + ## 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 diff --git a/docs/requirements.md b/docs/requirements.md index d3670a383..f75063876 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -147,6 +147,8 @@ request, to another check that proves the same thing; loosening a requirement or | A two-host podcast episode, every claim cited and checked against its source, in two voices | [test_podcasts.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/domain/test_podcasts.py) `test_episode_is_made_by_a_job`, `test_fact_check_rewrites_or_drops`, `test_episode_gets_two_voices`; [journeys.mjs](https://github.com/adeelahmad/lense/blob/main/ci/clicks/journeys.mjs) `podcast-create`; [baseline.json](https://github.com/adeelahmad/lense/blob/main/ci/clicks/baseline.json) `podcast-create` ≤ 5 clicks | | Notes beside every asset, entity and topic, written by you or the assistant | [test_notebook.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_notebook.py) `test_pages_of_things`, `test_links_and_backlinks`, `test_assistant_keeps_notes`; [journeys.mjs](https://github.com/adeelahmad/lense/blob/main/ci/clicks/journeys.mjs) `note-create` | | A tree of notes renamed, moved and pinned (pins are your own), today's note one click away, and a search | [test_notebook.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_notebook.py) `test_tree`, `test_pins`, `test_search`; [notes-tree.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/notes-tree.test.tsx); [notes-today.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/notes-today.test.tsx) `is one click from the Notes page` | +| A note, or all of a namespace's notes, downloaded as Markdown in folders that follow the tree | [test_notebook.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_notebook.py) `test_markdown_export`; [notes-tree.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/notes-tree.test.tsx) `downloads a note as Markdown`; [notes-find.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/notes-find.test.tsx) `downloads every note as Markdown from its menu` | +| Templates a note starts from, and a copy of any note | [test_notebook.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_notebook.py) `test_templates_and_copies`; [notes-templates.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/notes-templates.test.tsx); [notes-tree.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/notes-tree.test.tsx) `makes a copy beside the note and opens it` | | Undo and Recently deleted instead of a confirm | [test_notebook.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_notebook.py) `test_recently_deleted`; [notes-delete.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/notes-delete.test.tsx) | | An asset or a collection exported as an evidence PDF, whole or the parts you pick | [test_evidence.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_evidence.py) `test_a_collection_as_one_evidence_pdf`, `test_everything_lens_found_goes_in`, `test_picking_the_parts`; [evidence-parts.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/evidence-parts.test.tsx) | diff --git a/fastapi_backend/app/api/v1/routes/notebook.py b/fastapi_backend/app/api/v1/routes/notebook.py index 43218d06c..d9ba3bbd5 100644 --- a/fastapi_backend/app/api/v1/routes/notebook.py +++ b/fastapi_backend/app/api/v1/routes/notebook.py @@ -23,6 +23,7 @@ from app.domain.store import DB from app.schemas.common import Ok from app.schemas.notebook import ( + NoteCopy, NoteDeleted, NoteFile, NoteHistory, @@ -37,6 +38,9 @@ NotePageMove, NotePageUpdate, NoteSearch, + NoteTemplate, + NoteTemplates, + NoteTemplatesCreate, NoteToday, NoteTree, NoteVersion, @@ -128,6 +132,26 @@ def today_page(body: NoteToday, user: Writer, acl: Acl, db: Db) -> NotePage: return _out(acl, db, notebook.get(db, pid), user) +@router.get("/templates") +def list_templates(ns: str, user: CurrentUser, acl: Acl, db: Db) -> NoteTemplates: + """The namespace's templates: the notes inside its "Templates" note, in the tree's order. Start a note from one + with `POST /notes/{pid}/copy`.""" + sid = acl.namespace(ns) + return NoteTemplates( + namespace=ns, root=notebook.templates_root(db, sid), templates=[NoteTemplate(**t) for t in notebook.templates(db, sid)] + ) + + +@router.post("/templates") +def templates_note(body: NoteTemplatesCreate, user: Writer, acl: Acl, db: Db) -> NotePage: + """The namespace's "Templates" note, made the first time it's asked for: each note put inside it is a template. + Needs editor access.""" + sid = acl.namespace(body.ns, "editor") + with domain_errors(): + pid = notebook.templates_root(db, sid, user.id) + return _out(acl, db, notebook.get(db, pid), user) + + @router.get("/targets") def link_targets( ns: str, user: CurrentUser, acl: Acl, db: Db, q: str = "", sign: str = "@", limit: int = Query(20, ge=1, le=50) @@ -363,6 +387,16 @@ def move_page(pid: int, body: NotePageMove, user: Writer, acl: Acl, db: Db) -> N return _out(acl, db, notebook.get(db, pid), user) +@router.post("/{pid}/copy") +def copy_page(pid: int, body: NoteCopy, user: Writer, acl: Acl, db: Db, cfg: Cfg) -> NotePage: + """A new free note with this page's text, drawings, files, filing and view: a note started from a template, or a + copy. Titled `title` (default the page's), inside `parent` (default the top). Needs editor access.""" + _page(acl, db, pid, "editor") + with domain_errors(), _vault(): + new = notebook.copy(db, cfg, pid, user.id, body.title, body.parent) + return _out(acl, db, notebook.get(db, new), 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 diff --git a/fastapi_backend/app/domain/notebook.py b/fastapi_backend/app/domain/notebook.py index ba85995e8..7b968c715 100644 --- a/fastapi_backend/app/domain/notebook.py +++ b/fastapi_backend/app/domain/notebook.py @@ -30,6 +30,8 @@ import json import os import re +import shutil +import tempfile import zipfile from . import activity, store @@ -435,6 +437,63 @@ def today(db, sid, account, date=None): return pid +TEMPLATES_ROOT = "Templates" + + +def templates_root(db, sid, account=None): + """The id of the namespace's "Templates" note, whose notes are its templates; made when `account` is given and + there's none yet. None otherwise.""" + root = db.one("SELECT VALUE record::id(id) FROM note_page WHERE space = $s AND templates_root = true LIMIT 1", s=sid) + if root or account is None: + return int(root) if root else None + root = create( + db, sid, account, TEMPLATES_ROOT, "Each note inside this one is a template for new notes.", summary="Notes to start new notes from" + ) + db.q("UPDATE $r SET templates_root = true", r=R("note_page", root)) + return root + + +def templates(db, sid): + """The namespace's templates, the notes inside its "Templates" note, in the tree's order: [{id, title, summary}].""" + root = templates_root(db, sid) + if root is None: + return [] + rows = db.rows( + "SELECT record::id(id) AS id, title, summary, position FROM note_page WHERE space = $s AND parent = $p AND about = NONE", + s=sid, + p=root, + ) + rows.sort(key=lambda r: (r.get("position") or 0, r["id"])) + return [{"id": r["id"], "title": r["title"], "summary": r.get("summary")} for r in rows] + + +def copy(db, cfg, pid, account, title=None, parent=None): + """A new free note with page pid's text, drawings, files, filing and view: to start a note from a template, or + to make a copy. Titled `title` (default the page's), inside `parent` (default the top), dated today. Its id.""" + p = get(db, pid) + new = create( + db, + p["space"], + account, + title or p["title"], + p.get("body") or "", + place=p.get("place"), + parent=parent, + doc=p.get("doc"), + view=p.get("view"), + ) + # the editor's images and attachments, under the same keys, so the copied drawings and pictures find them + to = get(db, new) + for f in files(db, pid): + _, opened = open_file(db, cfg, pid, f["key"]) + with opened as src, tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "file") + with open(path, "wb") as out: + shutil.copyfileobj(src, out) + add_file(db, cfg, to, f["key"], path, f.get("name"), f.get("type"), account) + return new + + PINS_MAX = 50 # a person's pinned notes, per namespace diff --git a/fastapi_backend/app/schemas/notebook.py b/fastapi_backend/app/schemas/notebook.py index 0b806a575..3837a730f 100644 --- a/fastapi_backend/app/schemas/notebook.py +++ b/fastapi_backend/app/schemas/notebook.py @@ -154,6 +154,27 @@ class NoteToday(RequestModel): date: str | None = Field(None, description="YYYY-MM-DD, your today (default: the server's)") +class NoteTemplate(ResponseModel): + id: int + title: str + summary: str | None = None + + +class NoteTemplates(ResponseModel): + namespace: str + root: int | None = Field(None, description='the "Templates" note: each note inside it is a template; null until made') + templates: list[NoteTemplate] + + +class NoteTemplatesCreate(RequestModel): + ns: str = Field(description="the namespace whose Templates note to make") + + +class NoteCopy(RequestModel): + title: str | None = Field(None, min_length=1, max_length=200, description="its title (default: the page's)") + parent: int | None = Field(None, description="put it inside this page (default: the top)") + + class NotePageMove(RequestModel): parent: int | None = Field(None, description="the page to put it inside; null for the top") before: int | None = Field(None, description="put it before this sibling; null for the end") diff --git a/fastapi_backend/tests/api/test_notebook.py b/fastapi_backend/tests/api/test_notebook.py index 061c77d27..6e8cb0368 100644 --- a/fastapi_backend/tests/api/test_notebook.py +++ b/fastapi_backend/tests/api/test_notebook.py @@ -593,6 +593,46 @@ def test_daily_notes(client, env, db): assert again["parent"] not in (None, root["id"]) +def test_templates_and_copies(client, env, db, cfg, folder): + """Notes inside the Templates note are templates; a copy of one, or of any note, has its text, files and filing.""" + he, hv = env["he"], env["hv"] + assert client.get("/api/v1/notes/templates?ns=pods", headers=hv).json() == {"namespace": "pods", "root": None, "templates": []} + assert client.post("/api/v1/notes/templates", headers=hv, json={"ns": "pods"}).status_code == 403 + root = client.post("/api/v1/notes/templates", headers=he, json={"ns": "pods"}).json() + assert (root["title"], root["parent"]) == ("Templates", None) + assert client.post("/api/v1/notes/templates", headers=he, json={"ns": "pods"}).json()["id"] == root["id"] # one + body = f"## Agenda\n\n- [ ] \n\nSee @[the call](recording:{env['a']})." + meeting = _new(client, he, title="Meeting", body=body, summary="For weekly calls", place="area", parent=root["id"]) + _new(client, he, title="Trip", parent=root["id"]) + got = client.get("/api/v1/notes/templates?ns=pods", headers=hv).json() + assert got["root"] == root["id"] + assert [(t["title"], t["summary"]) for t in got["templates"]] == [("Meeting", "For weekly calls"), ("Trip", None)] + # an image in the template comes with it, under the same key + png = b"\x89PNG\r\n\x1a\n" + b"pixels" * 50 + key = base64.urlsafe_b64encode(hashlib.sha256(png).digest()).decode() + r = client.put( + f"/api/v1/notes/{meeting['id']}/blobs", + params={"key": key, "name": "logo.png"}, + content=png, + headers={**he, "Content-Type": "image/png"}, + ) + assert r.status_code == 200, r.text + r = client.post(f"/api/v1/notes/{meeting['id']}/copy", headers=he, json={}) + assert r.status_code == 200, r.text + new = r.json() + assert new["id"] != meeting["id"] and (new["title"], new["body"], new["place"], new["parent"]) == ("Meeting", body, "area", None) + assert new["summary"] is None and new["author"] == "person" + assert [x["target"] for x in new["links"]] == [f"recording:{env['a']}"] + assert client.get(f"/api/v1/notes/{new['id']}/blobs", params={"key": key}, headers=hv).content == png + # a copy of any note, titled and placed + inside = client.post(f"/api/v1/notes/{new['id']}/copy", headers=he, json={"title": "Copy", "parent": new["id"]}).json() + assert (inside["title"], inside["parent"]) == ("Copy", new["id"]) + # editors only; other namespaces' notes can't be a parent + assert client.post(f"/api/v1/notes/{meeting['id']}/copy", headers=hv, json={}).status_code == 403 + other = notebook.create(db, store.ns_id(db, "calls"), None, "Elsewhere") + assert client.post(f"/api/v1/notes/{meeting['id']}/copy", headers=he, json={"parent": other}).status_code == 400 + + def test_markdown_export(client, env, db): import io import zipfile diff --git a/nextjs-frontend/__tests__/notes-find.test.tsx b/nextjs-frontend/__tests__/notes-find.test.tsx index 46e17675f..7574878f2 100644 --- a/nextjs-frontend/__tests__/notes-find.test.tsx +++ b/nextjs-frontend/__tests__/notes-find.test.tsx @@ -13,12 +13,19 @@ jest.mock("@/app/openapi-client", () => ({ searchPages: jest.fn(), createPage: jest.fn(), deletedPages: jest.fn(() => Promise.resolve({ data: [], response: { ok: true, status: 200 } })), + listTemplates: jest.fn(), + copyPage: jest.fn(), }, Resources: { listRecordings: jest.fn(() => Promise.resolve({ data: [], response: { ok: true, status: 200 } })) }, })); jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: "t" } }) })); const push = jest.fn(); -jest.mock("next/navigation", () => ({ usePathname: () => "/notes", useRouter: () => ({ push }) })); +let search = ""; +jest.mock("next/navigation", () => ({ + usePathname: () => "/notes", + useRouter: () => ({ push }), + useSearchParams: () => new URLSearchParams(search), +})); jest.mock("@/components/ui/toast", () => ({ useToast: () => jest.fn() })); const download = jest.fn, [string, string | undefined, string]>(() => Promise.resolve()); jest.mock("@/components/library/actions", () => ({ @@ -124,6 +131,24 @@ describe("the Notes page", () => { await waitFor(() => expect(download).toHaveBeenCalledWith("/api/v1/notes/export?ns=home", "t", "home notes.zip")); }); + it("starts a note from a template, from its menu or Jump to's link", async () => { + m(Notes.listTemplates).mockImplementation(() => + ok({ namespace: "home", root: 1, templates: [{ id: 5, title: "Meeting" }] }), + ); + m(Notes.copyPage).mockImplementation(() => ok({ id: 8, title: "Meeting" })); + const first = show(); + fireEvent.keyDown(await screen.findByRole("button", { name: "More on Notes" }), { key: "Enter" }); + fireEvent.click(await screen.findByRole("menuitem", { name: "New note from a template…" })); + fireEvent.keyDown(await screen.findByRole("combobox", { name: "Template" }), { key: "Enter" }); + await waitFor(() => expect(push).toHaveBeenCalledWith("/notes/8?new=1")); + expect(m(Notes.copyPage).mock.calls[0][0].path).toEqual({ pid: 5 }); + first.unmount(); + search = "template"; + show(); + expect(await screen.findByRole("combobox", { name: "Template" })).toBeInTheDocument(); + search = ""; + }); + 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-templates.test.tsx b/nextjs-frontend/__tests__/notes-templates.test.tsx new file mode 100644 index 000000000..579b3d752 --- /dev/null +++ b/nextjs-frontend/__tests__/notes-templates.test.tsx @@ -0,0 +1,74 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import "@testing-library/jest-dom"; + +import { Notes } from "@/app/openapi-client"; +import { TemplatePicker } from "@/components/notes/templates"; + +jest.mock("@/app/openapi-client", () => ({ + Notes: { listTemplates: jest.fn(), templatesNote: jest.fn(), copyPage: jest.fn() }, +})); +jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: "t" } }) })); +const push = jest.fn(); +jest.mock("next/navigation", () => ({ useRouter: () => ({ push }) })); +const toast = jest.fn(); +jest.mock("@/components/ui/toast", () => ({ useToast: () => toast })); + +const ok = (data: unknown) => Promise.resolve({ data, response: { ok: true, status: 200 } }); +const m = (f: unknown) => f as jest.Mock; +const show = (ui: React.ReactNode) => + render( + + {ui} + , + ); + +beforeAll(() => { + Element.prototype.scrollIntoView = jest.fn(); +}); +beforeEach(() => jest.clearAllMocks()); + +describe("new note from a template", () => { + it("finds a template as you type, and Enter starts a note from the first", async () => { + m(Notes.listTemplates).mockImplementation(() => + ok({ + namespace: "home", + root: 1, + templates: [ + { id: 2, title: "Meeting", summary: "For weekly calls" }, + { id: 3, title: "Trip" }, + ], + }), + ); + m(Notes.copyPage).mockImplementation(() => ok({ id: 9, title: "Trip" })); + const onClose = jest.fn(); + show(); + const box = await screen.findByRole("combobox", { name: "Template" }); + expect(await screen.findByText("Meeting")).toBeInTheDocument(); + expect(screen.getByText("For weekly calls")).toBeInTheDocument(); + fireEvent.change(box, { target: { value: "tri" } }); + await waitFor(() => expect(screen.queryByText("Meeting")).not.toBeInTheDocument()); + fireEvent.keyDown(box, { key: "Enter" }); + await waitFor(() => expect(push).toHaveBeenCalledWith("/notes/9?new=1")); + expect(m(Notes.copyPage).mock.calls[0][0]).toMatchObject({ path: { pid: 3 }, body: { title: null, parent: null } }); + await waitFor(() => expect(onClose).toHaveBeenCalled()); + }); + + it("with no templates yet, makes the Templates note and opens it", async () => { + m(Notes.listTemplates).mockImplementation(() => ok({ namespace: "home", root: null, templates: [] })); + m(Notes.templatesNote).mockImplementation(() => ok({ id: 4, title: "Templates" })); + show(); + expect(await screen.findByText(/A template is any note inside the Templates note/)).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Make the Templates note" })); + await waitFor(() => expect(push).toHaveBeenCalledWith("/notes/4")); + expect(m(Notes.templatesNote).mock.calls[0][0].body).toEqual({ ns: "home" }); + }); + + it("with an empty Templates note, opens it", async () => { + m(Notes.listTemplates).mockImplementation(() => ok({ namespace: "home", root: 4, templates: [] })); + show(); + fireEvent.click(await screen.findByRole("button", { name: "Open the Templates note" })); + expect(push).toHaveBeenCalledWith("/notes/4"); + expect(Notes.templatesNote).not.toHaveBeenCalled(); + }); +}); diff --git a/nextjs-frontend/__tests__/notes-today.test.tsx b/nextjs-frontend/__tests__/notes-today.test.tsx index d2e0e79c5..b5a6b2467 100644 --- a/nextjs-frontend/__tests__/notes-today.test.tsx +++ b/nextjs-frontend/__tests__/notes-today.test.tsx @@ -18,7 +18,10 @@ jest.mock("@/app/openapi-client", () => ({ })); jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: "t" } }) })); const replace = jest.fn(); -jest.mock("next/navigation", () => ({ useRouter: () => ({ replace, push: jest.fn() }) })); +jest.mock("next/navigation", () => ({ + useRouter: () => ({ replace, push: jest.fn() }), + useSearchParams: () => new URLSearchParams(), +})); jest.mock("@/components/ui/toast", () => ({ useToast: () => jest.fn() })); let roles: Record = { home: "editor", pods: "viewer" }; let picked: string | null = "home"; diff --git a/nextjs-frontend/__tests__/notes-tree.test.tsx b/nextjs-frontend/__tests__/notes-tree.test.tsx index 1e2495bcc..592630480 100644 --- a/nextjs-frontend/__tests__/notes-tree.test.tsx +++ b/nextjs-frontend/__tests__/notes-tree.test.tsx @@ -15,6 +15,7 @@ jest.mock("@/app/openapi-client", () => ({ restoreDeleted: jest.fn(), pinPage: jest.fn(), unpinPage: jest.fn(), + copyPage: jest.fn(), }, })); jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: "t" } }) })); @@ -118,6 +119,18 @@ describe("the notes tree", () => { expect(m(Notes.createPage).mock.calls[0][0].body).toMatchObject({ ns: "home", parent: 4 }); }); + it("makes a copy beside the note and opens it", async () => { + m(Notes.copyPage).mockImplementation(() => ok({ id: 10, title: "Copy of Pi 5 shopping list" })); + localStorage.setItem("lens.notes.open", "[1]"); + show(); + await choose("Pi 5 shopping list", "Make a copy"); + await waitFor(() => expect(push).toHaveBeenCalledWith("/notes/10?new=1")); + expect(m(Notes.copyPage).mock.calls[0][0]).toMatchObject({ + path: { pid: 2 }, + body: { title: "Copy of Pi 5 shopping list", parent: 1 }, + }); + }); + it("deletes a note with Undo on the notice, and leaves it when it was open", async () => { pathname = "/notes/4"; m(Notes.deletePage).mockImplementation(() => ok({ ok: true })); diff --git a/nextjs-frontend/app/openapi-client/index.ts b/nextjs-frontend/app/openapi-client/index.ts index 54ca13c0f..e8ca1b083 100644 --- a/nextjs-frontend/app/openapi-client/index.ts +++ b/nextjs-frontend/app/openapi-client/index.ts @@ -427,6 +427,11 @@ export type { ControlWorkerResponses, ConversionNodeTestResult, Converters, + CopyPageData, + CopyPageError, + CopyPageErrors, + CopyPageResponse, + CopyPageResponses, CopyWork, CountApprovalsData, CountApprovalsResponse, @@ -2017,7 +2022,12 @@ export type { ListTagsErrors, ListTagsResponse, ListTagsResponses, + ListTemplates2Data, + ListTemplates2Response, + ListTemplates2Responses, ListTemplatesData, + ListTemplatesError, + ListTemplatesErrors, ListTemplatesResponse, ListTemplatesResponses, ListTokensData, @@ -2244,6 +2254,7 @@ export type { NodeType, Note, NoteBacklink, + NoteCopy, NoteCreate, NoteDeleted, NoteFile, @@ -2260,6 +2271,9 @@ export type { NotePageMove, NotePageUpdate, NoteSearch, + NoteTemplate, + NoteTemplates, + NoteTemplatesCreate, NoteToday, NoteTree, NoteUpdate, @@ -3204,6 +3218,11 @@ export type { TemplatePreviewIn, TemplatePreviewOut, TemplatePreviewRequest, + TemplatesNoteData, + TemplatesNoteError, + TemplatesNoteErrors, + TemplatesNoteResponse, + TemplatesNoteResponses, TemplateSummary, TemplateUpdate, TemplateVersionCreate, diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index 2365f8277..d63e38c7b 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -145,6 +145,9 @@ import type { ControlWorkerData, ControlWorkerErrors, ControlWorkerResponses, + CopyPageData, + CopyPageErrors, + CopyPageResponses, CountApprovalsData, CountApprovalsResponses, CreateAutomationData, @@ -1014,7 +1017,10 @@ import type { ListTagsData, ListTagsErrors, ListTagsResponses, + ListTemplates2Data, + ListTemplates2Responses, ListTemplatesData, + ListTemplatesErrors, ListTemplatesResponses, ListTokensData, ListTokensResponses, @@ -1523,6 +1529,9 @@ import type { TelegramStatusResponses, TelemetryStatusData, TelemetryStatusResponses, + TemplatesNoteData, + TemplatesNoteErrors, + TemplatesNoteResponses, TestAnalyticsData, TestAnalyticsResponses, TestAutomationData, @@ -5879,6 +5888,40 @@ export class Notes { }); } + /** + * List Templates + * + * The namespace's templates: the notes inside its "Templates" note, in the tree's order. Start a note from one + * with `POST /notes/{pid}/copy`. + */ + public static listTemplates( + options: Options, + ): RequestResult { + return (options.client ?? client).get({ + url: "/api/v1/notes/templates", + ...options, + }); + } + + /** + * Templates Note + * + * The namespace's "Templates" note, made the first time it's asked for: each note put inside it is a template. + * Needs editor access. + */ + public static templatesNote( + options: Options, + ): RequestResult { + return (options.client ?? client).post({ + url: "/api/v1/notes/templates", + ...options, + headers: { + "Content-Type": "application/json", + ...options.headers, + }, + }); + } + /** * Link Targets * @@ -6133,6 +6176,25 @@ export class Notes { }); } + /** + * Copy Page + * + * A new free note with this page's text, drawings, files, filing and view: a note started from a template, or a + * copy. Titled `title` (default the page's), inside `parent` (default the top). Needs editor access. + */ + public static copyPage( + options: Options, + ): RequestResult { + return (options.client ?? client).post({ + url: "/api/v1/notes/{pid}/copy", + ...options, + headers: { + "Content-Type": "application/json", + ...options.headers, + }, + }); + } + /** * Unpin Page * @@ -9181,9 +9243,9 @@ export class Templates { * List Templates */ public static listTemplates( - options?: Options, - ): RequestResult { - return (options?.client ?? client).get({ + options?: Options, + ): RequestResult { + return (options?.client ?? client).get({ url: "/api/v1/templates", ...options, }); diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index 0b7e5f461..8d0de2518 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -12618,6 +12618,24 @@ export type NoteBacklink = { [key: string]: unknown; }; +/** + * NoteCopy + */ +export type NoteCopy = { + /** + * Title + * + * its title (default: the page's) + */ + title?: string | null; + /** + * Parent + * + * put it inside this page (default: the top) + */ + parent?: number | null; +}; + /** * NoteCreate */ @@ -13282,6 +13300,58 @@ export type NoteSearch = { [key: string]: unknown; }; +/** + * NoteTemplate + */ +export type NoteTemplate = { + /** + * Id + */ + id: number; + /** + * Title + */ + title: string; + /** + * Summary + */ + summary?: string | null; + [key: string]: unknown; +}; + +/** + * NoteTemplates + */ +export type NoteTemplates = { + /** + * Namespace + */ + namespace: string; + /** + * Root + * + * the "Templates" note: each note inside it is a template; null until made + */ + root?: number | null; + /** + * Templates + */ + templates: Array; + [key: string]: unknown; +}; + +/** + * NoteTemplatesCreate + */ +export type NoteTemplatesCreate = { + /** + * Ns + * + * the namespace whose Templates note to make + */ + ns: string; +}; + /** * NoteToday */ @@ -31359,6 +31429,61 @@ export type TodayPageResponses = { export type TodayPageResponse = TodayPageResponses[keyof TodayPageResponses]; +export type ListTemplatesData = { + body?: never; + path?: never; + query: { + /** + * Ns + */ + ns: string; + }; + url: "/api/v1/notes/templates"; +}; + +export type ListTemplatesErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type ListTemplatesError = ListTemplatesErrors[keyof ListTemplatesErrors]; + +export type ListTemplatesResponses = { + /** + * Successful Response + */ + 200: NoteTemplates; +}; + +export type ListTemplatesResponse = ListTemplatesResponses[keyof ListTemplatesResponses]; + +export type TemplatesNoteData = { + body: NoteTemplatesCreate; + path?: never; + query?: never; + url: "/api/v1/notes/templates"; +}; + +export type TemplatesNoteErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type TemplatesNoteError = TemplatesNoteErrors[keyof TemplatesNoteErrors]; + +export type TemplatesNoteResponses = { + /** + * Successful Response + */ + 200: NotePage; +}; + +export type TemplatesNoteResponse = TemplatesNoteResponses[keyof TemplatesNoteResponses]; + export type LinkTargetsData = { body?: never; path?: never; @@ -31932,6 +32057,36 @@ export type MovePageResponses = { export type MovePageResponse = MovePageResponses[keyof MovePageResponses]; +export type CopyPageData = { + body: NoteCopy; + path: { + /** + * Pid + */ + pid: number; + }; + query?: never; + url: "/api/v1/notes/{pid}/copy"; +}; + +export type CopyPageErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type CopyPageError = CopyPageErrors[keyof CopyPageErrors]; + +export type CopyPageResponses = { + /** + * Successful Response + */ + 200: NotePage; +}; + +export type CopyPageResponse = CopyPageResponses[keyof CopyPageResponses]; + export type UnpinPageData = { body?: never; path: { @@ -38020,14 +38175,14 @@ export type ScanWatchResponses = { export type ScanWatchResponse = ScanWatchResponses[keyof ScanWatchResponses]; -export type ListTemplatesData = { +export type ListTemplates2Data = { body?: never; path?: never; query?: never; url: "/api/v1/templates"; }; -export type ListTemplatesResponses = { +export type ListTemplates2Responses = { /** * Response Templates-List Templates * @@ -38036,7 +38191,7 @@ export type ListTemplatesResponses = { 200: Array; }; -export type ListTemplatesResponse = ListTemplatesResponses[keyof ListTemplatesResponses]; +export type ListTemplates2Response = ListTemplates2Responses[keyof ListTemplates2Responses]; export type CreateTemplateData = { body: TemplateCreate; diff --git a/nextjs-frontend/components/app-shell/command-palette.tsx b/nextjs-frontend/components/app-shell/command-palette.tsx index a45dbc19d..6249be150 100644 --- a/nextjs-frontend/components/app-shell/command-palette.tsx +++ b/nextjs-frontend/components/app-shell/command-palette.tsx @@ -87,6 +87,12 @@ export function CommandPalette() { href: "/notes/today", icon: , }, + { + group: "Actions", + label: "New note from a template", + href: "/notes?template", + icon: , + }, ] : []), { diff --git a/nextjs-frontend/components/notes/notes-home.tsx b/nextjs-frontend/components/notes/notes-home.tsx index f96496fdd..8e0b9175b 100644 --- a/nextjs-frontend/components/notes/notes-home.tsx +++ b/nextjs-frontend/components/notes/notes-home.tsx @@ -1,9 +1,20 @@ "use client"; import { keepPreviousData, useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query"; -import { CalendarDays, Download, Ellipsis, FileText, NotebookPen, Pin, Plus, Search, Sparkles } from "lucide-react"; +import { + CalendarDays, + Download, + Ellipsis, + FileText, + LayoutTemplate, + NotebookPen, + Pin, + Plus, + Search, + Sparkles, +} from "lucide-react"; import Link from "next/link"; -import { useRouter } from "next/navigation"; +import { useRouter, useSearchParams } from "next/navigation"; import { useMemo, useState } from "react"; import { Notes } from "@/app/openapi-client"; @@ -11,9 +22,10 @@ import type { NotePageItem } from "@/app/openapi-client/types.gen"; import { PLACES, pageOf } from "@/components/notes/links"; import { useNoteDownloads } from "@/components/notes/download"; import { RecentlyDeleted } from "@/components/notes/recently-deleted"; +import { TemplatePicker } from "@/components/notes/templates"; import { Button, IconButton } from "@/components/ui/button"; import { SearchInput } from "@/components/ui/field"; -import { Menu, MenuContent, MenuItem, MenuTrigger } from "@/components/ui/menu"; +import { Menu, MenuContent, MenuItem, MenuSeparator, MenuTrigger } from "@/components/ui/menu"; import { EmptyState, PageHeader, SkeletonRows } from "@/components/ui/states"; import { Segmented } from "@/components/ui/tabs"; import { useToast } from "@/components/ui/toast"; @@ -99,6 +111,8 @@ export function NotesHome() { ) : null; const downloads = useNoteDownloads(); + // A new note from a template (Jump to's action opens /notes?template) + const [picking, setPicking] = useState(useSearchParams().has("template")); // Every namespace's notes as Markdown, for other notes apps const more = names.length > 0 ? ( @@ -109,6 +123,14 @@ export function NotesHome() { + {editable && ( + <> + } onSelect={() => setPicking(true)}> + New note from a template… + + + + )} {names.map((ns) => ( } onSelect={() => void downloads.all(ns)}> {names.length > 1 ? `Download ${ns}’s notes as Markdown` : "Download all as Markdown"} @@ -260,6 +282,15 @@ export function NotesHome() { )} + {picking && editable && ( + { + setPicking(false); + if (window.location.search) window.history.replaceState(window.history.state, "", "/notes"); + }} + /> + )} ); } diff --git a/nextjs-frontend/components/notes/notes-tree.tsx b/nextjs-frontend/components/notes/notes-tree.tsx index ef67d33d9..30164e441 100644 --- a/nextjs-frontend/components/notes/notes-tree.tsx +++ b/nextjs-frontend/components/notes/notes-tree.tsx @@ -4,6 +4,7 @@ import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/rea import { ArrowUpToLine, ChevronRight, + Copy, Download, Ellipsis, FileText, @@ -24,6 +25,7 @@ import type { NotePageItem as PageItem } from "@/app/openapi-client/types.gen"; import { useDeleteNote } from "@/components/notes/delete"; import { useNoteDownloads } from "@/components/notes/download"; import { usePin } from "@/components/notes/pin"; +import { useCopyNote } from "@/components/notes/templates"; import { Dialog } from "@/components/ui/dialog"; import { FindBox } from "@/components/ui/find-box"; import { Menu, MenuContent, MenuItem, MenuSeparator, MenuTrigger } from "@/components/ui/menu"; @@ -191,6 +193,7 @@ function NamespaceNotes({ const deleteNote = useDeleteNote(); const pin = usePin(); const downloads = useNoteDownloads(); + const copy = useCopyNote(); const pathname = usePathname(); const [renaming, setRenaming] = useState(null); const [moving, setMoving] = useState(null); @@ -208,6 +211,10 @@ function NamespaceNotes({ }, startMove: setMoving, pin: (p, on) => void pin(ns, p.id, on), + copy: (p) => + void copy(p.id, { title: `Copy of ${p.title}`.slice(0, 200), parent: p.parent ?? null }).then( + (id) => id != null && onNavigate?.(), + ), download: (p) => void downloads.note(p.id, p.title), remove: async (p) => { // deleting the note that's open leaves it for the Notes page @@ -300,6 +307,7 @@ type RowActions = { moveTo: (id: number, parent: number | null) => void; startMove: (page: PageItem) => void; pin: (page: PageItem, on: boolean) => void; + copy: (page: PageItem) => void; download: (page: PageItem) => void; remove: (page: PageItem) => void; }; @@ -486,6 +494,9 @@ function Node({ Move to the top )} + } onSelect={() => actions.copy(page)}> + Make a copy + )} {/* pins are each person's own, so viewers pin too */} diff --git a/nextjs-frontend/components/notes/templates.tsx b/nextjs-frontend/components/notes/templates.tsx new file mode 100644 index 000000000..bc6df4be1 --- /dev/null +++ b/nextjs-frontend/components/notes/templates.tsx @@ -0,0 +1,128 @@ +"use client"; + +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { useRouter } from "next/navigation"; +import { useCallback, useState } from "react"; + +import { Notes } from "@/app/openapi-client"; +import { Button } from "@/components/ui/button"; +import { Dialog } from "@/components/ui/dialog"; +import { FindBox } from "@/components/ui/find-box"; +import { useToast } from "@/components/ui/toast"; +import { ApiError, data, useApiClient } from "@/lib/api/browser"; + +/** Makes a new note from a page (a template, or any note to copy) with its text, drawings, files and filing, and + * opens it with its title selected, ready to type over. Resolves the new note's id, or null when it couldn't. */ +export function useCopyNote() { + const client = useApiClient(); + const qc = useQueryClient(); + const router = useRouter(); + const toast = useToast(); + return useCallback( + async (pid: number, opts: { title?: string; parent?: number | null } = {}) => { + try { + const p = await data( + Notes.copyPage({ client, path: { pid }, body: { title: opts.title ?? null, parent: opts.parent ?? null } }), + ); + qc.invalidateQueries({ queryKey: ["notes-tree"] }); + router.push(`/notes/${p.id}?new=1`); + return p.id; + } catch (err) { + toast({ + title: "Couldn’t make the note", + body: err instanceof ApiError ? err.message : "Please try again.", + tone: "red", + }); + return null; + } + }, + [client, qc, router, toast], + ); +} + +/** Picks one of a namespace's templates (the notes inside its Templates note) and starts a new note from it: type to + * find, Enter takes the first. With none yet, it offers to make the Templates note. */ +export function TemplatePicker({ ns, onClose }: { ns: string; onClose: () => void }) { + const client = useApiClient(); + const qc = useQueryClient(); + const router = useRouter(); + const toast = useToast(); + const copy = useCopyNote(); + const [q, setQ] = useState(""); + const [busy, setBusy] = useState(false); + const list = useQuery({ + queryKey: ["notes-templates", ns], + queryFn: () => data(Notes.listTemplates({ client, query: { ns } })), + }); + const words = q.trim().toLowerCase(); + const items = (list.data?.templates ?? []) + .filter((t) => !words || t.title.toLowerCase().includes(words)) + .map((t) => ({ id: t.id, name: t.title, meta: t.summary ?? undefined })); + const makeRoot = async () => { + setBusy(true); + try { + const root = await data(Notes.templatesNote({ client, body: { ns } })); + qc.invalidateQueries({ queryKey: ["notes-tree"] }); + onClose(); + router.push(`/notes/${root.id}`); + } catch (err) { + toast({ + title: "Couldn’t make the Templates note", + body: err instanceof ApiError ? err.message : "Please try again.", + tone: "red", + }); + } finally { + setBusy(false); + } + }; + const none = list.isSuccess && !list.data.templates.length; + return ( + !o && onClose()} + title="New note from a template" + description={ + none + ? "A template is any note inside the Templates note: put notes there to start new ones from them." + : undefined + } + actions={ + none && !list.data.root ? ( + + ) : none && list.data.root ? ( + + ) : undefined + } + > + {!none && ( + { + setBusy(true); + if ((await copy(it.id)) != null) onClose(); + setBusy(false); + }} + onCancel={onClose} + placeholder="The template to start from" + label="Template" + autoFocus + busy={busy} + /> + )} + + ); +} diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index 672c03188..7777c7e6d 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -11688,6 +11688,89 @@ } } }, + "/api/v1/notes/templates": { + "get": { + "tags": [ + "notes" + ], + "summary": "List Templates", + "description": "The namespace's templates: the notes inside its \"Templates\" note, in the tree's order. Start a note from one\nwith `POST /notes/{pid}/copy`.", + "operationId": "list_templates", + "parameters": [ + { + "name": "ns", + "in": "query", + "required": true, + "schema": { + "type": "string", + "title": "Ns" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NoteTemplates" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "post": { + "tags": [ + "notes" + ], + "summary": "Templates Note", + "description": "The namespace's \"Templates\" note, made the first time it's asked for: each note put inside it is a template.\nNeeds editor access.", + "operationId": "templates_note", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NoteTemplatesCreate" + } + } + } + }, + "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/targets": { "get": { "tags": [ @@ -12601,6 +12684,59 @@ } } }, + "/api/v1/notes/{pid}/copy": { + "post": { + "tags": [ + "notes" + ], + "summary": "Copy Page", + "description": "A new free note with this page's text, drawings, files, filing and view: a note started from a template, or a\ncopy. Titled `title` (default the page's), inside `parent` (default the top). Needs editor access.", + "operationId": "copy_page", + "parameters": [ + { + "name": "pid", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "title": "Pid" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NoteCopy" + } + } + } + }, + "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}/pin": { "put": { "tags": [ @@ -52412,6 +52548,39 @@ ], "title": "NoteBacklink" }, + "NoteCopy": { + "properties": { + "title": { + "anyOf": [ + { + "type": "string", + "maxLength": 200, + "minLength": 1 + }, + { + "type": "null" + } + ], + "title": "Title", + "description": "its title (default: the page's)" + }, + "parent": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Parent", + "description": "put it inside this page (default: the top)" + } + }, + "additionalProperties": false, + "type": "object", + "title": "NoteCopy" + }, "NoteCreate": { "properties": { "text": { @@ -53657,6 +53826,85 @@ ], "title": "NoteSearch" }, + "NoteTemplate": { + "properties": { + "id": { + "type": "integer", + "title": "Id" + }, + "title": { + "type": "string", + "title": "Title" + }, + "summary": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Summary" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "id", + "title" + ], + "title": "NoteTemplate" + }, + "NoteTemplates": { + "properties": { + "namespace": { + "type": "string", + "title": "Namespace" + }, + "root": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Root", + "description": "the \"Templates\" note: each note inside it is a template; null until made" + }, + "templates": { + "items": { + "$ref": "#/components/schemas/NoteTemplate" + }, + "type": "array", + "title": "Templates" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "namespace", + "templates" + ], + "title": "NoteTemplates" + }, + "NoteTemplatesCreate": { + "properties": { + "ns": { + "type": "string", + "title": "Ns", + "description": "the namespace whose Templates note to make" + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "ns" + ], + "title": "NoteTemplatesCreate" + }, "NoteToday": { "properties": { "ns": {