Skip to content

Build your personal knowledge base with Trilium Notes

docs(skills): record what the client needs under Preact 11

Elian Doran0e52dbcf488a
diff --git a/.claude/skills/building-client-ui/SKILL.md b/.claude/skills/building-client-ui/SKILL.md
index 538622c4de..ec49d0a43f 100644
--- a/.claude/skills/building-client-ui/SKILL.md
+++ b/.claude/skills/building-client-ui/SKILL.md
@@ -182,6 +182,56 @@ Two `Modal` footguns:
Full prop reference, `LazyDialog` mechanics and the eager exceptions: [references/dialogs.md](references/dialogs.md).
+## Preact 11 conventions
+
+**Where a name comes from.** Components, `createPortal`, `Fragment` and every type come from
+`preact`; hooks come from `preact/hooks`. Import from `preact/compat` only what nothing else
+provides: `memo`, `lazy`, `Suspense`, `flushSync`, `useSyncExternalStore`.
+
+- The DOM helper types are top-level exports of `preact`: `CSSProperties`, `HTMLAttributes`,
+ `ButtonHTMLAttributes`, `TargetedMouseEvent` (and the pointer, focus, keyboard, wheel and drag
+ twins), `MouseEventHandler`. The `JSX` namespace keeps only `JSX.Element` and
+ `JSX.IntrinsicElements`.
+- `MutableRef` is gone; its shape is `RefObject<T>`. `HTMLProps` exists only in compat; use
+ `HTMLAttributes`.
+- In an ambient `.d.ts` (`types-lib.d.ts`), import the Preact types an augmentation uses
+ explicitly: inside `declare module "preact"`, a name Preact only re-exports does not resolve.
+ `skipLibCheck` keeps `.d.ts` errors silent, so the broken augmentation shows up only where the
+ element is used.
+
+**Refs.** `useRef<T>(null)` returns `RefObject<T | null>`, so a hook or prop taking an element ref
+declares `RefObject<T | null>`. The argument-less `useRef<T>()` is gone: a value ref is
+`useRef<T | undefined>(undefined)`, and a callback type needs parentheses,
+`useRef<(() => void) | undefined>(undefined)`, or the union lands on its return type. Passing a
+nullable ref to `useImperativeHandle` infers `T` without its `null`; give both type arguments.
+
+**Unmount cleanups.** A removed component's `useEffect` cleanups run after the next paint, not during
+the unmount. A cleanup that must happen while the tree is torn down goes in `useLayoutEffect`
+instead:
+
+- it reports to a host that lets go of its state right after `render(null)` (`useForwardedKeys()`
+ clearing the editor's `aria-activedescendant` for `createHostedList()`);
+- it reads a child or library instance, which a class component's `componentWillUnmount()` tears
+ down synchronously (the canvas attachment editor's `release()` reading Excalidraw's scene).
+
+Clearing a timer, aborting a request or setting a flag can stay a passive cleanup: a frame late does
+no harm, and Preact runs all pending cleanups before any new effect.
+
+**`preact/compat` is always loaded**, and its `options.vnode` hook changes every element: `onChange`
+on a text-like `<input>`/`<textarea>` (including `range` and `color`) fires on `input`, `onFocus`/
+`onBlur` are the bubbling `focusin`/`focusout`, and numeric style values get `px`. Still write the
+unit (`` `${width}px` ``): core no longer adds it. `defaultProps` also works only through compat;
+use parameter defaults.
+
+**Per-element attribute types.** `role` is typed by element, following ARIA in HTML:
+
+- `<menu>` requires a `role`. Our menus use `role="none"`, as their rows carry their own roles.
+- Props spread onto a `<button>` are `ButtonHTMLAttributes`, not the generic `HTMLAttributes`.
+- `<input>` and `<img>` are discriminated unions keyed on `type` and on the accessible name. A
+ wrapper forwarding its caller's props cannot prove which branch it hits, so it casts once where
+ it spreads them (`AccessibleInputHTMLAttributes`, `AccessibleImgHTMLAttributes`), as `FormTextBox`
+ and `SafeImage` do. Narrowing the wrapper's props does not satisfy the union.
+
## Footgun checklist
- **Reinventing a hook** — `useState` + `server.get` + a manual `entitiesReloaded` listener that a hook already provides. Check the catalogue.
@@ -192,6 +242,8 @@ Full prop reference, `LazyDialog` mechanics and the eager exceptions: [reference
- **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.
+- **A `useEffect` cleanup that must run during the unmount** — it runs after paint; reporting to a host or reading a child instance belongs in a `useLayoutEffect` cleanup (see "Preact 11 conventions").
+- **Importing core names through `preact/compat`** — `createPortal`, hooks and types come from `preact` / `preact/hooks`; compat is for `memo`, `lazy`, `Suspense`, `flushSync`, `useSyncExternalStore`.
- **Diagnosing a style or placement bug from the stylesheets** — the load order in a hand-built test page does not match the app's, so the bug can fail to reproduce and send you after the wrong cause. Measure computed styles in a running instance: [references/inspecting-the-running-app.md](references/inspecting-the-running-app.md).
> 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.
diff --git a/.claude/skills/building-client-ui/references/inspecting-the-running-app.md b/.claude/skills/building-client-ui/references/inspecting-the-running-app.md
index ab2441fc3c..9a2199c590 100644
--- a/.claude/skills/building-client-ui/references/inspecting-the-running-app.md
+++ b/.claude/skills/building-client-ui/references/inspecting-the-running-app.md
@@ -69,6 +69,18 @@ Get-NetTCPConnection -LocalPort 37999 -State Listen | % { Stop-Process -Id $_.Ow
`filter` and `container-type` rather than reading the stylesheets; any of them creates a
containing block and a stacking context (see "Dropdown menus and the backdrop blur" in `SKILL.md`).
+- **A flicker, a ghost or a jump** — a state that lasts one frame cannot be screenshotted reliably.
+ Record it instead: start a `requestAnimationFrame` loop in the page that pushes, per frame, the
+ rects and row counts of the elements in question onto a `window` array, drive the interaction
+ with Playwright, then read the array back and print only the frames that differ. That shows which
+ change landed in which frame (a popup placed at the new caret one frame before its rows change).
+ Work driven from CodeMirror's `requestMeasure()` runs inside a rAF callback, so an effect it
+ schedules lands a full frame later.
+- **"It did not do this before"** — measure the old build next to the new one instead of reasoning
+ about the diff: `git worktree add --detach <scratch>/wt-main main`, `pnpm install --frozen-lockfile`
+ there, and boot it on another port (`TRILIUM_PORT=38000`) with the same fixture. Run the same
+ recording against both. Remove the worktree and `fuser -k` both ports afterwards.
+
**Transient state can vanish between reading it and screenshotting it.** An async re-render between
the `evaluate()` that dumps computed styles and the later `screenshot()` can wipe the state you are
studying (`fancytree-active`, a hover class, an open menu), which reads as "the CSS never painted"
diff --git a/.claude/skills/writing-unit-tests/client-components.md b/.claude/skills/writing-unit-tests/client-components.md
index f7887e1d4b..2dcd1292b7 100644
--- a/.claude/skills/writing-unit-tests/client-components.md
+++ b/.claude/skills/writing-unit-tests/client-components.md
@@ -10,6 +10,7 @@ Put this in a shared `apps/client/src/test/render.ts` (recommended) or inline pe
```ts
import { render } from "preact";
+import { act } from "preact/test-utils";
import { afterEach } from "vitest";
let container: HTMLDivElement | undefined;
@@ -20,21 +21,39 @@ export function renderInto(vnode: any) {
return container;
}
// Always tear down, or bootstrap Tooltips / listeners leak between tests.
-afterEach(() => { if (container) { render(null, container); container.remove(); container = undefined; } });
+afterEach(() => {
+ const mounted = container;
+ if (mounted) {
+ act(() => render(null, mounted));
+ mounted.remove();
+ container = undefined;
+ }
+});
```
+**Unmount inside `act()`.** Preact 11 runs a removed component's `useEffect` cleanups after the next
+paint, as React does. `act()` flushes them on the spot; a bare `render(null, container)` leaves them
+to fire during the *next* test, after its `beforeEach` has cleared the mocks, so that test sees a call
+it never made (`Modal`'s `hide()`, a font unregistering). The same goes for an unmount inside a test
+followed by an assertion on the cleanup. Copy a `let container` into a `const` first: TypeScript's
+narrowing does not reach into the arrow function.
+
Spec files that use JSX must be named `*.spec.tsx`.
## Firing events — match Preact's delegated event names
-Set the value, then dispatch the **native** event Preact listens for, always with `{ bubbles: true }`:
+Set the value, then dispatch the **native** event Preact listens for, always with `{ bubbles: true }`.
+`setup.ts` loads `preact/compat` for every spec, as the app always has it loaded, and compat's
+`options.vnode` hook renames several handlers. Dispatch what the renamed handler listens to:
| Handler | Dispatch | Notes |
|---|---|---|
| `onClick` | `el.click()` | simplest |
| `onInput` | `new Event("input", { bubbles: true })` | text inputs |
-| `onChange` (on `<select>`) | `new Event("change", { bubbles: true })` | |
-| **`onBlur`** | **`new Event("focusout", { bubbles: true })`** | ⚠️ Preact delegates blur→`focusout`; a `"blur"` event silently does **nothing** |
+| **`onChange` on a text-like `<input>`/`<textarea>`** | **`new Event("input", { bubbles: true })`** | ⚠️ compat maps it to `input` for every type but checkbox, radio and file — that includes `range` and `color`. A `"change"` event does **nothing** |
+| `onChange` on `<select>`, checkbox, radio, file | `new Event("change", { bubbles: true })` | |
+| **`onFocus` / `onBlur`** | **`new Event("focusin"/"focusout", { bubbles: true })`** | ⚠️ compat maps them to the bubbling events; `"focus"`/`"blur"` silently do **nothing** |
+| any other `on<Name>` | the lowercase DOM name (`dragover`, `dragstart`, `drop`) | Preact 11 always lowercases a camel-case handler. Preact 10 kept `DragOver` where the DOM had no `ondragover` property, as under happy-dom — don't bring that casing back |
## Tier A — presentational (props → DOM + click)
@@ -150,6 +169,15 @@ describe("ActionButton", () => {
- **Preact runs `useEffect` after the next frame**, so a listener registered there is not in place when a spec dispatches an event right after `render`, and `await new Promise(r => setTimeout(r))` is not long enough. Register listeners the first interaction needs in `useLayoutEffect` (as `FormList` and `Popup` do), or `vi.waitFor` the effect's result.
- **`t()` returns `undefined`** without an initialized i18next, and Preact then drops the attribute. To assert on a translated label, `vi.mock("../../services/i18n", () => ({ t: (key: string) => key }))` and expect the key.
- **Popups placed by Floating UI** (`Popup`, `Menu`, `Dropdown`, `Popover`) need sizes, since happy-dom lays out nothing: stub `document.documentElement`'s `clientWidth`/`clientHeight` and `HTMLElement.prototype`'s `offsetWidth`/`offsetHeight`, and give the anchor a rect with `vi.spyOn(anchor, "getBoundingClientRect")`. Don't stub `getBoundingClientRect` on the whole prototype: Floating UI also measures `<html>`, and the popup lands somewhere else. Where several elements need rects, stub by selector (`this.matches(".tn-menu, .dropdown-item")`) and fall back to the original. Worked examples: `Popup.spec.tsx`, `Menu.spec.tsx`, `Dropdown.spec.tsx`.
+- **Preact runs no handler on an element it has removed.** Interact only with what is drawn now: a
+ menu closes on a pick, so a second pick needs the menu opened again and its item looked up again.
+ A reference taken before the first click points at a detached node, and clicking it does nothing
+ (Preact 10 still ran its handler, which let such a spec pass for the wrong reason). Assert the
+ re-queried element exists before clicking it.
+- **Bootstrap's transition timers outlive a spec.** happy-dom runs no transitions, so Bootstrap
+ finishes each fade with a ~5 ms `setTimeout()` of its own that the environment's teardown does
+ not cancel. `setup.ts` waits them out in a global `afterAll()`; without it a file ending mid-fade
+ throws `parameter 1 is not of type 'Event'` against whichever file runs next in that worker.
- **Bootstrap's dropdown key handler is live in specs** (`setup.ts` imports Bootstrap). It captures Up, Down and Escape at `document` for any `.dropdown-menu` and throws when no `data-bs-toggle` is next to it, so a spec that presses those keys in a toggle-less `.dropdown-menu` fails with `reading 'parentNode'` unless the component captures them first.
- Pre-existing stderr noise (KaTeX "quirks mode", the `setup.ts` "vi.mock not at top level" warning) is **not** a failure — ignore it.
diff --git a/CLAUDE.md b/CLAUDE.md
index cd5b20f997..a9f6336607 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -22,7 +22,7 @@ pnpm dev:format-check | dev:format-fix # stylistic formatting
- **Never run ESLint** (`dev:linter-check`, `dev:linter-fix`, `npx eslint`) — it dies with an out-of-memory error, so a run tells you nothing. CI does not lint either — there is no `eslint`/`linter-check` step anywhere in `.github/workflows/`, so lint findings never block a merge; the gates are `pnpm typecheck` and the per-package `test --coverage` runs. (`packages/*` is ignored by the ESLint config anyway.)
- **Never run `pnpm test:all`, `test:parallel`, `test:sequential`, or a whole-package `coverage`** during development — CI runs them on every push. Run the **narrowest** suite that covers what you touched: `pnpm --filter <pkg> test <pattern>` (Vitest treats the trailing argument as a substring filter over spec paths). Core specs need **two** runs, server and standalone (see Testing). Only reach for a full suite if the user asks or wants a final check.
-- **Typecheck with `pnpm typecheck`, not a raw `tsc`** — it resolves the project references a hand-written `tsc -p …` gets wrong, and is far cheaper than a test suite. Still, run it **once, after a piece of work is finished** — not after every edit: it builds the project references, and repeating it is a common way to lose minutes across a session.
+- **Typecheck with `pnpm typecheck`, not a raw `tsc`** — it resolves the project references a hand-written `tsc -p …` gets wrong, and is far cheaper than a test suite. Still, run it **once, after a piece of work is finished** — not after every edit: it builds the project references, and repeating it is a common way to lose minutes across a session. Two ways its output misleads: the incremental build does not recheck the files that use an ambient `.d.ts` (`types-lib.d.ts`) after it changes — delete `apps/client/dist/*.tsbuildinfo` (gitignored) before trusting the result; and a dependent project (`tsconfig.spec.json`, `apps/build-docs`) is checked only once the app project compiles, so its errors appear only after the app's are fixed, and some vanish with them.
- **Two TypeScript versions, on purpose**: root `package.json` has `typescript` 6.x (the JS compiler API that TypeDoc, typescript-eslint and the browser-bundled language service in `packages/codemirror` load) and `@typescript/native` (7, drives `pnpm typecheck` and owns the `tsc` bin). Do **not** bump `typescript` to 7, dedupe them, or switch to the `@typescript/typescript6` shim (no `lib.*.d.ts` → client build breaks). Reasoning: `docs/Developer Guide/Developer Guide/Environment Setup.md`, "TypeScript".
## Git Workflow
@@ -110,6 +110,8 @@ Frontend widgets in `apps/client/src/widgets/`:
**Widget lifecycle**: `doRenderBody()` for initial render, `refreshWithNote()` for note changes, `entitiesReloadedEvent({loadResults})` for entity updates. Fluent builder pattern: `.child()`, `.class()`, `.css()` chaining with position-based ordering. These legacy widgets are jQuery; new UI is Preact under `widgets/react/` — don't mix the two inside one component.
+The client runs **Preact 11**: components, `createPortal` and types come from `preact`, hooks from `preact/hooks`, and `preact/compat` only for `memo`, `lazy`, `Suspense`, `flushSync` and `useSyncExternalStore`. Compat is nonetheless always loaded, so `onChange` on a text input fires on `input` and `onFocus`/`onBlur` bubble. A removed component's `useEffect` cleanup runs after paint, so one that must happen during the unmount is a `useLayoutEffect` cleanup. Ref typing, per-element ARIA types and the rest: the **`building-client-ui` skill**, "Preact 11 conventions"; for specs (unmount inside `act()`, which events to dispatch): **`writing-unit-tests`**.
+
#### Reusable Preact Components
Shared components live in `apps/client/src/widgets/react/` — **always** reuse them (`FormTextBox`, `FormSelect`, `Button`, `Badge`, `NoItems`, `Dropdown`, `Table`, `Calendar`, …) instead of writing raw HTML elements or a custom implementation, and never put Bootstrap utility classes (`form-control-sm`, `input-group`, …) on them. Any control floating **over** a note's content (map, mind map, image, diagram) goes on `OverlayControlGroup` / `OverlayToolbar` — never a hand-rolled `<button>`. The full catalogue, when to use a `Dropdown` menu and when a `DropdownPanel` and the overlay-control contract are in the **`building-client-ui` skill** — load it before building client UI.