diff --git a/CHANGELOG.md b/CHANGELOG.md index 0dc844b..6d28e3b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,38 @@ # Changelog +## 0.8.0 + +The library window is finished: everything in it now stays still while it loads and while you work. + +### New +- Collections inside collections. Each collection has a "New subcollection" action, and the tree can be folded. +- Move through the collection tree with the keyboard: up and down between rows, left and right to fold, unfold or step in and out, Enter to choose. +- Drop a PDF on the window in a browser and it is identified and added with the file attached. Dropping the same file again does not attach it twice. +- Notes can be added, edited in place and deleted in the item pane. +- Connections shows an app you approved that has not collected its access yet, and you can withdraw that approval. + +### Changed +- Adding, restoring or removing an item now changes only the rows that move in the list, where it used to read the page again. +- A title can no longer be saved empty from the item pane. +- Deleting a collection, restoring or deleting from the trash, and merging duplicates take effect at the click, and are put back if the engine refuses. +- The readme says that the window and agent tools look things up too, and that Preferences holds the switches. + +### Fixed +- The side pane no longer jumps one row when collections and tags first appear, or when a collection is created or deleted. +- Preferences no longer shifts when the services and libraries fill in, or when a library is created or switched; a new library row used to appear empty. +- The Trash button in the item pane no longer moves when it asks you to confirm. +- After renaming or deleting a collection, keyboard focus stays in the tree. + +### Known issues +- "Open in FormPDF" still opens the system viewer: FormPDF cannot yet take a file from another Form app. +- Removing an item the list has not loaded yet still reads the list again. +- Creators are still edited as one line of text. +- The tag list was not measured with real tags in this release. +- The desktop app has not been built yet; the window runs in a browser against the engine. + +### Under the hood +- A new engine route says where a row falls in the current sort and filter, and a raw upload route takes a dropped PDF. + ## 0.7.0 The window shows your library for the first time. This is a first pass: it works end to end, and parts of it have not yet been checked as closely as the rest. diff --git a/README.md b/README.md index 2ae8417..f4d8811 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ Another app on this computer, or an agent you run, can use your library only wit ## What FormCite sends over the network -Nothing, unless you ask for a lookup. `./formcite cli add doi=...` (or `arxiv=`, `isbn=`, `pmid=`) and `./formcite cli identify FILE.pdf` send the identifier, and only the identifier, to the service that knows it. A PDF and its text never leave your computer. There is no timer, no update check and no call at start-up. +Nothing, unless you ask for a lookup. `./formcite cli add doi=...` (or `arxiv=`, `isbn=`, `pmid=`) and `./formcite cli identify FILE.pdf` send the identifier, and only the identifier, to the service that knows it. The window does the same when you add by identifier or drop a PDF on it, and so do the lookup tools an agent calls. A PDF and its text never leave your computer. There is no timer, no update check and no call at start-up. | Service | Host | Asked for | | --- | --- | --- | @@ -60,7 +60,7 @@ Nothing, unless you ask for a lookup. `./formcite cli add doi=...` (or `arxiv=`, | Open Library | `openlibrary.org` | a book by ISBN | | PubMed | `eutils.ncbi.nlm.nih.gov` | an article by PubMed ID | -`./formcite cli network list` shows these with their switches, `network off` stops every call, `network disable NAME` stops one service, and `network log` shows every call that was made. Setting `FORMCITE_OFFLINE=1` forces the network off. No email address is sent unless you set one with `network contact`. The rules are in [`docs/NETWORK.md`](docs/NETWORK.md). +In the window, Preferences lists every service with a switch for each. `./formcite cli network list` shows these with their switches, `network off` stops every call, `network disable NAME` stops one service, and `network log` shows every call that was made. Setting `FORMCITE_OFFLINE=1` forces the network off. No email address is sent unless you set one with `network contact`. The rules are in [`docs/NETWORK.md`](docs/NETWORK.md). The data folder is `~/FormCite` (`FORMCITE_DATA_DIR`). Working on the code: see [`CONTRIBUTING.md`](CONTRIBUTING.md) and [`AGENTS.md`](AGENTS.md). diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 8c57e60..b9c5f93 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of all comment content, explainers, rationale, TODOs, & removed (hashed-out) code for this side of the repo. Source files stay comment-free per dev-rules `sub-skills/hashout-log/SUB-SKILL.md`; everything they would have said lives here, indexed. This file is also the compressed contextual map of this side: read it first, then edit code surgically. -Current build version: v0.7.0 +Current build version: v0.8.0 Last updated: 2026-11-27 (US Eastern) · the lean rows route for the window's list and opening an attachment --- @@ -1649,3 +1649,15 @@ The item list's lean rows: one SQL statement per page, never `items.get` per row - logged: v0.7.0 · 2026-11-27 FormTxt hands a PDF to FormPDF by POSTing `{"path"}` to `http://127.0.0.1:8198/api/pdf/open-path` (`formtxt/backend/app/services/versions_docs.py :: sign_handoff`). FormPDF's `WindowKeyGuard` refuses every POST without its own window key, and `/api/pdf/open-path` is not in its `OPEN` list, so that handoff is refused today; FormCite also may not open connections outside `app/net`, which is https only. So FormCite only reports whether a FormPDF install is present (`FORMCITE_FORMPDF_APP`, or `FormPDF.app` under `/Applications` or `~/Applications`) and always opens with the system viewer. The viewer is started from an argument list (`xdg-open`, `open`) or `os.startfile`, never a shell string, detached with `start_new_session` and no standard streams. The route sits behind `window_only` as well as the global guard, so a reader token can never open files. + +## app/routers/pair.py {#app-routers-pair-waiting} + +New in v0.7.0 (2026-11-27). `GET /api/cite/v1/pair/approved/waiting` lists approved pairing requests that have not been collected, from `pairing.listing(True)` filtered to `approved`. It lives under the service prefix, which the global guard lets through without a window key, so the route checks `window_key.valid` itself and answers 403 without it. It is declared before `/{request_id}` so it is not read as a request id. The token is still made when the app collects it. There is no withdraw route: `pairing._decide` only answers pending requests and `store` has no function to remove a request, both outside this slice. + +## app/routers/upload.py {#app-routers-upload-identify} + +New in v0.7.0 (2026-11-27). `POST /api/library/identify/upload?name=` reads the raw body with `Request.stream()`, so python-multipart is not needed. Neither guard looks at the content type: `WindowKeyGuard` only wants the key header on a non-read method and `LocalGuard` only checks host and origin, so the route is guarded exactly like `/identify`. `content-length` over `MAX_BYTES` (100 MB) is refused before reading, and the streamed count is checked again since the header can be absent or false. The first five bytes must be `%PDF-` or the answer is 415. The name is cut to its last path part and cleaned by `SAFE`, inside a fresh `mkdtemp` folder, so `..%2F..%2Fetc%2Fpasswd` becomes `passwd.pdf` there. `identify_file` runs in the thread pool through the path route's `_run`, so error mapping is shared; the file and folder are removed in `finally`. Dropping the same PDF twice no longer adds a second row: `identify._already` checks the matched item's attachments by sha256 before `_attach`, returns the existing row (with `path`) as `attached`, and the message says nothing was changed. It runs before any store, so `move` leaves the source file in place. Path route, upload route and CLI all go through `identify_file`, so they agree; the CLI was checked twice against the same data. + +## app/routers/window.py, app/services/window_rows.py {#app-window-row-position} + +New in v0.8.0 (2026-11-27). `GET /api/library/rows/{id}/position` takes the same `scope`, `id`, `q`, `sort` and `desc` as `GET /api/library/rows` and returns `{index, total}`. The index is `ROW_NUMBER() OVER (ORDER BY ...) - 1` built from the same `SORTS` expression, direction and `i.id` tie-break, under the same `_where`, so it can never disagree with the rows route. It is `-1` when the item exists but is outside the scope or filter (a trashed item is always `-1`), and the route answers 404 when no item has that id. Checked against `list_rows` on 2,002 items: year descending at offsets 700 to 702 and title with `q=river` at offsets 100 and 101 all matched. diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 49e0fc1..777f190 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -1 +1 @@ -__version__ = "0.7.0" +__version__ = "0.8.0" diff --git a/backend/app/routers/pair.py b/backend/app/routers/pair.py index 021a313..04230f7 100644 --- a/backend/app/routers/pair.py +++ b/backend/app/routers/pair.py @@ -3,6 +3,7 @@ from fastapi import APIRouter, Header, HTTPException from pydantic import BaseModel +from app.core import window_key from app.service import pairing, store from app.store.errors import Invalid, NotFound @@ -34,6 +35,14 @@ def ask(body: Ask) -> dict: return _run(pairing.ask, body.host, body.name, body.scope) +@router.get("/approved/waiting") +def approved_waiting(x_formcite_window_key: str | None = Header(default=None)) -> dict: + if not window_key.valid(x_formcite_window_key): + raise HTTPException(403, window_key.REFUSED) + rows = [r for r in _run(pairing.listing, True) if r["status"] == "approved"] + return {"requests": rows} + + @router.get("/{request_id}") def collect(request_id: str, x_formcite_pair_secret: str | None = Header(default=None)) -> dict: return _run(pairing.collect, request_id, x_formcite_pair_secret) diff --git a/backend/app/routers/registry.py b/backend/app/routers/registry.py index b3a8770..2b7ef3f 100644 --- a/backend/app/routers/registry.py +++ b/backend/app/routers/registry.py @@ -38,3 +38,4 @@ def mount(app: FastAPI) -> None: register("service", __import__("app.routers.service", fromlist=["router"]).router) register("cite_write", __import__("app.routers.cite_write", fromlist=["router"]).router) register("window", __import__("app.routers.window", fromlist=["router"]).router) +register("upload", __import__("app.routers.upload", fromlist=["router"]).router) diff --git a/backend/app/routers/service.py b/backend/app/routers/service.py index bab3859..4961e8b 100644 --- a/backend/app/routers/service.py +++ b/backend/app/routers/service.py @@ -45,6 +45,11 @@ def deny(request_id: str) -> dict: return _run(pairing.deny, request_id) +@router.post("/requests/{request_id}/withdraw") +def withdraw(request_id: str) -> dict: + return _run(pairing.withdraw, request_id) + + @router.get("/tokens") def tokens() -> dict: return {"tokens": _run(store.tokens)} diff --git a/backend/app/routers/upload.py b/backend/app/routers/upload.py new file mode 100644 index 0000000..58956f2 --- /dev/null +++ b/backend/app/routers/upload.py @@ -0,0 +1,59 @@ +import os +import re +import tempfile +from pathlib import Path + +from fastapi import APIRouter, HTTPException, Request +from fastapi.concurrency import run_in_threadpool + +from app.routers.identify import _run +from app.services import identify as svc + +GROUP = "upload" +router = APIRouter(prefix="/library", tags=[GROUP]) + +MAX_BYTES = 100 * 1024 * 1024 +MAGIC = b"%PDF-" +SAFE = re.compile(r"[^A-Za-z0-9._ -]+") + + +def _safe_name(name: str) -> str: + base = SAFE.sub("_", Path(name.replace("\\", "/")).name).strip(" .")[:120] + stem = base[:-4] if base.lower().endswith(".pdf") else base + return (stem or "dropped") + ".pdf" + + +@router.post("/identify/upload") +async def identify_upload(request: Request, name: str = "dropped.pdf") -> dict: + declared = request.headers.get("content-length", "") + if declared.isdigit() and int(declared) > MAX_BYTES: + raise HTTPException(413, f"The file is larger than {MAX_BYTES // (1024 * 1024)} MB") + folder = tempfile.mkdtemp(prefix="formcite-upload-") + target = os.path.join(folder, _safe_name(name)) + try: + size = 0 + head = b"" + with open(target, "wb") as out: + async for chunk in request.stream(): + if not chunk: + continue + size += len(chunk) + if size > MAX_BYTES: + raise HTTPException(413, f"The file is larger than {MAX_BYTES // (1024 * 1024)} MB") + if len(head) < len(MAGIC): + head += chunk[: len(MAGIC) - len(head)] + if len(head) >= len(MAGIC) and head != MAGIC: + raise HTTPException(415, "Only PDF files can be identified") + out.write(chunk) + if head != MAGIC: + raise HTTPException(415, "Only PDF files can be identified") + return await run_in_threadpool(_run, svc.identify_file, target, attach="copy", on_duplicate="skip", add=True) + finally: + try: + os.remove(target) + except OSError: + pass + try: + os.rmdir(folder) + except OSError: + pass diff --git a/backend/app/routers/window.py b/backend/app/routers/window.py index 71632d1..3315fa6 100644 --- a/backend/app/routers/window.py +++ b/backend/app/routers/window.py @@ -41,6 +41,18 @@ def rows( ) +@router.get("/rows/{item_id}/position") +def row_position( + item_id: str, + scope: str = "all", + id: str | None = None, + q: str | None = None, + sort: str = "title", + desc: bool = False, +) -> dict: + return _run(window_rows.row_position, item_id, scope=scope, scope_id=id, q=q, sort=sort, desc=desc) + + @router.get("/rows/{item_id}") def row(item_id: str) -> dict: return _run(window_rows.one_row, item_id) diff --git a/backend/app/service/pairing.py b/backend/app/service/pairing.py index dd3bbb9..941f912 100644 --- a/backend/app/service/pairing.py +++ b/backend/app/service/pairing.py @@ -93,6 +93,23 @@ def deny(request_id: str) -> dict[str, Any]: return _decide(request_id, "denied") +def withdraw(request_id: str) -> dict[str, Any]: + now = int(time.time()) + with store._locked(): + data = store._read() + _expire(data, now) + req = next((r for r in data["requests"] if r["id"] == request_id), None) + if req is None: + store._write(data) + raise NotFound(f"pairing request {request_id}") + if req["status"] != "approved" or req.get("token_id"): + store._write(data) + raise Invalid(f"The pairing request {request_id} is {req['status']}, so its approval cannot be withdrawn.") + req["status"] = "denied" + store._write(data) + return public(req) + + SAY = { "pending": "Waiting for a person to approve or deny this request in FormCite.", "denied": "The person who uses FormCite denied this request.", diff --git a/backend/app/services/identify.py b/backend/app/services/identify.py index 56bf2d4..fc360d0 100644 --- a/backend/app/services/identify.py +++ b/backend/app/services/identify.py @@ -66,6 +66,14 @@ def _finish(lib, path: str, mode: str, attached: dict) -> dict: return {**attached, "path": str(files.abs_path(lib, attached))} +def _already(lib, conn, item_id: str, path: str) -> dict | None: + sha = files.sha256_of(path) + for found in attachments.for_item(conn, item_id): + if found["sha256"] == sha: + return {**found, "path": str(files.abs_path(lib, found))} + return None + + def _attach(lib, conn, item_id: str, path: str, mode: str) -> dict: stored = None try: @@ -117,10 +125,12 @@ def identify_file(path: str, *, attach: str = "copy", on_duplicate: str = "skip" return {**base, "found": True, "source": source, "record": resolved["record"], "duplicates": matches, "message": "Looked up; nothing was added."} if matches and on_duplicate == "skip": - attached = _attach(lib, conn, matches[0], path, attach) + held = _already(lib, conn, matches[0], path) + attached = held or _attach(lib, conn, matches[0], path, attach) + said = "this file was already attached to it, so nothing was changed" if held else "the file was attached to it" return {**base, "found": True, "source": source, "duplicate_of": matches[0], "attached": attached, "item": detail(conn, matches[0]), - "message": f"The item is already in the library as {matches[0]}; the file was attached to it."} + "message": f"The item is already in the library as {matches[0]}; {said}."} made, attached = _create(lib, conn, resolved["record"], source, path, attach) return {**base, "found": True, "added": True, "source": source, "duplicate_of": None, "attached": attached, "item": detail(conn, made["id"]), diff --git a/backend/app/services/window_rows.py b/backend/app/services/window_rows.py index bff4c55..e897af5 100644 --- a/backend/app/services/window_rows.py +++ b/backend/app/services/window_rows.py @@ -107,6 +107,37 @@ def rows( return {"total": total, "offset": offset, "rows": [_row(r) for r in found]} +def position( + conn: sqlite3.Connection, + item_id: str, + *, + scope: str = "all", + scope_id: str | None = None, + q: str | None = None, + sort: str = "title", + desc: bool = False, +) -> dict: + if sort not in SORTS: + raise Invalid(f"sort must be one of {', '.join(SORTS)}") + if conn.execute("SELECT 1 FROM items WHERE id = ?", (item_id,)).fetchone() is None: + raise NotFound(f"no item {item_id}") + clauses, args = _where(scope, scope_id, q) + where = " WHERE " + " AND ".join(clauses) + total = conn.execute("SELECT COUNT(*) FROM items i" + where, args).fetchone()[0] + direction = "DESC" if desc else "ASC" + ranked = ( + f"SELECT n FROM (SELECT i.id AS id, ROW_NUMBER() OVER (ORDER BY {SORTS[sort]} {direction}, " + f"i.id {direction}) - 1 AS n FROM items i{where}) WHERE id = ?" + ) + found = conn.execute(ranked, [*args, item_id]).fetchone() + return {"index": found[0] if found else -1, "total": total} + + +def row_position(item_id: str, **kwargs) -> dict: + with session() as (_, conn): + return position(conn, item_id, **kwargs) + + def row(conn: sqlite3.Connection, item_id: str) -> dict: found = conn.execute(COLUMNS + " WHERE i.id = ?", (item_id,)).fetchone() if found is None: diff --git a/docs/IDENTIFY_PDF.md b/docs/IDENTIFY_PDF.md index 2388b83..c2575b0 100644 --- a/docs/IDENTIFY_PDF.md +++ b/docs/IDENTIFY_PDF.md @@ -6,6 +6,8 @@ FormCite can read a PDF you give it, find an identifier printed in it, look that - Command line: `./formcite cli identify FILE`. Options: `--no-add` looks up and adds nothing; `--move` moves the file into the library, `--link` leaves it where it is (the default copies it); `--add-duplicate` adds a new item even when the library already holds the work; `--scan` only lists the identifiers and never goes to the network. - Routes: `POST /api/library/identify` with `{path, attach?, add?, on_duplicate?}` (`attach` is `copy`, `move` or `link`); `POST /api/library/identify/scan` with `{path}` only lists the identifiers. Both need the window key like every other route. +- Upload: `POST /api/library/identify/upload?name=FILE_NAME` with the raw PDF bytes as the body (not a form). It needs the window key too. The bytes must start with `%PDF-` (otherwise 415) and stay within 100 MB (otherwise 413). They are written to a temporary folder under a name cleaned from `name` (only its last part, letters, digits, dot, dash, underscore and space, ending in `.pdf`), identified with `attach` copy, `add` on and `on_duplicate` skip, and the temporary file is removed afterwards. The answer has the same shape as the path route; its `file` is the temporary path, which no longer exists. +- Window: a PDF dropped on the window is sent to the upload route, since a browser never gives a path. Only when the desktop shell hands over a real path is the path route used. Progress and the answer appear in the line under the Import tab, which keeps its height, and in a short notice. ## What is read @@ -33,7 +35,7 @@ Where it was found comes first: the metadata, then the first page, then later pa ## What is added -The item, its import batch and the attachment are written together: a failed lookup or a failed write leaves neither an item nor a stored file. When the library already holds the work (the duplicate check by DOI, then by title, year and first author), the file is attached to that item and the answer says so. A moved file is removed from its old place only after everything is written. +The item, its import batch and the attachment are written together: a failed lookup or a failed write leaves neither an item nor a stored file. When the library already holds the work (the duplicate check by DOI, then by title, year and first author), the file is attached to that item and the answer says so. When that item already holds an attachment with the same contents (same sha256), nothing is stored or recorded, `attached` is the existing attachment, and the answer says the file was already attached and nothing was changed; with `--move` the file then stays where it was. A moved file is removed from its old place only after everything is written. ## Limits diff --git a/docs/NETWORK.md b/docs/NETWORK.md index 8a562f9..b758085 100644 --- a/docs/NETWORK.md +++ b/docs/NETWORK.md @@ -4,7 +4,7 @@ FormCite works offline. From version 0.5.0 it can look a reference up by its ide ## The rules -1. **Nothing in the background.** FormCite calls a service only when a person or an agent asked for exactly that lookup: a verb such as `./formcite cli add doi=...`, a route such as `POST /api/library/lookup`, or identifying a file someone dropped. There is no timer, no start-up check, no update check and no prefetch. +1. **Nothing in the background.** FormCite calls a service only when a person or an agent asked for exactly that lookup: a verb such as `./formcite cli add doi=...`, a route such as `POST /api/library/lookup`, or identifying a PDF someone named (`POST /api/library/identify`, `/identify/scan`) or dropped on the window (`POST /api/library/identify/upload`). There is no timer, no start-up check, no update check and no prefetch: the engine's start-up only writes its own discovery file, and the window's only repeating calls go to the engine on this computer. 2. **Every host is declared.** A service is registered with a name, one host, a purpose and the address of its own documentation. A fetch is refused unless the address is `https` and its host is exactly the registered host. A redirect is followed only to `https` on a host some registered service declares, at most three times, and never to a service you have switched off. 3. **You hold the switches.** The whole network can be switched off, and so can each service. When a switch is off, the lookup fails with a plain sentence before any connection is opened, and nothing is added to the library. 4. **Every call is logged** in a file in your data folder that you can read. @@ -26,6 +26,8 @@ They live in `network.json` in the data folder, beside `libraries.json` (the dat | One service off or on | `./formcite cli network disable NAME`, `network enable NAME` | `PUT /api/network/services/NAME` `{"enabled": false}` | | Read the log | `./formcite cli network log --limit 20` | `GET /api/network/log?limit=20` | +The window shows the same list in Preferences under Network: the master switch, one switch per service with its purpose, the contact address and the recent calls. Its list comes from `GET /api/network/services`. + Setting the environment variable `FORMCITE_OFFLINE=1` forces the network off for that process, whatever `network.json` says. It is read on every call and never written to the file. ## The log diff --git a/docs/SERVICE_TOKENS.md b/docs/SERVICE_TOKENS.md index 86af968..f9d87ea 100644 --- a/docs/SERVICE_TOKENS.md +++ b/docs/SERVICE_TOKENS.md @@ -66,6 +66,8 @@ In the window, on routes that need the window key on every method (GETs too, bec - `GET /api/service/requests` lists waiting requests - `POST /api/service/requests/{id}/approve` with `{"scope":"read"}` or `{"scope":"write"}` (leave it out to grant what was asked) - `POST /api/service/requests/{id}/deny` +- `GET /api/cite/v1/pair/approved/waiting` lists requests that are approved and not yet collected (same window key rule, though it sits under the pairing path; answers 403 without the key). The Connections view shows them as "Approved, waiting for the app to collect" until the app collects its token, which moves the row to the connected apps, or fifteen minutes pass. The row has a "Withdraw approval" button. +- `POST /api/service/requests/{id}/withdraw` withdraws an approval while it is approved and no token was made. The request ends as `denied`, so the app's next poll answers `"denied"` and no token is ever made. After the app has collected, it answers 422; revoke the token instead. - `GET /api/service/tokens` lists tokens, never their values - `DELETE /api/service/tokens/{id}` revokes one diff --git a/docs/WINDOW.md b/docs/WINDOW.md index aee0d2c..e50c192 100644 --- a/docs/WINDOW.md +++ b/docs/WINDOW.md @@ -11,7 +11,8 @@ The **Items** view has three panes side by side. ### Library pane (left) - **All items** shows every item that is not in the trash. **Unfiled** shows the items that belong to no collection. Each entry has its count beside it. -- **Collections** is a tree. Click a collection to list its items. You can create a collection, rename it and delete it in place, without a dialog. Deleting a collection does not delete its items. +- **Collections** is a tree. Click a collection to list its items. You can create a collection, rename it and delete it in place, without a dialog. Each collection row also has a plus button, **New subcollection**, that adds a collection inside it. Deleting a collection does not delete its items. The row (and the collections inside it) is hidden at the click and comes back if the engine refuses; if the focus was on it, the focus moves to the next row at the same or a shallower level, or the one above. +- The tree works from the keyboard: the up and down arrows move between visible rows, Home and End jump to the first and last, the right arrow opens a collection (and a second press moves into it), the left arrow closes it (or moves to its parent), and Enter or Space picks the row. - **Tags** lists every tag. Click one to list the items that carry it. A tag can be renamed or deleted from here. - The entry you are looking at stays marked. @@ -20,12 +21,14 @@ The **Items** view has three panes side by side. - Columns: title, creator, year, type and date added. Click a column head to sort by it, click again to reverse. - The search box filters the list by words in titles, creators, container titles, abstracts, notes and tags. - Click a row or use the arrow keys to select it. The list stays smooth with thousands of items: only the rows on screen exist, and scrolling rewrites them. +- When an item is added or restored, the window asks the engine where that one row falls in the current list (`GET /api/library/rows/{id}/position`) and inserts only that row. When an item is removed, the rows below move up and only rows that were not yet loaded are fetched. If the engine cannot say where a row falls, or a removed item was never loaded, the list is read again. - The creator column shows the first author, "A and B" for two authors, or "A et al." for more. Items with no year sort after the rest. ### Detail pane (right) - Shows the selected item: type, title, creators, date, container, volume, issue, pages, DOI, URL, abstract, tags, attachments and notes. -- Edit a field and leave it (or press Enter) to save that one field. Escape puts the old value back. +- Edit a field and leave it (or press Enter) to save that one field. Escape puts the old value back. A title cannot be saved empty: the window refuses with "A title is required." +- Notes are editable in place: change a note's text and leave it (or press Ctrl or Cmd with Enter) to save it, and Escape puts the old text back. A note cannot be saved empty. Type in the box under the notes and press Enter to add one. **Delete** on a note asks for a second click, labelled Confirm, within 3 seconds. - Add a tag by typing it, remove one with its remove button. - **Move to trash** asks you to confirm in place, then sends the item to the trash. @@ -37,17 +40,21 @@ The **Add** button opens a dialog with three ways in: - **Import.** Paste text or pick a file in BibTeX, RIS or CSL-JSON. The format can be picked or left for FormCite to recognise. - **Export.** Save the items you are looking at in one of those formats. -You can also drop PDF files anywhere on the window. FormCite reads each one, finds its identifier, looks it up and attaches the file to the new item. Other files that FormCite can import are imported. +You can also drop PDF files anywhere on the window. The window sends each dropped file's bytes to the engine, which reads it, finds its identifier, looks it up and attaches the file to the new item; no file path is needed, and progress shows in place. If the item is already in the library and already holds a file with the same content, the file is not attached a second time. Other files that FormCite can import are imported. When the network is switched off, or the one service a lookup needs is off, the dialog says so in the engine's own words and nothing is added. ## Trash -The **Trash** view lists the items you have moved to the trash. Each row has **Restore**, which puts the item back where it was, and **Delete for good**. **Empty trash** removes everything in it after you confirm in the same row. Nothing leaves the trash on its own. +The **Trash** view lists the items you have moved to the trash. Each row has **Restore**, which puts the item back where it was, and **Delete for good**, which asks for a second click in the same row and goes back to normal after 3 seconds. **Empty trash** removes everything in it after you confirm beside the button. A row leaves the list as you click, and comes back with a message if the engine refuses. Nothing leaves the trash on its own. ## Duplicates -The **Duplicates** view lists sets of items that look like the same reference: the same DOI, or the same title, year and first author. Each set shows its members side by side with the fields that differ. Choose the one to keep and press **Merge**: the others are folded into it, keeping their tags, collections, notes and attachments. +The **Duplicates** view lists sets of items that look like the same reference: the same DOI, or the same title, year and first author. Each set shows its members side by side with the fields that differ. The oldest copy is kept unless you choose another. Press **Merge** and the set leaves the list at once: the others go to the trash, and the kept item is updated. + +## Connections + +The **Connections** view lists the apps and agents that use FormCite's service. Apps whose request you approved but that have not yet collected their token are listed in a third group, **Approved, waiting for the app to collect**, with how long the app has left to collect it. That row has **Withdraw approval**, which takes the approval back before the app collects it. ## Preferences diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 38e9321..d7a9c17 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of all comment content, explainers, rationale, TODOs, & removed (hashed-out) code for this side of the repo. Source files stay comment-free per dev-rules `sub-skills/hashout-log/SUB-SKILL.md`; everything they would have said lives here, indexed. This file is also the compressed contextual map of this side: read it first, then edit code surgically. -Current build version: v0.7.0 +Current build version: v0.8.0 Last updated: 2026-11-26 (US Eastern) · window skeleton: shell, engine store, window key, health status --- @@ -380,3 +380,31 @@ New in v0.7.0 (2026-11-27). The detail pane appends one form to its host at moun ## src/ui/trash.ts, src/ui/duplicates.ts, src/engine/review.ts, src/io/review.ts, src/styles/review.css {#src-review} New in v0.7.0 (2026-11-27). The Trash and Duplicates views, each built once into its pane host and loaded when `engine.library` emits `view` for it; rows and groups are keyed and patched with `patchList`, so a restore or a merge removes one node. Confirmations (delete one for good, empty the trash) swap hidden buttons in the same reserved space. Duplicate groups show only the fields the engine's summary carries (title, creator, year, DOI, added), so a group can read "identical" while stored fields not shown differ. The stylesheet is imported from the two view modules because `index.html` is a scaffold file this slice does not edit. The window key is claimed once per engine process, and the engine must be started with `FORMCITE_UI_PORT` set to the dev UI port or its origin guard refuses the page. + +## src/ui/connections.ts, src/engine/connections.ts, src/io/service.ts {#src-connections-waiting} + +New in v0.7.0 (2026-11-27). A third group in the Connections view lists approved requests the app has not collected yet, read from `GET /api/cite/v1/pair/approved/waiting` with the other two lists in one `Promise.all`. The engine keeps a `waiting` map and emits `waiting:add`, `waiting:update` and `waiting:remove`; approving a request re-reads waiting and apps, so the row leaves the pending list and appears in waiting without a rebuild. The waiting row has no action: the store has no way to take an approval back and `deny` only works on a pending request. Checked in a private built copy under CPU 4x and 400 ms latency: no layout shift on approve or on collect, and one node added and one removed per change. A waiting row is about 3 px shorter than a pending row (it has no buttons), which stays inside its own list. + +## src/ui/side.ts, src/styles/side.css {#src-side-tree} + +New in v0.8.0 (2026-11-27). The side sections sit under `visibility: hidden` (`.fc-side-pane.is-held`) until the first collections, tags and totals reads settle, and a status line with no text is `display: none`, so `p.fc-empty.fc-side-msg` no longer moves a row down when the lists fill or a collection is created or deleted. Collection rows carry a third action, new subcollection, which opens the existing name field with the row as `parent_id` (`POST /api/library/collections` already takes it). The collection list is an aria tree: `li` has `role="none"`, the entry button is the `treeitem` with `aria-level`, `aria-expanded` when it has children and `aria-selected`, and one roving `tabindex="0"`. Up, Down, Home and End move between visible rows; Right unfolds or steps to the first child; Left folds or steps to the parent; Enter and Space select. Folded state lives in the pane and is not stored. Checked in a private built copy with 2,000 items under CPU 4x and 400 ms latency: no layout shift without input and none on creating a subcollection. + +## src/engine/itemlist.ts, src/ui/itemlist.ts {#src-itemlist-single-rows} + +New in v0.8.0 (2026-11-27). `items:removed` calls `ItemListModel.remove`: the ids are dropped from the sparse row cache, every later cached index moves up by the number of removed indices before it, the count drops, and `reset` repaints the 55 pool rows through the guarded `setText`/`setClass` writes, so only rows whose content moved are written. `ensure` now fetches runs of missing indices (at most `PAGE` long) instead of whole pages, so the rows that slide into the window at the end are the only ones read. An id the cache has never seen falls back to `reload`, because its place among unread pages is unknown. `items:added` and `items:restored` call `insert`: each row is read with `GET /api/library/rows/{id}`, its place is guessed from the cached rows with a client comparator (lowercase `localeCompare`, numbers for added, updated and year), and one nine-row probe of `GET /api/library/rows` around the guess confirms it; the engine has no route that returns a row's position in a sort and filter, so a probe that misses the id falls back to `reload`, and a probe whose total did not grow means the row is outside the scope or filter and nothing is written. Scroll top, selection and focus are not touched. Checked in a private built copy with 2,000 items under CPU 4x and 400 ms latency, title sort, scrolled to row 300: remove, restore and add each wrote 43 or 44 rows (only the rows at and after the change), zero pool nodes added or removed, no layout shift. Later the same day the guess and probe were replaced: `insert` now calls `fetchPosition`, which uses `GET /api/library/rows/{id}/position`, and re-reads only when the route answers 404 or 405 (an older engine) or when the total it returns does not agree. A remove of an id the cache never loaded still re-reads, because a trashed item has no position to ask for. + +## src/ui/trash.ts, src/ui/duplicates.ts {#src-review-click} + +New in v0.8.0 (2026-11-27). Checked in a private built copy with 2,000 items (20 added as deliberate duplicates), CPU 4x, 400 ms and about 400 kbit/s, after a hard reload. A row that left only when the reply arrived moved the rows below it more than 500 ms after the click, which counted as 0.1498 of shift without input (the merged group). Restore, Delete for good and Merge now take the row out of the list at the click and put it back with the message if the engine refuses, so every shift sits inside the input window (about 0.01 per trash row, 0.1498 for the group). Delete for good drops its second-click confirmation after 3 seconds. The trash listens for `items:removed` and `items:restored` and reloads while hidden, so reopening it after a merge or a trashing elsewhere inserts nothing in view (a stale list that gained a row at the top had counted 0.0092 without input). + +## src/ui/preferences.ts, src/styles/preferences.css {#src-preferences-rows} + +New in v0.8.0 (2026-11-27). `patchList` calls `update` only for rows it already had, so service and library rows were born empty and got their text on the next load, which grew `.fc-pr-text` from 2 px to about 40 px and moved `fc-btn` (0.00036 on a switch). Each row is now filled in `create`, and every line in a service or library row is a fixed 15 px block. Checked in a private built copy with 2,000 items under CPU 4x, 400 ms and about 400 kbit/s: 0 shift without input and 0 with input on opening, creating and switching; a create adds one row, a switch moves the badge text only. Preferences lists seven services (arxiv, crosscite, crossref, datacite, doi-org, openlibrary, pubmed), the same set the backend registers in `app/lookup/`; no other module opens an outbound connection. + +## src/engine/detail.ts, src/styles/detail.css {#src-detail-click} + +New in v0.8.0 (2026-11-27). The engine stores an empty title without complaint, so `DetailModel.save` refuses it before any request and the pane shows "Title: A title is required." in its error line with the row marked; Escape puts the stored title back. The Trash button keeps its 88 px width and now starts its content at the left, with a hidden `::after` holding "Confirm" so the label box is sized for the longer label; the icon stays at the same x when armed. Checked in a private built copy with 2,000 items under CPU 4x, 400 ms and about 400 kbit/s after a hard reload: remove tag, Open and Trash each take the click at their centre, Open sends `POST /api/library/attachments/{id}/open` and gets 200 with `opened_with: "system"`, Trash removes the row and drops the count by one, and layout shift was 0 with and without input. + +## src/io/detail.ts, src/engine/detail.ts, src/ui/detail.ts, src/styles/detail.css {#src-detail-notes} + +New in v0.8.0 (2026-11-27). Notes are editable in the pane through `POST /api/library/items/{id}/notes`, `PATCH /api/library/notes/{id}` and `DELETE /api/library/notes/{id}`, each with `{body}`. Each note is a one-line textarea inside the fixed-height notes box; it saves on blur or Ctrl or Cmd plus Enter, Escape puts back the stored text (kept in `data-saved`), and an empty edit is refused with a sentence in the reserved `.fc-dt-note-error` line. A line under the box adds a note on Enter. Delete asks for a second click within 3 seconds and its label box is sized for "Confirm", so the icon does not move. Notes are shown and sent as plain text: an HTML body from an import is flattened the first time it is saved. Checked in a fresh copy from HEAD with the 2,000-item library under CPU 4x, 400 ms and about 400 kbit/s: add, edit, Escape, delete and a reload all held, the box height did not change, and layout shift was 0 with and without input. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index f867907..81a9f70 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "formcite", - "version": "0.7.0", + "version": "0.8.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formcite", - "version": "0.7.0", + "version": "0.8.0", "license": "GPL-3.0-only", "devDependencies": { "typescript": "7.0.2", diff --git a/frontend/package.json b/frontend/package.json index 8bbaf69..78a47d2 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "formcite", "private": true, - "version": "0.7.0", + "version": "0.8.0", "description": "FormCite: a local-first personal research library from the Form family", "license": "GPL-3.0-only", "type": "module", diff --git a/frontend/src/engine/add.ts b/frontend/src/engine/add.ts index d47d2fa..c21d3e4 100644 --- a/frontend/src/engine/add.ts +++ b/frontend/src/engine/add.ts @@ -85,9 +85,9 @@ export class Adding { } } - async identify(path: string): Promise { + async identify(source: string | File): Promise { try { - const r = await io.identifyPath(path); + const r = typeof source === 'string' ? await io.identifyPath(source) : await io.identifyUpload(source); if (r.added && r.item) this.library.itemsAdded([r.item.id]); else if (r.duplicate_of) this.library.itemChanged(r.duplicate_of); if (!r.found) return { ok: false, text: r.message }; diff --git a/frontend/src/engine/connections.ts b/frontend/src/engine/connections.ts index 8b2a1e0..ea292a1 100644 --- a/frontend/src/engine/connections.ts +++ b/frontend/src/engine/connections.ts @@ -25,8 +25,10 @@ export interface ConnectedApp { export interface ConnectionsTransport { requests(): Promise; apps(): Promise; + waiting(): Promise; approve(id: string, scope: Grant): Promise; deny(id: string): Promise; + withdraw(id: string): Promise; revoke(id: string): Promise; } @@ -41,6 +43,9 @@ export interface ConnectionsEvents { 'request:update': PendingRequest; 'request:remove': string; 'request:arrived': PendingRequest[]; + 'waiting:add': PendingRequest; + 'waiting:update': PendingRequest; + 'waiting:remove': string; 'app:add': ConnectedApp; 'app:update': ConnectedApp; 'app:remove': string; @@ -61,6 +66,7 @@ export class Connections { readonly events = new Emitter(); private readonly requests = new Map(); private readonly apps = new Map(); + private readonly waiting = new Map(); private readonly busy = new Set(); private status: ConnectionsStatus = { loaded: false, loading: false, error: '' }; private transport: ConnectionsTransport | null = null; @@ -81,9 +87,10 @@ export class Connections { const t = this.transport; if (!t) return Promise.resolve(); this.setStatus({ ...this.status, loading: true }); - this.inflight = Promise.all([t.requests(), t.apps()]) - .then(([reqs, apps]) => { + this.inflight = Promise.all([t.requests(), t.apps(), t.waiting()]) + .then(([reqs, apps, waiting]) => { this.mergeRequests(reqs); + this.mergeWaiting(waiting); this.mergeApps(apps); this.setStatus({ loaded: true, loading: false, error: '' }); }) @@ -102,6 +109,12 @@ export class Connections { return this.act(id, (t) => t.deny(id), () => this.dropRequest(id), false); } + withdraw(id: string): Promise { + return this.act(id, (t) => t.withdraw(id), () => { + if (this.waiting.delete(id)) this.events.emit('waiting:remove', id); + }, false); + } + revoke(id: string): Promise { return this.act(id, (t) => t.revoke(id), () => { const app = this.apps.get(id); @@ -120,7 +133,11 @@ export class Connections { try { await run(t); done(); - if (reloadApps) this.mergeApps(await t.apps()); + if (reloadApps) { + const [waiting, apps] = await Promise.all([t.waiting(), t.apps()]); + this.mergeWaiting(waiting); + this.mergeApps(apps); + } return true; } catch (err) { this.setStatus({ ...this.status, error: err instanceof Error ? err.message : String(err) }); @@ -163,6 +180,16 @@ export class Connections { if (this.requests.size !== before || arrived.length) this.events.emit('count', this.requests.size); } + private mergeWaiting(list: PendingRequest[]): void { + const seen = new Set(list.map((r) => r.id)); + for (const id of [...this.waiting.keys()]) if (!seen.has(id)) { this.waiting.delete(id); this.events.emit('waiting:remove', id); } + for (const r of list) { + const old = this.waiting.get(r.id); + if (!old) { this.waiting.set(r.id, r); this.events.emit('waiting:add', r); } + else if (!sameRequest(old, r)) { this.waiting.set(r.id, r); this.events.emit('waiting:update', r); } + } + } + private mergeApps(list: ConnectedApp[]): void { const seen = new Set(list.map((a) => a.id)); for (const id of [...this.apps.keys()]) if (!seen.has(id)) { this.apps.delete(id); this.events.emit('app:remove', id); } @@ -191,5 +218,6 @@ export function registerConnectionCommands(commands: CommandRegistry, c: Connect }, }); commands.register({ id: 'connections.deny', title: 'Deny a connection request', run: (args) => { void c.deny(idOf(args)); } }); + commands.register({ id: 'connections.withdraw', title: 'Withdraw an approval', run: (args) => { void c.withdraw(idOf(args)); } }); commands.register({ id: 'connections.revoke', title: 'Remove an app\'s access', run: (args) => { void c.revoke(idOf(args)); } }); } diff --git a/frontend/src/engine/detail.ts b/frontend/src/engine/detail.ts index 8ee90e1..0a9649c 100644 --- a/frontend/src/engine/detail.ts +++ b/frontend/src/engine/detail.ts @@ -1,4 +1,4 @@ -import { detailApi, type CslName, type ItemDetail } from '../io/detail'; +import { detailApi, type CslName, type ItemDetail, type Note } from '../io/detail'; import type { Library } from './library'; export type FieldKind = 'line' | 'block' | 'type'; @@ -96,6 +96,7 @@ export class DetailModel { if (!item) return false; const value = text.trim(); if (value === fieldText(item, spec.key)) return false; + if (spec.key === 'title' && !value) throw new Error('A title is required.'); const next = await detailApi.editField(item.id, spec.sendKey, value); if (this.current?.id === item.id) this.current = next; this.library.itemChanged(item.id); @@ -131,4 +132,31 @@ export class DetailModel { } open(attachmentId: string) { return detailApi.openAttachment(attachmentId); } + + async addNote(body: string): Promise { + const item = this.current; + const clean = body.trim(); + if (!item || !clean) return item?.notes ?? []; + const note = await detailApi.noteAdd(item.id, clean); + item.notes = [...(item.notes ?? []), note]; + return item.notes; + } + + async editNote(noteId: string, body: string): Promise { + const item = this.current; + if (!item) return []; + const clean = body.trim(); + if (!clean) throw new Error('A note cannot be empty; delete it instead.'); + const note = await detailApi.noteEdit(noteId, clean); + item.notes = (item.notes ?? []).map((n) => (n.id === noteId ? note : n)); + return item.notes; + } + + async deleteNote(noteId: string): Promise { + const item = this.current; + if (!item) return []; + await detailApi.noteDelete(noteId); + item.notes = (item.notes ?? []).filter((n) => n.id !== noteId); + return item.notes; + } } diff --git a/frontend/src/engine/itemlist.ts b/frontend/src/engine/itemlist.ts index 1739946..bd860c0 100644 --- a/frontend/src/engine/itemlist.ts +++ b/frontend/src/engine/itemlist.ts @@ -1,5 +1,5 @@ import type { Library } from './library'; -import { fetchRow, fetchRows, type Row } from '../io/itemlist'; +import { fetchPosition, fetchRow, fetchRows, type Row } from '../io/itemlist'; export const PAGE = 200; @@ -29,25 +29,39 @@ export class ItemListModel { this.generation++; for (const c of this.pending.values()) c.abort(); this.pending.clear(); - void this.load(0, true); + this.spans.clear(); + void this.load(0, PAGE, true); } ensure(first: number, last: number): void { if (!this.ready) return; - const lo = Math.floor(Math.max(0, first) / PAGE); - const hi = Math.floor(Math.max(0, Math.min(last, this.total - 1)) / PAGE); - for (let p = lo; p <= hi; p++) { - if (!this.cache.has(p * PAGE) && !this.pending.has(p)) void this.load(p, false); + const lo = Math.max(0, first); + const hi = Math.min(last, this.total - 1); + let i = lo; + while (i <= hi) { + if (this.cache.has(i) || this.covered(i)) { i++; continue; } + let j = i; + while (j <= hi && j - i < PAGE && !this.cache.has(j) && !this.covered(j)) j++; + void this.load(i, j - i, false); + i = j; } } - private async load(page: number, fresh: boolean): Promise { + private covered(i: number): boolean { + for (const [o, [, n]] of this.spans) if (i >= o && i < o + n) return true; + return false; + } + + private spans = new Map(); + + private async load(offset: number, limit: number, fresh: boolean): Promise { const gen = this.generation; const ctl = new AbortController(); - this.pending.set(page, ctl); + this.pending.set(offset, ctl); + this.spans.set(offset, [ctl, limit]); if (fresh) this.sink.busy(true); try { - const res = await fetchRows({ scope: this.lib.scope, q: this.lib.query, sort: this.lib.sort, offset: page * PAGE, limit: PAGE }, ctl.signal); + const res = await fetchRows({ scope: this.lib.scope, q: this.lib.query, sort: this.lib.sort, offset, limit }, ctl.signal); if (gen !== this.generation) return; if (fresh) { this.cache.clear(); this.index.clear(); } res.rows.forEach((r, k) => { this.cache.set(res.offset + k, r); this.index.set(r.id, res.offset + k); }); @@ -61,11 +75,69 @@ export class ItemListModel { } catch (e) { if (gen === this.generation && !ctl.signal.aborted) this.sink.error(e instanceof Error ? e.message : String(e)); } finally { - if (this.pending.get(page) === ctl) this.pending.delete(page); + if (this.pending.get(offset) === ctl) { this.pending.delete(offset); this.spans.delete(offset); } if (fresh && gen === this.generation) this.sink.busy(false); } } + remove(ids: string[]): void { + if (!this.ready) return; + const gone = new Set(); + let unknown = 0; + for (const id of ids) { const i = this.indexOf(id); if (i >= 0) gone.add(i); else unknown++; } + if (unknown) { this.reload(); return; } + if (!gone.size) return; + const order = Array.from(gone).sort((a, b) => a - b); + const next = new Map(); + for (const [i, r] of this.cache) { + if (gone.has(i)) continue; + let lo = 0, hi = order.length; + while (lo < hi) { const m = (lo + hi) >> 1; if (order[m] < i) lo = m + 1; else hi = m; } + next.set(i - lo, r); + } + this.cache = next; + this.index.clear(); + for (const [i, r] of this.cache) this.index.set(r.id, i); + for (const c of this.pending.values()) c.abort(); + this.pending.clear(); + this.spans.clear(); + this.total =Math.max(0, this.total - gone.size); + this.lib.setCounts({ shown: this.total, total: this.total }); + this.sink.reset(this.total); + } + + async insert(ids: string[]): Promise { + if (!this.ready) return; + const gen = this.generation; + for (const id of ids) { + if (this.indexOf(id) >= 0) continue; + try { + const r = await fetchRow(id); + if (gen !== this.generation) return; + const pos = await fetchPosition(id, { scope: this.lib.scope, q: this.lib.query, sort: this.lib.sort }); + if (gen !== this.generation) return; + if (!pos || (pos.index >= 0 && pos.total !== this.total + 1)) { this.reload(); return; } + if (pos.index < 0) continue; + const at = pos.index; + const next = new Map(); + for (const [i, x] of this.cache) next.set(i >= at ? i + 1 : i, x); + next.set(at, r); + this.cache = next; + this.index.clear(); + for (const [i, x] of this.cache) this.index.set(x.id, i); + for (const c of this.pending.values()) c.abort(); + this.pending.clear(); + this.spans.clear(); + this.total = pos.total; + this.lib.setCounts({ shown: this.total, total: this.total }); + this.sink.reset(this.total); + } catch (e) { + if (gen === this.generation) this.sink.error(e instanceof Error ? e.message : String(e)); + return; + } + } + } + async refreshOne(id: string): Promise { const i = this.indexOf(id); if (i < 0) return; diff --git a/frontend/src/io/add.ts b/frontend/src/io/add.ts index 7cf3c3f..3a51bd9 100644 --- a/frontend/src/io/add.ts +++ b/frontend/src/io/add.ts @@ -40,6 +40,20 @@ export const importText = (text: string, format: string | null) => export const listFormats = () => api.get('/library/formats'); export const identifyPath = (path: string) => api.post('/library/identify', { path }); +export async function identifyUpload(file: File): Promise { + const res = await fetch(`/api/library/identify/upload?name=${encodeURIComponent(file.name)}`, { + method: 'POST', + headers: { ...keyHeaders(), 'content-type': 'application/pdf' }, + body: file, + }); + if (!res.ok) { + let detail = res.statusText; + try { detail = String((await res.json()).detail ?? detail); } catch { void 0; } + throw new EngineError(detail, res.status); + } + return res.json() as Promise; +} + export async function exportText(format: string, scope: ExportScope): Promise { const p = new URLSearchParams({ format }); if (scope.collection) p.set('collection', scope.collection); diff --git a/frontend/src/io/detail.ts b/frontend/src/io/detail.ts index 5db041e..3547a43 100644 --- a/frontend/src/io/detail.ts +++ b/frontend/src/io/detail.ts @@ -55,4 +55,7 @@ export const detailApi = { removeTags: (id: string, names: string[]) => delWith<{ item_id: string; tags: string[] }>(`/library/items/${enc(id)}/tags`, { names }), trash: (id: string) => api.post(`/library/items/${enc(id)}/trash`, {}), openAttachment: (attachmentId: string) => api.post(`/library/attachments/${enc(attachmentId)}/open`, {}), + noteAdd: (id: string, body: string) => api.post(`/library/items/${enc(id)}/notes`, { body }), + noteEdit: (noteId: string, body: string) => patch(`/library/notes/${enc(noteId)}`, { body }), + noteDelete: (noteId: string) => delWith(`/library/notes/${enc(noteId)}`, {}), }; diff --git a/frontend/src/io/itemlist.ts b/frontend/src/io/itemlist.ts index 0856c6a..82781d4 100644 --- a/frontend/src/io/itemlist.ts +++ b/frontend/src/io/itemlist.ts @@ -84,6 +84,20 @@ export async function fetchRows(rq: RowQuery, signal?: AbortSignal): Promise): Promise { + if (rowsRoute === false) return null; + const p = scopeParams(rq.scope, false); + if (rq.q) p.set('q', rq.q); + p.set('sort', rq.sort.key); + p.set('desc', String(rq.sort.desc)); + try { return await api.get(`/library/rows/${encodeURIComponent(id)}/position?${p}`); } catch (e) { + if (e instanceof EngineError && (e.status === 404 || e.status === 405)) return null; + throw e; + } +} + export async function fetchRow(id: string): Promise { if (rowsRoute !== false) { try { return await api.get(`/library/rows/${encodeURIComponent(id)}`); } catch (e) { diff --git a/frontend/src/io/service.ts b/frontend/src/io/service.ts index dc7b752..1aff1ab 100644 --- a/frontend/src/io/service.ts +++ b/frontend/src/io/service.ts @@ -44,7 +44,9 @@ export function toApp(r: Row): ConnectedApp { export const serviceTransport: ConnectionsTransport = { requests: async () => rows(await api.get('/service/requests'), 'requests').map(toRequest).filter((r) => r.id), apps: async () => rows(await api.get('/service/tokens'), 'tokens').map(toApp).filter((a) => a.id), + waiting: async () => rows(await api.get('/cite/v1/pair/approved/waiting'), 'requests').map(toRequest).filter((r) => r.id), approve: async (id, scope) => { await api.post(`/service/requests/${encodeURIComponent(id)}/approve`, { scope }); }, deny: async (id) => { await api.post(`/service/requests/${encodeURIComponent(id)}/deny`, {}); }, + withdraw: async (id) => { await api.post(`/service/requests/${encodeURIComponent(id)}/withdraw`, {}); }, revoke: async (id) => { await api.del(`/service/tokens/${encodeURIComponent(id)}`); }, }; diff --git a/frontend/src/styles/detail.css b/frontend/src/styles/detail.css index 87c5064..fabeef5 100644 --- a/frontend/src/styles/detail.css +++ b/frontend/src/styles/detail.css @@ -23,7 +23,9 @@ .fc-dt-btn { display: inline-flex; align-items: center; gap: var(--space-1); height: var(--dt-row-h); padding: 0 var(--space-2); border: 1px solid var(--line-2); border-radius: var(--radius-sm); background: var(--surface-2); color: var(--text-primary); font: inherit; cursor: pointer; } .fc-dt-btn:hover:not(:disabled) { background: var(--bg-hover); } .fc-dt-btn:disabled { opacity: 0.5; cursor: default; } -.fc-dt-trash { width: 88px; justify-content: center; } +.fc-dt-trash { width: 88px; justify-content: flex-start; } +.fc-dt-trash-text { display: inline-grid; } +.fc-dt-trash-text::after { content: "Confirm"; grid-area: 1 / 1; visibility: hidden; height: 0; } .fc-dt-trash.is-armed { border-color: var(--danger); color: var(--danger-text); } .fc-dt-fields { display: flex; flex-direction: column; gap: var(--space-1); } @@ -53,3 +55,11 @@ .fc-dt-item-name { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .fc-dt-item-meta { color: var(--text-muted); font-variant-numeric: tabular-nums; } .fc-dt-item .fc-dt-btn { height: 22px; } +.fc-dt-note { grid-template-columns: minmax(0, 1fr) auto; } +.fc-dt-note-body { box-sizing: border-box; width: 100%; height: 22px; padding: 2px var(--space-1); border: 1px solid transparent; border-radius: var(--radius-sm); background: transparent; color: var(--text-primary); font: inherit; line-height: 16px; resize: none; overflow: hidden; } +.fc-dt-note-body:focus { outline: none; border-color: var(--accent-color); background: var(--bg-primary); } +.fc-dt-note.is-error .fc-dt-note-body { border-color: var(--danger); } +.fc-dt-note-del { width: 76px; justify-content: flex-start; } +.fc-dt-note-del-text { display: inline-grid; } +.fc-dt-note-del-text::after { content: "Confirm"; grid-area: 1 / 1; visibility: hidden; height: 0; } +.fc-dt-note-del.is-armed { border-color: var(--danger); color: var(--danger-text); } diff --git a/frontend/src/styles/preferences.css b/frontend/src/styles/preferences.css index c9da311..85f4893 100644 --- a/frontend/src/styles/preferences.css +++ b/frontend/src/styles/preferences.css @@ -4,6 +4,7 @@ --fc-pr-log-h: 22px; --fc-pr-lib-h: 48px; --fc-pr-line-h: 20px; + --fc-pr-text-line-h: 15px; --fc-pr-label-w: 200px; display: grid; align-content: start; row-gap: var(--space-6); max-width: 760px; padding: var(--space-4); } @@ -39,11 +40,10 @@ .fc-pr-empty:empty { display: none; } .fc-pr-service, .fc-pr-lib { display: grid; align-items: center; column-gap: var(--space-3); padding: var(--space-2) var(--space-3); border: 1px solid var(--line-1); border-radius: var(--radius); background: var(--surface-1); box-sizing: border-box; } .fc-pr-service { grid-template-columns: minmax(0, 1fr) auto; height: var(--fc-pr-service-h); } -.fc-pr-service > .fc-pr-text { grid-template-rows: auto var(--fc-pr-line-h) var(--fc-pr-line-h); } +.fc-pr-service > .fc-pr-text, .fc-pr-lib > .fc-pr-text { grid-auto-rows: var(--fc-pr-text-line-h); row-gap: 0; } +.fc-pr-service > .fc-pr-text > *, .fc-pr-lib > .fc-pr-text > * { display: block; height: var(--fc-pr-text-line-h); line-height: var(--fc-pr-text-line-h); } .fc-pr-service > .fc-pr-text > .fc-pr-hint:nth-child(2) { font-family: var(--font-mono); font-size: var(--fs-11); } -.fc-pr-service > .fc-pr-text > .fc-pr-hint { height: auto; } .fc-pr-lib { grid-template-columns: minmax(0, 1fr) 64px auto; height: var(--fc-pr-lib-h); } -.fc-pr-lib > .fc-pr-text > .fc-pr-hint { height: auto; } .fc-pr-lib.is-current { border-color: var(--accent-color); } .fc-pr-badge { color: var(--accent-color); font-size: var(--fs-12); text-align: end; } .fc-pr-lib .fc-btn { min-width: 72px; } diff --git a/frontend/src/styles/side.css b/frontend/src/styles/side.css index ef54129..ca690f5 100644 --- a/frontend/src/styles/side.css +++ b/frontend/src/styles/side.css @@ -42,6 +42,9 @@ .fc-side-msg { height: var(--fc-side-row-h); line-height: var(--fc-side-row-h); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .fc-section > .fc-side-msg { padding-top: 0; } .fc-side-msg.is-error { color: var(--danger); } +.fc-side-msg:empty { display: none; } +.fc-side-row.is-folded { display: none; } +.fc-side-pane.is-held .fc-section { visibility: hidden; } .fc-side-edit { position: absolute; @@ -74,6 +77,7 @@ opacity: 0; pointer-events: none; } +.fc-side-actions.is-three { width: calc(var(--fc-side-actions-w) * 1.5); grid-template-columns: 1fr 1fr 1fr; } .fc-side-row:hover > .fc-side-actions, .fc-side-row:focus-within > .fc-side-actions, .fc-side-row.is-armed > .fc-side-actions { opacity: 1; pointer-events: auto; } diff --git a/frontend/src/ui/add.ts b/frontend/src/ui/add.ts index 0727d57..8df571f 100644 --- a/frontend/src/ui/add.ts +++ b/frontend/src/ui/add.ts @@ -53,7 +53,7 @@ export function mountAdd(engine: Engine, host: HTMLElement): void { const exp = mountExport(engine, adding, body); sections.set('export', exp.node); show('id'); - mountDrop(adding, overlay); + mountDrop(adding, overlay, q(imp.node, '.fc-add-line')); void adding.loadFormats().then((fs) => { const names = fs.map((f) => f.name); imp.setFormats(names); @@ -65,11 +65,12 @@ function hasFiles(e: DragEvent): boolean { return Array.from(e.dataTransfer?.types ?? []).includes('Files'); } -async function dropOne(adding: Adding, f: File): Promise { +async function dropOne(adding: Adding, f: File, line: HTMLElement): Promise { const path = (f as File & { path?: string }).path; - if (/\.pdf$/i.test(f.name)) { - if (!path) { toast(`${f.name}: this window cannot read where the file is stored, so it cannot be identified here.`, 'error'); return; } - const r = await adding.identify(path); + if (/\.pdf$/i.test(f.name) || f.type === 'application/pdf') { + say(line, true, `Identifying ${f.name}...`); + const r = await adding.identify(path ? path : f); + say(line, r.ok, `${f.name}: ${r.text}`); toast(`${f.name}: ${r.text}`, r.ok ? 'info' : 'error'); return; } @@ -79,7 +80,7 @@ async function dropOne(adding: Adding, f: File): Promise { toast(`${f.name}: ${r.text}`, r.ok ? 'info' : 'error'); } -function mountDrop(adding: Adding, overlay: HTMLElement): void { +function mountDrop(adding: Adding, overlay: HTMLElement, line: HTMLElement): void { const zone = el(``); overlay.append(zone); let depth = 0; @@ -92,7 +93,7 @@ function mountDrop(adding: Adding, overlay: HTMLElement): void { e.preventDefault(); off(); const files = Array.from(e.dataTransfer?.files ?? []); - void (async () => { for (const f of files) await dropOne(adding, f); })(); + void (async () => { for (const f of files) await dropOne(adding, f, line); })(); }); } diff --git a/frontend/src/ui/connections.ts b/frontend/src/ui/connections.ts index 7bb3db0..d2769c4 100644 --- a/frontend/src/ui/connections.ts +++ b/frontend/src/ui/connections.ts @@ -19,6 +19,10 @@ export const CONNECTIONS_PANE = `

${icon('info', 14)}Waiting for your answer

No app is asking right now.

+
+

${icon('info', 14)}Approved, waiting for the app to collect

+

No approved request is waiting.

+

${icon('link', 14)}Connected apps

No apps are connected.

@@ -76,6 +80,23 @@ function updateRequestRow(n: HTMLElement, r: PendingRequest, now: number): void for (const b of n.querySelectorAll('[data-act="approve"], [data-act="approve-read"]')) setDisabled(b, gone || n.classList.contains('is-busy')); } +function waitingRow(r: PendingRequest): HTMLElement { + const n = el(`
+
+
+
`); + n.dataset.key = r.id; + updateWaitingRow(n, r, Date.now()); + return n; +} + +function updateWaitingRow(n: HTMLElement, r: PendingRequest, now: number): void { + setText(q(n, '.fc-conn-name'), r.name); + setText(q(n, '.fc-conn-host'), r.host); + setText(q(n, '.fc-conn-what'), `${may(r.scope)} once the app collects its token`); + setText(q(n, '.fc-conn-when'), r.expiresAt && r.expiresAt <= now ? 'Not collected in time' : r.expiresAt ? `Collect within ${span(r.expiresAt - now)}` : ''); +} + function appRow(a: ConnectedApp): HTMLElement { const n = el(`
@@ -107,6 +128,8 @@ export function bindConnections(engine: Engine, host: HTMLElement): void { const pane = q(host, '.fc-conn'); const reqList = q(pane, '[data-list="requests"]'); const appList = q(pane, '[data-list="apps"]'); + const waitList = q(pane, '[data-list="waiting"]'); + const waiting = new Map(); const errorLine = q(pane, '.fc-conn-error'); const count = q(host, '.fc-nav-count'); const navs = Array.from(host.querySelectorAll('.fc-nav-item')); @@ -117,11 +140,14 @@ export function bindConnections(engine: Engine, host: HTMLElement): void { c.events.on('request:add', (r) => { requests.set(r.id, r); if (!rowOf(reqList, r.id)) reqList.append(requestRow(r)); }); c.events.on('request:update', (r) => { requests.set(r.id, r); const n = rowOf(reqList, r.id); if (n) updateRequestRow(n, r, Date.now()); }); c.events.on('request:remove', (id) => { requests.delete(id); rowOf(reqList, id)?.remove(); }); + c.events.on('waiting:add', (r) => { waiting.set(r.id, r); if (!rowOf(waitList, r.id)) waitList.append(waitingRow(r)); }); + c.events.on('waiting:update', (r) => { waiting.set(r.id, r); const n = rowOf(waitList, r.id); if (n) updateWaitingRow(n, r, Date.now()); }); + c.events.on('waiting:remove', (id) => { waiting.delete(id); rowOf(waitList, id)?.remove(); }); c.events.on('app:add', (a) => { apps.set(a.id, a); if (!rowOf(appList, a.id)) appList.append(appRow(a)); }); c.events.on('app:update', (a) => { apps.set(a.id, a); const n = rowOf(appList, a.id); if (n) updateAppRow(n, a, Date.now()); }); c.events.on('app:remove', (id) => { apps.delete(id); rowOf(appList, id)?.remove(); }); c.events.on('busy', ({ id, busy }) => { - const n = rowOf(reqList, id) ?? rowOf(appList, id); + const n = rowOf(reqList, id) ?? rowOf(appList, id) ?? rowOf(waitList, id); if (!n) return; setClass(n, 'is-busy', busy); for (const b of n.querySelectorAll('button')) setDisabled(b, busy); @@ -163,6 +189,7 @@ export function bindConnections(engine: Engine, host: HTMLElement): void { const act = btn.dataset.act; if (act === 'approve') engine.dispatch('connections.approve', { id, scope: requests.get(id)?.scope ?? 'read' }); else if (act === 'approve-read') engine.dispatch('connections.approve', { id, scope: 'read' }); + else if (act === 'withdraw') engine.dispatch('connections.withdraw', { id }); else if (act === 'deny') engine.dispatch('connections.deny', { id }); else if (act === 'revoke') { setClass(row, 'is-confirming', true); q(row, '[data-act="revoke-no"]').focus(); } else if (act === 'revoke-no') { setClass(row, 'is-confirming', false); q(row, '[data-act="revoke"]').focus(); } @@ -174,6 +201,7 @@ export function bindConnections(engine: Engine, host: HTMLElement): void { const now = Date.now(); for (const [id, r] of requests) { const n = rowOf(reqList, id); if (n) updateRequestRow(n, r, now); } for (const [id, a] of apps) { const n = rowOf(appList, id); if (n) updateAppRow(n, a, now); } + for (const [id, r] of waiting) { const n = rowOf(waitList, id); if (n) updateWaitingRow(n, r, now); } }, TICK_MS); } diff --git a/frontend/src/ui/detail.ts b/frontend/src/ui/detail.ts index 90dda6c..a839eff 100644 --- a/frontend/src/ui/detail.ts +++ b/frontend/src/ui/detail.ts @@ -47,6 +47,8 @@ const SHELL = `

Notes

+ +
`; @@ -132,11 +134,70 @@ export function mountDetail(engine: Engine, host: HTMLElement): void { setText(noteCount, String(list.length)); patchList(notesHost, list, { key: (n) => n.id, - create: (n) => el(`
${escapeHtml(plain(n.body))}
`), - update: (node, n) => { const text = plain(n.body); setText(q(node, '.fc-dt-item-name'), text); setTitle(node, text); }, + create: (n) => el(`
`), + update: (node, n) => { + const box = q(node, '.fc-dt-note-body'); + const text = plain(n.body); + if (box.value !== text && document.activeElement !== box) box.value = text; + box.dataset.saved = text; + }, }); + for (const box of notesHost.querySelectorAll('.fc-dt-note-body')) if (box.dataset.saved === undefined) box.dataset.saved = box.value; } + const noteInput = q(root, '.fc-dt-note-input'); + const noteError = q(root, '.fc-dt-note-error'); + const showNoteError = (text: string): void => { setText(noteError, text); setTitle(noteError, text); }; + + noteInput.addEventListener('keydown', (e) => { + if (e.key !== 'Enter') return; + e.preventDefault(); + const body = noteInput.value.trim(); + if (!body) return; + setDisabled(noteInput, true); + model.addNote(body).then((notes) => { noteInput.value = ''; showNoteError(''); paintNotes(notes); }, (err: Error) => showNoteError(`Notes: ${err.message}`)) + .finally(() => setDisabled(noteInput, false)); + }); + + function saveNote(box: HTMLTextAreaElement): void { + const id = box.closest('.fc-dt-note')?.dataset.key; + if (!id || box.value.trim() === (box.dataset.saved ?? '')) return; + const node = box.closest('.fc-dt-note'); + model.editNote(id, box.value).then( + (notes) => { if (node) setClass(node, 'is-error', false); showNoteError(''); paintNotes(notes); }, + (err: Error) => { if (node) setClass(node, 'is-error', true); showNoteError(`Notes: ${err.message}`); }, + ); + } + + notesHost.addEventListener('focusout', (e) => { + const box = e.target as HTMLElement; + if (box instanceof HTMLTextAreaElement) saveNote(box); + }); + notesHost.addEventListener('keydown', (e) => { + const box = e.target as HTMLElement; + if (!(box instanceof HTMLTextAreaElement)) return; + if (e.key === 'Escape') { box.value = box.dataset.saved ?? ''; box.blur(); } + else if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); saveNote(box); } + }); + + const noteArmed = new Map(); + notesHost.addEventListener('click', (e) => { + const btn = (e.target as Element).closest('.fc-dt-note-del'); + const id = btn?.closest('.fc-dt-note')?.dataset.key; + if (!btn || !id) return; + const label = q(btn, '.fc-dt-note-del-text'); + const disarm = (): void => { clearTimeout(noteArmed.get(id)); noteArmed.delete(id); setClass(btn, 'is-armed', false); setText(label, 'Delete'); }; + if (!noteArmed.has(id)) { + setClass(btn, 'is-armed', true); + setText(label, 'Confirm'); + noteArmed.set(id, window.setTimeout(disarm, 3000)); + return; + } + disarm(); + setDisabled(btn, true); + model.deleteNote(id).then((notes) => { showNoteError(''); paintNotes(notes); }, (err: Error) => { setDisabled(btn, false); showNoteError(`Notes: ${err.message}`); }); + }); + async function commit(row: Row): Promise { if (!model.current) return; const value = row.control.value; diff --git a/frontend/src/ui/duplicates.ts b/frontend/src/ui/duplicates.ts index 4b0fa51..de0c057 100644 --- a/frontend/src/ui/duplicates.ts +++ b/frontend/src/ui/duplicates.ts @@ -120,14 +120,14 @@ export function mountDuplicates(engine: Engine, host: HTMLElement): void { if (!g || !gnode) return; const keep = keepOf(g); const others = g.members.filter((m) => m.id !== keep).map((m) => m.id); - gnode.classList.add('is-busy'); + const before = groups; + groups = groups.filter((x) => x.key !== g.key); + render(); mergeGroup(keep, others).then((res) => { - groups = groups.filter((x) => x.key !== g.key); - render(); engine.library.itemsRemoved(res.trashed); engine.library.itemChanged(res.kept); toast(`Merged ${plural(res.trashed.length, 'copy', 'copies')}. The extras are in the trash.`, 'info'); - }).catch((e: Error) => { gnode.classList.remove('is-busy'); showNote(e.message, true); }); + }).catch((e: Error) => { groups = before; render(); showNote(e.message, true); }); }); engine.library.events.on('view', (view) => { if (view === 'duplicates') void load(); }); diff --git a/frontend/src/ui/itemlist.ts b/frontend/src/ui/itemlist.ts index c73c076..0f1e906 100644 --- a/frontend/src/ui/itemlist.ts +++ b/frontend/src/ui/itemlist.ts @@ -192,9 +192,9 @@ export function mountItemList(engine: Engine, host: HTMLElement): void { lib.events.on('sort', () => { markSort(); model.reload(); }); lib.events.on('selected', () => { for (const node of pool) if (!node.hidden) fill(node, Number(node.dataset.index)); }); lib.events.on('item:changed', (id) => { void model.refreshOne(id); }); - lib.events.on('items:added', () => model.reload()); - lib.events.on('items:removed', () => model.reload()); - lib.events.on('items:restored', () => model.reload()); + lib.events.on('items:added', (ids) => { void model.insert(ids); }); + lib.events.on('items:removed', (ids) => model.remove(ids)); + lib.events.on('items:restored', (ids) => { void model.insert(ids); }); markSort(); model.reload(); diff --git a/frontend/src/ui/preferences.ts b/frontend/src/ui/preferences.ts index ffbc179..f5935bd 100644 --- a/frontend/src/ui/preferences.ts +++ b/frontend/src/ui/preferences.ts @@ -92,17 +92,18 @@ export function mountPreferences(engine: Engine, host: HTMLElement): void { setChecked(master, n.enabled); setText(masterHint, n.forced_offline ? 'Held off by the FORMCITE_OFFLINE setting of this computer.' : n.enabled ? 'On. Individual services can still be turned off below.' : 'Off. No lookup will run.'); setDisabled(master, n.forced_offline); + const fill = (node: HTMLElement, s: NetService): void => { + setText(q(node, '[data-f="name"]'), s.name); + setText(q(node, '[data-f="host"]'), s.host); + setText(q(node, '[data-f="purpose"]'), s.purpose); + const input = q(node, 'input'); + setChecked(input, s.enabled); + setDisabled(input, !n.enabled || n.forced_offline); + }; patchList(services, n.services, { key: (s) => s.name, - create: serviceRow, - update: (node, s) => { - setText(q(node, '[data-f="name"]'), s.name); - setText(q(node, '[data-f="host"]'), s.host); - setText(q(node, '[data-f="purpose"]'), s.purpose); - const input = q(node, 'input'); - setChecked(input, s.enabled); - setDisabled(input, !n.enabled || n.forced_offline); - }, + create: (s) => { const node = serviceRow(s); fill(node, s); return node; }, + update: fill, }); setText(servicesEmpty, n.services.length === 0 ? 'No services are declared.' : ''); setValue(contact, n.contact ?? ''); @@ -120,17 +121,18 @@ export function mountPreferences(engine: Engine, host: HTMLElement): void { }; const showLibraries = (list: LibraryInfo[]): void => { + const fill = (node: HTMLElement, l: LibraryInfo): void => { + setText(q(node, '[data-f="name"]'), l.name); + setText(q(node, '[data-f="root"]'), l.root); + const isCurrent = l.name === current; + setText(q(node, '[data-f="badge"]'), isCurrent ? 'Current' : ''); + setClass(node, 'is-current', isCurrent); + setDisabled(q(node, 'button'), isCurrent); + }; patchList(libs, list, { key: (l) => l.name, - create: libRow, - update: (node, l) => { - setText(q(node, '[data-f="name"]'), l.name); - setText(q(node, '[data-f="root"]'), l.root); - const isCurrent = l.name === current; - setText(q(node, '[data-f="badge"]'), isCurrent ? 'Current' : ''); - setClass(node, 'is-current', isCurrent); - setDisabled(q(node, 'button'), isCurrent); - }, + create: (l) => { const node = libRow(l); fill(node, l); return node; }, + update: fill, }); setText(libsEmpty, list.length === 0 ? 'No libraries yet.' : ''); }; diff --git a/frontend/src/ui/side.ts b/frontend/src/ui/side.ts index 9b69324..9d82ecd 100644 --- a/frontend/src/ui/side.ts +++ b/frontend/src/ui/side.ts @@ -27,6 +27,7 @@ interface Pane { collMsg: HTMLElement; tags: HTMLUListElement; tagMsg: HTMLElement; + collapsed: Set; } const EDIT_PARTS = ` @@ -35,11 +36,15 @@ const EDIT_PARTS = `${sideIcon('remove')} `; +const SUB_ACT = ``; + function rowShell(kind: string, iconName: string): HTMLLIElement { const editable = kind === 'collection' || kind === 'tag'; - return el(`
  • - - ${editable ? EDIT_PARTS : ''} + const parts = kind === 'collection' ? EDIT_PARTS.replace('', `${SUB_ACT}`) : EDIT_PARTS; + const tree = kind === 'collection'; + return el(`
  • + + ${editable ? parts : ''}
  • `); } @@ -61,9 +66,79 @@ function updateCollection(node: HTMLElement, entry: TreeEntry, pane: Pane): void setStyleVar(node, '--fc-side-depth', String(entry.depth)); node.dataset.scope = scopeKey({ kind: 'collection', id: entry.id }); node.dataset.name = entry.name; + node.dataset.parent = entry.parentId ?? ''; + const btn = node.querySelector('.fc-side-entry'); + if (btn && btn.getAttribute('aria-level') !== String(entry.depth + 1)) btn.setAttribute('aria-level', String(entry.depth + 1)); setClass(node, 'is-active', node.dataset.scope === scopeKey(pane.engine.library.scope)); } +function treeRows(pane: Pane): HTMLElement[] { + return Array.from(pane.tree.children) as HTMLElement[]; +} + +function applyTree(pane: Pane): void { + const rows = treeRows(pane); + const parents = new Set(rows.map((r) => r.dataset.parent ?? '')); + const hidden = new Set(); + let roving: HTMLElement | null = null; + let first: HTMLElement | null = null; + for (const row of rows) { + const key = row.dataset.key ?? ''; + const parent = row.dataset.parent ?? ''; + const isHidden = parent !== '' && (hidden.has(parent) || pane.collapsed.has(parent)); + if (isHidden) hidden.add(key); + setClass(row, 'is-folded', isHidden); + const btn = row.querySelector('.fc-side-entry'); + if (!btn) continue; + const expanded = parents.has(key) ? String(!pane.collapsed.has(key)) : null; + if (expanded === null) btn.removeAttribute('aria-expanded'); + else if (btn.getAttribute('aria-expanded') !== expanded) btn.setAttribute('aria-expanded', expanded); + if (!isHidden && !first) first = btn; + if (!isHidden && btn.tabIndex === 0) roving = btn; + if (btn.getAttribute('aria-selected') !== String(row.classList.contains('is-active'))) btn.setAttribute('aria-selected', String(row.classList.contains('is-active'))); + } + const keep = roving ?? first; + for (const row of rows) { + const btn = row.querySelector('.fc-side-entry'); + if (btn) btn.tabIndex = btn === keep ? 0 : -1; + } +} + +function moveFocus(pane: Pane, btn: HTMLElement): void { + for (const row of treeRows(pane)) { + const b = row.querySelector('.fc-side-entry'); + if (b) b.tabIndex = b === btn ? 0 : -1; + } + btn.focus(); +} + +function treeKey(pane: Pane, ev: KeyboardEvent): void { + const btn = (ev.target as HTMLElement).closest('.fc-side-entry'); + const row = btn?.closest('.fc-side-row'); + if (!btn || !row || row.parentElement !== pane.tree) return; + const visible = treeRows(pane).filter((r) => !r.classList.contains('is-folded')); + const at = visible.indexOf(row); + const key = row.dataset.key ?? ''; + const entryOf = (r: HTMLElement | undefined): HTMLElement | null => r?.querySelector('.fc-side-entry') ?? null; + let next: HTMLElement | null = null; + if (ev.key === 'ArrowDown') next = entryOf(visible[at + 1]); + else if (ev.key === 'ArrowUp') next = entryOf(visible[at - 1]); + else if (ev.key === 'Home') next = entryOf(visible[0]); + else if (ev.key === 'End') next = entryOf(visible[visible.length - 1]); + else if (ev.key === 'ArrowRight') { + if (btn.getAttribute('aria-expanded') === 'false') { pane.collapsed.delete(key); applyTree(pane); } + else if (btn.getAttribute('aria-expanded') === 'true') next = entryOf(visible[at + 1]); + else return; + } else if (ev.key === 'ArrowLeft') { + if (btn.getAttribute('aria-expanded') === 'true') { pane.collapsed.add(key); applyTree(pane); } + else if (row.dataset.parent) next = entryOf(visible.find((r) => r.dataset.key === row.dataset.parent)); + else return; + } else if (ev.key === 'Enter' || ev.key === ' ') { pick(pane, row); } + else return; + ev.preventDefault(); + if (next) moveFocus(pane, next); +} + async function loadCollections(pane: Pane): Promise { const done = pendingClass(pane.tree); try { @@ -73,6 +148,7 @@ async function loadCollections(pane: Pane): Promise { create: (e) => { const n = rowShell('collection', 'folder'); updateCollection(n, e, pane); return n; }, update: (n, e) => updateCollection(n, e, pane), }); + applyTree(pane); setText(pane.collMsg, entries.length ? '' : 'No collections yet.'); setClass(pane.collMsg, 'is-error', false); } catch (err) { @@ -192,9 +268,11 @@ async function commitCreate(pane: Pane, row: HTMLElement): Promise { if (!input || !row.classList.contains('is-editing')) return; const name = cleanName(input.value); endEdit(row); + const parent = row.dataset.parent || null; + delete row.dataset.parent; if (!name) return; try { - const made = await sideApi.createCollection(name); + const made = await sideApi.createCollection(name, parent); pane.engine.library.collectionsChanged(); pane.engine.library.setScope({ kind: 'collection', id: made.id, label: made.name }); } catch (err) { @@ -208,6 +286,19 @@ function commitEdit(pane: Pane, row: HTMLElement): Promise { const armed = new WeakMap(); +function focusNeighbor(pane: Pane, row: HTMLElement): void { + const list = row.parentElement; + const visible = list ? (Array.from(list.children) as HTMLElement[]).filter((r) => r === row || !r.classList.contains('is-folded')) : []; + const at = visible.indexOf(row); + const depth = (r: HTMLElement): number => Number(r.style.getPropertyValue('--fc-side-depth') || 0); + const target = visible.slice(at + 1).find((r) => depth(r) <= depth(row)) ?? visible[at - 1]; + const btn = target?.querySelector('.fc-side-entry') + ?? (list === pane.tree ? q(pane.tree.parentElement ?? pane.tree, '.fc-side-add') : pane.fixed.querySelector('.fc-side-entry')); + if (!btn) return; + if (list === pane.tree && target) moveFocus(pane, btn); + else btn.focus(); +} + async function removeRow(pane: Pane, row: HTMLElement): Promise { const btn = row.querySelector('[data-act="delete"]'); if (!armed.has(row)) { @@ -226,6 +317,14 @@ async function removeRow(pane: Pane, row: HTMLElement): Promise { if (btn) btn.title = 'Delete'; const id = row.dataset.key ?? ''; const lib = pane.engine.library; + const gone = new Set([id]); + const hide = (Array.from(row.parentElement?.children ?? []) as HTMLElement[]).filter((r) => { + if (r === row) return true; + if (r.dataset.parent && gone.has(r.dataset.parent)) { gone.add(r.dataset.key ?? ''); return true; } + return false; + }); + if (row.contains(document.activeElement)) focusNeighbor(pane, row); + for (const r of hide) setClass(r, 'is-folded', true); try { if (row.dataset.kind === 'collection') await sideApi.deleteCollection(id); else await sideApi.deleteTag(id); @@ -233,6 +332,8 @@ async function removeRow(pane: Pane, row: HTMLElement): Promise { if (row.dataset.kind === 'collection') lib.collectionsChanged(); else lib.tagsChanged(); } catch (err) { + for (const r of hide) setClass(r, 'is-folded', false); + if (row.parentElement === pane.tree) applyTree(pane); showError(pane, row, err); } } @@ -255,7 +356,7 @@ export function mountSide(engine: Engine, host: HTMLElement): void { collMsg.classList.add('fc-side-msg'); setText(collMsg, ''); const fixed = el('
      '); - const tree = el('
        '); + const tree = el('
          '); const all = rowShell('all', 'all'); setText(all.querySelector('.fc-side-name'), 'All items'); all.dataset.scope = scopeKey(ALL); @@ -276,20 +377,22 @@ export function mountSide(engine: Engine, host: HTMLElement): void { const tags = el('
            '); tagMsg.before(tags); - const pane: Pane = { engine, fixed, tree, collMsg, tags, tagMsg }; + const pane: Pane = { engine, fixed, tree, collMsg, tags, tagMsg, collapsed: new Set() }; + tree.addEventListener('keydown', (ev) => treeKey(pane, ev)); host.addEventListener('click', (ev) => { const target = ev.target as HTMLElement; const act = target.closest('.fc-side-act'); const actRow = act?.closest('.fc-side-row'); if (act && actRow) { - if (act.dataset.act === 'rename') startEdit(actRow, actRow.dataset.name ?? ''); + if (act.dataset.act === 'sub') { newRow.dataset.parent = actRow.dataset.key ?? ''; startEdit(newRow, ''); } + else if (act.dataset.act === 'rename') startEdit(actRow, actRow.dataset.name ?? ''); else if (act.dataset.act === 'delete') void removeRow(pane, actRow); return; } const entry = target.closest('.fc-side-entry'); if (!entry) return; - if (entry.classList.contains('fc-side-add')) { startEdit(newRow, ''); return; } + if (entry.classList.contains('fc-side-add')) { delete newRow.dataset.parent; startEdit(newRow, ''); return; } const row = entry.closest('.fc-side-row'); if (row) pick(pane, row); }); @@ -302,7 +405,7 @@ export function mountSide(engine: Engine, host: HTMLElement): void { const input = (ev.target as HTMLElement).closest('.fc-side-edit'); const row = input?.closest('.fc-side-row'); if (!input || !row) return; - if (ev.key === 'Enter') { ev.preventDefault(); void commitEdit(pane, row); } + if (ev.key === 'Enter') { ev.preventDefault(); void commitEdit(pane, row); row.querySelector('.fc-side-entry')?.focus(); } else if (ev.key === 'Escape') { ev.preventDefault(); endEdit(row); row.querySelector('.fc-side-entry')?.focus(); } }); host.addEventListener('focusout', (ev) => { @@ -311,7 +414,7 @@ export function mountSide(engine: Engine, host: HTMLElement): void { if (row) void commitEdit(pane, row); }); - engine.library.events.on('scope', (s) => markActive(pane, s)); + engine.library.events.on('scope', (s) => { markActive(pane, s); applyTree(pane); }); markActive(pane, engine.library.scope); const ev = engine.library.events; const refreshCollections = coalesce(() => loadCollections(pane)); @@ -326,7 +429,7 @@ export function mountSide(engine: Engine, host: HTMLElement): void { ev.on('items:restored', refreshAll); ev.on('item:changed', refreshAll); - void loadCollections(pane); - void loadTags(pane); - void loadTotals(pane); + host.classList.add('is-held'); + void Promise.allSettled([loadCollections(pane), loadTags(pane), loadTotals(pane)]) + .then(() => host.classList.remove('is-held')); } diff --git a/frontend/src/ui/trash.ts b/frontend/src/ui/trash.ts index fbc0c80..135f89c 100644 --- a/frontend/src/ui/trash.ts +++ b/frontend/src/ui/trash.ts @@ -116,24 +116,30 @@ export function mountTrash(engine: Engine, host: HTMLElement): void { toast('The trash is empty.', 'info'); }).catch((e: Error) => showNote(e.message, true)); } else if (row && id) { - if (act === 'purge') setConfirm(row, true); + if (act === 'purge') { + setConfirm(row, true); + window.setTimeout(() => { if (row.isConnected) setConfirm(row, false); }, 3000); + } else if (act === 'purge-no') setConfirm(row, false); else if (act === 'restore') { - row.classList.add('is-busy'); + const before = items; + drop(id); restoreItem(id).then(() => { - drop(id); engine.library.itemsRestored([id]); - }).catch((e: Error) => { row.classList.remove('is-busy'); showNote(e.message, true); }); + }).catch((e: Error) => { items = before; render(); showNote(e.message, true); }); } else if (act === 'purge-yes') { - row.classList.add('is-busy'); + const before = items; + drop(id); purgeItem(id).then(() => { - drop(id); engine.library.itemsRemoved([id]); - }).catch((e: Error) => { row.classList.remove('is-busy'); setConfirm(row, false); showNote(e.message, true); }); + }).catch((e: Error) => { items = before; render(); showNote(e.message, true); }); } } }); engine.library.events.on('view', (view) => { if (view === 'trash') void load(); }); + const refreshHidden = (): void => { if (engine.library.view !== 'trash') void load(); }; + engine.library.events.on('items:removed', refreshHidden); + engine.library.events.on('items:restored', refreshHidden); if (engine.library.view === 'trash') void load(); } diff --git a/frontend/src/version.ts b/frontend/src/version.ts index b6d55fa..ca24a8e 100644 --- a/frontend/src/version.ts +++ b/frontend/src/version.ts @@ -1 +1 @@ -export const VERSION = '0.7.0'; +export const VERSION = '0.8.0'; diff --git a/native/formcite-style/Cargo.lock b/native/formcite-style/Cargo.lock index 6c8cffe..5b596ec 100644 --- a/native/formcite-style/Cargo.lock +++ b/native/formcite-style/Cargo.lock @@ -81,7 +81,7 @@ dependencies = [ [[package]] name = "formcite-style" -version = "0.7.0" +version = "0.8.0" dependencies = [ "hayagriva", "pyo3", diff --git a/native/formcite-style/Cargo.toml b/native/formcite-style/Cargo.toml index 541f670..ed26cf5 100644 --- a/native/formcite-style/Cargo.toml +++ b/native/formcite-style/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formcite-style" -version = "0.7.0" +version = "0.8.0" edition = "2024" rust-version = "1.95" license = "Apache-2.0" diff --git a/native/formcite-style/pyproject.toml b/native/formcite-style/pyproject.toml index d206ec5..2effc06 100644 --- a/native/formcite-style/pyproject.toml +++ b/native/formcite-style/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "maturin" [project] name = "formcite-style" -version = "0.7.0" +version = "0.8.0" description = "FormCite citation style engine for the FormCite engine service" license = { text = "Apache-2.0" } requires-python = ">=3.10" diff --git a/setup/HASHOUT_LOG.md b/setup/HASHOUT_LOG.md index 0207fca..dd9d81c 100644 --- a/setup/HASHOUT_LOG.md +++ b/setup/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of all comment content, explainers, rationale, TODOs, and removed code for the root launcher scripts and the `setup/` suite. The scripts stay comment-free; everything they would have said lives here, indexed. Read this first, then edit the scripts surgically. -Current build version: v0.7.0 +Current build version: v0.8.0 Last updated: 2026-11-27 · initial port of the launcher and setup suite --- diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 2d8d7ac..29488e1 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -918,7 +918,7 @@ dependencies = [ [[package]] name = "formcite" -version = "0.7.0" +version = "0.8.0" dependencies = [ "fontdb", "objc2", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 1468ca6..03a01ee 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formcite" -version = "0.7.0" +version = "0.8.0" description = "FormCite desktop shell" authors = ["NodeAgentc, Inc."] license = "GPL-3.0-only" diff --git a/src-tauri/HASHOUT_LOG.md b/src-tauri/HASHOUT_LOG.md index 9d728c7..3d6fcf0 100644 --- a/src-tauri/HASHOUT_LOG.md +++ b/src-tauri/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of all comment content, explainers, rationale, TODOs, & removed (hashed-out) code for the desktop shell side of the repo. Source files stay comment-free per dev-rules `sub-skills/hashout-log/SUB-SKILL.md`; everything they would have said lives here, indexed. This file is also the compressed contextual map of this side: read it first, then edit code surgically. -Current build version: v0.7.0 +Current build version: v0.8.0 Last updated: 2026-11-26 (US Eastern) · Tauri 2 shell ported from FormTxt, renamed, launch code added --- diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index e2990bd..fc6aa04 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "FormCite", - "version": "0.7.0", + "version": "0.8.0", "identifier": "ai.nodemode.formcite", "build": { "devUrl": "http://localhost:5330",