Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 6 additions & 2 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.

Expand Down
14 changes: 11 additions & 3 deletions docs/notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
28 changes: 26 additions & 2 deletions fastapi_backend/app/api/v1/routes/notebook.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
Expand All @@ -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,
Expand All @@ -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("")
Expand Down Expand Up @@ -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
Expand Down
17 changes: 16 additions & 1 deletion fastapi_backend/app/domain/notebook.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)


Expand Down Expand Up @@ -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


Expand Down
1 change: 1 addition & 0 deletions fastapi_backend/app/schemas/notebook.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
31 changes: 31 additions & 0 deletions fastapi_backend/tests/api/test_notebook.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
12 changes: 12 additions & 0 deletions nextjs-frontend/__tests__/notes-find.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(<NotesHome />);
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(<NotesHome />);
Expand Down
40 changes: 39 additions & 1 deletion nextjs-frontend/__tests__/notes-tree.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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" } }) }));
Expand All @@ -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 } });
Expand Down Expand Up @@ -54,6 +57,7 @@ beforeEach(() => {
jest.clearAllMocks();
localStorage.clear();
pathname = "/notes";
editor = true;
m(Notes.listPages).mockImplementation(() => ok({ namespace: "home", pages: PAGES }));
});

Expand Down Expand Up @@ -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();
});
});
10 changes: 10 additions & 0 deletions nextjs-frontend/app/openapi-client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2147,6 +2147,11 @@ export type {
PhotoHit,
PhotoResults,
PickedLine,
PinPageData,
PinPageError,
PinPageErrors,
PinPageResponse,
PinPageResponses,
Pipeline,
PipelineCatalog,
PipelineCreate,
Expand Down Expand Up @@ -3094,6 +3099,11 @@ export type {
UnlockVaultErrors,
UnlockVaultResponse,
UnlockVaultResponses,
UnpinPageData,
UnpinPageError,
UnpinPageErrors,
UnpinPageResponse,
UnpinPageResponses,
UnsealVaultData,
UnsealVaultError,
UnsealVaultErrors,
Expand Down
35 changes: 35 additions & 0 deletions nextjs-frontend/app/openapi-client/sdk.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1060,6 +1060,9 @@ import type {
PasskeySetupOptionsErrors,
PasskeySetupOptionsResponses,
PasskeySetupResponses,
PinPageData,
PinPageErrors,
PinPageResponses,
PlaceRecordingsData,
PlaceRecordingsErrors,
PlaceRecordingsResponses,
Expand Down Expand Up @@ -1492,6 +1495,9 @@ import type {
UnlockVaultData,
UnlockVaultErrors,
UnlockVaultResponses,
UnpinPageData,
UnpinPageErrors,
UnpinPageResponses,
UnsealVaultData,
UnsealVaultErrors,
UnsealVaultResponses,
Expand Down Expand Up @@ -5390,6 +5396,35 @@ export class Notes {
});
}

/**
* Unpin Page
*
* Unpin the page for you.
*/
public static unpinPage<ThrowOnError extends boolean = false>(
options: Options<UnpinPageData, ThrowOnError>,
): RequestResult<UnpinPageResponses, UnpinPageErrors, ThrowOnError> {
return (options.client ?? client).delete<UnpinPageResponses, UnpinPageErrors, ThrowOnError>({
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<ThrowOnError extends boolean = false>(
options: Options<PinPageData, ThrowOnError>,
): RequestResult<PinPageResponses, PinPageErrors, ThrowOnError> {
return (options.client ?? client).put<PinPageResponses, PinPageErrors, ThrowOnError>({
url: "/api/v1/notes/{pid}/pin",
...options,
});
}

/**
* Delete Page File
*
Expand Down
Loading
Loading