From af021fc6dc5a38cc07e1082447677fd66c4af0c0 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Thu, 15 Oct 2026 08:05:35 +0000 Subject: [PATCH] feat(topics): merge and delete topics at once, with undo Merges and deletes keep what they changed in topic_change, so either can be taken back: the topics return with their ids, labels, recordings, broader and related lists and note pages, and a topic made from an entity hides it again. The drawer merges through a find box and deletes without a confirm dialog, with Undo on the notice; topics merge on the graph canvas too. GET /namespaces/{name}/topics/changes lists recent ones and POST /topics/changes/{id}/undo takes one back. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EzVhJCpwskyo5NhHEtS822 --- CHANGELOG.md | 5 + docs/graph.md | 2 +- docs/topics.md | 25 +- fastapi_backend/app/api/v1/routes/topics.py | 44 ++- fastapi_backend/app/domain/store.py | 3 + fastapi_backend/app/domain/topics.py | 178 +++++++++- fastapi_backend/app/schemas/topics.py | 20 +- fastapi_backend/tests/api/test_topics.py | 73 ++++- .../__tests__/graph-curate.test.ts | 9 +- .../__tests__/topics-curate.test.tsx | 110 +++++++ nextjs-frontend/app/openapi-client/index.ts | 13 + nextjs-frontend/app/openapi-client/sdk.gen.ts | 41 ++- .../app/openapi-client/types.gen.ts | 190 ++++++++++- .../components/entities/curate.tsx | 116 ++----- nextjs-frontend/components/graph/join.ts | 33 +- nextjs-frontend/components/topics/curate.tsx | 229 +++++++++++++ .../components/topics/topic-drawer.tsx | 131 ++------ nextjs-frontend/components/ui/find-box.tsx | 123 +++++++ nextjs-frontend/openapi.json | 310 +++++++++++++++++- 19 files changed, 1403 insertions(+), 252 deletions(-) create mode 100644 nextjs-frontend/__tests__/topics-curate.test.tsx create mode 100644 nextjs-frontend/components/topics/curate.tsx create mode 100644 nextjs-frontend/components/ui/find-box.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 6423ea713..bac839d46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,11 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version same editor as its own page, and an entity's has **Merge** and **Maybe the same**. The node menu has **Edit…** and **Merge into another…**, which merges the node into the one clicked next (entities and speakers of one namespace; entities of two namespaces are linked as the same thing), each with **Undo** ([The graph](docs/graph.md)). +- **Undo topic merges and deletes.** Merging or deleting a topic happens at once, with **Undo** on its notice instead + of a confirm step: the topics come back with their labels, recordings, broader and related topics and pages. A + topic's drawer has a find box to merge another topic in, and topics merge on the graph canvas too. The API answers + a merge or delete with an `undo` id (`POST /api/v1/topics/changes/{id}/undo`) and lists recent ones + ([Topics](docs/topics.md)). ## 0.9.0 October 15, 2026 {id="0.9.0"} diff --git a/docs/graph.md b/docs/graph.md index f8d6747c3..cb37aa396 100644 --- a/docs/graph.md +++ b/docs/graph.md @@ -27,7 +27,7 @@ to itself and has one. On a computer the Find in graph box has the focus, so typ topics), and an entity's has **Merge**, a find box where Enter merges the entity picked into it, and **Maybe the same**, its likely doubles. From the node menu, **Edit…** does the same and **Merge into another…** merges the node into the one you pick next: entities of one namespace are merged, entities of two namespaces are linked as the same - thing, and speakers of one namespace are merged. Each happens at once with **Undo** on its notice. A node that joins + thing, and speakers and topics of one namespace are merged. Each happens at once with **Undo** on its notice. A node that joins entities of several namespaces (all shared) offers **Edit in** each namespace. Looking at an earlier version, the graph is read-only. - **Route**: add stops from the node menu; the route follows the shortest path between each pair of stops, laid out diff --git a/docs/topics.md b/docs/topics.md index 5b1363248..3723f4aee 100644 --- a/docs/topics.md +++ b/docs/topics.md @@ -14,13 +14,16 @@ assistant and MCP tools for topics. **Topics** in the navigation shows a namespace's vocabulary as a tree: top topics first, each opening onto its narrower ones (a topic under two broader topics shows under both). Search finds topics by any of their labels. Pick a topic to edit it in a drawer: its labels, definition, broader and related topics, its narrower topics, and the -recordings about it, where suggested ones can be accepted or removed. The drawer also merges topics and deletes one. -Editors add topics at the top or under another with **+**. +recordings about it, where suggested ones can be accepted or removed. **Merge** in the drawer opens a find box: type +part of a label and pick (or press Enter) to merge that topic into this one at once. **Delete** deletes it at once. +Both say what they did with **Undo** on the message, so there is no confirm step. Editors add topics at the top or +under another with **+**. A recording's **Entities** tab starts with its topics: editors add one from the vocabulary, take one off, or accept or dismiss a suggestion. An entity of type Term has **Make a topic** in its drawer. On the graph canvas topics are green tags, with About, Narrower and Related edges; ask the graph (for example `MATCH (t:Topic) RETURN t`) or open a -recording's children to bring them in. +recording's children to bring them in. Editors edit a topic from the graph (**Edit…** on a node's menu, or **Edit** +in its panel) and merge one into another with **Merge into another…** and a click on the one to keep. ## A topic @@ -66,11 +69,16 @@ recordings join it. Deleting a topic moves its narrower topics up to its broader ones. Merging topics makes the others' labels the kept topic's other labels and brings their recordings over. +Either can be undone: the topics come back with their ids, labels, definitions, recordings and note pages, the +broader and related lists they were taken out of are put back, and a topic made from an entity hides that entity +again. Whatever changed since stays. Undo is refused when another topic has taken one of their labels meanwhile: +rename that one first. + ## Rights Reading needs a role in the namespace; changing the vocabulary or which recordings are about a topic needs the editor role there. Every change is in the audit log (`topic.create`, `topic.update`, `topic.delete`, `topic.merge`, -`topic.tag`, `topic.untag`, `topic.from_entity`). +`topic.tag`, `topic.untag`, `topic.from_entity`, `topic.merge.undo`, `topic.delete.undo`). ## The API @@ -80,8 +88,10 @@ role there. Every change is in the audit log (`topic.create`, `topic.update`, `t | `GET /api/v1/topics/{id}` | A topic with its broader, narrower and related topics and the recordings about it. | | `POST /api/v1/namespaces/{name}/topics` | Add a topic `{label, alt, definition, broader, related}`. | | `PATCH /api/v1/topics/{id}` | Change any of those; an empty definition clears it. | -| `DELETE /api/v1/topics/{id}` | Delete it. | -| `POST /api/v1/topics/merge` `{keep, others}` | Merge topics into one. | +| `DELETE /api/v1/topics/{id}` | Delete it; the answer's `undo` takes it back. | +| `POST /api/v1/topics/merge` `{keep, others}` | Merge topics into one; the answer's `undo` takes it back. | +| `GET /api/v1/namespaces/{name}/topics/changes` | The latest merges and deletes, newest first, each with whether it was undone. | +| `POST /api/v1/topics/changes/{id}/undo` | Take a merge or a delete back. | | `POST /api/v1/topics/{id}/recordings` `{recordings, remove}` | Say recordings are about it, or aren't. | | `GET /api/v1/resources/{id}/topics` | The topics a recording is about, and those suggested. | | `POST /api/v1/entities/{id}/topic` | Make a TERM entity a topic. | @@ -108,7 +118,8 @@ In RDF ([Linked data](rdf.md)) a topic is `/id/topic/`, a `skos:Concept` in - Vocabularies shared by several namespaces, and imported schemes (LCSH, Wikidata) linked with `skos:exactMatch`. - Entities as authority records: variant names and external identifiers. -- History and undo for topic merges and deletes. +- A page listing the latest topic merges and deletes, to undo one after its message has gone. +- Picking several topics on the Topics page to merge them in one go. ## Notes, the assistant and agents diff --git a/fastapi_backend/app/api/v1/routes/topics.py b/fastapi_backend/app/api/v1/routes/topics.py index 276c5e33c..0d6b9c186 100644 --- a/fastapi_backend/app/api/v1/routes/topics.py +++ b/fastapi_backend/app/api/v1/routes/topics.py @@ -15,10 +15,13 @@ from app.schemas.topics import ( RecordingTopic, TopicCandidate, + TopicChange, TopicCreate, + TopicDeleted, TopicDetail, TopicList, TopicMerge, + TopicMerged, TopicRecordings, TopicSkip, TopicUpdate, @@ -129,26 +132,51 @@ def update_topic(tid: int, body: TopicUpdate, request: Request, user: Writer, ac @router.delete("/topics/{tid}") -def delete_topic(tid: int, request: Request, user: Writer, acl: Acl, db: Db) -> Ok: - """Delete it: its narrower topics move up, recordings stop being about it, and an entity it was made from shows again.""" +def delete_topic(tid: int, request: Request, user: Writer, acl: Acl, db: Db) -> TopicDeleted: + """Delete it: its narrower topics move up, recordings stop being about it, and an entity it was made from shows + again. `undo` takes it back (POST /topics/changes/{undo}/undo).""" _topic_space(db, acl, tid, "curate") with domain_errors(): - eid = topics.delete(db, tid) + eid, cid = topics.delete(db, tid, user=user.email) auth.audit(db, user.as_audit(), "topic.delete", f"topic:{tid}", {"entity": eid} if eid else None) _changed(request) - return Ok() + return TopicDeleted(undo=cid) @router.post("/topics/merge") -def merge_topics(body: TopicMerge, request: Request, user: Writer, acl: Acl, db: Db) -> TopicDetail: - """Fold topics into one: their labels become its other labels and their recordings are about it.""" +def merge_topics(body: TopicMerge, request: Request, user: Writer, acl: Acl, db: Db) -> TopicMerged: + """Fold topics into one: their labels become its other labels and their recordings are about it. `undo` takes it + back (POST /topics/changes/{undo}/undo).""" for t in [body.keep, *body.others]: _topic_space(db, acl, t, "curate") with domain_errors(): - topics.merge(db, body.keep, body.others, user=user.email) + cid = topics.merge(db, body.keep, body.others, user=user.email) auth.audit(db, user.as_audit(), "topic.merge", f"topic:{body.keep}", {"others": body.others}) _changed(request) - return _detail(db, acl, body.keep) + return TopicMerged(**_detail(db, acl, body.keep).model_dump(), undo=cid) + + +@router.get("/namespaces/{name}/topics/changes") +def list_topic_changes(name: str, user: CurrentUser, acl: Acl, db: Db, limit: int = 50) -> list[TopicChange]: + """The namespace's latest topic merges and deletes, newest first, each with whether it was undone.""" + sid = acl.nsid(name) + acl.need(sid, "viewer") + return [TopicChange(**c) for c in topics.changes(db, sid, min(max(limit, 1), 200))] + + +@router.post("/topics/changes/{cid}/undo") +def undo_topic_change(cid: int, request: Request, user: Writer, acl: Acl, db: Db) -> Ok: + """Take back a merge or a delete: the topics come back with their labels, recordings and pages. What changed + since stays. Refused (400) when another topic has taken one of their labels meanwhile.""" + row = db.one("SELECT space FROM $r", r=R("topic_change", int(cid))) + if not row: + raise HTTPException(404, "not found") + acl.need(row["space"], "curate") + with domain_errors(): + out = topics.undo(db, cid, user=user.email) + auth.audit(db, user.as_audit(), f"topic.{out['kind']}.undo", f"topic_change:{cid}", {"topics": out["topics"]}) + _changed(request) + return Ok() @router.post("/topics/{tid}/recordings") diff --git a/fastapi_backend/app/domain/store.py b/fastapi_backend/app/domain/store.py index 61133a55e..669133df4 100644 --- a/fastapi_backend/app/domain/store.py +++ b/fastapi_backend/app/domain/store.py @@ -1142,6 +1142,9 @@ def close(self): "DEFINE INDEX IF NOT EXISTS topic_about_rec ON topic_about FIELDS recording", "DEFINE INDEX IF NOT EXISTS topic_about_topic ON topic_about FIELDS topic", "DEFINE INDEX IF NOT EXISTS topic_about_space ON topic_about FIELDS space", + # merges and deletes of topics, kept so they can be undone (app/domain/topics.py) + "DEFINE TABLE IF NOT EXISTS topic_change SCHEMALESS", + "DEFINE INDEX IF NOT EXISTS topic_change_space ON topic_change FIELDS space", # Note: on 2.x, CONTAINS against an indexed field also returns nothing; use string::contains() there. # settings, people and access "DEFINE TABLE IF NOT EXISTS app_setting SCHEMALESS", diff --git a/fastapi_backend/app/domain/topics.py b/fastapi_backend/app/domain/topics.py index afdba2e55..d890fa82d 100644 --- a/fastapi_backend/app/domain/topics.py +++ b/fastapi_backend/app/domain/topics.py @@ -13,8 +13,13 @@ (accepted), waits for someone to accept it (suggested) or was turned down (dismissed: analysis won't suggest it again). Analysis suggests the vocabulary's topics for recordings whose summary or transcript says one of their labels (`suggest`), and lists what summaries talk about that the vocabulary lacks (`candidates`), for people to add or skip. Labels are unique within a namespace, alternative labels too. -A topic made from an entity hides that entity; deleting the topic shows it again. Callers check roles and write the -audit log. +A topic made from an entity hides that entity; deleting the topic shows it again. Merging and deleting topics keep +what they changed in `topic_change`, so either can be undone (`undo`). Callers check roles and write the audit log. + + topic_change {kind: merge | delete, space, keep, topics: [the rows that went], lists: [{id, before, after}] (the + alt, broader and related lists of the topics left that changed), about: [topic_about rows before], + kept: [the kept topic's topic_about rows after a merge], pages: [their note pages], entity, by, at, + undone, undone_by, undone_at} """ from __future__ import annotations @@ -215,11 +220,12 @@ def update(db, tid, label=None, alt=None, definition=None, broader=None, related return tid -def delete(db, tid): +def delete(db, tid, user=None): """Delete a topic: its narrower topics move up to its broader ones, recordings stop being about it, and an entity it - was made from shows again. Returns that entity's id, if any.""" + was made from shows again. Returns (that entity's id or None, the change's id to undo it with).""" t = _topic(db, tid) tid = t["id"] + before, about, pages = _lists(db, t["space"]), _abouts(db, [tid]), _pages(db, [tid]) for n in db.rows("SELECT record::id(id) AS id, broader FROM topic WHERE space = $s AND $t IN broader", s=t["space"], t=tid): up = [b for b in n.get("broader") or [] if b != tid] up += [b for b in t.get("broader") or [] if b not in up and b != n["id"]] @@ -229,11 +235,13 @@ def delete(db, tid): db.q("DELETE $r", r=R("topic", tid)) notebook.release(db, f"topic:{tid}") # its page stays, as a free note eid = (t.get("origin") or {}).get("entity") + shown = None if eid and db.one("SELECT id FROM $r", r=R("entity", int(eid))): with graph_history.change(db, "entity.show", entities=[int(eid)], why=f"topic {tid} was deleted"): db.q("UPDATE $r SET hidden = false, hidden_reason = NONE", r=R("entity", int(eid))) - return int(eid) - return None + shown = int(eid) + cid = _remember(db, "delete", t["space"], [t], before, about, pages, user, entity=shown) + return shown, cid def merge(db, keep, others, user=None): @@ -247,6 +255,7 @@ def merge(db, keep, others, user=None): gone = [_topic(db, o) for o in others] if any(o["space"] != k["space"] for o in gone): raise ValueError("Topics are merged within one namespace.") + before, about, pages = _lists(db, k["space"]), _abouts(db, [keep, *others]), _pages(db, others) alt = list(k.get("alt") or []) broader = list(k.get("broader") or []) related = list(k.get("related") or []) @@ -282,8 +291,163 @@ def merge(db, keep, others, user=None): r=R("topic", keep), d={"alt": _clean_alt(alt, k["label"])[:ALT_MAX], "broader": broader, "related": related, "updated": store.now(), "by": user}, ) + cid = _remember(db, "merge", k["space"], gone, before, about, pages, user, keep=keep, kept=_abouts(db, [keep])) suggest(db, k["space"]) - return keep + return cid + + +# ---------- undoing a merge or a delete ---------- +LISTS = ("alt", "broader", "related") +ABOUT_FIELDS = "recording, topic, space, source, weight, status, at, by" + + +def _lists(db, sid): + """The alt, broader and related lists (and key) of every topic in a namespace, by id.""" + return { + t["id"]: {"key": t["key"], **{f: list(t.get(f) or []) for f in LISTS}} + for t in db.rows("SELECT record::id(id) AS id, key, alt, broader, related FROM topic WHERE space = $s", s=int(sid)) + } + + +def _abouts(db, tids): + return db.rows(f"SELECT {ABOUT_FIELDS} FROM topic_about WHERE topic IN $t", t=[int(t) for t in tids]) if tids else [] + + +def _pages(db, tids): + q = "SELECT record::id(id) AS id, about, about_key, parent, position FROM note_page WHERE about IN $a" + return db.rows(q, a=[f"topic:{int(t)}" for t in tids]) if tids else [] + + +def _remember(db, kind, sid, gone, before, about, pages, user, **extra): + """Keep what a merge or delete changed, for `undo`. Returns the change's id.""" + after = _lists(db, sid) + lists = [ + {"id": i, "before": {f: before[i][f] for f in LISTS}, "after": {f: a[f] for f in LISTS}} + for i, a in after.items() + if i in before and any(before[i][f] != a[f] for f in LISTS) + ] + cid = db.next_id("topic_change") + db.q( + "CREATE $r CONTENT $d", + r=R("topic_change", cid), + d=store.clean( + { + "kind": kind, + "space": int(sid), + "topics": gone, + "lists": lists, + "about": about, + "pages": pages, + "by": user, + "at": store.now(), + "undone": False, + **extra, + } + ), + ) + return cid + + +def _undiff(now, before, after): + """`now` with the change from `before` to `after` taken back; what changed since stays.""" + added = [x for x in after if x not in before] + dropped = [x for x in before if x not in after] + out = [x for x in now if x not in added] + return out + [x for x in dropped if x not in out] + + +def changes(db, sid, limit=50): + """A namespace's latest topic merges and deletes, newest first, to undo.""" + rows = db.rows( + "SELECT record::id(id) AS id, kind, keep, topics, by, at, undone FROM topic_change WHERE space = $s ORDER BY at DESC LIMIT $n", + s=int(sid), + n=int(limit), + ) + return [ + store.clean( + { + "id": r["id"], + "kind": r["kind"], + "keep": r.get("keep"), + "labels": [t["label"] for t in r.get("topics") or []], + "by": r.get("by"), + "at": r.get("at"), + "undone": bool(r.get("undone")), + } + ) + for r in rows + ] + + +def undo(db, cid, user=None): + """Take back a merge or a delete: the topics come back with their ids, labels and recordings, the lists they were + taken out of (or a merge put them in) are put back, and their note pages are theirs again. What changed since stays. + Refused when another topic has taken one of their labels meanwhile.""" + c = db.one("SELECT * FROM $r", r=R("topic_change", int(cid))) + if not c or c.get("undone"): + raise ValueError("Nothing to undo.") + sid, keep = c["space"], c.get("keep") + gone = c.get("topics") or [] + gone_ids = {t["id"] for t in gone} + now = _lists(db, sid) + lists = { + x["id"]: {f: _undiff(now[x["id"]][f], x["before"][f], x["after"][f]) for f in LISTS} for x in c.get("lists") or [] if x["id"] in now + } + for t in gone: # its labels must still be free, once the merge has given back the ones it took + if t["id"] in now: + raise ValueError(f"{t['label']} is back already.") + mine = {t["key"]} | {key_of(a) for a in t.get("alt") or []} + for i, o in now.items(): + if i in gone_ids: + continue + theirs = {o["key"]} | {key_of(a) for a in lists.get(i, o)["alt"]} + if mine & theirs: + raise ValueError(f"Another topic is called {t['label']} now; rename it to bring this one back.") + alive = set(now) | gone_ids + for t in gone: + row = {k: v for k, v in t.items() if k != "id"} + row["tkey"] = f"{sid}:{t['key']}" + row["broader"] = [b for b in row.get("broader") or [] if b in alive] + row["related"] = [r for r in row.get("related") or [] if r in alive] + db.q("CREATE $r CONTENT $d", r=R("topic", t["id"]), d=store.clean(row)) + for i, ls in lists.items(): + db.q( + "UPDATE $r SET alt = $a, broader = $b, related = $rel", + r=R("topic", i), + a=ls["alt"], + b=[b for b in ls["broader"] if b in alive], + rel=[r for r in ls["related"] if r in alive], + ) + before = c.get("about") or [] + rids = {a["recording"] for a in before} | {a["recording"] for a in c.get("kept") or []} + there = ( + set(db.values("SELECT VALUE record::id(id) FROM recording WHERE id IN $r", r=[R("recording", x) for x in rids])) if rids else set() + ) + if keep is not None: # the kept topic's recordings as they were: the merge's additions go, what it changed returns + had = {a["recording"] for a in before if a["topic"] == keep} + for a in c.get("kept") or []: + if a["recording"] not in had: + db.q("DELETE $r", r=_about_id(a["recording"], keep)) + for a in before: + if a["recording"] in there: + db.q("UPSERT $r CONTENT $d", r=_about_id(a["recording"], a["topic"]), d=store.clean(dict(a))) + for p in c.get("pages") or []: # their pages, unless someone has filed them elsewhere since + db.q( + "UPDATE $r SET about = $a, about_key = $k, parent = $p, position = $pos WHERE about = NONE", + r=R("note_page", p["id"]), + a=p["about"], + k=p.get("about_key"), + p=p.get("parent"), + pos=p.get("position"), + ) + eid = c.get("entity") + if eid and db.one("SELECT id FROM $r", r=R("entity", int(eid))): # the entity it was made from hides again + tid = gone[0]["id"] + with graph_history.change(db, "entity.hide", entities=[int(eid)], why=f"topic {tid} is back"): + db.q("UPDATE $r SET hidden = true, hidden_reason = $why", r=R("entity", int(eid)), why=f"became topic {tid}") + db.q("UPDATE $r SET undone = true, undone_by = $u, undone_at = $t", r=R("topic_change", int(cid)), u=user, t=store.now()) + suggest(db, sid) + return {"kind": c["kind"], "topics": sorted(gone_ids), "keep": keep} def _about(db, sid, rid, tid, source, weight, status, user): diff --git a/fastapi_backend/app/schemas/topics.py b/fastapi_backend/app/schemas/topics.py index 1f1734964..996ce9a4f 100644 --- a/fastapi_backend/app/schemas/topics.py +++ b/fastapi_backend/app/schemas/topics.py @@ -6,7 +6,7 @@ from pydantic import Field -from app.schemas.common import RequestModel, ResponseModel +from app.schemas.common import Ok, RequestModel, ResponseModel class TopicRef(ResponseModel): @@ -77,6 +77,24 @@ class TopicMerge(RequestModel): others: list[int] = Field(min_length=1) +class TopicMerged(TopicDetail): + undo: int = Field(description="the change to take back with POST /topics/changes/{undo}/undo") + + +class TopicDeleted(Ok): + undo: int = Field(description="the change to take back with POST /topics/changes/{undo}/undo") + + +class TopicChange(ResponseModel): + id: int + kind: str = Field(description="merge or delete") + keep: int | None = Field(None, description="the topic a merge kept") + labels: list[str] = Field([], description="the topics that went") + by: str | None = None + at: str | None = None + undone: bool = False + + class TopicRecordings(RequestModel): recordings: list[int] = Field(min_length=1, max_length=500) remove: bool = Field(False, description="say they aren't about it") diff --git a/fastapi_backend/tests/api/test_topics.py b/fastapi_backend/tests/api/test_topics.py index 0d77d1895..6d2e50eb3 100644 --- a/fastapi_backend/tests/api/test_topics.py +++ b/fastapi_backend/tests/api/test_topics.py @@ -1,5 +1,5 @@ """Topics: the vocabulary (labels, broader, narrower, related), recordings about topics, topics made from entities, -and topics in the property graph and in RDF.""" +undoing merges and deletes, and topics in the property graph and in RDF.""" from __future__ import annotations @@ -7,7 +7,7 @@ from rdflib import Graph, URIRef from rdflib.namespace import SKOS -from app.domain import analyze, topics +from app.domain import analyze, notebook, store, topics from app.domain.store import R from tests.api.test_entities import Env @@ -96,6 +96,75 @@ def test_topic_from_entity(env): ] +def test_undo_a_merge(env): + c, ed, vi, db = env.c, env.h["editor"], env.h["viewer"], env.db + t = make(c, ed, "Funding") + u = make(c, ed, "Grants", alt=["bursaries"], definition="Money given.") + v = make(c, ed, "Money", broader=[u["id"]], related=[u["id"]]) + c.post(f"/api/v1/topics/{t['id']}/recordings", json={"recordings": [1, 2]}, headers=ed) + c.post(f"/api/v1/topics/{u['id']}/recordings", json={"recordings": [2, 4]}, headers=ed) + page = notebook.create(db, store.ns_id(db, "pods"), "ed@x.io", "Grant notes", about_thing=f"topic:{u['id']}") + m = c.post("/api/v1/topics/merge", json={"keep": t["id"], "others": [u["id"]]}, headers=ed).json() + assert m["alt"] == ["Grants", "bursaries"] and [a["recording"] for a in m["about"]] == [1, 2, 4] + assert c.get(f"/api/v1/topics/{v['id']}", headers=vi).json()["broader"] == [{"id": t["id"], "label": "Funding"}] + changes = c.get("/api/v1/namespaces/pods/topics/changes", headers=vi).json() + assert [(x["id"], x["kind"], x["keep"], x["labels"], x["undone"]) for x in changes] == [ + (m["undo"], "merge", t["id"], ["Grants"], False) + ] + assert c.post(f"/api/v1/topics/changes/{m['undo']}/undo", headers=vi).status_code == 403 + assert c.post(f"/api/v1/topics/changes/{m['undo']}/undo", headers=ed).status_code == 200 + # both topics as they were: labels, recordings, broader and related, and the page + back = c.get(f"/api/v1/topics/{u['id']}", headers=vi).json() + assert (back["label"], back["alt"], back["definition"]) == ("Grants", ["bursaries"], "Money given.") + assert [a["recording"] for a in back["about"]] == [2, 4] + assert back["related"] == [{"id": v["id"], "label": "Money"}] + kept = c.get(f"/api/v1/topics/{t['id']}", headers=vi).json() + assert kept["alt"] == [] and kept["related"] == [] and [a["recording"] for a in kept["about"]] == [1, 2] + money = c.get(f"/api/v1/topics/{v['id']}", headers=vi).json() + assert money["broader"] == money["related"] == [{"id": u["id"], "label": "Grants"}] + assert db.one("SELECT about FROM $r", r=R("note_page", page))["about"] == f"topic:{u['id']}" + # once only + again = c.post(f"/api/v1/topics/changes/{m['undo']}/undo", headers=ed) + assert again.status_code == 400 and "Nothing to undo" in again.text + assert c.get("/api/v1/namespaces/pods/topics/changes", headers=vi).json()[0]["undone"] is True + assert c.post("/api/v1/topics/changes/999/undo", headers=ed).status_code == 404 + + +def test_undo_a_delete(env): + c, ed, vi = env.c, env.h["editor"], env.h["viewer"] + bio = make(c, ed, "Biology") + gene = make(c, ed, "Gene therapy", alt=["GT"], broader=[bio["id"]]) + vec = make(c, ed, "Viral vectors", broader=[gene["id"]]) + c.post(f"/api/v1/topics/{gene['id']}/recordings", json={"recordings": [1]}, headers=ed) + d = c.delete(f"/api/v1/topics/{gene['id']}", headers=ed).json() + assert c.get(f"/api/v1/topics/{vec['id']}", headers=vi).json()["broader"] == [{"id": bio["id"], "label": "Biology"}] + assert c.post(f"/api/v1/topics/changes/{d['undo']}/undo", headers=ed).status_code == 200 + g = c.get(f"/api/v1/topics/{gene['id']}", headers=vi).json() + assert (g["label"], g["alt"], g["broader"]) == ("Gene therapy", ["GT"], [{"id": bio["id"], "label": "Biology"}]) + assert [a["recording"] for a in g["about"]] == [1] + assert c.get(f"/api/v1/topics/{vec['id']}", headers=vi).json()["broader"] == [{"id": gene["id"], "label": "Gene therapy"}] + # a label someone has taken since keeps the topic away + d = c.delete(f"/api/v1/topics/{gene['id']}", headers=ed).json() + make(c, ed, "gt") + clash = c.post(f"/api/v1/topics/changes/{d['undo']}/undo", headers=ed) + assert clash.status_code == 400 and "Another topic is called Gene therapy" in clash.text + assert c.get(f"/api/v1/topics/{gene['id']}", headers=vi).status_code == 404 + + +def test_undo_deleting_a_topic_made_from_an_entity(env): + c, ed, vi = env.c, env.h["editor"], env.h["viewer"] + aws = env.eid("Amazon Web Services") + t = c.post(f"/api/v1/entities/{aws}/topic", headers=ed).json() + d = c.delete(f"/api/v1/topics/{t['id']}", headers=ed).json() + assert c.get(f"/api/v1/entities/{aws}", headers=vi).json()["hidden"] is False + assert c.post(f"/api/v1/topics/changes/{d['undo']}/undo", headers=ed).status_code == 200 + back = c.get(f"/api/v1/topics/{t['id']}", headers=vi).json() + assert back["from_entity"] == aws and {a["source"] for a in back["about"]} == {"entity"} + assert c.get(f"/api/v1/entities/{aws}", headers=vi).json()["hidden"] is True + hist = c.get("/api/v1/graph/history", headers=vi, params={"entity": aws}).json()["versions"] + assert (hist[0]["op"], hist[0]["why"]) == ("entity.hide", f"topic {t['id']} is back") + + def test_topics_in_the_graph_and_rdf(env): c, ed, vi = env.c, env.h["editor"], env.h["viewer"] bio = make(c, ed, "Biology") diff --git a/nextjs-frontend/__tests__/graph-curate.test.ts b/nextjs-frontend/__tests__/graph-curate.test.ts index 001efce09..1d25de1b0 100644 --- a/nextjs-frontend/__tests__/graph-curate.test.ts +++ b/nextjs-frontend/__tests__/graph-curate.test.ts @@ -37,11 +37,11 @@ describe("editing from the graph", () => { }); describe("merging on the canvas", () => { - it("joins entities and speakers of one namespace, nothing that spans several", () => { - expect([joinKind(acme), joinKind(alice), joinKind(joined), joinKind(topic), joinKind(null)]).toEqual([ + it("joins entities, speakers and topics of one namespace, nothing that spans several", () => { + expect([joinKind(acme), joinKind(alice), joinKind(topic), joinKind(joined), joinKind(null)]).toEqual([ "entity", "speaker", - null, + "topic", null, null, ]); @@ -56,5 +56,8 @@ describe("merging on the canvas", () => { expect(joinPlan(alice, topic)).toBe("A speaker merges into another speaker."); expect(joinPlan(alice, node("s8", "speaker", [8], ["calls"]))).toBe("Speakers are merged within one namespace."); expect(joinPlan(acme, joined)).toBe("An entity merges into another entity."); + expect(joinPlan(node("t6", "topic", [6], ["pods"]), topic)).toBe("merge-topic"); + expect(joinPlan(topic, acme)).toBe("A topic merges into another topic."); + expect(joinPlan(topic, node("t7", "topic", [7], ["calls"]))).toBe("Topics are merged within one namespace."); }); }); diff --git a/nextjs-frontend/__tests__/topics-curate.test.tsx b/nextjs-frontend/__tests__/topics-curate.test.tsx new file mode 100644 index 000000000..d06c63f6f --- /dev/null +++ b/nextjs-frontend/__tests__/topics-curate.test.tsx @@ -0,0 +1,110 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import "@testing-library/jest-dom"; + +import { Topics } from "@/app/openapi-client"; +import { findTopics, TopicMergeInto, topicMergeTitle } from "@/components/topics/curate"; +import type { TopicItem } from "@/components/topics/model"; +import { TopicDrawer } from "@/components/topics/topic-drawer"; +import { TooltipProvider } from "@/components/ui/tooltip"; + +jest.mock("@/app/openapi-client", () => ({ + Topics: { + getTopic: jest.fn(), + listTopics: jest.fn(), + mergeTopics: jest.fn(), + deleteTopic: jest.fn(), + undoTopicChange: jest.fn(), + }, +})); +jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: "t" } }) })); +jest.mock("@/lib/hooks/session", () => ({ useArchive: () => ({ can: () => true }), needRole: () => "" })); +jest.mock("@/components/similar/similar-list", () => ({ SimilarSection: () => null })); +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) => { + const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + return render( + + {ui} + , + ); +}; + +const topic = (id: number, label: string, recordings = 0, alt: string[] = []): TopicItem => ({ + id, + label, + alt, + broader: [], + related: [], + recordings, + narrower: 0, +}); +const vocab = [topic(1, "Funding", 5), topic(2, "Grants", 2, ["bursaries"]), topic(3, "Crowdfunding", 1)]; + +beforeEach(() => jest.clearAllMocks()); + +describe("finding a topic", () => { + it("puts labels that start with the text first, then other labels, then any match", () => { + expect(findTopics(vocab, "fund").map((t) => t.label)).toEqual(["Funding", "Crowdfunding"]); + expect(findTopics(vocab, "burs").map((t) => t.label)).toEqual(["Grants"]); + expect(findTopics(vocab, "", [1]).map((t) => t.label)).toEqual(["Grants", "Crowdfunding"]); // the most used first + expect(findTopics(vocab, "zzz")).toEqual([]); + }); + + it("says what was merged into what", () => { + expect(topicMergeTitle("Funding", ["Grants"])).toBe("Merged Grants into Funding"); + expect(topicMergeTitle("Funding", ["Grants", "Bursaries"])).toBe("Merged 2 topics into Funding"); + }); +}); + +describe("merging into a topic", () => { + it("finds one by typing and merges it at once, with Undo on the toast", async () => { + m(Topics.mergeTopics).mockReturnValue(ok({ ...vocab[0], undo: 12 })); + m(Topics.undoTopicChange).mockReturnValue(ok({ ok: true })); + show( undefined} />); + const box = screen.getByRole("combobox", { name: "Topic to merge into Funding" }); + expect(box).toHaveFocus(); + fireEvent.change(box, { target: { value: "gra" } }); + expect(screen.getAllByRole("option")).toHaveLength(1); + fireEvent.keyDown(box, { key: "Enter" }); + await waitFor(() => expect(Topics.mergeTopics).toHaveBeenCalled()); + expect(m(Topics.mergeTopics).mock.calls[0][0].body).toEqual({ keep: 1, others: [2] }); + await waitFor(() => expect(toast).toHaveBeenCalled()); + const t = toast.mock.calls[0][0]; + expect(t.title).toBe("Merged Grants into Funding"); + t.action.onClick(); + await waitFor(() => expect(Topics.undoTopicChange).toHaveBeenCalled()); + expect(m(Topics.undoTopicChange).mock.calls[0][0].path).toEqual({ cid: 12 }); + }); +}); + +describe("the topic drawer", () => { + const detail = { ...vocab[1], about: [], narrower: [], broader: [], related: [] }; + + it("deletes at once, with Undo instead of a confirm", async () => { + m(Topics.getTopic).mockReturnValue(ok(detail)); + m(Topics.deleteTopic).mockReturnValue(ok({ ok: true, undo: 30 })); + m(Topics.undoTopicChange).mockReturnValue(ok({ ok: true })); + const onClose = jest.fn(); + show( undefined} onClose={onClose} />); + fireEvent.click(await screen.findByRole("button", { name: "Delete" })); + await waitFor(() => expect(Topics.deleteTopic).toHaveBeenCalled()); + expect(screen.queryByRole("dialog", { name: /Delete/ })).not.toBeInTheDocument(); + await waitFor(() => expect(onClose).toHaveBeenCalled()); + const t = toast.mock.calls[0][0]; + expect(t.title).toBe("Deleted Grants"); + t.action.onClick(); + await waitFor(() => expect(m(Topics.undoTopicChange).mock.calls[0][0].path).toEqual({ cid: 30 })); + }); + + it("opens a find box to merge another topic in", async () => { + m(Topics.getTopic).mockReturnValue(ok(detail)); + show( undefined} onClose={() => undefined} />); + fireEvent.click(await screen.findByRole("button", { name: "Merge" })); + expect(screen.getByRole("combobox", { name: "Topic to merge into Grants" })).toHaveFocus(); + }); +}); diff --git a/nextjs-frontend/app/openapi-client/index.ts b/nextjs-frontend/app/openapi-client/index.ts index 382e38372..af490230d 100644 --- a/nextjs-frontend/app/openapi-client/index.ts +++ b/nextjs-frontend/app/openapi-client/index.ts @@ -1815,6 +1815,11 @@ export type { ListTokensData, ListTokensResponse, ListTokensResponses, + ListTopicChangesData, + ListTopicChangesError, + ListTopicChangesErrors, + ListTopicChangesResponse, + ListTopicChangesResponses, ListTopicsData, ListTopicsError, ListTopicsErrors, @@ -2957,11 +2962,14 @@ export type { TopicCandidatesErrors, TopicCandidatesResponse, TopicCandidatesResponses, + TopicChange, TopicCreate, + TopicDeleted, TopicDetail, TopicItem, TopicList, TopicMerge, + TopicMerged, TopicRecordings, TopicRef, TopicSkip, @@ -3012,6 +3020,11 @@ export type { UndoSpeakerMergeErrors, UndoSpeakerMergeResponse, UndoSpeakerMergeResponses, + UndoTopicChangeData, + UndoTopicChangeError, + UndoTopicChangeErrors, + UndoTopicChangeResponse, + UndoTopicChangeResponses, UnlinkEntityData, UnlinkEntityError, UnlinkEntityErrors, diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index 218930060..e3bfc4787 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -929,6 +929,9 @@ import type { ListTemplatesResponses, ListTokensData, ListTokensResponses, + ListTopicChangesData, + ListTopicChangesErrors, + ListTopicChangesResponses, ListTopicsData, ListTopicsErrors, ListTopicsResponses, @@ -1450,6 +1453,9 @@ import type { UndoSpeakerMergeData, UndoSpeakerMergeErrors, UndoSpeakerMergeResponses, + UndoTopicChangeData, + UndoTopicChangeErrors, + UndoTopicChangeResponses, UnlinkEntityData, UnlinkEntityErrors, UnlinkEntityResponses, @@ -6765,7 +6771,8 @@ export class Topics { /** * Delete Topic * - * Delete it: its narrower topics move up, recordings stop being about it, and an entity it was made from shows again. + * Delete it: its narrower topics move up, recordings stop being about it, and an entity it was made from shows + * again. `undo` takes it back (POST /topics/changes/{undo}/undo). */ public static deleteTopic( options: Options, @@ -6862,7 +6869,8 @@ export class Topics { /** * Merge Topics * - * Fold topics into one: their labels become its other labels and their recordings are about it. + * Fold topics into one: their labels become its other labels and their recordings are about it. `undo` takes it + * back (POST /topics/changes/{undo}/undo). */ public static mergeTopics( options: Options, @@ -6877,6 +6885,35 @@ export class Topics { }); } + /** + * List Topic Changes + * + * The namespace's latest topic merges and deletes, newest first, each with whether it was undone. + */ + public static listTopicChanges( + options: Options, + ): RequestResult { + return (options.client ?? client).get({ + url: "/api/v1/namespaces/{name}/topics/changes", + ...options, + }); + } + + /** + * Undo Topic Change + * + * Take back a merge or a delete: the topics come back with their labels, recordings and pages. What changed + * since stays. Refused (400) when another topic has taken one of their labels meanwhile. + */ + public static undoTopicChange( + options: Options, + ): RequestResult { + return (options.client ?? client).post({ + url: "/api/v1/topics/changes/{cid}/undo", + ...options, + }); + } + /** * Tag Recordings * diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index e6a8c7fb5..b0d2a2f70 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -18473,6 +18473,47 @@ export type TopicCandidate = { [key: string]: unknown; }; +/** + * TopicChange + */ +export type TopicChange = { + /** + * Id + */ + id: number; + /** + * Kind + * + * merge or delete + */ + kind: string; + /** + * Keep + * + * the topic a merge kept + */ + keep?: number | null; + /** + * Labels + * + * the topics that went + */ + labels?: Array; + /** + * By + */ + by?: string | null; + /** + * At + */ + at?: string | null; + /** + * Undone + */ + undone?: boolean; + [key: string]: unknown; +}; + /** * TopicCreate */ @@ -18499,6 +18540,23 @@ export type TopicCreate = { related?: Array; }; +/** + * TopicDeleted + */ +export type TopicDeleted = { + /** + * Ok + */ + ok?: boolean; + /** + * Undo + * + * the change to take back with POST /topics/changes/{undo}/undo + */ + undo: number; + [key: string]: unknown; +}; + /** * TopicDetail */ @@ -18642,6 +18700,67 @@ export type TopicMerge = { others: Array; }; +/** + * TopicMerged + */ +export type TopicMerged = { + /** + * Id + */ + id: number; + /** + * Namespace + */ + namespace?: string | null; + /** + * Label + */ + label: string; + /** + * Alt + */ + alt?: Array; + /** + * Definition + */ + definition?: string | null; + /** + * Broader + */ + broader?: Array; + /** + * Narrower + */ + narrower?: Array; + /** + * Related + */ + related?: Array; + /** + * Recordings + */ + recordings?: number; + /** + * From Entity + */ + from_entity?: number | null; + /** + * Updated + */ + updated?: string | null; + /** + * About + */ + about?: Array; + /** + * Undo + * + * the change to take back with POST /topics/changes/{undo}/undo + */ + undo: number; + [key: string]: unknown; +}; + /** * TopicRecordings */ @@ -29657,7 +29776,7 @@ export type DeleteTopicResponses = { /** * Successful Response */ - 200: Ok; + 200: TopicDeleted; }; export type DeleteTopicResponse = DeleteTopicResponses[keyof DeleteTopicResponses]; @@ -29839,11 +29958,78 @@ export type MergeTopicsResponses = { /** * Successful Response */ - 200: TopicDetail; + 200: TopicMerged; }; export type MergeTopicsResponse = MergeTopicsResponses[keyof MergeTopicsResponses]; +export type ListTopicChangesData = { + body?: never; + path: { + /** + * Name + */ + name: string; + }; + query?: { + /** + * Limit + */ + limit?: number; + }; + url: "/api/v1/namespaces/{name}/topics/changes"; +}; + +export type ListTopicChangesErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type ListTopicChangesError = ListTopicChangesErrors[keyof ListTopicChangesErrors]; + +export type ListTopicChangesResponses = { + /** + * Response Topics-List Topic Changes + * + * Successful Response + */ + 200: Array; +}; + +export type ListTopicChangesResponse = ListTopicChangesResponses[keyof ListTopicChangesResponses]; + +export type UndoTopicChangeData = { + body?: never; + path: { + /** + * Cid + */ + cid: number; + }; + query?: never; + url: "/api/v1/topics/changes/{cid}/undo"; +}; + +export type UndoTopicChangeErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type UndoTopicChangeError = UndoTopicChangeErrors[keyof UndoTopicChangeErrors]; + +export type UndoTopicChangeResponses = { + /** + * Successful Response + */ + 200: Ok; +}; + +export type UndoTopicChangeResponse = UndoTopicChangeResponses[keyof UndoTopicChangeResponses]; + export type TagRecordingsData = { body: TopicRecordings; path: { diff --git a/nextjs-frontend/components/entities/curate.tsx b/nextjs-frontend/components/entities/curate.tsx index 7bb2fa5e2..d51ff2100 100644 --- a/nextjs-frontend/components/entities/curate.tsx +++ b/nextjs-frontend/components/entities/curate.tsx @@ -1,16 +1,16 @@ "use client"; import { useQuery, useQueryClient } from "@tanstack/react-query"; -import { GitMerge, Loader2, X } from "lucide-react"; -import { useCallback, useEffect, useId, useRef, useState } from "react"; +import { GitMerge, X } from "lucide-react"; +import { useCallback, useEffect, useState } from "react"; import { Entities } from "@/app/openapi-client"; import { Button } from "@/components/ui/button"; +import { FindBox } from "@/components/ui/find-box"; import { Skeleton } from "@/components/ui/states"; import { useToast } from "@/components/ui/toast"; import { ApiError, data, useApiClient } from "@/lib/api/browser"; import { count, plural } from "@/lib/format"; -import { cn } from "@/lib/utils"; /** * Entity curation wherever entities show (the Entities page and its drawer, the graph, a recording): merging with an @@ -168,18 +168,12 @@ export function EntityFind({ busy?: boolean; }) { const client = useApiClient(); - const listId = useId(); const [q, setQ] = useState(""); const [debounced, setDebounced] = useState(""); - const [active, setActive] = useState(0); - const input = useRef(null); useEffect(() => { const t = setTimeout(() => setDebounced(q.trim()), 200); return () => clearTimeout(t); }, [q]); - useEffect(() => { - if (autoFocus) input.current?.focus(); - }, [autoFocus]); const found = useQuery({ queryKey: ["entity-find", ns, debounced], queryFn: () => @@ -193,90 +187,28 @@ export function EntityFind({ }); const items = ((found.data?.items ?? []) as unknown as Found[]) .filter((e) => !e.builtin && !exclude.includes(e.id)) - .slice(0, 8); - useEffect(() => setActive(0), [debounced]); - const pick = (e: Found | undefined) => { - if (!e || busy) return; - onPick({ id: e.id, name: e.name }); - setQ(""); - }; - // Enter before the list caught up with what was typed picks from the list for that text, not the one still showing - const [want, setWant] = useState(false); - const waiting = found.isFetching || debounced !== q.trim(); - useEffect(() => { - if (!want || waiting) return; - setWant(false); - pick(items[active]); - }); + .slice(0, 8) + .map((e) => ({ + id: e.id, + name: e.name, + meta: `${e.type_label ?? "Entity"} · ${plural(e.mentions ?? 0, "mention")}`, + })); return ( -
-
- 0} - aria-controls={listId} - aria-activedescendant={items[active] ? `${listId}-${items[active].id}` : undefined} - aria-autocomplete="list" - value={q} - placeholder={placeholder} - disabled={busy} - onChange={(e) => setQ(e.target.value)} - onKeyDown={(e) => { - if (e.key === "ArrowDown") { - e.preventDefault(); - setActive((a) => Math.min(items.length - 1, a + 1)); - } else if (e.key === "ArrowUp") { - e.preventDefault(); - setActive((a) => Math.max(0, a - 1)); - } else if (e.key === "Enter") { - e.preventDefault(); - if (!waiting) pick(items[active]); - else { - setDebounced(q.trim()); - setWant(true); - } - } else if (e.key === "Escape" && onCancel) { - e.preventDefault(); - e.stopPropagation(); - onCancel(); - } - }} - className="h-9 w-full rounded-sm border border-border bg-background px-3 pr-9 text-[14px] text-fg outline-hidden placeholder:text-fg-muted focus:border-blue focus:shadow-[0_0_0_3px_var(--intent-surface)]" - /> - {(busy || found.isFetching) && ( - - )} -
-
    - {items.map((e, i) => ( -
  • setActive(i)} - onMouseDown={(ev) => ev.preventDefault()} - onClick={() => pick(e)} - className={cn( - "flex h-8 cursor-pointer items-center gap-2 rounded-sm px-2 text-[13px]", - i === active ? "bg-hl" : "hover:bg-surface-neutral", - )} - > - {e.name} - - {e.type_label ?? "Entity"} · {plural(e.mentions ?? 0, "mention")} - -
  • - ))} - {found.data && !items.length && ( -
  • - {debounced ? `Nothing in ${ns} is called “${debounced}”.` : "No other entities here."} -
  • - )} -
-
+ onPick({ id: e.id, name: e.name })} + onCancel={onCancel} + placeholder={placeholder} + label={label} + autoFocus={autoFocus} + busy={busy} + /> ); } diff --git a/nextjs-frontend/components/graph/join.ts b/nextjs-frontend/components/graph/join.ts index ec0dc8747..b89c351b6 100644 --- a/nextjs-frontend/components/graph/join.ts +++ b/nextjs-frontend/components/graph/join.ts @@ -6,31 +6,38 @@ import { useCallback } from "react"; import { Speakers } from "@/app/openapi-client"; import { useLinkEntities, useMergeEntities } from "@/components/entities/curate"; import type { GraphNode } from "@/components/graph/model"; +import { useTopicChanges } from "@/components/topics/curate"; import { useToast } from "@/components/ui/toast"; import { ApiError, data, useApiClient } from "@/lib/api/browser"; import { useArchive } from "@/lib/hooks/session"; +type Joins = "entity" | "speaker" | "topic"; +const JOINS: string[] = ["entity", "speaker", "topic"]; +const NOUN: Record = { entity: "An entity", speaker: "A speaker", topic: "A topic" }; + /** What one node can join: an entity of one namespace joins another entity (merged in its namespace, linked across - * namespaces) and a speaker joins a speaker of its namespace. A global node joining several namespaces joins nothing. */ -export function joinKind(n: Pick | null | undefined): "entity" | "speaker" | null { + * namespaces), and a speaker or a topic joins one of its namespace. A global node joining several namespaces joins + * nothing. */ +export function joinKind(n: Pick | null | undefined): Joins | null { if (!n || n.refs.length !== 1 || n.ns.length !== 1) return null; - return n.kind === "entity" || n.kind === "speaker" ? n.kind : null; + return JOINS.includes(n.kind) ? (n.kind as Joins) : null; } /** How `from` joins `into` (`into` is kept), or why it can't. */ export function joinPlan( from: Pick, into: Pick, -): "merge" | "link" | "merge-speaker" | string { - const k = joinKind(from); +): "merge" | "link" | "merge-speaker" | "merge-topic" | string { + const k = joinKind(from) ?? "entity"; if (into.id === from.id) return "Pick another node to merge into."; - if (!k || joinKind(into) !== k) - return k === "speaker" ? "A speaker merges into another speaker." : "An entity merges into another entity."; - if (k === "speaker") return from.ns[0] === into.ns[0] ? "merge-speaker" : "Speakers are merged within one namespace."; - return from.ns[0] === into.ns[0] ? "merge" : "link"; + if (!joinKind(from) || joinKind(into) !== k) return `${NOUN[k]} merges into another ${k}.`; + if (k === "entity") return from.ns[0] === into.ns[0] ? "merge" : "link"; + if (from.ns[0] !== into.ns[0]) return `${k === "speaker" ? "Speakers" : "Topics"} are merged within one namespace.`; + return k === "speaker" ? "merge-speaker" : "merge-topic"; } -/** Merging nodes on the graph canvas: entities (with Undo), entities of two namespaces linked, and speakers. */ +/** Merging nodes on the graph canvas, each with Undo: entities, entities of two namespaces linked, speakers and + * topics. */ export function useGraphJoin() { const client = useApiClient(); const qc = useQueryClient(); @@ -38,6 +45,7 @@ export function useGraphJoin() { const { can } = useArchive(); const { merge } = useMergeEntities(); const link = useLinkEntities(); + const topics = useTopicChanges(); const joinable = useCallback( (n: GraphNode | null | undefined): boolean => Boolean(n && joinKind(n) && can("editor", n.ns[0])), [can], @@ -84,7 +92,7 @@ export function useGraphJoin() { const join = useCallback( async (from: GraphNode, into: GraphNode): Promise => { const plan = joinPlan(from, into); - if (plan === "merge-speaker" || plan === "merge" || plan === "link") { + if (plan === "merge-speaker" || plan === "merge-topic" || plan === "merge" || plan === "link") { if (!joinable(into)) { toast({ title: "You can’t change that one", @@ -98,6 +106,7 @@ export function useGraphJoin() { const b = { id: into.refs[0], name: into.label }; if (plan === "merge") return merge(b, [a]); if (plan === "merge-speaker") return speakers(from, into); + if (plan === "merge-topic") return topics.merge({ id: b.id, label: b.name }, [{ id: a.id, label: a.name }]); if (plan === "link") { await link(b, a); return false; @@ -105,7 +114,7 @@ export function useGraphJoin() { toast({ title: "Those can’t be merged", body: plan, tone: "red" }); return false; }, - [joinable, merge, speakers, link, toast], + [joinable, merge, speakers, topics, link, toast], ); return { joinable, join }; } diff --git a/nextjs-frontend/components/topics/curate.tsx b/nextjs-frontend/components/topics/curate.tsx new file mode 100644 index 000000000..99e9e1765 --- /dev/null +++ b/nextjs-frontend/components/topics/curate.tsx @@ -0,0 +1,229 @@ +"use client"; + +import { useQueryClient } from "@tanstack/react-query"; +import { GitMerge, X } from "lucide-react"; +import { useCallback, useState } from "react"; + +import { Topics } from "@/app/openapi-client"; +import type { TopicItem } from "@/components/topics/model"; +import { FindBox } from "@/components/ui/find-box"; +import { useToast } from "@/components/ui/toast"; +import { ApiError, data, useApiClient } from "@/lib/api/browser"; +import { plural } from "@/lib/format"; + +/** + * Topic curation wherever topics show (the Topics page and its drawer, the graph): merging and deleting at once, with + * an Undo instead of a confirm, and finding the topic to merge by typing. + */ + +export type TopicPick = { id: number; label: string }; + +/** What shows a topic, so a merge or delete is seen everywhere at once (a topic made from an entity hides it). */ +export const TOPIC_KEYS = [["topic"], ["topics"], ["recording-topics"], ["graph"], ["entities"], ["entity"]] as const; + +export function useTopicRefresh(): () => void { + const qc = useQueryClient(); + return useCallback(() => { + for (const k of TOPIC_KEYS) void qc.invalidateQueries({ queryKey: [...k] }); + }, [qc]); +} + +const why = (err: unknown) => (err instanceof ApiError ? err.message : "Please try again."); + +/** "Merged Grants into Funding", "Merged 3 topics into Funding". */ +export function topicMergeTitle(keep: string, others: string[]): string { + return others.length === 1 + ? `Merged ${others[0]} into ${keep}` + : `Merged ${plural(others.length, "topic")} into ${keep}`; +} + +/** Topics that match typed text: label first, then another label, then anywhere in the label; the most used first. */ +export function findTopics(all: TopicItem[], q: string, exclude: number[] = [], limit = 8): TopicItem[] { + const k = q.trim().toLowerCase(); + const rank = (t: TopicItem) => { + if (!k) return 0; + const l = t.label.toLowerCase(); + if (l.startsWith(k)) return 0; + if (t.alt.some((a) => a.toLowerCase().startsWith(k))) return 1; + if (l.includes(k) || t.alt.some((a) => a.toLowerCase().includes(k))) return 2; + return -1; + }; + return all + .filter((t) => !exclude.includes(t.id)) + .map((t) => ({ t, r: rank(t) })) + .filter((x) => x.r >= 0) + .sort( + (a, b) => + a.r - b.r || + b.t.recordings - a.t.recordings || + a.t.label.localeCompare(b.t.label, undefined, { sensitivity: "base" }), + ) + .slice(0, limit) + .map((x) => x.t); +} + +/** Merging and deleting topics at once, with Undo on the toast. Both return true when it was done. */ +export function useTopicChanges() { + const client = useApiClient(); + const toast = useToast(); + const refresh = useTopicRefresh(); + const [pending, setPending] = useState(false); + // the toast outlives whatever opened it (a drawer closes, a node goes), so undo isn't tied to a mounted component + const undo = useCallback( + async (cid: number, what: string) => { + try { + await data(Topics.undoTopicChange({ client, path: { cid } })); + refresh(); + toast({ title: `${what} undone`, tone: "green" }); + } catch (err) { + toast({ title: `Couldn’t undo the ${what.toLowerCase()}`, body: why(err), tone: "red" }); + } + }, + [client, refresh, toast], + ); + const merge = useCallback( + async (keep: TopicPick, others: TopicPick[]): Promise => { + const rest = others.filter((o) => o.id !== keep.id); + if (!rest.length) return false; + setPending(true); + try { + const r = await data(Topics.mergeTopics({ client, body: { keep: keep.id, others: rest.map((o) => o.id) } })); + refresh(); + toast({ + title: topicMergeTitle( + keep.label, + rest.map((o) => o.label), + ), + body: "Their labels and recordings are this one’s now.", + tone: "green", + duration: 10000, + action: { label: "Undo", onClick: () => void undo(r.undo, "Merge") }, + }); + return true; + } catch (err) { + toast({ title: "Couldn’t merge them", body: why(err), tone: "red" }); + return false; + } finally { + setPending(false); + } + }, + [client, refresh, toast, undo], + ); + const remove = useCallback( + async (t: TopicPick): Promise => { + setPending(true); + try { + const r = await data(Topics.deleteTopic({ client, path: { tid: t.id } })); + refresh(); + toast({ + title: `Deleted ${t.label}`, + body: "Its narrower topics moved up, and recordings aren’t about it any more.", + tone: "green", + duration: 10000, + action: { label: "Undo", onClick: () => void undo(r.undo, "Delete") }, + }); + return true; + } catch (err) { + toast({ title: "Couldn’t delete it", body: why(err), tone: "red" }); + return false; + } finally { + setPending(false); + } + }, + [client, refresh, toast, undo], + ); + return { merge, remove, pending }; +} + +/** Find a topic of the vocabulary by typing: arrow keys move, Enter picks, Escape leaves. */ +export function TopicFind({ + all, + exclude = [], + onPick, + onCancel, + placeholder = "Find a topic…", + label, + autoFocus, + busy, +}: { + all: TopicItem[]; + exclude?: number[]; + onPick: (t: TopicPick) => void; + onCancel?: () => void; + placeholder?: string; + label: string; + autoFocus?: boolean; + busy?: boolean; +}) { + const [q, setQ] = useState(""); + const items = findTopics(all, q, exclude).map((t) => ({ + id: t.id, + name: t.label, + meta: plural(t.recordings, "recording"), + })); + const typed = q.trim(); + return ( + onPick({ id: t.id, label: t.name })} + onCancel={onCancel} + placeholder={placeholder} + label={label} + autoFocus={autoFocus} + busy={busy} + /> + ); +} + +/** "Merge another topic into this one": a find box; the one picked is merged at once, with Undo. */ +export function TopicMergeInto({ + keep, + all, + open, + onOpenChange, +}: { + keep: TopicPick; + all: TopicItem[]; + open: boolean; + onOpenChange: (o: boolean) => void; +}) { + const { merge, pending } = useTopicChanges(); + if (!open) return null; + return ( +
+
+ +

+ Merge into {keep.label} +

+ +
+

+ Pick the topic that means the same. Its labels and recordings become {keep.label}’s, and you can undo it. +

+ onOpenChange(false)} + onPick={(t) => void merge(keep, [t])} + /> +
+ ); +} diff --git a/nextjs-frontend/components/topics/topic-drawer.tsx b/nextjs-frontend/components/topics/topic-drawer.tsx index 4c2fad8e9..dbff1de2f 100644 --- a/nextjs-frontend/components/topics/topic-drawer.tsx +++ b/nextjs-frontend/components/topics/topic-drawer.tsx @@ -1,12 +1,13 @@ "use client"; -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { Check, Merge, NotebookPen, Trash2, X } from "lucide-react"; +import { useMutation, useQuery } from "@tanstack/react-query"; +import { Check, GitMerge, NotebookPen, Trash2, X } from "lucide-react"; import Link from "next/link"; import { useEffect, useState } from "react"; import { Topics } from "@/app/openapi-client"; import { SimilarSection } from "@/components/similar/similar-list"; +import { TopicMergeInto, useTopicChanges, useTopicRefresh } from "@/components/topics/curate"; import { broaderChoices, splitLabels, type TopicItem } from "@/components/topics/model"; import { TopicPicker } from "@/components/topics/topic-picker"; import { Badge } from "@/components/ui/badge"; @@ -40,7 +41,6 @@ export function TopicDrawer({ onClose: () => void; }) { const client = useApiClient(); - const qc = useQueryClient(); const toast = useToast(); const { can } = useArchive(); const canEdit = can("editor", ns); @@ -61,7 +61,7 @@ export function TopicDrawer({ const [broader, setBroader] = useState([]); const [related, setRelated] = useState([]); const [merging, setMerging] = useState(false); - const [deleting, setDeleting] = useState(false); + const changes = useTopicChanges(); const d = t.data; useEffect(() => { if (d) { @@ -73,12 +73,7 @@ export function TopicDrawer({ } }, [d]); - const refresh = () => { - qc.invalidateQueries({ queryKey: ["topic"] }); - qc.invalidateQueries({ queryKey: ["topics"] }); - qc.invalidateQueries({ queryKey: ["recording-topics"] }); - qc.invalidateQueries({ queryKey: ["graph"] }); - }; + const refresh = useTopicRefresh(); const fail = (title: string) => (err: unknown) => toast({ title, body: err instanceof ApiError ? err.message : "Please try again.", tone: "red" }); @@ -117,16 +112,6 @@ export function TopicDrawer({ onSuccess: refresh, onError: fail("Couldn’t change it"), }); - const remove = useMutation({ - mutationFn: () => data(Topics.deleteTopic({ client, path: { tid: id } })), - onSuccess: () => { - refresh(); - qc.invalidateQueries({ queryKey: ["entities"] }); - toast({ title: "Topic deleted", tone: "green" }); - onClose(); - }, - onError: fail("Couldn’t delete it"), - }); const accepted = (d?.about ?? []).filter((a) => a.status === "accepted"); const suggested = (d?.about ?? []).filter((a) => a.status === "suggested"); @@ -144,10 +129,22 @@ export function TopicDrawer({ {canEdit && ( <> - - @@ -161,6 +158,7 @@ export function TopicDrawer({ {t.isError && {t.error.message}} {d && ( <> + {d.from_entity ? (

Made from an entity of the same name, hidden while this topic exists. Deleting the topic shows it again. @@ -321,99 +319,10 @@ export function TopicDrawer({ )} - {d && ( - { - refresh(); - setMerging(false); - }} - /> - )} -

- - - - } - /> ); } -/** Fold other topics into this one: their labels become its other labels, their recordings are about it. */ -function MergeDialog({ - open, - onOpenChange, - keep, - label, - all, - onMerged, -}: { - open: boolean; - onOpenChange: (o: boolean) => void; - keep: number; - label: string; - all: TopicItem[]; - onMerged: () => void; -}) { - const client = useApiClient(); - const [others, setOthers] = useState([]); - const merge = useMutation({ - mutationFn: () => data(Topics.mergeTopics({ client, body: { keep, others } })), - onSuccess: () => { - setOthers([]); - onMerged(); - }, - }); - return ( - - - - - } - > -
- t.id !== keep)} - all={all} - placeholder="Pick a topic to merge…" - /> - {merge.isError && ( -

- {merge.error instanceof ApiError ? merge.error.message : "Couldn’t merge them. Please try again."} -

- )} -
-
- ); -} - /** Add a topic to a namespace's vocabulary, optionally under broader topics. */ export function NewTopicDialog({ ns, diff --git a/nextjs-frontend/components/ui/find-box.tsx b/nextjs-frontend/components/ui/find-box.tsx new file mode 100644 index 000000000..31557d970 --- /dev/null +++ b/nextjs-frontend/components/ui/find-box.tsx @@ -0,0 +1,123 @@ +"use client"; + +import { Loader2 } from "lucide-react"; +import { useEffect, useId, useRef, useState } from "react"; + +import { cn } from "@/lib/utils"; + +export type FindItem = { id: number; name: string; meta?: string }; + +/** A find box with its list of matches: arrow keys move, Enter picks, Escape leaves. The caller finds the matches + * for the typed text `q`. */ +export function FindBox({ + q, + onQ, + items, + loading, + empty, + onPick, + onCancel, + placeholder, + label, + autoFocus, + busy, +}: { + q: string; + onQ: (q: string) => void; + items: FindItem[]; + /** The list doesn't show the matches for `q` yet (a search is on its way); Enter waits for them. */ + loading?: boolean; + /** What shows when nothing matches; nothing shows while it's undefined (still looking). */ + empty?: string; + onPick: (item: FindItem) => void; + onCancel?: () => void; + placeholder?: string; + label: string; + autoFocus?: boolean; + busy?: boolean; +}) { + const listId = useId(); + const [active, setActive] = useState(0); + const input = useRef(null); + useEffect(() => { + if (autoFocus) input.current?.focus(); + }, [autoFocus]); + const first = items[0]?.id; + useEffect(() => setActive(0), [first]); + const pick = (it: FindItem | undefined) => { + if (!it || busy) return; + onPick(it); + onQ(""); + }; + // Enter before the list caught up with what was typed picks from the list for that text, not the one still showing + const [want, setWant] = useState(false); + useEffect(() => { + if (!want || loading) return; + setWant(false); + pick(items[active]); + }); + return ( +
+
+ 0} + aria-controls={listId} + aria-activedescendant={items[active] ? `${listId}-${items[active].id}` : undefined} + aria-autocomplete="list" + value={q} + placeholder={placeholder} + disabled={busy} + onChange={(e) => { + setActive(0); + onQ(e.target.value); + }} + onKeyDown={(e) => { + if (e.key === "ArrowDown") { + e.preventDefault(); + setActive((a) => Math.min(items.length - 1, a + 1)); + } else if (e.key === "ArrowUp") { + e.preventDefault(); + setActive((a) => Math.max(0, a - 1)); + } else if (e.key === "Enter") { + e.preventDefault(); + if (loading) setWant(true); + else pick(items[active]); + } else if (e.key === "Escape" && onCancel) { + e.preventDefault(); + e.stopPropagation(); + onCancel(); + } + }} + className="h-9 w-full rounded-sm border border-border bg-background px-3 pr-9 text-[14px] text-fg outline-hidden placeholder:text-fg-muted focus:border-blue focus:shadow-[0_0_0_3px_var(--intent-surface)]" + /> + {(busy || loading) && ( + + )} +
+
    + {items.map((it, i) => ( +
  • setActive(i)} + onMouseDown={(ev) => ev.preventDefault()} + onClick={() => pick(it)} + className={cn( + "flex h-8 cursor-pointer items-center gap-2 rounded-sm px-2 text-[13px]", + i === active ? "bg-hl" : "hover:bg-surface-neutral", + )} + > + {it.name} + {it.meta && {it.meta}} +
  • + ))} + {empty !== undefined && !items.length &&
  • {empty}
  • } +
+
+ ); +} diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index 084187067..257441c20 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -15134,7 +15134,7 @@ "topics" ], "summary": "Delete Topic", - "description": "Delete it: its narrower topics move up, recordings stop being about it, and an entity it was made from shows again.", + "description": "Delete it: its narrower topics move up, recordings stop being about it, and an entity it was made from shows\nagain. `undo` takes it back (POST /topics/changes/{undo}/undo).", "operationId": "delete_topic", "parameters": [ { @@ -15153,7 +15153,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Ok" + "$ref": "#/components/schemas/TopicDeleted" } } } @@ -15340,7 +15340,7 @@ "topics" ], "summary": "Merge Topics", - "description": "Fold topics into one: their labels become its other labels and their recordings are about it.", + "description": "Fold topics into one: their labels become its other labels and their recordings are about it. `undo` takes it\nback (POST /topics/changes/{undo}/undo).", "operationId": "merge_topics", "requestBody": { "content": { @@ -15358,7 +15358,107 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/TopicDetail" + "$ref": "#/components/schemas/TopicMerged" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/v1/namespaces/{name}/topics/changes": { + "get": { + "tags": [ + "topics" + ], + "summary": "List Topic Changes", + "description": "The namespace's latest topic merges and deletes, newest first, each with whether it was undone.", + "operationId": "list_topic_changes", + "parameters": [ + { + "name": "name", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Name" + } + }, + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "default": 50, + "title": "Limit" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/TopicChange" + }, + "title": "Response Topics-List Topic Changes" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/api/v1/topics/changes/{cid}/undo": { + "post": { + "tags": [ + "topics" + ], + "summary": "Undo Topic Change", + "description": "Take back a merge or a delete: the topics come back with their labels, recordings and pages. What changed\nsince stays. Refused (400) when another topic has taken one of their labels meanwhile.", + "operationId": "undo_topic_change", + "parameters": [ + { + "name": "cid", + "in": "path", + "required": true, + "schema": { + "type": "integer", + "title": "Cid" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Ok" } } } @@ -59134,6 +59234,74 @@ ], "title": "TopicCandidate" }, + "TopicChange": { + "properties": { + "id": { + "type": "integer", + "title": "Id" + }, + "kind": { + "type": "string", + "title": "Kind", + "description": "merge or delete" + }, + "keep": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Keep", + "description": "the topic a merge kept" + }, + "labels": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Labels", + "description": "the topics that went", + "default": [] + }, + "by": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "By" + }, + "at": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "At" + }, + "undone": { + "type": "boolean", + "title": "Undone", + "default": false + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "id", + "kind" + ], + "title": "TopicChange" + }, "TopicCreate": { "properties": { "label": { @@ -59186,6 +59354,26 @@ ], "title": "TopicCreate" }, + "TopicDeleted": { + "properties": { + "ok": { + "type": "boolean", + "title": "Ok", + "default": true + }, + "undo": { + "type": "integer", + "title": "Undo", + "description": "the change to take back with POST /topics/changes/{undo}/undo" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "undo" + ], + "title": "TopicDeleted" + }, "TopicDetail": { "properties": { "id": { @@ -59440,6 +59628,120 @@ ], "title": "TopicMerge" }, + "TopicMerged": { + "properties": { + "id": { + "type": "integer", + "title": "Id" + }, + "namespace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Namespace" + }, + "label": { + "type": "string", + "title": "Label" + }, + "alt": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Alt", + "default": [] + }, + "definition": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Definition" + }, + "broader": { + "items": { + "$ref": "#/components/schemas/TopicRef" + }, + "type": "array", + "title": "Broader", + "default": [] + }, + "narrower": { + "items": { + "$ref": "#/components/schemas/TopicRef" + }, + "type": "array", + "title": "Narrower", + "default": [] + }, + "related": { + "items": { + "$ref": "#/components/schemas/TopicRef" + }, + "type": "array", + "title": "Related", + "default": [] + }, + "recordings": { + "type": "integer", + "title": "Recordings", + "default": 0 + }, + "from_entity": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "From Entity" + }, + "updated": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Updated" + }, + "about": { + "items": { + "$ref": "#/components/schemas/TopicAbout" + }, + "type": "array", + "title": "About", + "default": [] + }, + "undo": { + "type": "integer", + "title": "Undo", + "description": "the change to take back with POST /topics/changes/{undo}/undo" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "id", + "label", + "undo" + ], + "title": "TopicMerged" + }, "TopicRecordings": { "properties": { "recordings": {