Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
chore(skills): add froca hooks, reload filters and dialogs to building-client-ui
Elian Doran6c87d028cb82
diff --git a/.claude/skills/building-client-ui/SKILL.md b/.claude/skills/building-client-ui/SKILL.mdindex b799233ecd..0006c2c183 100644--- a/.claude/skills/building-client-ui/SKILL.md+++ b/.claude/skills/building-client-ui/SKILL.md@@ -1,6 +1,6 @@---name: building-client-ui-description: Use when building or changing any UI in the Trilium client (`apps/client`) — a dialog, a settings pane, a form, a toolbar, a badge, a dropdown menu, a type widget, a control floating over a note's content (map, mind map, image, diagram, presentation). Catalogues the reusable Preact components under `apps/client/src/widgets/react/` (which one to reach for instead of a hand-rolled `<input>`/`<button>`/pill), the `Dropdown` backdrop-blur rules (`noDropdownListStyle` / `portalToBody`), and the `OverlayControlGroup` / `OverlayToolbar` contract for controls over a canvas. The home for client UI guidance that outgrows CLAUDE.md.+description: Use when building or changing any UI in the Trilium client (`apps/client`) — a dialog, a settings pane, a form, a toolbar, a badge, a dropdown menu, a type widget, a control floating over a note's content (map, mind map, image, diagram, presentation), or any component that reads/writes a note's title, label, relation, blob or option. Catalogues the froca-reactive hooks (useNoteProperty / useNoteLabel / useNoteBlob / useChildNotes / useTriliumOption / useNoteContext) and which `loadResults` filter each already wires, the reusable Preact components under `apps/client/src/widgets/react/` (which one to reach for instead of a hand-rolled `<input>`/`<button>`/pill), the `Dropdown` backdrop-blur rules (`noDropdownListStyle` / `portalToBody`), the `OverlayControlGroup` / `OverlayToolbar` contract for controls over a canvas, and the event-summoned Modal/LazyDialog wiring. The home for client UI guidance that outgrows CLAUDE.md.---# Building client UI@@ -9,6 +9,50 @@ The client is a Preact app (legacy widgets are jQuery `BasicWidget`s; new UI isThe general styling rules (no inline styles, one `.css` file per component imported at the top, scope by root class + native CSS nesting) are in the repo `CLAUDE.md`; this skill is about *which component* and *how to drive it*.+> **CLAUDE.md still foregrounds the jQuery widget lifecycle** (`doRenderBody` / `refreshWithNote` / `this.$widget`). That is for maintaining existing widgets. New UI is a `.tsx` component using the hooks below; reach for `useLegacyWidget` only to embed an existing jQuery widget into a Preact tree.++## Don't reinvent froca-reactive state++The most common mistake on this surface is writing `useState` + `server.get`/`froca` + a hand-rolled `entitiesReloaded` listener for something a **one-line hook already does** — with the right reload filter, the right echo-suppression, and the stale-request guard. `apps/client/src/widgets/react/hooks.tsx` exports 60 `use*` hooks. Check the catalogue first: [references/hooks-catalog.md](references/hooks-catalog.md).++| You need… | Use | It already wires |+|---|---|---|+| a scalar `FNote` field (title, isProtected, type, mime) | `useNoteProperty(note, "title", componentId)` | `loadResults.isNoteReloaded(noteId, componentId)` |+| a label value (read/write) | `useNoteLabel` / `…Boolean` / `…Int` / `…WithDefault` / `…OptionalBool` | `getAttributeRows()` + `attributes.isAffecting(attr, note)` — handles inheritance and templates |+| a label the user named themselves | `useNoteLabelByName` | same; `useNoteLabel` delegates to it but types the name to the declared vocabulary |+| a relation (read/write, or resolve the target) | `useNoteRelation` / `useNoteRelationTarget` | the same attribute filter |+| note binary content / blob | `useNoteBlob(note, componentId, { reportLoadStateTo })` | `isNoteContentReloaded` + an explicit delete check + a requestId stale-guard |+| child notes / subtree | `useChildNotes(parentNoteId)` | `getBranchRows()` parent match + `frocaReloaded` |+| an `FNote` by id | `useNote` / `useNoteTitle` / `useNoteIcon` / `useNoteColorClass` | cache-first + the matching reload filter |+| a synced option (read/write) | `useTriliumOption` / `…Bool` / `…Int` / `…Json` / `useTriliumOptions` | `getOptionNames()` |+| the split's note context | `useNoteContext()` | setNoteContext / noteSwitched / frocaReloaded / hoisted / readOnly |+| the *active* (focused) context | `useActiveNoteContext()` | same, plus re-resolving notePath when the note is moved |+| read-only / temporarily-editable state | `useIsNoteReadOnly` / `useEffectiveReadOnly` | the `readOnly` label + `readOnlyTemporarilyDisabled` |+| editor autosave plumbing | `useEditorSpacedUpdate` / `useBlobEditorSpacedUpdate` | spaced-update + the provenance guard for #9614 |+| fullscreen state for an overlay button | `useFullscreen(element)` | the Fullscreen API + `fullscreenchange` |+| publish/consume cross-widget data | `useSetContextData` / `useGetContextData` | `contextDataChanged` |+| a raw Trilium event | `useTriliumEvent` / `useTriliumEvents` | registerHandler/removeHandler on `ParentComponent` |+| embed a legacy jQuery widget | `useLegacyWidget` | the `child()` / `render()` / `activeContextChanged` bridge |++## The `entitiesReloaded` filter taxonomy++If you genuinely must hand-write `useTriliumEvent("entitiesReloaded", ({ loadResults }) => …)`, pick the **right predicate** — the wrong one silently never fires:++| Changed | Predicate |+|---|---|+| note row or its attributes | `loadResults.isNoteReloaded(noteId, componentId)` |+| blob / content (**not** the note row) | `loadResults.isNoteContentReloaded(noteId, componentId)` |+| a label or relation | iterate `loadResults.getAttributeRows()`, keep `attributes.isAffecting(attr, note)` |+| children added/removed/moved | `loadResults.getBranchRows()` (match `parentNoteId`) |+| options | `loadResults.getOptionNames()` |+| the whole cache was swapped (e.g. protected session) | the separate `frocaReloaded` event — re-read `FNote` refs, the old ones are orphaned |++Three things people get wrong:++- **`isNoteReloaded` ≠ `isNoteContentReloaded`.** The note row/attributes and the blob are tracked in *separate* maps. Using one to refresh the other compiles, runs, and never updates.+- **Attribute ownership is not `attr.noteId === note.noteId`.** `attributes.isAffecting()` walks `getNotesToInheritAttributesFrom()` and, for inheritable attributes, `hasAncestor()` — so a naive id check misses inherited and templated attributes.+- **Pass `componentId`** when the same component both saves and listens. `isNoteReloaded`/`isNoteContentReloaded` skip the originating component, so without it the widget gets its own save echoed back and clobbers fresher user-typed input.+## Reusable component catalogueForm controls:@@ -83,3 +127,55 @@ Rules for `OverlayControlButton`, which cover every case seen so far:- Reuse shared labels from the `common` translation namespace (e.g. `common.fullscreen`) rather than adding a per-widget copy of a string the app already has.Worked examples to read before adding a new one: `apps/client/src/widgets/type_widgets/mind_map/MapToolbar.tsx` (group + toolbar + fullscreen), `type_widgets/relation_map/MapToolbar.tsx`, `collections/geomap/MapToolbar.tsx`, `type_widgets/helpers/SvgSplitEditor.tsx`.++## Dialogs++Dialogs are **event-summoned** and **lazy-mounted**. Worked example: `apps/client/src/widgets/dialogs/sort_child_notes.tsx`.++1. **State:** `const [ shown, setShown ] = useState(false);`+2. **Summon:** `useTriliumEvent("yourEvent", (data) => { …; setShown(true); });`+3. **Render** a controlled `<Modal>`:+ ```tsx+ <Modal+ className="your-dialog" // static literal — Bootstrap mutates classList (fade/show)+ show={shown}+ onHidden={() => setShown(false)} // MANDATORY — see below+ onSubmit={onSubmit} // optional: wraps the body in a form, Enter submits+ title={t("…")} size="lg"+ >…</Modal>+ ```+4. **Register it** in `applyModals()` in `apps/client/src/layouts/layout_commons.tsx`:+ ```tsx+ .child(<LazyDialog triggerEvents={["yourEvent"]} loader={() => import("../widgets/dialogs/your.js")} />)+ ```+ Skip this and **nothing summons the dialog** — the event has no listener and the modal never mounts.+5. **Eager (un-lazy) registration is only for the four documented exceptions** at the end of `applyModals()` — see the reference.++Two `Modal` footguns:++- **`onHidden` is required and must `setShown(false)`.** Bootstrap closing the modal (backdrop, close button, submit) does **not** touch React state; if `show` stays `true`, the next `show=true` is a no-op and the dialog can't reopen.+- **Keep `className` a static string.** It is rendered as `` `modal fade mx-auto ${className}` `` and Bootstrap toggles `fade`/`show` on that same element, so a dynamic className fights it.++Full prop reference, `LazyDialog` mechanics and the eager exceptions: [references/dialogs.md](references/dialogs.md).++## Footgun checklist++- **Reinventing a hook** — `useState` + `server.get` + a manual `entitiesReloaded` listener that a hook already provides. Check the catalogue.+- **Wrong reload predicate** — `isNoteReloaded` (row/attrs) vs `isNoteContentReloaded` (blob) vs `getAttributeRows()` + `isAffecting` (labels/relations, including inherited) vs `getBranchRows()` (children) vs `getOptionNames()`.+- **Omitting `componentId`** — the saving widget echoes its own change back and overwrites fresher input.+- **Dialog registered but not wired** — no `<LazyDialog triggerEvents={…}>` in `applyModals()`, so the summon event has no listener and nothing happens.+- **Modal can't reopen** — a missing/empty `onHidden`, or a dynamic `className` fighting Bootstrap's `fade`/`show`.+- **Bootstrap utility classes or inline static styles on `Form*` components** — use the sibling per-component `.css` scoped under a root class.+- **Hand-rolled overlay buttons** — `tn-overlay-*` classes at a call site instead of `OverlayControlGroup` / `OverlayControlButton`.+- **Copying the jQuery lifecycle** (`doRenderBody` / `refreshWithNote` / `this.$widget`) into new `.tsx` — use `useLegacyWidget` only to embed an existing widget.++> Not a footgun here: `isElectron()` / `isMac()` from `apps/client/src/services/utils.ts` are runtime checks safe at module load. The "call only after init" trap is a **trilium-core** concern (`utils/index.ts` → `getPlatform()`), not client UI.++## Reference map++| File | Read it for |+|---|---|+| [references/hooks-catalog.md](references/hooks-catalog.md) | All 60 `use*` hooks grouped by purpose, one line each with the `loadResults` filter it wires — the anti-re-derivation asset. |+| [references/dialogs.md](references/dialogs.md) | Full `Modal` prop reference, the 5-step summon→register recipe, `LazyDialog` mechanics, the four eager exceptions, the `sort_child_notes.tsx` walkthrough. |++Related skills: **writing-unit-tests** (rendering these components and testing hooks with the easy-froca fixtures), **analyzing-coverage** (measuring client coverage), **working-with-translations** (adding the English strings these components display).diff --git a/.claude/skills/building-client-ui/references/dialogs.md b/.claude/skills/building-client-ui/references/dialogs.mdnew file mode 100644index 0000000000..835feb8ddb--- /dev/null+++ b/.claude/skills/building-client-ui/references/dialogs.md@@ -0,0 +1,107 @@+# Dialogs — `Modal` + `LazyDialog`++Dialogs in the main window are **event-summoned** and **lazy-mounted**. You write a self-contained `.tsx` component that renders a controlled `<Modal>`, then register it once in `applyModals()`. Until its summon event first fires, neither the component nor its module graph is loaded.++Files: `apps/client/src/widgets/react/Modal.tsx`, `apps/client/src/layouts/layout_commons.tsx`, worked example `apps/client/src/widgets/dialogs/sort_child_notes.tsx`.++## The 5-step recipe++1. **Local `shown` state.** `const [ shown, setShown ] = useState(false);`+2. **Summon handler.** `useTriliumEvent("yourEvent", (data) => { /* stash data */ setShown(true); });` — the event carries any inputs and callbacks.+3. **Render a controlled `<Modal>`** with `show={shown}`, `onHidden={() => setShown(false)}`, and a **static** `className`.+4. **Register in `applyModals()`** (`layout_commons.tsx`) as `<LazyDialog triggerEvents={["yourEvent"]} loader={() => import("../widgets/dialogs/your.js")} />`. **Without this the dialog never mounts** — nothing listens for the summon event.+5. **Trigger it** from anywhere via `appContext.triggerCommand("yourEvent", …)` / `triggerEvent`.++### Worked example (`sort_child_notes.tsx`, abridged)++```tsx+export default function SortChildNotesDialog() {+ const [ parentNoteId, setParentNoteId ] = useState<string>();+ const [ shown, setShown ] = useState(false);++ useTriliumEvent("sortChildNotes", ({ node, noteId }) => {+ const targetNoteId = noteId ?? node?.data.noteId;+ if (!targetNoteId) return;+ setParentNoteId(targetNoteId);+ setShown(true); // step 2+ });++ async function onSubmit() {+ await server.put(`notes/${parentNoteId}/sort-children`, { /* … */ });+ setShown(false); // close on success+ }++ return (+ <Modal+ className="sort-child-notes-dialog" // static literal+ title={t("sort_child_notes.sort_children_by")}+ size="lg" maxWidth={500}+ onSubmit={onSubmit} // form + Enter-to-submit+ onHidden={() => setShown(false)} // MANDATORY+ show={shown}+ footer={<Button text={t("sort_child_notes.sort")} keyboardShortcut="Enter" />}+ >+ {/* FormRadioGroup / FormCheckbox / FormTextBox … */}+ </Modal>+ );+}+```++Registration, one line in `applyModals()`:+```tsx+.child(<LazyDialog triggerEvents={["sortChildNotes"]} loader={() => import("../widgets/dialogs/sort_child_notes.js")} />)+```++## Two Modal footguns++- **`onHidden` is required and must `setShown(false)`.** Its doc comment says so explicitly. When Bootstrap closes the modal (close button, backdrop click, or submit) it fires `hidden.bs.modal` → `onHidden`, but does **not** touch your React state. If `show` stays `true`, the next `show=true` render is a no-op and the dialog cannot reopen.+- **Keep `className` a static string literal.** Modal renders the outer element as `` `modal fade mx-auto ${className}` `` and Bootstrap toggles `fade`/`show` on that **same** element. A dynamic className overwrites those classes on the next render and fights the transition.++## `Modal` prop reference++The full set is the `ModalProps` interface at the top of `Modal.tsx` (~28 props, each doc-commented). The ones that come up:++| Prop | Type | Notes |+|---|---|---|+| `className` | `string` (required) | static literal; appended to `modal fade mx-auto`. |+| `show` | `boolean` (required) | controlled visibility. |+| `onHidden` | `() => void` (required) | fired on any close; **must set `show` false**. |+| `title` | `string \| ComponentChildren` | string → `<h5 class="modal-title">`; node → rendered as-is. |+| `size` | `"xl" \| "lg" \| "md" \| "sm"` | maps to `modal-{size}`. |+| `onSubmit` | `() => void` | wraps body+footer in a `<form>`; Enter submits. |+| `onShown` | `() => void` | fired on `shown.bs.modal`. |+| `footer` | `ComponentChildren` | rendered in `.modal-footer`; the usual place for the submit `Button`. |+| `footerStyle` / `footerAlignment` | `CSSProperties` / `"right" \| "between"` | `"between"` sets `justify-content: space-between`. |+| `header` | `ComponentChildren` | extra header items beside the title. |+| `sidebar` / `hideSidebarHeader` | `ComponentChildren` / `boolean` | full-height left sidebar; switches to a horizontal split layout. |+| `helpPageId` | `string` | renders a `?` button opening in-app help. |+| `customTitleBarButtons` | `(CustomTitleBarButton \| null)[]` | extra header buttons. |+| `minWidth` / `maxWidth` / `zIndex` | `string` / `number` / `number` | sizing / stacking. |+| `scrollable` | `boolean` | scroll the body, keep header/footer fixed. |+| `stackable` | `boolean` | keep existing modals open instead of closing them (confirm dialogs). |+| `keepInDom` | `boolean` | stay mounted in the DOM when hidden (transitions / hover-preview latency). |+| `noFocus` | `boolean` | don't focus the modal after it shows. |+| `isFullPageOnMobile` | `boolean` | full-page presentation on mobile. |+| `modalRef` / `formRef` | `RefObject` | the underlying `<div>` / `<form>` (`formRef` only set with `onSubmit`). |+| `bodyStyle` | `CSSProperties` | style on `.modal-body`. |+| `ariaLabel` | `string` | accessible name for the dialog. |++## `LazyDialog` mechanics++`LazyDialog` is defined at the bottom of `layout_commons.tsx`; its doc comment is the authority. In short:++- `loader: () => Promise<{ default: ComponentType }>` — dynamic import of the dialog module; `triggerEvents: EventNames[]` — the events that summon it.+- The **first** matching event starts the import, guarded by a `loadStarted` ref so a second summons mid-load doesn't double-load (the `Component` state is still `undefined` then, so it can't short-circuit the load itself). Once loaded, the dialog stays mounted and handles further events directly.+- The buffered first event is **re-delivered through the subtree's host component in an effect**, because parent effects run *after* the children's — that ordering guarantees the dialog's own handlers are registered by the time the event arrives. Delivery also waits on the host component being available, since clearing `pendingEvent` early would drop the summons.+- **Limitation:** a second summons arriving while the module is still being fetched *replaces* the buffered event rather than queueing behind it.++## The eager (non-lazy) exceptions++Registered directly at the end of `applyModals()`, not wrapped in `LazyDialog`. Don't add another without an equally concrete reason:++| Component | Why eager |+|---|---|+| `PopupEditorDialog` | uses `keepInDom` for fast hover-preview latency; deferring its module defeats the purpose. |+| `CallToActionDialog` | has **no summon event** — it decides on startup whether to show itself, so there is nothing to lazily mount against. |+| `ToastContainer` | needed immediately and continuously to surface messages and errors, including those raised during startup. |+| `ShortcutHintsPanel` | a persistent panel fed by `useContextualShortcutHints`, not an event-summoned dialog. |diff --git a/.claude/skills/building-client-ui/references/hooks-catalog.md b/.claude/skills/building-client-ui/references/hooks-catalog.mdnew file mode 100644index 0000000000..b04fb505ee--- /dev/null+++ b/.claude/skills/building-client-ui/references/hooks-catalog.md@@ -0,0 +1,138 @@+# Hooks catalog — `apps/client/src/widgets/react/hooks.tsx`++Every exported `use*` hook (60 at the time of writing: `grep -cE "^export function use" apps/client/src/widgets/react/hooks.tsx`), grouped by purpose. The point of this file: **find the hook before writing `useState` + `server.get` + a hand-rolled `entitiesReloaded` listener.**++No line numbers here — the file moves too fast for them to stay true. Jump with `grep -n "export function <name>" apps/client/src/widgets/react/hooks.tsx`.++## Note fields / identity++| Hook | Does | Reacts to |+|---|---|---|+| `useNoteProperty(note, prop, componentId?)` | scalar `FNote` field (`title`, `isProtected`, `type`, `mime`) | `loadResults.isNoteReloaded(noteId, componentId)` |+| `useNote(noteId, silentNotFoundError?)` | resolve an `FNote` by id | cache-first, then `froca.getNote`, with a `requestId` stale-guard |+| `useNoteTitle(noteId, parentNoteId?)` | title via `tree.getNoteTitle` (handles protected/placeholder) | `isNoteReloaded` + branch match + `protectedSessionStarted` |+| `useNoteIcon(note)` | `note.getIcon()` | the `iconClass` label |+| `useNoteColorClass(note)` | `note.getColorClass()` | the `color` label |+| `useNoteSavedData(noteId)` | last-saved content via `useSyncExternalStore` over `noteSavedDataStore` | store subscription |++## Labels (read/write, inheritance-aware)++All iterate `loadResults.getAttributeRows()` and keep rows where `attributes.isAffecting(attr, note)` — which covers inherited and templated attributes. Don't replace that with `attr.noteId === note.noteId`.++| Hook | Notes |+|---|---|+| `useNoteLabel(note, name)` | `[value, setter]`. Setter: `undefined` → create a valueless label (tag); `null` → remove. `name` is typed to the declared label vocabulary. |+| `useNoteLabelByName(note, name)` | The same, for a label the app does **not** know by name — one the user named themselves. `useNoteLabel` delegates to it; prefer `useNoteLabel` wherever the name is a builtin, so it stays held to the vocabulary. |+| `useNoteLabelWithDefault(note, name, default)` | as `useNoteLabel`, value falls back to `default`. |+| `useNoteLabelBoolean(note, name)` | `[bool, setter]`; setter uses `attributes.setBooleanWithInheritance`. |+| `useNoteLabelOptionalBool(note, name)` | `undefined` when the label is absent → distinguishes "unset" from "false". |+| `useNoteLabelInt(note, name)` | parsed int, `undefined` when absent/non-finite. |++## Relations++| Hook | Does |+|---|---|+| `useNoteRelation(note, name)` | `[value, setter]`; same `getAttributeRows()` + `isAffecting` filter; setter calls `attributes.setAttribute`. |+| `useNoteRelationTarget(note, name)` | resolves the relation's target `FNote` (`note.getRelationTarget`). |++## Options (synced, read/write)++All react to `loadResults.getOptionNames()` and persist via `options.save`.++| Hook | Value type |+|---|---|+| `useTriliumOption(name, needsRefresh?)` | `string` (optionally reloads the frontend on change) |+| `useTriliumOptionBool(name, needsRefresh?)` | `boolean` |+| `useTriliumOptionInt(name)` | `number` |+| `useTriliumOptionJson<T>(name, needsRefresh?)` | parsed `T` |+| `useTriliumOptions(...names)` | record of many at once; setter is `options.saveMany` |++## Note context++| Hook | Does |+|---|---|+| `useNoteContext()` | the split's context: `{ note, noteId, notePath, hoistedNoteId, ntxId, viewScope, componentId, noteContext, parentComponent, isReadOnlyTemporarilyDisabled }`; reacts to setNoteContext / activeContextChanged / noteSwitched / frocaReloaded / noteTypeMimeChanged / readOnlyTemporarilyDisabled / hoistedNoteChanged. |+| `useActiveNoteContext()` | same shape but for the *focused* context; additionally **re-resolves `notePath` when the active note is moved** (entitiesReloaded + `getBranchRows`). |+| `useIsNoteReadOnly(note, noteContext)` | `{ isReadOnly, enableEditing, temporarilyEditable }` — read-only with an editing mode available. |+| `useEffectiveReadOnly(note, noteContext)` | synchronous effective read-only for widgets honoring `#readOnly` (mermaid/canvas/mind-map/spreadsheet). |++## Content & editor autosave++| Hook | Does |+|---|---|+| `useNoteBlob(note, componentId?, opts?)` | binary/blob content; `isNoteContentReloaded` + an explicit `isDeleted` check + a `requestId` stale-guard; optionally publishes `contentLoad` state to a note context via `reportLoadStateTo`. |+| `useSpacedUpdate(callback, interval?, stateCallback?)` | generic `SpacedUpdate` wrapper (debounced commit). |+| `useEditorSpacedUpdate({...})` | note-data autosave with a **provenance guard** so content typed into one note is never saved under the next note's id (#9614). |+| `useBlobEditorSpacedUpdate({...})` | as above but uploads a `Blob`/`File` (attachments, images); optional `replaceWithoutRevision`. |+| `useTextEditor(noteContext)` | the live `CKTextEditor` instance for a context; reacts to `textEditorRefreshed`. |+| `useContentElement(noteContext)` | the content `HTMLElement` for a context; reacts to `contentElRefreshed`. |++## Tree / children++| Hook | Does |+|---|---|+| `useChildNotes(parentNoteId)` | child `FNote[]`; `getBranchRows()` parent match + `frocaReloaded` (swaps to fresh refs after a cache wipe). |+| `useLauncherVisibility(launchNoteId)` | whether a launcher sits in a visible-launchers branch; reacts to branch changes. |++## Cross-widget context data++| Hook | Does |+|---|---|+| `useSetContextData(noteContext, key, value)` | publish data (TOC, PDF pages, save state) on a context; auto-clears on unmount/note switch. |+| `useGetContextData(key)` | consume context data from the **active** context. |+| `useGetContextDataFrom(noteContext, key)` | consume from a **specific** context; reacts to `contextDataChanged`. |++## Events / imperative interop++| Hook | Does |+|---|---|+| `useTriliumEvent(name, handler)` | register one event handler on the nearest `ParentComponent`; auto-unregisters. |+| `useTriliumEvents(names, handler)` | one handler for many events (handler gets `(data, eventName)`). |+| `useLegacyWidget(factory, opts)` | embed a jQuery `BasicWidget`/`NoteContextAwareWidget`; returns `[VNode, widget]`; bridges `child()`/`render()`/`activeContextChanged`. **The only sanctioned bridge to old widgets.** |+| `useLegacyImperativeHandlers(handlers)` | expose imperative methods on the host legacy component, so legacy callers can invoke them. |+| `useLegacyComponentElement(elRef)` | tag a DOM element with the owning component so jQuery's `.prop("component")` lookup finds it. |+| `useSyncedRef(externalRef?, initial?)` | merge an external ref with an internal one. |++## Keyboard & shortcuts++| Hook | Does |+|---|---|+| `useKeyboardShortcuts(scope, containerRef, parentComponent, ntxId)` | bind a note-type scope's actions (`code-detail`/`text-detail`) to a container; unbinds on cleanup. |+| `useGlobalShortcut(shortcut, handler)` | register a global shortcut under a random namespace. |+| `useContextualShortcutHints(hints)` | contribute shortcut hints for the current context to the hints panel. Registers once per host via a ref, so an inline array/function doesn't re-register every render. A standalone Preact root hosted by `appContext` itself is skipped — registering there would surface the hints in *every* context. |++## Tooltips++| Hook | Does |+|---|---|+| `useTooltip(elRef, config)` | Bootstrap tooltip with an imperative `{ showTooltip, hideTooltip }`. |+| `useStaticTooltip(elRef, config?)` | tooltip with no imperative API; auto-hides siblings. |+| `useStaticTooltipWithKeyboardShortcut(elRef, title, actionName, opts?)` | static tooltip whose title appends the action's effective shortcut. |++## DOM / observers / sizing / navigation++| Hook | Does |+|---|---|+| `useElementSize(ref)` | element `DOMRect` via `ResizeObserver`. |+| `useWindowSize()` | `{ windowWidth, windowHeight }`, reacts to resize. |+| `useResizeObserver(ref, callback)` | run a callback on element resize. |+| `useFullscreen(element, onChange?)` | `[isFullscreen, toggle]` over the Fullscreen API. Reads `onChange` from a ref so a listener bound once follows a handler passed anew each render. Feed it to `OverlayFullscreenButton`. |+| `useNoteTreeDrag(containerRef, opts)` | drag-drop of notes onto a container (parses `DragData[]`). |+| `useCollectionTreeDrag(containerRef, opts)` | `useNoteTreeDrag` for a collection view; adds `dragEnabled`/`includeArchived` and warns when dropped notes are archived-and-hidden. |+| `useLongPressContextMenu(handler, holdMs?)` | right-click + touch long-press → context-menu props to spread. |+| `useContainedLinkNavigation(containerRef, onNavigate)` | keep internal note-link clicks inside a popup/dialog instead of the global handler (capture-phase). |+| `useImperativeSearchHighlighlighting(tokens)` | returns a fn that `mark.js`-highlights search tokens in an element. |+| `useMathRendering(containerRef, deps)` | lazily KaTeX-render `.math-tex` elements (TOC/highlights sidebars). |++## Misc utilities++| Hook | Does |+|---|---|+| `useUniqueName(prefix?)` | stable random name for inputs (unique across tabbed widgets). |+| `useColorScheme()` | `"dark"` / `"light"`, reacting to theme + `prefers-color-scheme`. |+| `useDelayedVisibility(active, opts?)` | flicker-free loading phase `"hidden"` / `"visible"` / `"stalled"` (grace + min-visible + stall escalation). |+| `useDebouncedValue(value, delay)` | the value, settled after `delay` ms without a change. |++---++**Testing these hooks:** see the **writing-unit-tests** skill — render via raw `preact` `render()` into happy-dom, drive entity changes with the easy-froca fixtures, and prefer extracting pure decision logic out of a component into a top-level `export function` you can test directly.