xref: /plugin/annotations/DESIGN.md (revision 8d8701f5afabecdb73a7226eaf85b736f630ddd2)
15fa3d185Stracker-user# Annotations Plugin — Design & Architecture
25fa3d185Stracker-user
35fa3d185Stracker-userA developer reference for the annotations plugin. For installation and end-user
45fa3d185Stracker-userbehaviour see [README.md](README.md); for the wider review/environment
55fa3d185Stracker-userconventions see `CLAUDE.md` in the plugins root.
65fa3d185Stracker-user
75fa3d185Stracker-user## Concept
85fa3d185Stracker-user
95fa3d185Stracker-userWord- and sentence-level annotations on wiki pages, in the spirit of
105fa3d185Stracker-userHypothes.is and `ep_comments_page`:
115fa3d185Stracker-user
125fa3d185Stracker-user- **Out-of-band.** Annotations live in a separate per-page JSON file, never in
135fa3d185Stracker-user  the page text or the wiki changelog. Creating one needs only `AUTH_READ`, so
145fa3d185Stracker-user  a group whose page *edit* access is blocked can still annotate.
155fa3d185Stracker-user- **Text-quote anchored.** Each annotation is tied to the quoted text plus a
165fa3d185Stracker-user  little surrounding context, not to a character position, so it survives minor
175fa3d185Stracker-user  edits and is re-found in the rendered DOM on each page load.
185fa3d185Stracker-user- **Threaded.** Annotations carry replies; both have open/resolved status at the
195fa3d185Stracker-user  annotation level.
205fa3d185Stracker-user- **Orphan-aware.** When the quoted text disappears from the page the annotation
215fa3d185Stracker-user  becomes an *orphan* — still stored, surfaced through a counter, and bulk-
225fa3d185Stracker-user  removable by an admin.
235fa3d185Stracker-user
245fa3d185Stracker-user## Components
255fa3d185Stracker-user
265fa3d185Stracker-user| File | Owns |
275fa3d185Stracker-user|------|------|
28*8d8701f5Stracker-user| `plugin.info.txt` | Manifest: name, author, version date, description, repository URL. |
295fa3d185Stracker-user| `helper.php` | The per-page store, all CRUD, server-side orphan detection, and the **permission rules as the single source of truth**. Pure logic — permission methods take facts (user, admin flag, ACL level) as parameters and read no globals. |
305fa3d185Stracker-user| `action.php` | Event registration; injecting the page payload into `JSINFO`; the AJAX endpoint and **permission enforcement** (gathers facts from DokuWiki globals, calls the helper). |
315fa3d185Stracker-user| `script.js` | All front-end behaviour: boot/gate, load + re-anchor, highlights, gutter markers, counter, selection→new-annotation flow, thread panels, and AJAX. Plain IIFE, vanilla JS. |
325fa3d185Stracker-user| `style.css` | Styling via DokuWiki theme tokens (`__background__`, `__text__`, …). Only the amber (open) / green (resolved) highlight colours are hard-coded. |
335fa3d185Stracker-user| `lang/en/lang.php` | The usersettings toggle label/description (used) plus a set of UI strings that are **not yet wired into the JS** — see *Known gaps*. |
345fa3d185Stracker-user
35*8d8701f5Stracker-userDocumentation lives in [`README.md`](README.md) (end users) and this file
36*8d8701f5Stracker-user(developers); the licence is in `LICENSE` (GPL 2).
37*8d8701f5Stracker-user
385fa3d185Stracker-user## Data model & storage
395fa3d185Stracker-user
405fa3d185Stracker-userOne pretty-printed JSON file per page at `metaFN($id, '.annotations')`
415fa3d185Stracker-user(`data/meta/<namespace>/<page>.annotations`):
425fa3d185Stracker-user
435fa3d185Stracker-user```json
445fa3d185Stracker-user{
455fa3d185Stracker-user  "version": 1,
465fa3d185Stracker-user  "annotations": [
475fa3d185Stracker-user    {
485fa3d185Stracker-user      "id": "a1b2c3d4e5f6g7h8",
495fa3d185Stracker-user      "anchor": { "exact": "...", "prefix": "...", "suffix": "...", "start": 123 },
505fa3d185Stracker-user      "author": "alice",
515fa3d185Stracker-user      "created": 1716336000,
525fa3d185Stracker-user      "modified": 1716336000,
535fa3d185Stracker-user      "body": "Does this cover remuxes?",
545fa3d185Stracker-user      "status": "open",
555fa3d185Stracker-user      "resolved_by": "",
565fa3d185Stracker-user      "resolved_at": 0,
575fa3d185Stracker-user      "replies": [
585fa3d185Stracker-user        {
595fa3d185Stracker-user          "id": "x1y2z3a4b5c6d7e8",
605fa3d185Stracker-user          "author": "bob",
615fa3d185Stracker-user          "created": 1716336100,
625fa3d185Stracker-user          "modified": 1716336100,
635fa3d185Stracker-user          "body": "Yes, remuxes count."
645fa3d185Stracker-user        }
655fa3d185Stracker-user      ]
665fa3d185Stracker-user    }
675fa3d185Stracker-user  ]
685fa3d185Stracker-user}
695fa3d185Stracker-user```
705fa3d185Stracker-user
715fa3d185Stracker-userLimits and identifiers (`helper.php` constants): `SCHEMA_VERSION = 1`,
725fa3d185Stracker-user`MAX_QUOTE = 1000`, `MAX_CONTEXT = 64`, `MAX_BODY = 10000`. IDs are
735fa3d185Stracker-user`bin2hex(random_bytes(8))` — 16 hex chars. Writes go through `io_lock()` →
745fa3d185Stracker-usermodify → `io_saveFile()` → `io_unlock()` (the `mutate()` helper); a modifier
755fa3d185Stracker-userreturning `false` aborts the write (used for "target not found").
765fa3d185Stracker-user
775fa3d185Stracker-user## Text-quote anchoring
785fa3d185Stracker-user
795fa3d185Stracker-userAn anchor is `{exact, prefix, suffix, start}`:
805fa3d185Stracker-user
815fa3d185Stracker-user- `exact` — the selected text, whitespace-normalised (runs collapsed to one
825fa3d185Stracker-user  space, trimmed). The same normalisation is applied on capture (JS), on
835fa3d185Stracker-user  storage (PHP), and on matching, so client and server agree.
845fa3d185Stracker-user- `prefix` / `suffix` — context on each side to disambiguate a quote that
855fa3d185Stracker-user  appears more than once. Client captures ~30 chars; server caps at 64.
865fa3d185Stracker-user- `start` — a character-offset hint into the page text, used only as a
875fa3d185Stracker-user  tie-breaker.
885fa3d185Stracker-user
895fa3d185Stracker-user**Re-anchoring (client, `findRange`)**: collect the content text with a
905fa3d185Stracker-user`TreeWalker`, search for the normalised `exact`, disambiguate repeats with
915fa3d185Stracker-user`prefix`/`suffix`, tie-break with the `start` hint, then map the chosen
925fa3d185Stracker-usercharacter offset back to a DOM `Range` and wrap it in a highlight `<span>`. A
935fa3d185Stracker-userquote that cannot be located is an orphan (no highlight, no gutter marker).
945fa3d185Stracker-user
955fa3d185Stracker-user## Orphan detection (two layers)
965fa3d185Stracker-user
975fa3d185Stracker-user- **Client (live UI).** Anything `findRange` cannot anchor on page load is
985fa3d185Stracker-user  counted as orphaned; the count feeds the counter bar, and the orphaned link
995fa3d185Stracker-user  opens a drawer at the bottom of the content area with those threads.
1005fa3d185Stracker-user- **Server (authoritative, `findOrphaned`).** For the admin "clear orphaned"
1015fa3d185Stracker-user  action the page is rendered with `p_wiki_xhtml`, block-closing tags are turned
1025fa3d185Stracker-user  into spaces, tags/entities are stripped, whitespace normalised, and each
1035fa3d185Stracker-user  annotation's `exact` is searched with `mb_strpos`. This re-check is the source
1045fa3d185Stracker-user  of truth for deletion, so a stale client can't cause data loss.
1055fa3d185Stracker-user
1065fa3d185Stracker-user## JSINFO injection (important gotcha)
1075fa3d185Stracker-user
1085fa3d185Stracker-user`script.js` needs per-page facts at boot without an extra round-trip, but you
1095fa3d185Stracker-user**cannot** add them by writing `$JSINFO` inside `TPL_METAHEADER_OUTPUT`:
1105fa3d185Stracker-user`tpl_metaheaders()` calls `jsinfo()` and serialises `$JSINFO` into the inline
1115fa3d185Stracker-user`var JSINFO = …;` script **before** firing that event. Instead `handleMetaHeader`
1125fa3d185Stracker-userfinds that inline `<script>` in `$event->data['script']` and appends a
1135fa3d185Stracker-user`JSINFO.annotations = {…};` statement so it runs in the same scope. Injection is
1145fa3d185Stracker-usergated to `show` / `export_xhtml` views.
1155fa3d185Stracker-user
1165fa3d185Stracker-userPayload: `{ enabled, pageId, stats, user, isAdmin, token }`. `user`, `isAdmin`
1175fa3d185Stracker-userand `token` are included because stock `JSINFO` exposes no user identity and no
1185fa3d185Stracker-usersecurity token — the script reads them from `JSINFO.annotations`, not from
1195fa3d185Stracker-user`JSINFO.userinfo` (which does not exist) or the `#dw__token` field.
1205fa3d185Stracker-user
1215fa3d185Stracker-user## Per-user toggle
1225fa3d185Stracker-user
1235fa3d185Stracker-userRegistered with the **usersettings** plugin via `PLUGIN_USERSETTINGS_REGISTER`
1245fa3d185Stracker-user(key `annotations_enabled`, checkbox, default on). `isEnabledForUser()` reads the
1255fa3d185Stracker-userpreference through the usersettings helper; if that plugin is absent, or the
1265fa3d185Stracker-usertoggle has not been registered yet, the feature defaults to **on**. When a user
1275fa3d185Stracker-userturns it off, `boot()` returns early and nothing is rendered (annotations are
1285fa3d185Stracker-userstill stored).
1295fa3d185Stracker-user
1305fa3d185Stracker-user## Permission model
1315fa3d185Stracker-user
1325fa3d185Stracker-userThe rules live in `helper.php` and are pure; `action.php` gathers the facts and
1335fa3d185Stracker-usercalls them. `isAdmin` is true for the `admin` group or DokuWiki's `$INFO['isadmin']`.
1345fa3d185Stracker-user
1355fa3d185Stracker-user| Action | Rule (helper method) |
1365fa3d185Stracker-user|--------|----------------------|
1375fa3d185Stracker-user| Create annotation / reply / resolve / reopen | logged in **and** `AUTH_READ` on the page — *not* `AUTH_EDIT` (`canAnnotate`) |
1385fa3d185Stracker-user| Edit / delete own annotation | author (`canEditAnnotation`) |
1395fa3d185Stracker-user| Edit / delete own reply | author (`canEditReply`) |
1405fa3d185Stracker-user| Edit / delete **any** annotation or reply | admin (`canEditAnnotation` / `canEditReply`) |
1415fa3d185Stracker-user| Clear resolved / clear orphaned (per page) | admin (`canClear`) |
1425fa3d185Stracker-user| Load (read) annotations | `AUTH_READ` on the page |
1435fa3d185Stracker-user
1445fa3d185Stracker-user## Security
1455fa3d185Stracker-user
1465fa3d185Stracker-user- **CSRF.** Every state-changing action requires a valid DokuWiki security
1475fa3d185Stracker-user  token. The token is injected into `JSINFO.annotations.token` and sent back as
1485fa3d185Stracker-user  `sectok` in the JSON body. Because `checkSecurityToken()` reads `$_REQUEST`
1495fa3d185Stracker-user  (empty for a JSON body), `handleAjax` copies `sectok` into `$_POST`/`$_REQUEST`
1505fa3d185Stracker-user  before validating. The read-only `load` action is exempt (GET, no token) but
1515fa3d185Stracker-user  still ACL-checked.
1525fa3d185Stracker-user- **ACL.** `auth_quickaclcheck($id)` gates both reading and writing.
1535fa3d185Stracker-user- **Output.** Bodies are stored as plain text (newlines kept, length-capped) and
1545fa3d185Stracker-user  rendered client-side via `textContent`, so user content is never interpolated
1555fa3d185Stracker-user  as HTML.
1565fa3d185Stracker-user
1575fa3d185Stracker-user## AJAX endpoint
1585fa3d185Stracker-user
1595fa3d185Stracker-user`…/lib/exe/ajax.php?call=annotations` (handled on `AJAX_CALL_UNKNOWN`). The
1605fa3d185Stracker-user`load` action is a GET with query params; everything else is `POST` with an
1615fa3d185Stracker-user`application/json` body. Every response is `{ "success": true, … }` or
1625fa3d185Stracker-user`{ "success": false, "error": "…" }`.
1635fa3d185Stracker-user
1645fa3d185Stracker-user| Action | Method | Token | Extra fields |
1655fa3d185Stracker-user|--------|--------|-------|--------------|
1665fa3d185Stracker-user| `load` | GET | — | — |
1675fa3d185Stracker-user| `create` | POST | ✓ | `anchor`, `body` |
1685fa3d185Stracker-user| `reply` | POST | ✓ | `annId`, `body` |
1695fa3d185Stracker-user| `edit_annotation` | POST | ✓ | `annId`, `body` |
1705fa3d185Stracker-user| `edit_reply` | POST | ✓ | `annId`, `replyId`, `body` |
1715fa3d185Stracker-user| `delete_annotation` | POST | ✓ | `annId` |
1725fa3d185Stracker-user| `delete_reply` | POST | ✓ | `annId`, `replyId` |
1735fa3d185Stracker-user| `resolve` | POST | ✓ | `annId`, `status` (`open`\|`resolved`) |
1745fa3d185Stracker-user| `clear_resolved` | POST | ✓ | — |
1755fa3d185Stracker-user| `clear_orphaned` | POST | ✓ | — |
1765fa3d185Stracker-user
1775fa3d185Stracker-userAll actions also take the page `id`.
1785fa3d185Stracker-user
1795fa3d185Stracker-user## Constraints
1805fa3d185Stracker-user
1815fa3d185Stracker-user- **JS/CSS floor: Firefox 78 ESR.** No `#private` fields, `??=`/`||=`/`&&=`,
1825fa3d185Stracker-user  `Array.at`, `structuredClone`, `Object.hasOwn`, native `<dialog>`; no CSS
1835fa3d185Stracker-user  `:has()`, selector `:not()`, `aspect-ratio`, container queries, or nesting.
1845fa3d185Stracker-user  `async`/`await`, `fetch`, classes, `?.`, `??`, `Map`/`Set` are fine.
1855fa3d185Stracker-user- **PHP:** developed against 8.3; requires the `mbstring` extension.
1865fa3d185Stracker-user
1875fa3d185Stracker-user## Known gaps / next steps
1885fa3d185Stracker-user
1895fa3d185Stracker-user- **UI localisation.** `script.js` renders hardcoded English; `annInfo.lang` is
1905fa3d185Stracker-user  never populated, so the `counter_*`, `btn_*`, `status_*`, `placeholder_*`,
1915fa3d185Stracker-user  `tooltip_*`, `orphaned_*`, `error_*` and `confirm_*` strings in
1925fa3d185Stracker-user  `lang/en/lang.php` are currently dead. To localise: inject `lang` into the
1935fa3d185Stracker-user  `JSINFO.annotations` payload in `handleMetaHeader` and read `_lang` in the JS
1945fa3d185Stracker-user  string sites. Only `toggle_label` / `toggle_desc` are wired (via `getLang`).
1955fa3d185Stracker-user- **Translations.** No `de` / `ru` / `ja` yet (depends on the localisation work
1965fa3d185Stracker-user  above).
1975fa3d185Stracker-user- **Tests.** No `_test/` suite. Candidates: helper CRUD, input cleaning,
1985fa3d185Stracker-user  permission rules, and `findOrphaned` against a rendered page.
1995fa3d185Stracker-user- **Config.** No `conf/` — nothing is configurable (highlight colours, context
2005fa3d185Stracker-user  length, body cap are all constants/CSS).
2015fa3d185Stracker-user- **Cleanup.** The `ann-highlight-orphaned` JS constant has no CSS rule and no
2025fa3d185Stracker-user  call site (orphans have no in-page range to highlight).
203