@linkdesk/plugin-docs 0.1.57 → 0.1.58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,849 +1,849 @@
1
- # Plugin UI Authoring Conventions
2
-
3
- > **In one line: the core already provides the standard components and registries—don't hand-roll wheels. Hand-rolling = inconsistent style + something to tear out at the next normalization.**
4
- > Skim this before writing a plugin, to avoid the same kind of rework.
5
- > **Reconciled against the implementation on 2026-09-06**: flatten-to-single-root (no plugins/{builtin,user}) · shared controls go through @linkdesk/ui · distribution = `.linkdesk-plugin` zip. References to the corresponding mechanisms have been cleaned out of this page.
6
-
7
- ---
8
-
9
- ## 1. Context Menu → `<ContextMenu>` + MenuRegistry
10
-
11
- **❌ Forbidden:** hand-writing `<div className="my-menu">` + `useState` + a click-outside listener.
12
-
13
- **✅ Right:**
14
- ```json
15
- // ① Declare the menu items—plugin.json contributes.menus (preferred, declarative)
16
- {
17
- "contributes": {
18
- "menus": {
19
- "editorContext": [
20
- { "command": "myPlugin.copy", "group": "navigation" },
21
- { "command": "myPlugin.clear", "group": "edit" }
22
- ]
23
- }
24
- }
25
- }
26
- ```
27
-
28
- ```tsx
29
- // Dynamic registration at runtime (equivalent)—window.linkdesk.menu.registerItems(menuId, pluginId, items)
30
- window.linkdesk.menu.registerItems("editorContext", "myPlugin", [
31
- { command: "myPlugin.copy", group: "navigation" },
32
- { command: "myPlugin.clear", group: "edit" },
33
- ]);
34
-
35
- // ② Use the unified component—MenuId is an open string, so just write a string literal
36
- <ContextMenu menuId="editorContext" />
37
- ```
38
-
39
- **Rationale:** `<ContextMenu>` brings its own backdrop + four blur paths (Escape / backdrop click / window blur / option click) + keyboard navigation + when-condition filtering. You can't hand-roll those four blur paths.
40
-
41
- **MenuId is an open string (`src/core/registry/commands/MenuRegistry.ts` `export type MenuId = string`)—a plugin declaring any string at all is the contract; no shell code change is needed.** Shell built-in registration points (the MENU_SLOTS constant table):
42
-
43
- | MenuId (string literal) | Scenario |
44
- |---|---|
45
- | `commandPalette` | Ctrl+Shift+P command palette |
46
- | `tabContext` | Tab Bar tab right-click |
47
- | `panelViewContext` | Panel tab bar right-click (position/alignment submenu + view show/hide list) |
48
- | `editorContext` | Tab page main content area right-click |
49
- | `extensionGear` | Bottom gear menu (settings/command palette/theme picker) |
50
- | `marketplaceItemGear` | Marketplace entry gear (enable/disable/uninstall) |
51
- | `menuBar` | ☰ hamburger menu bar |
52
- | `panel` | The "Panel" menu in the menu bar |
53
- | `fileContext` | File tree right-click |
54
- | `cardContext` | Card right-click |
55
- | `quickSendContext` | Quick-send pill right-click |
56
- | `iconBar` | Icon bar right-click |
57
- | `settingItemGear` | Setting item gear (Settings Editor row hover) |
58
- | `viewTitleContext` | Sidebar view title right-click (collapse/reset position/group the view) |
59
-
60
- New context-menu scenarios → just declare a new open-string MenuId (e.g. `"myMenu"`): declare `contributes.menus.myMenu` + consume it with `<ContextMenu menuId="myMenu" />`—**zero shell changes** (the plugin-independence iron rule). The shell only needs to add a MENU_SLOTS entry if it wants to provide a unified render point for that scenario.
61
-
62
- ---
63
-
64
- ## 2. Overlays / Dialogs → `createPortal`
65
-
66
- **❌ Forbidden:** a dialog nested deep inside a div in the component tree.
67
-
68
- **✅ Right:**
69
- ```tsx
70
- import { createPortal } from "react-dom";
71
-
72
- return createPortal(
73
- <div className="my-dialog">{/* ... */}</div>,
74
- document.body // ← the key: render into body
75
- );
76
- ```
77
-
78
- **Rationale:** under the keep-alive architecture inactive tabs are `display: none`, and children aren't visible even with `position: fixed`. Only rendering into `document.body` escapes the component-tree constraint.
79
-
80
- ---
81
-
82
- ## 3. Persistence → `window.linkdesk.configuration` (declared via plugin.json contributes.configuration)
83
-
84
- **❌ Forbidden:** `localStorage.setItem()` / `PreferenceService.loadPrefs()` / hand-written file I/O / `import ... from "@src/core/..."`.
85
-
86
- **✅ Right—go through `window.linkdesk.configuration` (plugin communication iron rule: only `window.linkdesk.*`, never `import` from @src/core):**
87
- ```tsx
88
- // Read configuration (a Promise—the value is dynamic at runtime)
89
- useEffect(() => {
90
- window.linkdesk.configuration.get<boolean>("myPlugin.showLineNumbers").then((v) => {
91
- setShowLineNumbers(v);
92
- });
93
- }, []);
94
-
95
- // Write configuration
96
- await window.linkdesk.configuration.set("myPlugin.showLineNumbers", true);
97
-
98
- // Subscribe to changes—returns an unsubscribe; call it on unmount
99
- useEffect(() => {
100
- return window.linkdesk.configuration.onChange<boolean>("myPlugin.showLineNumbers", (v) => {
101
- setShowLineNumbers(v);
102
- });
103
- }, []);
104
- ```
105
-
106
- **Declaring configuration items in plugin.json:**
107
- ```json
108
- {
109
- "contributes": {
110
- "configuration": {
111
- "title": "My Plugin",
112
- "properties": {
113
- "myPlugin.showLineNumbers": {
114
- "type": "boolean",
115
- "default": true,
116
- "description": "Show line numbers"
117
- }
118
- }
119
- }
120
- }
121
- }
122
- ```
123
-
124
- **Rationale:** the shell persists automatically + restores on restart + the Settings Editor renders it automatically. Hand-rolled localStorage → you lose Settings Editor integration + get the next persistence bug.
125
-
126
- ---
127
-
128
- ## 4. Keyboard Shortcuts → Two Tracks: Declarative (non-text keys) + Pool-side self-handling (text keys / focus-bound keys)
129
-
130
- Shortcuts have **two tracks**, and which one you pick depends on the nature of the key. **Picking the wrong track = a dead key or a hijack of the whole pool** (lesson).
131
-
132
- ### 4.1 Track one: `contributes.keybindings` (visible in the settings panel)—**non-text keys only**
133
-
134
- **❌ Forbidden:** putting **text-editing keys** such as `ctrl+c` / `ctrl+v` / `ctrl+x` / `ctrl+a` / `f2` into `contributes.keybindings`.
135
-
136
- **✅ Right:** (non-text keys—such as `ctrl+k` / `ctrl+shift+e` / `f5`)
137
- ```json
138
- {
139
- "contributes": {
140
- "keybindings": [
141
- {
142
- "key": "ctrl+k",
143
- "command": "myPlugin.clear",
144
- "when": "activeEditor == 'myPlugin'"
145
- }
146
- ]
147
- }
148
- }
149
- ```
150
-
151
- **Rationale (why text keys are a landmine):** declared/registered keys sync into the main-process keyCache → when `before-input-event` hits, the key is **swallowed unconditionally** (it doesn't respect when, doesn't respect an editable state, doesn't respect whether a handler even exists). Register one `ctrl+c` in the shell and you swallow the native `ctrl+c` of every input box / Monaco instance in the whole pool. The right answer for text keys = track two.
152
-
153
- ### 4.2 Track two: pool-side self-handling (container onKeyDown)—the right answer for text keys + focus-bound keys
154
-
155
- **✅ Right:** a component handles its own keyboard interaction inside its own **container's `onKeyDown`**:
156
-
157
- ```tsx
158
- <div
159
- tabIndex={0} // makes the container focusable—clicking a child makes the browser give focus to the nearest focusable ancestor
160
- onKeyDown={(e) => {
161
- if (e.key === "F2") { e.preventDefault(); startRename(); }
162
- }}
163
- >
164
- {items}
165
- </div>
166
- ```
167
-
168
- **Why this is the right answer:** every plugin in the pool shares one document—**DOM focus partitions naturally**. Only a focused container receives the key; a focused Monaco doesn't, and multiple plugins can each do their own `ctrl+c` without stepping on each other. No when needed, no conflict detection needed. File tree clipboard keys = the shared `useClipboardKeys` hook + the same command chain. Clipboard-related keys can reuse `src/pool/hooks/useClipboardKeys` (declarative `onCopy`/`onCut`/`onPaste` callbacks, one implementation and one fix location for the mechanism).
169
-
170
- **❌ Anti-pattern (red flag):** `document.addEventListener("keydown", ...)` / `window.addEventListener("keydown", ...)` = **global hijack**—it bypasses the partitioning premise, and while the plugin has an active session it hijacks that key across the whole pool (serial F2 once hijacked the file tree's F2). **`tabIndex` + container `onKeyDown` is the right answer for focus partitioning**; non-focusable elements don't trigger it, so add `tabIndex={0}` to receive keys.
171
-
172
- **Note:** track-two keys **do not appear in the keyboard shortcuts settings panel**—the panel only shows KeybindingRegistry bindings (track one). This is a design trade-off (registering means swallowing across the pool, see 4.1), not a bug.
173
-
174
- ### 4.3 Clipboard channel picker
175
-
176
- | What you want to copy | Channel | Example |
177
- |---|---|---|
178
- | Text inside an editable element (input/textarea/Monaco) | **Browser native**—write nothing | Ctrl+C/V inside an input box |
179
- | Arbitrary text | `window.linkdesk.clipboard.writeText` | Copy selected text to the system clipboard |
180
- | File/path list | `window.linkdesk.clipboard.writeFileList` | File tree copy → pasteable in Explorer (CF_HDROP) |
181
-
182
- **Note:** editable elements take the browser-native path—**don't** declare a shortcut and don't intercept it; Electron/Chromium wires up the system clipboard automatically.
183
-
184
- ---
185
-
186
- ## 5. Colors → CSS Variables `var(--xxx)`
187
-
188
- **❌ Forbidden:** hardcoding `#0078d4` / `#1e1e1e` / `#ffffff`.
189
-
190
- **✅ Right:**
191
- ```css
192
- .my-element {
193
- color: var(--text-primary);
194
- background: var(--bg-input);
195
- border: 1px solid var(--border);
196
- }
197
- ```
198
-
199
- **Rationale:** after a theme switch hardcoded colors stay the same → under a dark theme you get white text on a white background. See `src/index.css` for all available CSS variables.
200
-
201
- ---
202
-
203
- ## 6. Text → `t()` Internationalization
204
-
205
- **❌ Forbidden:** bypassing `t()` and hardcoding display strings (`<button>发送</button>` / `<button>Send</button>`).
206
-
207
- **✅ Right:**
208
- ```tsx
209
- import { useTranslation } from "react-i18next";
210
- const { t } = useTranslation();
211
- <button>{t("发送")}</button> // the i18n key = the plugin UI's source text (a Chinese plugin uses Chinese, an English/French plugin uses its own language)
212
- ```
213
-
214
- ---
215
-
216
- ## 7. Sidebar List Item Selection → `onMouseDown` (not `onClick`)
217
-
218
- **❌ Forbidden:** using `onClick` to select items in a vertical Sidebar list.
219
-
220
- **✅ Right:**
221
- ```tsx
222
- <div
223
- className={`my-list-item${isActive ? " active" : ""}`}
224
- onMouseDown={() => onSelect(item.id)}
225
- >
226
- <span>{item.label}</span>
227
- </div>
228
- ```
229
-
230
- **Rationale:** sidebar items sit vertically adjacent—on a fast click the mousedown lands on item A and the mouseup slides onto item B. Per the browser `click` event spec: when mousedown and mouseup land on different elements → click is dispatched to their common ancestor → React finds no handler on the ancestor → the event is silently lost. `onMouseDown` only cares about where the press happened and doesn't require the release on the same element—eliminating lost events on fast clicks.
231
-
232
- **Aligned with VS Code:** the Explorer file tree selects files with `onMouseDown`, not `onClick`. This is a pattern validated by tens of millions of users; don't design your own.
233
-
234
- **When it applies:** any clickable list in a Sidebar that is vertically arranged with small gaps between items—session lists, file trees, database connections, MQTT topics, device lists, and so on.
235
-
236
- **Handling child elements:** action buttons/input boxes inside an item need `onMouseDown={(e) => e.stopPropagation()}` to avoid accidentally selecting the parent item:
237
- ```tsx
238
- <button
239
- onMouseDown={(e) => e.stopPropagation()}
240
- onClick={(e) => { e.stopPropagation(); handleDelete(); }}
241
- >
242
- ✕
243
- </button>
244
- ```
245
-
246
- ---
247
-
248
- ## 8. Plugin-Owned Data Models → `Emitter` Reactive Pattern
249
-
250
- **❌ Forbidden:** mutating the model in a command handler and then manually calling `rerender()` / `setVersion()` / passing a `treeVersion` prop.
251
-
252
- **✅ Right—the web-standard `EventTarget` (zero core imports; plugin-owned classes extend it directly):**
253
- ```typescript
254
- class MyModel extends EventTarget {
255
- private _items: Item[] = [];
256
-
257
- add(item: Item): void {
258
- this._items.push(item);
259
- this.dispatchEvent(new CustomEvent("change")); // ← dispatch at the end of every state-changing method
260
- }
261
-
262
- remove(id: string): void {
263
- this._items = this._items.filter(i => i.id !== id);
264
- this.dispatchEvent(new CustomEvent("change"));
265
- }
266
- }
267
- ```
268
-
269
- ```tsx
270
- // Subscribe on component mount, clean up on unmount
271
- function MyView({ model }: { model: MyModel }) {
272
- const [version, setVersion] = useState(0);
273
-
274
- useEffect(() => {
275
- const onChange = () => setVersion(v => v + 1);
276
- model.addEventListener("change", onChange);
277
- return () => model.removeEventListener("change", onChange); // auto-unregistered on unmount
278
- }, [model]);
279
-
280
- const items = useMemo(() => computeItems(model), [model, version]);
281
- // ...
282
- }
283
- ```
284
-
285
- **Rationale:** three timing bugs (badge stuck at 0 / when stops working / refresh doesn't update the tree) all traced back to a module-level command handler mutating a mutable model, with React unable to perceive it. The model announces its own changes (`EventTarget`/`CustomEvent` are web standards; you don't need the shell's `Emitter`)—handlers only mutate the model and never touch React.
286
-
287
- **When it applies:** a plugin has module-level command handlers that need to trigger a UI refresh after changing data.
288
-
289
- **⚠️ Plugins must not `import { Emitter } from "@src/core/CoreEvents"`—that is a shell-internal implementation (plugin communication iron rule + ESLint `noCoreImportInPlugin` at error level). Plugin-owned models use the web-standard `EventTarget`; events between plugins, or between a plugin and the shell, go through `window.linkdesk.events` (see `07-plugin-to-plugin-communication.md`).**
290
-
291
- ---
292
-
293
- ## 9. System UI Overlays → linkdesk API (quickPick / notifications / dialog)
294
-
295
- **❌ Forbidden:** hand-rolled picker overlays / `window.alert()` / `window.confirm()` / `import ... from "@src/core/..."`.
296
-
297
- **✅ Right:**
298
- ```tsx
299
- // Picker—window.linkdesk.quickPick.show({ items, placeholder, prefix })
300
- const picked = await window.linkdesk.quickPick.show({
301
- placeholder: "Select target session",
302
- items: [
303
- { label: "Session A", description: "/dev/ttyUSB0" },
304
- { label: "Session B", description: "/dev/ttyUSB1" },
305
- ],
306
- });
307
-
308
- // Notification—window.linkdesk.notifications.show(message, { type })
309
- await window.linkdesk.notifications.show("Connected", { type: "info" });
310
- await window.linkdesk.notifications.show("Validation failed", { type: "error" });
311
-
312
- // Confirm / alert / file picker—window.linkdesk.dialog
313
- const ok = await window.linkdesk.dialog.confirm("Delete this session?");
314
- await window.linkdesk.dialog.alert("Version conflict, skipped");
315
- const file = await window.linkdesk.dialog.openFile({
316
- filters: [{ name: "DXF files", extensions: ["dxf"] }],
317
- });
318
- ```
319
-
320
- **Rationale:** all three are rendered uniformly by the in-pool host (QuickPickHost / **the bell wide notification panel** / DialogHost)—styles match the shell and scale with the theme and font size. Hand-rolled overlays = inconsistent style + `position: fixed` breaking under keep-alive. Full signatures are in `contracts/linkdesk.d.ts`.
321
-
322
- > ⚠️ **Notifications are not "auto-vanishing floating cards"** (notification-surface unification and correction): the bottom-right narrow toast pipeline has been deleted entirely, and **the only notification surface = the status bar bell wide panel**. Three things authors need to know:
323
- > 1. **Notifications don't pop a card, don't steal focus, and don't block interaction**—they go into the bell (unread count +1), and the user only sees them after opening it. Don't treat notifications as a "must be seen" channel: if the user has to decide on the spot → use `dialog.confirm` (modal, steals focus).
324
- > 2. **Persistent notifications per source are quota-limited**—grouped by `options.source`, at most 5 persistent per group; beyond that, the oldest one from the same source is pushed out. A flood won't pile into a wall, but **don't count on notifications for long-term records either**.
325
- > 3. **Keyboard reachability means "the panel is reachable", not "notifications are reachable"**—the bell can be focused and opened with the keyboard, everything inside the panel can be reached with Tab, and `Esc` closes it; but the panel **has no focus trap** (non-modal, focus can leave freely). **Don't write assumptions like "Tab gets you to my notification button"**—the user may never open the panel at all; and **don't count on a second surface**: the bell panel is the only notification face (user directive restated 2026-10-01 — the bottom-right "auto-vanishing card" was built twice and deleted twice).
326
-
327
- **Notification action buttons (`actions` on `notifications.show`):** failure / user-action-required notifications can carry an `actions` button array—clicking runs through the **command system** (modeled after VS Code's `showErrorMessage(msg, { title, command })` actions). Command handlers are registered by the plugin itself (`commands.registerCommand`):
328
-
329
- ```tsx
330
- // Failure toast + [Retry]/[View dependencies]—command = a command the plugin registered itself
331
- await window.linkdesk.notifications.show("Install failed: cannot connect to source", {
332
- type: "error", // error toasts linger 8s (enough to read the diagnostics); info/warning linger 6s
333
- actions: [
334
- { id: "retry", label: "Retry", isPrimary: true, command: "myplugin.retryInstall" },
335
- { id: "deps", label: "View dependencies", command: "myplugin.openDeps" },
336
- ],
337
- });
338
- // Commands can take arguments—clicking runs command(...args)
339
- await window.linkdesk.notifications.show("Save conflict", {
340
- type: "warning",
341
- actions: [{ label: "Force save", command: "myplugin.saveForce", args: [filePath] }],
342
- });
343
- ```
344
-
345
- Button text = the final display text (the shell does not translate it a second time); `isPrimary: true` = primary button (accent), unset = secondary text button. **Not passing `actions` = no buttons today, zero behavioral change.** Full types are in `contracts/linkdesk.d.ts` (the `actions` of the `notifications.show` options).
346
-
347
- **Progress notifications + persistent notifications + source identity:** `show` **always returns a handle** (it isn't only progress bars that get one). The three easiest things to get wrong:
348
-
349
- ```tsx
350
- // ① Progress notification—the handle drives the same single notification (it won't spawn N of them)
351
- const h = await window.linkdesk.notifications.show("Downloading…", {
352
- progress: true, // turns on a real progress bar; not passing percent = indeterminate animation
353
- source: "myplugin", // see ③
354
- });
355
- await h.update("Downloading…", 42); // 0-100; passing only message keeps it indeterminate
356
- await h.finish("Download complete"); // closes the progress bar, optionally adds a completion notification
357
- // or await h.cancel(); // close it outright, no completion notification
358
-
359
- // ② Persistent notification—doesn't auto-dismiss, waits for the user to click × (use for error diagnostics)
360
- await window.linkdesk.notifications.show("Port is in use, please close other programs", {
361
- type: "error",
362
- persistent: true,
363
- });
364
-
365
- // ③ Source identity—the panel groups by it, 5 persistent slots per group
366
- await window.linkdesk.notifications.show("Sync failed", { source: "myplugin" });
367
- ```
368
-
369
- **Three things you must know:**
370
-
371
- 1. **The handle is the only key**: a notification **can only be updated/removed by the handle that created it**. A `show` with the same text elsewhere = another notification, and you can't retract theirs. To retract a persistent notification (e.g. a failed `persistent`), use its own handle or let the user click ×.
372
- 2. **`source` must be self-reported**: the pool is a single process sharing one realm, all plugins share the same `window.linkdesk`, and preload **cannot** know which plugin issued this `show` ⇒ only the author can pass it explicitly. **Not passing it → everything lands in the "Other" group**; plugins pass their own plugin id, and the shell's own domains use `app.<domain>`.
373
- 3. **`persistent` has a quota**: at most 5 persistent per group (by `source`); beyond that the oldest of the same source is pushed out and a summary hint is shown. **Persistent ≠ unlimited retention**—if you need retention, write your own file.
374
-
375
- > The full **behavior contract** (not signatures—for signatures see `contracts/linkdesk.d.ts`) is in the `notifications` row of [`01-plugin-api-contract.md`](01-plugin-api-contract.md) §3.2—this section only covers usage, and that one is authoritative for semantics.
376
-
377
- **Rich-content confirm dialogs (`dialog.confirmContent`):** use this when the confirm dialog needs **more than one line of text** (a form / list / screenshot / custom layout)—**the dialog is the shell (centered, masking, Esc, focus lock, click-mask to cancel) and your view draws the content** (modeled after VS Code's "the dialog is the shell, the plugin defines the content"):
378
-
379
- ```tsx
380
- // 1) First declare the view for this content in plugin.json (any contributes.views container works)
381
- // 2) In code, address and open it by the "declared id"
382
- const ok = await window.linkdesk.dialog.confirmContent({
383
- pluginId: "myplugin", // the plugin the content belongs to (the shell uses this for composite addressing)
384
- viewId: "myplugin.confirmImport", // declared id of the content view
385
- title: "Confirm import", // fallback title—if the content view fails to resolve, the shell falls back to a plain-text confirm
386
- message: "3 entries will be overwritten", // fallback body
387
- payload: { files: ["a.ts", "b.ts"] }, // opaque payload: the shell doesn't interpret it, your view reads it itself
388
- });
389
- if (ok) { /* user confirmed */ } // false = cancelled / closed
390
- ```
391
-
392
- The other half—the content view (**another view in the same code**, reading the payload and stating a verdict):
393
-
394
- ```tsx
395
- // In your content view component—mounting opens it, reading once is enough (every new dialog is a fresh mount)
396
- function MyConfirmContent() {
397
- const data = window.linkdesk.dialogHost.current();
398
- if (!data || data.open !== true) return null; // defensive: don't render blank
399
- const payload = data.content?.payload as MyPayload;
400
- return (
401
- <div>
402
- {/* The body layout and the buttons are entirely yours to draw */}
403
- <button onClick={() => window.linkdesk.dialogHost.cancel()}>Cancel</button>
404
- <button onClick={() => window.linkdesk.dialogHost.confirm()}>OK</button>
405
- </div>
406
- );
407
- }
408
- ```
409
-
410
- **The fallback is hard**: if `viewId` can't be resolved (view not declared / the declaring plugin isn't installed) → the shell **falls back to a plain-text confirm** (using `title`/`message`), the dialog still appears and **never dies silently**. So don't skip `title`/`message`. The payload crosses IPC via structured clone, so only cloneable data can go in it (no functions/React elements). There are only two ways to settle: `dialogHost.confirm()` / `dialogHost.cancel()`—**don't close the dialog yourself with `setState`**; the shell won't recognize it.
411
-
412
- ---
413
-
414
- ## 10. Font Sizes → `--font-size-*` tokens + `--ui-scale` (measurement-system normalization)
415
-
416
- **❌ Forbidden:** writing bare `px` for plugin text font sizes (`font-size: 14px`)—the `check-font-scale-audit` gate (`npm run check`) rejects it mechanically.
417
-
418
- **✅ Right:** font sizes consume `var(--font-size-*)`; line-height is unitless (`1.5`) or `calc(... * var(--ui-scale))`; fixed upper bounds (input box/button/status bar heights) are written as `calc(Npx * var(--ui-scale))` to scale with the global setting. Unified global font-size scaling (the `app.uiFontScale` setting, 85–150%, always shown and always in effect).
419
-
420
- **Scale table** (100% render = `--ui-scale: 1`; the engine computes the final px from the scale factor):
421
-
422
- | Step | Base px | Meaning |
423
- |---|---|---|
424
- | `--font-size-2xs` | 11 | badges/paths |
425
- | `--font-size-xs` | 12 | secondary text/buttons/stats |
426
- | `--font-size-sm` | 13 | main UI text (aligned with VS Code's 13px) |
427
- | `--font-size-md` | 14 | menus/tabs/file tree name |
428
- | `--font-size-lg` | 16 | icon glyphs/content icons (paired with 14px text) |
429
- | `--font-size-xl` | 18 | region titles |
430
- | `--font-size-2xl` | 22 | row icons/large text |
431
- | `--font-size-3xl` | 28 | pd-name |
432
- | `--font-size-4xl` | 30 | welcome-title |
433
-
434
- **Iron rules + boundaries (see the archive's §5 icon rulings / §6.2 monaco island decision):**
435
- - **Standalone display icons do not scale with font size** (decorative/brand semantics, not directly adjacent to text)—`.icon-btn .plugin-icon--codicon` 24 / `.plugin-icon--emoji` 24 / `.hamburger-btn` 20 / hero-icon 48 / row icons 20, and so on; for whitelist exemptions see `scripts/check-font-scale-audit.mjs`.
436
- - **Content-level font sizes go through `contributes.configuration`** (e.g. `editor.fontSize`)—large text areas/editor content are controlled by the plugin's own configuration and don't follow `--ui-scale`.
437
- - **The monaco content island precedent**: editor content reads `editor.fontSize`, while chrome (status bar/breadcrumbs) follows the global setting—two orthogonal axes, each minding its own business.
438
- - **Mapping rule**: migrating existing `NNpx` to the scale table goes "up one step"—`12→sm / 13→md / 11→xs / 10→2xs / 14→lg / 18→xl` (at 100% this enlarges to the new default baseline, aligned with VS Code).
439
-
440
- ---
441
-
442
- ## 11. The Token Contract—Six-Domain Matrix + Honest Boundaries + Data Discipline (.5)
443
-
444
- > **In one line:** before writing UI, check the 11.1 six-domain matrix—forms/controls/surfaces written with `var(--*)` **follow the theme + glass + global scaling automatically**, with zero plugin awareness. Doing it right is driven by recommendations, doing it wrong shows red through the gate but only as a WARN, and bypassing it takes a knowing declaration via a standard eslint-disable (content/brand fixed colors are legitimately exempt—see 11.2).
445
- > The gate = `linkdesk-plugin-sdk lint` (built into `@linkdesk/plugin-sdk`): the eslint rule leg + the three-check scanner leg, dual-track; all 15 items are **WARNs that never fail the build/upload**—advice, not a lockdown. Run it once at your project root; a violation shows red with self-explanatory fix text.
446
-
447
- ### 11.1 The six-domain token matrix—authors can only write "follows automatically" if they know what variables exist
448
-
449
- | Domain | var() keys (the full list always defers to `src/index.css`) | How authors write it | Gate coverage |
450
- |---|---|---|---|
451
- | **Color** | `--text-primary/--text-secondary/--text-muted` (the text-color source is controlled by fontTone) + `--bg-window/--bg-side-panel/--bg-card/--bg-input/--bg-selection` + `--accent/--accent-hover` | `color: var(--text-primary)` | `linkdesk/no-hardcoded-hex` |
452
- | **Surface** | `--bg-*` surface fills + `--surface-radius` (follows the shell's global corner-radius slider) | `background: var(--bg-card)` | `linkdesk/no-hardcoded-hex` |
453
- | **Radius** | `--radius-xs/sm/md/lg/xl/2xl` + `--surface-radius` | `border-radius: var(--radius-md)` | `linkdesk/no-hardcoded-radius` (bare px in border-radius is red) |
454
- | **Glass** | `--glass-blur/--glass-saturate/--glass-tint/--glass-morph/--glass-specular…` (the full group in `src/index.css`) | `backdrop-filter: blur(var(--glass-blur)) …` | contract guidance—composite forms are beyond per-item gating |
455
- | **Font size** | `--font-size-2xs … 4xl` + `--ui-scale` (the scaling axis for `app.uiFontScale`; the scale table is in §10) | `font-size: var(--font-size-md)` / em/rem | `check-font-scale` (the check leg—a bare px font size is red) |
456
- | **Font family** | `--font-ui` / `--font-mono` | `font-family: var(--font-ui)` | contract guidance (authors may legitimately choose their own font) |
457
-
458
- `var(--*)` = theme/glass/global scaling follow automatically, with zero plugin awareness—**this is exactly why the @linkdesk/ui control layer can be "follow without thinking"**—the controls are written entirely on tokens, so a plugin that does `npm i @linkdesk/ui` and consumes them follows along. Control reuse always imports from `@linkdesk/ui` (see §Quick Reference)—don't hand-roll wheels.
459
-
460
- ### 11.2 Honest boundaries / knowing bypasses—content and brand colors can have their own sky
461
-
462
- **Three gate tiers (07 §6):** recommended (copy it and you're right) / warning (15 self-explanatory items, red but **a WARN never fails**) / knowing bypass (a standard eslint-disable declaration with a reason). **No ecosystem can stop an author from hardcoding colors**—VS Code also has extensions that don't follow the theme. What the gate does is make "doing it right" the default and "doing it wrong" explicitly red but **knowingly bypassable**: a comment carrying a reason = the "proceed anyway" informed confirmation on a browser danger page, not silently switching off the light.
463
-
464
- **Legitimate exemption categories:** var() fallback hex (`color: var(--x, #fff)` = a compliant form, not blocked) / color-picker swatches / canvas drawing / engine regions / **view-level exemption for content canvases**.
465
-
466
- **The content vs. chrome boundary (empirically validated by the Angry Birds test):** a game / data visualization / canvas Main Area = **a content world, not UI chrome**—UI chrome follows the theme (var()/t()/@linkdesk/ui), while content can have its own sky (grass green / health-bar red / sky blue need not follow the theme). Authors **declare a view-level exemption once**, and the gate doesn't light up item by item inside content regions (item-by-item disables for the 5-10 hardcoded values in a game are far too noisy):
467
-
468
- ```tsx
469
- /* eslint-disable linkdesk/no-hardcoded-hex, linkdesk/no-hardcoded-radius -- content canvas: the game main area draws itself */
470
- export function GameBoard() {
471
- return <canvas /* draws blue sky, green grass, red health bar—a content world, not UI chrome */ />;
472
- }
473
- ```
474
-
475
- ```tsx
476
- // Line-level knowing bypass (a brand fixed-color badge—exempts only this line, other lines are still blocked)
477
- // eslint-disable-next-line linkdesk/no-hardcoded-hex -- brand fixed-color badge
478
- const PRO_BADGE = <span style={{ color: "#ff6b00" }}>PRO</span>;
479
- ```
480
-
481
- ```css
482
- /* The same format in CSS (the check script recognizes it)—a color-picker swatch with a fixed value, exempt on this line */
483
- /* eslint-disable-next-line linkdesk/no-hardcoded-hex -- color-picker swatch */
484
- .swatch--brand { background: #ffd700; }
485
- ```
486
-
487
- **Semantics:** a line that hits an exemption goes **entirely silent** and doesn't light up (aligned with eslint's native suppress—after a disable declaration nothing is reported item by item); **no declaration = an unhandled deviation**, and `linkdesk-plugin-sdk lint` reports it with a normal WARN. **This is not new syntax**—it's the same format as the shell's existing `no-hardcoded-hex` error suggestion. **Backgrounds not being glassed holds inherently at the mechanism layer**—backdrop-filter only paints shell surface elements and is not applied to a plugin view's root node, so content the author draws is simply never glassed.
488
-
489
- ### 11.3 Non-CSS engine adaptation—the translation bridge (self-rendering engines don't use CSS variables)
490
-
491
- monaco-style self-rendering engines (canvas / WebGL / rich-text engines likewise) don't consume CSS variables—following the theme requires a **translation bridge**: subscribe to theme changes → translate into the engine's own theme API. Precedent: `src/services/theme-sync.ts` (it lives in **the editor plugin's own repo**, `Encaron/linkdesk-plugin-editor`—shipped plugin source is not in the shell repo):
492
-
493
- ```ts
494
- // Subscribe to theme changes (the event may fire before mount → register at top level or guard on active, see 11.5)
495
- const off = window.linkdesk.events.on("theme:changed", () => {
496
- engine.updateTheme(translateTheme()); // translate your tokens → the engine's theme object
497
- });
498
- ```
499
-
500
- monaco's current opaque background and two-state (light/dark) following is **a transitional workaround, not a settled boundary**—full theme adaptation may come later.
501
-
502
- ### 11.4 Plugin-private data channels—choosing a channel when you build your own settings UI / manage your own saves
503
-
504
- When authors build their own settings UI or manage their own saves (without going through a shell settings-page declaration), pick the data landing spot by semantics:
505
-
506
- | Channel | Good for | Example |
507
- |---|---|---|
508
- | `window.linkdesk.pluginState` (**preferred**) | plugin-managed saves—centralized caching + file persistence (a proper API: `get/set/onChange(pluginId, key)`) | game score / level progress / high-score board / skin preference |
509
- | `window.linkdesk.configuration.set(key)` private namespace | follows settings semantics, readable by other plugins/themes, **must appear in the shell settings-page UI** (declaring contributes.configuration puts it there) | plugin parameters (declared = UI; undeclared = a purely private key that still persists when written) |
510
- | `window.linkdesk.filesystem` | large files / binary / cross-plugin sharing | screenshot export / save files |
511
- | `localStorage` | supplementary—in-pool temporary cache (no cross-machine, no shell management) | high-frequency temporary values within a session |
512
-
513
- **Iron rule: private keys that don't declare `contributes.configuration` do not appear in the shell settings-page UI**—`config.set` writes and persists even without a schema (only enums get filtered), so authors who want the shell settings page declare a contribution, and those who want their own UI write private keys directly; the two don't interfere.
514
-
515
- ### 11.5 Shell-discipline handoff list—each non-UI discipline sinks into the doc where it lands
516
-
517
- | Discipline | Where it's specified |
518
- |---|---|
519
- | The plugin's only entry is `window.linkdesk.*`; **importing @src/core (including any @src subpath) is forbidden** | `01-plugin-api-contract.md` |
520
- | Configuration: **subscribe, don't read once** (linkdesk.configuration is event-driven) | §3 of this file |
521
- | linkdesk.events subscription **timing**—the event may fire before mount (IPC buffering) → register at top level or guard on active | `02-plugin-lifecycle.md` |
522
- | **Don't hardcode other plugins' IDs** (differential behavior goes through plugin.json declaration fields, consumed via the Registry pattern) | `03-contributes-spec.md` |
523
- | Configuration keys **must have a default** | `06-plugin-json-spec.md` |
524
- | **Use only documented API namespaces** (don't casually hang undocumented `linkdesk.xxx` off the API) | `01-plugin-api-contract.md` |
525
- | Controls always come from `@linkdesk/ui` (built-in controls are imported from the npm package; `@src/components/shared/*` is forbidden) | §Quick Reference of this file |
526
-
527
- ---
528
-
529
- ## 12. CSS Class Names—Prefix Your Own Elements; Don't "Borrow" Reserved Names
530
-
531
- **One thing to remember first: the plugin view's stylesheet is not yours alone.** The same window loads the
532
- host's styles, the shared components' (`@linkdesk/ui`) styles, and **every loaded plugin's** styles at once —
533
- **class names are global identifiers**. Writing a class name claims that name; if someone else uses it too,
534
- both stylesheets land on the same element.
535
-
536
- **Three rules:**
537
-
538
- 1. **Class names you give your own elements must start with your `pluginId` plus a hyphen**—
539
- `settings-*`, `editor-*`, `file-tree-*` … (`pluginId` is the id you declare in `plugin.json`; every
540
- official plugin does this). **Don't use abbreviations**: the `ms-` / `mpd-` shorthand style is **retired**—
541
- an abbreviation guarantees nothing, and two plugins that each abbreviate to `ms-` collide. `pluginId` is
542
- unique by construction (immutable once published), so deriving the prefix from it is free collision
543
- protection.
544
- 2. **`@keyframes` names take the prefix too** (`file-tree-fadeIn`), and **rename the `animation:` reference in
545
- the same edit**—a keyframe name is a global identifier exactly like a class name: on a collision the later
546
- definition wins and the earlier animation silently stops.
547
- 3. **These names are reserved by the host—don't use them for your own elements** (if you do, the host's
548
- styles will hit you):
549
-
550
- | Source | Reserved names | Notes |
551
- |---|---|---|
552
- | The input-box utility the host **gives you** | `.ldk-input` | Input-box utility—**just use it** (it exists for your inputs). ⚠️ It is the **one** name in the whole `ldk-` family you're encouraged to **consume** (every other `ldk-` name means "hands off"; this one means "take it") |
553
- | Shared component classes + host container classes | **the whole `ldk-` namespace**—today: `ldk-badge`, `ldk-button`, `ldk-combobox`, `ldk-mdv`, `ldk-selectbox`, `ldk-sle`, `ldk-slider`, `ldk-toggle`, `ldk-hint-card` (2026-09-19, hover hint card) (shared components), plus the host's own container classes such as `ldk-titlebar`, `ldk-input`, `ldk-setting-group` | Class names of the badge / button / combobox / Markdown container / select / string-list editor / slider / toggle components in `@linkdesk/ui`. **You don't have to memorize them**—remember one thing: **anything starting with `ldk-` belongs to the host itself (shared components + host UI containers), so don't put it on your own elements** (the one exception is `.ldk-input` on the row above: that one is **for you**) |
554
-
555
- **`@keyframes` names work the same way**—the host already uses the animation names below, so avoid them when naming your own animations. A collision has the same consequence as a class name (the later definition wins, the earlier one is dropped), and it is equally **silent**: one of the two animations simply stops playing, with nothing in the console.
556
-
557
- | Reserved keyframe names | Notes |
558
- |---|---|
559
- | `ldk-selectbox-in` | the shared select dropdown's entrance animation |
560
- | `ldk-drop-zone-in` | the drop zone's entrance animation |
561
- | `ldk-dropdown-card-in` | the dropdown card's entrance animation |
562
- | `ldk-floating-panel-in` | the floating panel's entrance animation |
563
- | `ldk-notif-icon-spin` | the notification icon's spin |
564
- | `ldk-notif-progress-scan` | the notification progress scan |
565
- | `ldk-rn-spin` | the release-notes page's refresh icon spin |
566
- | `ldk-boot-mark-breath` | the boot brand screen's breathing |
567
- | `ldk-view-skeleton-breath` | the content loading skeleton's breathing |
568
- | `ldk-welcome-skeleton-breath` | the welcome recent list loading skeleton's breathing |
569
- | `ldk-welcome-in` | the welcome page's entrance fade-up (its single authored moment) |
570
-
571
- **The name you reference has to exist somewhere**—rule 2 above says "when you rename, change the reference in
572
- the same commit"; this is the other half, and **the machine checks it**: the name you write in
573
- `animation` / `animation-name` must either be defined by an `@keyframes` **in your own CSS** or be one of the
574
- names in **the reserved table above** (referencing the host's animations is **legitimate consumption**—you will
575
- not be flagged). Reference a name **nobody defined** and the animation **reports nothing, warns nothing, it
576
- just does not run**—the symptom is "why isn't my animation working", while the console stays silent (other
577
- plugins and the host are running in the same window, so it is hard to spot at a glance).
578
- From `@linkdesk/plugin-sdk` **≥ 0.1.37**, the plugin lint reports these **dangling references** one by one
579
- (**file name + line number + the name**); if you genuinely need a name the gate cannot see (say the animation
580
- is injected at runtime), use a standard `eslint-disable` comment stating why.
581
-
582
- > 🔧 **Maintainer note (authors can skip this)**—the **Reserved names** and **Reserved keyframe names** columns in the two tables above are **machine-read**: the gate
583
- > in `npm run check` (`scripts/check-reserved-names-doc-sync.mjs`) cross-checks them **both ways** against the
584
- > registry `packages/plugin-sdk/schemas/reserved-class-names.json`—every registry name must appear here, and
585
- > every name here must either be registered (bare names) or a real `ldk-` name present in the host source.
586
- > The keyframe table is cross-checked **both ways** against the registry's `keyframes` array in the same way.
587
- > ⇒ **Editing these two columns is a public-surface change**: add/remove a name in **three places in one commit**—
588
- > the registry plus these two tables in both language trees. Both columns hold **names only**; put prose in
589
- > the "Notes" column.
590
-
591
- **One more namespace rule**: your `pluginId` **must not start with `ldk-`**—the whole `ldk-` namespace belongs
592
- to the host, so a plugin called `ldk-tools` would derive its prefix (`ldk-tools-*`) **straight into host
593
- territory**, which also makes rule 1 meaningless. This constraint lives in the `plugin.json` schema, so your
594
- editor flags it immediately.
595
-
596
- **Want their look? Use their component**—`import { Button } from "@linkdesk/ui"`, don't hand-write its class
597
- name (hand-writing bypasses the component, and you fall behind the moment it changes).
598
-
599
- **Always use state classes in compound form**: `.your-class.active`, `.your-class.on` (never bare
600
- `.active {}` or `.on {}`—that would also restyle same-named state elements in the host and in other plugins).
601
-
602
- **A real example from this project**: using a host-reserved name as a "handy style name" on your own element
603
- painted the background and the text the same color, so the text was swallowed by its own background — the UI
604
- just looked like "a solid block". **No error**, just wrong, and hard to trace.
605
-
606
- ### 12.1 Upgrading from an older `@linkdesk/ui`—the one thing you have to change yourself
607
-
608
- Shared component class names now carry an `ldk-` prefix (as of `@linkdesk/ui` **0.2.0**). This affects exactly
609
- one kind of code: rules in **your own plugin's CSS** that use a descendant selector to fine-tune a shared
610
- component. **Nothing to do before you upgrade; when you upgrade, it's one prefix.**
611
-
612
- - **When it hits you**: after `@linkdesk/ui` moves to **0.2.0**—**not before**. In older versions these
613
- components' class names were bare (`.badge`), and the CSS shipped inside the package is consistent with the
614
- components, so **if you don't upgrade, nothing breaks**. (A `^0.1.x` range will not cross over to `0.2.0` by
615
- itself, so this only comes up on the upgrade you perform deliberately.)
616
- - **What is affected**: descendant selectors in **your own plugin CSS** such as
617
- `.control-bar .combobox { … }`, `.settings-slider-control .slider { … }`, `.changelog .mdv { … }`.
618
- **The components' own styles are unaffected, and your own class names don't change.**
619
- - **How to fix it**: add the `ldk-` prefix to **the part of the selector that points at the shared component**—
620
- `.combobox` → `.ldk-combobox`, `.slider` → `.ldk-slider`, `.mdv` → `.ldk-mdv`, `.badge` → `.ldk-badge`,
621
- `.selectbox-trigger` → `.ldk-selectbox-trigger`, `.combobox-field` → `.ldk-combobox-field`. **Family names
622
- (suffixes like `-trigger` / `-field` / `-input`) take the prefix too.** Your own prefixes (`.control-bar`,
623
- `.settings-*`) stay as they are. **After upgrading, grep your CSS for the eight old base names
624
- `.badge`, `.button`, `.combobox`, `.mdv`, `.selectbox`, `.sle`, `.slider`, `.toggle`**: add the prefix where
625
- the rule tunes a shared component, leave the rest alone.
626
- - **Why it isn't automatically compatible**: this kind of mismatch **raises no error**—a selector that no
627
- longer matches simply stops applying, so the UI looks "roughly right, just a bit off". Because it is silent,
628
- we moved the names under the `ldk-` prefix and wrote this section.
629
-
630
- ### 12.2 The prefix rules (§12 rules 1 and 2) are live—what about existing code?
631
-
632
- **In one line: it keeps working unchanged, but the next time you touch that file is when you fix it.**
633
-
634
- - **The official plugins have already been cleaned up under the new rules**—four plugins were renamed:
635
- `file-tree` (v1.0.9), `settings` (v1.0.11), `serial-monitor` (v1.0.12) and `marketplace` (v1.0.33); their
636
- bare class names and keyframe names now carry the `<pluginId>-` prefix. The remaining official plugin repos
637
- had no bare definitions to begin with (their class names either already carry a prefix or they define none).
638
- Measured against the official catalog, the audit reads **18/18 compliant**.
639
- - **Third-party authors have no repository to change**: this rule governs only **the class and keyframe names
640
- you write yourself**—it doesn't touch repo layout, your `pluginId`, or anyone else's code. You do **not**
641
- need to cut a release for it.
642
- - **Old unprefixed class names raise no error and don't stop working**—they work fine today. The cost is that
643
- **the collision risk is still there**: if another plugin defines the same class name, both stylesheets land
644
- on the same element (no error, just wrong-looking, and hard to trace).
645
- - **Compliance is judged by the check that ships with your project**: a scaffolded project carries a strict
646
- check leg (`npm run verify`) that scans your CSS for class names **bare-defined on your own elements** and
647
- for `@keyframes` names, and fails them when they don't start with `<pluginId>-`. So the real action is
648
- **rename them the next time you open that file**: `.panel {}` → `.myplugin-panel {}`, changing the CSS and
649
- the JSX that uses it together (identifiers only—don't touch style values).
650
-
651
- > Want to see whether your project has bare names right now? Run `npm run verify` in the project root.
652
-
653
- ### 12.3 The host's input-box utility was renamed: `.input` → `.ldk-input` (2026-09-16)
654
-
655
- **In one line: if your plugin wrote `className="input"`, change it to `className="ldk-input"`—the styling is identical, only the name changed.**
656
-
657
- - **What changed**: the host used to call its input-box utility **`.input`** (no prefix—the only host public name without `ldk-`). That conflicted with rule 1 above ("every cross-party name carries a namespace") ⇒ it is now **`.ldk-input`**. The host's **setting-group card**, `.setting-group`, was renamed to **`.ldk-setting-group`** at the same time.
658
- - **Who is affected**: **any plugin that wrote `className="input"` in its own JSX/TSX**—among the official plugins, `settings` and `serial-monitor` used it and were updated in the same release batch. **The fix is one place**: `className="input"` → `className="ldk-input"`; the same for concatenated forms (`"input my-input"` → `"ldk-input my-input"`). **Zero styling change**—same rule, same CSS variables, only the name.
659
- - **What happens if you don't**: the input doesn't error; it simply **loses the host-provided appearance** (background / border / radius / padding) and looks like a browser-native input.
660
- - **When you must change it**: as soon as you run on the **new shell**. The new shell version is **`0.2.0`**, and both official plugins now declare `minAppVersion: "0.2.0"` in `plugin.json`—declare the same value in your plugin and users on an older shell get a clear "requires app version ≥0.2.0" message instead of an unstyled input (see [04-distribution-format §minAppVersion](04-distribution-format.md) for the semantics).
661
-
662
- ### 12.4 The rest of the shared components' class names took the `ldk-` prefix too (2026-09-16)
663
-
664
- **In one line: same story as 12.1, just for the components that 12.1 didn't cover—if your own CSS tunes those components with descendant selectors, add the `ldk-` prefix when you upgrade.**
665
-
666
- - **What changed**: §12.1 covered the eight base names of `@linkdesk/ui` (`badge` / `button` / `combobox` / `mdv` / `selectbox` / `sle` / `slider` / `toggle`) at **0.2.0**. The remaining components' class names—plus one `@keyframes` name—now carry the prefix too (**since the 2026-09-16 round**; for how to read the version line see [19-Component Cheatsheet §2.1](19-component-cheatsheet.md)):
667
-
668
- | Old family | New family |
669
- |---|---|
670
- | `.colorpicker-*` | `.ldk-colorpicker-*` |
671
- | `.ctx-*` | `.ldk-ctx-*` |
672
- | `.form-row` | `.ldk-form-row` |
673
- | `.inline-input`, `.inline-input--compact/--normal` | `.ldk-inline-input`, `.ldk-inline-input--compact/--normal` |
674
- | `.number-input*` | `.ldk-number-input*` |
675
- | `.segmented-radio`, `.segmented-radio__option/__label` | `.ldk-segmented-radio`, `.ldk-segmented-radio__option/__label` |
676
- | `.sidebar-section*`, `.sidebar-pane-view`, `.sidebar-pane-sash` | `.ldk-sidebar-section*`, `.ldk-sidebar-section-pane-view`, `.ldk-sidebar-section-pane-sash` |
677
- | `.theme-picker*`, `.theme-card`, `.theme-preview` | `.ldk-theme-picker*`, `.ldk-theme-picker-card`, `.ldk-theme-picker-preview` |
678
- | `.tbadge` / `.tname` / `.pv-bar` / `.pv-dot` (theme-card internals) | `.ldk-theme-picker-badge` / `.ldk-theme-picker-name` / `.ldk-theme-picker-preview-bar` / `.ldk-theme-picker-preview-dot` |
679
- | `@keyframes selectbox-in` | `@keyframes ldk-selectbox-in` |
680
-
681
- - **Who is affected**: again **only your own CSS**'s descendant selectors that point at those components (e.g. `.settings-row:has(.theme-picker)`). **The components' own styling does not change, and your own class names stay as they are.** The whole point is that the shared components' names now all live in the `ldk-` namespace, whose rule you already know: **anything starting with `ldk-` belongs to the host—don't put it on your own elements** (the one exception is `.ldk-input`, the utility that is **for you**).
682
- - **What happens if you don't**: exactly the silent failure described in 12.1—the selector just stops matching and those few rules quietly stop applying. **No error.**
683
- - 🔴 **When the host renames a shared name or restyles a component, there is no code and no CSS for you to change** — components and styles are supplied by the shell pool (centralized supply, see [19-Component Cheatsheet §2](19-component-cheatsheet.md)): the same implementation follows the shell upgrade, so your UI stays consistent. The one thing to maintain is that your `@linkdesk/ui` dependency **stays on the current version line** (it decides what your local dev and types resolve to).
684
- - ⛔ **Component styles never come from your source either**: a line like `import "@linkdesk/ui/index.css"` (or its dist / `@import` form) is failed by the SDK lint leg `linkdesk/no-ui-css-import`, with **no exemption exit** — baking the styles into your plugin means "the shell restyles once, the whole ecosystem follows" stops being true for you.
685
- - **When you must change it**: when the shell you support moves to a version that contains this rename (how to read the version line: [19-Component Cheatsheet §2.1](19-component-cheatsheet.md) — ui version = shell version, one line). After upgrading, **grep your own CSS for the old families** in the table above: an official plugin (`settings`) had exactly one such spot and it was fixed in the same release batch.
686
- - **You get the same ruler** (`@linkdesk/plugin-sdk` 0.1.40 onward): your repo's lint ships with a dangling-name check—when the host renames a shared name and you didn't follow, **your own CI calls it out** (usage and fixes in [16-naming-conventions §7.6](16-naming-conventions.md)).
687
-
688
- ### 12.5 The **scope** of custom properties—`--x:` written under `:root` is written for the whole application
689
-
690
- The three rules above govern **names**; this one governs **territory**. For custom properties (`--xxx`) there is exactly one rule:
691
-
692
- > **Scope is the namespace.** The name is yours to choose; **which subtree it lives in** is what decides who it belongs to.
693
-
694
- **① Document-level scope is the host's alone.** Declarations on `:root` / `html` / `body` / `[data-theme="…"]` / `*` are **visible to the entire document**—that is not your territory:
695
-
696
- ```css
697
- /* ❌ this declaration is visible to the whole document */
698
- :root { --my-panel-gap: 8px; }
699
-
700
- /* ✅ hang it under your own root class: scope = your subtree */
701
- .my-plugin-root { --my-panel-gap: 8px; }
702
- ```
703
-
704
- **② Every other declaration hangs under one of your own classes.** Write `.your-class { --xxx: … }`—and note that **the name needs no prefix there**: a `--gap` under `:root` collides with someone else's, a `--gap` under `.my-plugin-root` cannot (the scope has already divided the territory).
705
-
706
- **③ Nobody may define a `--ldk-*` custom property** (same rule as class names and keyframes—the whole `ldk-` namespace belongs to the host).
707
-
708
- **Why this is nastier than a class-name collision**: most of the host's colors / radii / z-index layers are **provided by its stylesheets rather than written by code**. Write one of the host's contract names (say `--bg-card`) under `:root` and **you win**—the whole application's card background follows your value. And **switching themes may switch it back** (a theme overrides some of those names) ⇒ the symptom is "**works sometimes, breaks sometimes**", the hardest kind to diagnose.
709
-
710
- **One self-check** (glance at it when your CSS is done): **"is my `--x:` written under `:root`?"** If yes ⇒ move it under your own root class.
711
-
712
- **Migrating**—plugins that already define custom properties under `:root`:
713
-
714
- | Case | Level | What to do |
715
- |---|---|---|
716
- | Name **carries** your own prefix (`--my-plugin-gap`) | 🟡 suggested | Move it under your own root class. The name is yours and nobody competes for it, but there is no reason for it to sit under `:root`—after the move its scope shrinks from the whole document to your own subtree |
717
- | Name **carries no** prefix (`--gap`, `--bg-card`, …) | 🔴 required | It is live document-wide right now and may already be overriding the host's or another plugin's value ⇒ move it under your own root class (the name may stay as it is; **what changes is the scope**) |
718
- | Name starts with `ldk-` | 🔴 required | Give it one of your own names—`ldk-` is the host's namespace |
719
- | Written **under your own root class** | ✅ compliant | Nothing to do. Fine-tuning like `.your-root .ldk-x { --y: … }` is compliant too (one of your own classes appears in the selector) |
720
-
721
- **How it is enforced mechanically**: run `npm run lint` in the plugin project root (or `npm run verify` in CI) and each occurrence is reported—🔴 turns CI red, 🟡 only prints. When "it works locally but CI is red", read this section first.
722
-
723
- > 🔧 **Maintainer note (authors may skip)**: the rule text (including how the host registers its contract blocks and the floating-layer host exception) lives under `docs/02-Electron架构/插件生态与发布/01-插件独立构建/样式命名空间归一化/`; the shell side is guarded by `scripts/check-css-namespace.mjs`, the plugin side by the SDK's `check-css-namespace` leg (token scope is the third criterion of that same leg, sharing one disable-comment id with the class-name and keyframe criteria).
724
-
725
- ### 12.6 The selector itself needs a "landing spot" too—**anchorless selectors are forbidden** (2026-09-16)
726
-
727
- The five sections above govern **names** (class names / keyframes / custom properties). This one governs the **shape of the selector**—a rule that is even easier to overlook:
728
-
729
- > **Class names and ids are "name anchors"; element / universal / attribute / pseudo-class / pseudo-element selectors are not.**
730
- > The latter hit other people's elements **without sharing a single name with anyone.**
731
-
732
- ```css
733
- /* ❌ one rule rewrites *every* button in the document—including the host's and other plugins' */
734
- button { border: none; }
735
- * { box-sizing: border-box; }
736
- #some-id { display: none; } /* an id is global and guessable too, and outranks classes */
737
- :root { outline: none; } /* `:root` is an anchorless selector as well */
738
-
739
- /* ✅ hang it under your own root class—same intent, landing spot limited to your own subtree */
740
- .my-plugin-root button { border: none; }
741
- ```
742
-
743
- **Two rules** (both are **mechanically red** in `npm run lint` at the plugin project root / `npm run verify` in CI):
744
-
745
- | Rule | Verdict | Why |
746
- |---|---|---|
747
- | **No anchorless selectors** | The selector has **no** `.class` or `#id` subject (element / universal / attribute / pseudo-class / pseudo-element; **top-level *and* qualified, including inside `@media`**) ⇒ 🔴 | It hits "every element of that kind in the document", regardless of who rendered it |
748
- | **A cross-party hit must carry your own anchor** | The selector mentions an `ldk-*` class (**including a mention inside `:has(…)`**) but does **not** carry a `.<your pluginId>-*` class ⇒ 🔴 | `ldk-` is the host's namespace; **fine-tuning has to happen on your own territory** |
749
-
750
- ⚠️ **The second rule does not forbid restyling shared components**—that is a **legitimate feature** (scoped tuning). It only requires you to **carry your own prefix as the anchor**:
751
-
752
- ```css
753
- /* ❌ targets the host's / shared components' elements with no landing spot of your own ⇒ red */
754
- .ldk-toggle { transform: scale(1.1); }
755
-
756
- /* ✅ the same intent, written on your own territory ⇒ compliant */
757
- .my-plugin-root .ldk-toggle { transform: scale(1.1); }
758
- ```
759
-
760
- **Why it is worth remembering**: the host itself has **17** such "anchorless selectors" (`*` resets / `html`·`body` / `[data-theme]` / `*:focus-visible` / the scrollbar family / `input[type="number"]`·`select`)—they are a **deliberate shared baseline** that plugins rely on (and may override). Precisely because they exist, **your anchorless selector will hit them**: write `button { }` and the host's buttons plus every other plugin's buttons change with it.
761
-
762
- **Migration**: **zero instances today**—a full re-check of the official plugins plus the in-repo fixture (the "anchorless S2 / cross-party S3" columns of `npm run audit:plugin-prefix -- --all`) is **0** ⇒ **you have nothing to change**; this rule is **preventive**.
763
-
764
- > 🔧 **Maintainer note (authors may skip)**: the rule text (R0 scope / R1 host baseline / R2 / R3) plus the decision formulas and negative controls live in `docs/02-Electron架构/插件生态与发布/01-插件独立构建/样式命名空间归一化/32-任务-选择器形态轴门禁与落地.md`; the host side is guarded by criteria ⑩⑪ of `scripts/check-css-namespace.mjs` (plus the runtime mirror on axis ④ of the probe), and the plugin side by the **fourth and fifth criteria** of the SDK's `check-css-namespace` leg (`checks/selector-form.ts` for S2/S3, and `checks/keyframe-refs.ts` for dangling keyframe references—the latter in place since **2026-09-18**, SDK `≥ 0.1.37`).
765
-
766
- ---
767
-
768
- ## 13. Hover Hints → the `data-hint` attributes (or `<HintTip>`)
769
-
770
- **That little bar that appears when the pointer rests on your button/icon is not drawn by the browser.**
771
-
772
- The host ships one unified light hint (`HintTip`): light/dark theme, UI scaling, edge flipping, and the
773
- keycap look for shortcuts are all decided in one place by the shell. **You do not import anything** to use
774
- it—write attributes:
775
-
776
- ```tsx
777
- // ❌ native title: drawn by the browser; theme/scaling/keycaps never follow the shell (red since SDK >= 0.1.49)
778
- <button title={t("Refresh")}>
779
-
780
- // ✅ attribute form: swap title= for data-hint= (zero DOM structure change)
781
- <button data-hint={t("Refresh")} aria-label={t("Refresh")}>
782
-
783
- // ✅ with a shortcut: give the command id and the shell looks it up (name + keys come from that one table,
784
- // so the hint bar / context menu / command palette always say the same thing)
785
- <button data-hint-command="fileTree.refresh" aria-label={t("Refresh")}>
786
-
787
- // ✅ reveal kind ("see the whole truncated text"): it must appear at once, don't make it wait
788
- <div data-hint={fullPath} data-hint-delay="0">{truncated}</div>
789
-
790
- // ✅ composite cases (you want to control the wrapper): the component form
791
- import { HintTip } from "@linkdesk/ui";
792
- <HintTip label={t("Refresh")} command="fileTree.refresh"><button …>…</button></HintTip>
793
- ```
794
-
795
- Four attributes, all written on your own DOM elements:
796
-
797
- | Attribute | What it does |
798
- |---|---|
799
- | `data-hint` | The hint text (explain and reveal kinds share it—**the text is always yours**; the shell never ships sentences) |
800
- | `data-hint-command` | Command id—the shell reads name and shortcut from the command table. **Same source** as the context menu / command palette (change it once, everything follows) |
801
- | `data-hint-delay` | Intent delay in ms. Explain kind: **leave the default** (120 ms—prevents a flash while sweeping past); reveal kind: pass `"0"` |
802
- | `data-hint-placement` | Preferred side: `top`/`bottom`/`left`/`right` (default `top`; flips automatically when it does not fit) |
803
-
804
- **⚠️ Three rules**
805
-
806
- 1. **Explain kind waits, reveal kind does not**—"see the whole truncated text" must be immediate; a command
807
- explanation for an icon is exactly the case that should pause a moment.
808
- 2. **No more native `title=`**: the SDK leg `linkdesk/no-native-title` (SDK >= 0.1.49) marks it red—`lint`
809
- prints a red row and `ci-verify` fails. For the rare form where the hint renderer cannot reach (the
810
- legitimate exception), write `// eslint-disable-next-line linkdesk/no-native-title -- reason` (a **reason
811
- is mandatory**).
812
- 3. **No buttons inside the bar**: a hint is a hint, not a menu (use `<ContextMenu>` for interaction); for a
813
- **long text / title / footnote** or multi-line explanation use `HintCard`—that component is the one that
814
- owns "long explanations with a footnote".
815
-
816
- > 🔧 **Maintainer note (authors may skip)**: renderer = `src/components/shared/hint-tip/HintTipRenderer.tsx`
817
- > (a single mount in the pool: delegated `pointerover`/`pointerout`/`focusin`/`focusout` plus an intent-delay
818
- > state machine); the single source of truth for the attribute literals is `hintAttrs.ts` (⛔ never write a
819
- > `"data-hint"` literal anywhere else); the master switch is the shell config `app.hint.enabled` (default on,
820
- > visible in settings); the gates are three legs — shell-side `scripts/check-native-title.mjs` (legacy
821
- > white-list ledger, new sites only) and the SDK leg `checks/no-native-title.ts` (same id, pinned to each
822
- > other by the three 锚⑪ anchor sentences).
823
-
824
- ---
825
-
826
- ## Quick Reference
827
-
828
- | What you want to do | Core facility | How to bring it in |
829
- |---|---|---|
830
- | Context menu | `<ContextMenu>` (open-string menuId) | `@linkdesk/ui` (ContextMenu) + a `plugin.json contributes.menus` declaration (or `window.linkdesk.menu.registerItems`, see §1) |
831
- | Overlay/dialog | `createPortal` | `react-dom` (render into `document.body`, see §2) |
832
- | Persistence | `window.linkdesk.configuration.get/set/onChange` | plugin communication iron rule—only `window.linkdesk.*` (see §3) |
833
- | System picker | `window.linkdesk.quickPick.show` | uniform rendering by the in-pool QuickPickHost (see §9) |
834
- | Notifications | `window.linkdesk.notifications.show` | uniform rendering by the in-pool **bell wide notification panel** (see §9; semantics in `01-plugin-api-contract.md` §3.2) |
835
- | Confirm/alert/file picker | `window.linkdesk.dialog.confirm/alert/open/openFile` | uniform rendering by the in-pool DialogHost (see §9) |
836
- | Rich-content confirm | `window.linkdesk.dialog.confirmContent({ pluginId, viewId, payload })` | the in-pool DialogHost renders the shell, **the content = a plugin-drawn view** (see §9) |
837
- | Shortcuts (non-text keys) | `plugin.json contributes.keybindings` | — (putting text keys here = swallowing the whole pool, see §4.1) |
838
- | Shortcuts (text keys / focus-bound keys) | container `onKeyDown` + `tabIndex` | pool-side self-handling, see §4.2 (document/window keydown is forbidden) |
839
- | Hover hints | `data-hint` / `data-hint-command` / `data-hint-delay` attributes (or `<HintTip>`) | just write them on your own DOM elements — **no import needed** (see §13; a native `title=` is red) |
840
- | Colors | CSS variables | `var(--xxx)`, list in `src/index.css` |
841
- | Font sizes | CSS variables | `var(--font-size-*)` + `--ui-scale`, bare px forbidden (gate, see §10) |
842
- | Six-domain token overview | see the §11.1 matrix | color/surface/radius/glass/font size/font family—`var(--*)` follows theme+glass+scaling automatically; full list in `src/index.css` |
843
- | UI discipline gate | `linkdesk-plugin-sdk lint` | all 15 items are WARNs that never fail; a knowing bypass = a standard eslint-disable declaration (see §11.2) |
844
- | Text | `t()` | `useTranslation()` from `react-i18next` |
845
- | CSS class names / state classes | own prefix + host reserved-name list | see §12 (class names are global—all plugins share the document with the host) |
846
- | Element / id selectors | must hang under your own root class | see §12.6 (an anchorless selector hits everyone's elements, name or no name) |
847
- | Sidebar list selection | `onMouseDown` (not `onClick`) | aligned with VS Code Explorer—prevents lost events when a fast click crosses elements |
848
-
849
- **Use these facilities when writing plugins; don't hand-roll. Even if you write one, it'll have to be torn out later—better to normalize from day one.**
1
+ # Plugin UI Authoring Conventions
2
+
3
+ > **In one line: the core already provides the standard components and registries—don't hand-roll wheels. Hand-rolling = inconsistent style + something to tear out at the next normalization.**
4
+ > Skim this before writing a plugin, to avoid the same kind of rework.
5
+ > **Reconciled against the implementation on 2026-09-06**: flatten-to-single-root (no plugins/{builtin,user}) · shared controls go through @linkdesk/ui · distribution = `.linkdesk-plugin` zip. References to the corresponding mechanisms have been cleaned out of this page.
6
+
7
+ ---
8
+
9
+ ## 1. Context Menu → `<ContextMenu>` + MenuRegistry
10
+
11
+ **❌ Forbidden:** hand-writing `<div className="my-menu">` + `useState` + a click-outside listener.
12
+
13
+ **✅ Right:**
14
+ ```json
15
+ // ① Declare the menu items—plugin.json contributes.menus (preferred, declarative)
16
+ {
17
+ "contributes": {
18
+ "menus": {
19
+ "editorContext": [
20
+ { "command": "myPlugin.copy", "group": "navigation" },
21
+ { "command": "myPlugin.clear", "group": "edit" }
22
+ ]
23
+ }
24
+ }
25
+ }
26
+ ```
27
+
28
+ ```tsx
29
+ // Dynamic registration at runtime (equivalent)—window.linkdesk.menu.registerItems(menuId, pluginId, items)
30
+ window.linkdesk.menu.registerItems("editorContext", "myPlugin", [
31
+ { command: "myPlugin.copy", group: "navigation" },
32
+ { command: "myPlugin.clear", group: "edit" },
33
+ ]);
34
+
35
+ // ② Use the unified component—MenuId is an open string, so just write a string literal
36
+ <ContextMenu menuId="editorContext" />
37
+ ```
38
+
39
+ **Rationale:** `<ContextMenu>` brings its own backdrop + four blur paths (Escape / backdrop click / window blur / option click) + keyboard navigation + when-condition filtering. You can't hand-roll those four blur paths.
40
+
41
+ **MenuId is an open string (`src/core/registry/commands/MenuRegistry.ts` `export type MenuId = string`)—a plugin declaring any string at all is the contract; no shell code change is needed.** Shell built-in registration points (the MENU_SLOTS constant table):
42
+
43
+ | MenuId (string literal) | Scenario |
44
+ |---|---|
45
+ | `commandPalette` | Ctrl+Shift+P command palette |
46
+ | `tabContext` | Tab Bar tab right-click |
47
+ | `panelViewContext` | Panel tab bar right-click (position/alignment submenu + view show/hide list) |
48
+ | `editorContext` | Tab page main content area right-click |
49
+ | `extensionGear` | Bottom gear menu (settings/command palette/theme picker) |
50
+ | `marketplaceItemGear` | Marketplace entry gear (enable/disable/uninstall) |
51
+ | `menuBar` | ☰ hamburger menu bar |
52
+ | `panel` | The "Panel" menu in the menu bar |
53
+ | `fileContext` | File tree right-click |
54
+ | `cardContext` | Card right-click |
55
+ | `quickSendContext` | Quick-send pill right-click |
56
+ | `iconBar` | Icon bar right-click |
57
+ | `settingItemGear` | Setting item gear (Settings Editor row hover) |
58
+ | `viewTitleContext` | Sidebar view title right-click (collapse/reset position/group the view) |
59
+
60
+ New context-menu scenarios → just declare a new open-string MenuId (e.g. `"myMenu"`): declare `contributes.menus.myMenu` + consume it with `<ContextMenu menuId="myMenu" />`—**zero shell changes** (the plugin-independence iron rule). The shell only needs to add a MENU_SLOTS entry if it wants to provide a unified render point for that scenario.
61
+
62
+ ---
63
+
64
+ ## 2. Overlays / Dialogs → `createPortal`
65
+
66
+ **❌ Forbidden:** a dialog nested deep inside a div in the component tree.
67
+
68
+ **✅ Right:**
69
+ ```tsx
70
+ import { createPortal } from "react-dom";
71
+
72
+ return createPortal(
73
+ <div className="my-dialog">{/* ... */}</div>,
74
+ document.body // ← the key: render into body
75
+ );
76
+ ```
77
+
78
+ **Rationale:** under the keep-alive architecture inactive tabs are `display: none`, and children aren't visible even with `position: fixed`. Only rendering into `document.body` escapes the component-tree constraint.
79
+
80
+ ---
81
+
82
+ ## 3. Persistence → `window.linkdesk.configuration` (declared via plugin.json contributes.configuration)
83
+
84
+ **❌ Forbidden:** `localStorage.setItem()` / `PreferenceService.loadPrefs()` / hand-written file I/O / `import ... from "@src/core/..."`.
85
+
86
+ **✅ Right—go through `window.linkdesk.configuration` (plugin communication iron rule: only `window.linkdesk.*`, never `import` from @src/core):**
87
+ ```tsx
88
+ // Read configuration (a Promise—the value is dynamic at runtime)
89
+ useEffect(() => {
90
+ window.linkdesk.configuration.get<boolean>("myPlugin.showLineNumbers").then((v) => {
91
+ setShowLineNumbers(v);
92
+ });
93
+ }, []);
94
+
95
+ // Write configuration
96
+ await window.linkdesk.configuration.set("myPlugin.showLineNumbers", true);
97
+
98
+ // Subscribe to changes—returns an unsubscribe; call it on unmount
99
+ useEffect(() => {
100
+ return window.linkdesk.configuration.onChange<boolean>("myPlugin.showLineNumbers", (v) => {
101
+ setShowLineNumbers(v);
102
+ });
103
+ }, []);
104
+ ```
105
+
106
+ **Declaring configuration items in plugin.json:**
107
+ ```json
108
+ {
109
+ "contributes": {
110
+ "configuration": {
111
+ "title": "My Plugin",
112
+ "properties": {
113
+ "myPlugin.showLineNumbers": {
114
+ "type": "boolean",
115
+ "default": true,
116
+ "description": "Show line numbers"
117
+ }
118
+ }
119
+ }
120
+ }
121
+ }
122
+ ```
123
+
124
+ **Rationale:** the shell persists automatically + restores on restart + the Settings Editor renders it automatically. Hand-rolled localStorage → you lose Settings Editor integration + get the next persistence bug.
125
+
126
+ ---
127
+
128
+ ## 4. Keyboard Shortcuts → Two Tracks: Declarative (non-text keys) + Pool-side self-handling (text keys / focus-bound keys)
129
+
130
+ Shortcuts have **two tracks**, and which one you pick depends on the nature of the key. **Picking the wrong track = a dead key or a hijack of the whole pool** (lesson).
131
+
132
+ ### 4.1 Track one: `contributes.keybindings` (visible in the settings panel)—**non-text keys only**
133
+
134
+ **❌ Forbidden:** putting **text-editing keys** such as `ctrl+c` / `ctrl+v` / `ctrl+x` / `ctrl+a` / `f2` into `contributes.keybindings`.
135
+
136
+ **✅ Right:** (non-text keys—such as `ctrl+k` / `ctrl+shift+e` / `f5`)
137
+ ```json
138
+ {
139
+ "contributes": {
140
+ "keybindings": [
141
+ {
142
+ "key": "ctrl+k",
143
+ "command": "myPlugin.clear",
144
+ "when": "activeEditor == 'myPlugin'"
145
+ }
146
+ ]
147
+ }
148
+ }
149
+ ```
150
+
151
+ **Rationale (why text keys are a landmine):** declared/registered keys sync into the main-process keyCache → when `before-input-event` hits, the key is **swallowed unconditionally** (it doesn't respect when, doesn't respect an editable state, doesn't respect whether a handler even exists). Register one `ctrl+c` in the shell and you swallow the native `ctrl+c` of every input box / Monaco instance in the whole pool. The right answer for text keys = track two.
152
+
153
+ ### 4.2 Track two: pool-side self-handling (container onKeyDown)—the right answer for text keys + focus-bound keys
154
+
155
+ **✅ Right:** a component handles its own keyboard interaction inside its own **container's `onKeyDown`**:
156
+
157
+ ```tsx
158
+ <div
159
+ tabIndex={0} // makes the container focusable—clicking a child makes the browser give focus to the nearest focusable ancestor
160
+ onKeyDown={(e) => {
161
+ if (e.key === "F2") { e.preventDefault(); startRename(); }
162
+ }}
163
+ >
164
+ {items}
165
+ </div>
166
+ ```
167
+
168
+ **Why this is the right answer:** every plugin in the pool shares one document—**DOM focus partitions naturally**. Only a focused container receives the key; a focused Monaco doesn't, and multiple plugins can each do their own `ctrl+c` without stepping on each other. No when needed, no conflict detection needed. File tree clipboard keys = the shared `useClipboardKeys` hook + the same command chain. Clipboard-related keys can reuse `src/pool/hooks/useClipboardKeys` (declarative `onCopy`/`onCut`/`onPaste` callbacks, one implementation and one fix location for the mechanism).
169
+
170
+ **❌ Anti-pattern (red flag):** `document.addEventListener("keydown", ...)` / `window.addEventListener("keydown", ...)` = **global hijack**—it bypasses the partitioning premise, and while the plugin has an active session it hijacks that key across the whole pool (serial F2 once hijacked the file tree's F2). **`tabIndex` + container `onKeyDown` is the right answer for focus partitioning**; non-focusable elements don't trigger it, so add `tabIndex={0}` to receive keys.
171
+
172
+ **Note:** track-two keys **do not appear in the keyboard shortcuts settings panel**—the panel only shows KeybindingRegistry bindings (track one). This is a design trade-off (registering means swallowing across the pool, see 4.1), not a bug.
173
+
174
+ ### 4.3 Clipboard channel picker
175
+
176
+ | What you want to copy | Channel | Example |
177
+ |---|---|---|
178
+ | Text inside an editable element (input/textarea/Monaco) | **Browser native**—write nothing | Ctrl+C/V inside an input box |
179
+ | Arbitrary text | `window.linkdesk.clipboard.writeText` | Copy selected text to the system clipboard |
180
+ | File/path list | `window.linkdesk.clipboard.writeFileList` | File tree copy → pasteable in Explorer (CF_HDROP) |
181
+
182
+ **Note:** editable elements take the browser-native path—**don't** declare a shortcut and don't intercept it; Electron/Chromium wires up the system clipboard automatically.
183
+
184
+ ---
185
+
186
+ ## 5. Colors → CSS Variables `var(--xxx)`
187
+
188
+ **❌ Forbidden:** hardcoding `#0078d4` / `#1e1e1e` / `#ffffff`.
189
+
190
+ **✅ Right:**
191
+ ```css
192
+ .my-element {
193
+ color: var(--text-primary);
194
+ background: var(--bg-input);
195
+ border: 1px solid var(--border);
196
+ }
197
+ ```
198
+
199
+ **Rationale:** after a theme switch hardcoded colors stay the same → under a dark theme you get white text on a white background. See `src/index.css` for all available CSS variables.
200
+
201
+ ---
202
+
203
+ ## 6. Text → `t()` Internationalization
204
+
205
+ **❌ Forbidden:** bypassing `t()` and hardcoding display strings (`<button>发送</button>` / `<button>Send</button>`).
206
+
207
+ **✅ Right:**
208
+ ```tsx
209
+ import { useTranslation } from "react-i18next";
210
+ const { t } = useTranslation();
211
+ <button>{t("发送")}</button> // the i18n key = the plugin UI's source text (a Chinese plugin uses Chinese, an English/French plugin uses its own language)
212
+ ```
213
+
214
+ ---
215
+
216
+ ## 7. Sidebar List Item Selection → `onMouseDown` (not `onClick`)
217
+
218
+ **❌ Forbidden:** using `onClick` to select items in a vertical Sidebar list.
219
+
220
+ **✅ Right:**
221
+ ```tsx
222
+ <div
223
+ className={`my-list-item${isActive ? " active" : ""}`}
224
+ onMouseDown={() => onSelect(item.id)}
225
+ >
226
+ <span>{item.label}</span>
227
+ </div>
228
+ ```
229
+
230
+ **Rationale:** sidebar items sit vertically adjacent—on a fast click the mousedown lands on item A and the mouseup slides onto item B. Per the browser `click` event spec: when mousedown and mouseup land on different elements → click is dispatched to their common ancestor → React finds no handler on the ancestor → the event is silently lost. `onMouseDown` only cares about where the press happened and doesn't require the release on the same element—eliminating lost events on fast clicks.
231
+
232
+ **Aligned with VS Code:** the Explorer file tree selects files with `onMouseDown`, not `onClick`. This is a pattern validated by tens of millions of users; don't design your own.
233
+
234
+ **When it applies:** any clickable list in a Sidebar that is vertically arranged with small gaps between items—session lists, file trees, database connections, MQTT topics, device lists, and so on.
235
+
236
+ **Handling child elements:** action buttons/input boxes inside an item need `onMouseDown={(e) => e.stopPropagation()}` to avoid accidentally selecting the parent item:
237
+ ```tsx
238
+ <button
239
+ onMouseDown={(e) => e.stopPropagation()}
240
+ onClick={(e) => { e.stopPropagation(); handleDelete(); }}
241
+ >
242
+ ✕
243
+ </button>
244
+ ```
245
+
246
+ ---
247
+
248
+ ## 8. Plugin-Owned Data Models → `Emitter` Reactive Pattern
249
+
250
+ **❌ Forbidden:** mutating the model in a command handler and then manually calling `rerender()` / `setVersion()` / passing a `treeVersion` prop.
251
+
252
+ **✅ Right—the web-standard `EventTarget` (zero core imports; plugin-owned classes extend it directly):**
253
+ ```typescript
254
+ class MyModel extends EventTarget {
255
+ private _items: Item[] = [];
256
+
257
+ add(item: Item): void {
258
+ this._items.push(item);
259
+ this.dispatchEvent(new CustomEvent("change")); // ← dispatch at the end of every state-changing method
260
+ }
261
+
262
+ remove(id: string): void {
263
+ this._items = this._items.filter(i => i.id !== id);
264
+ this.dispatchEvent(new CustomEvent("change"));
265
+ }
266
+ }
267
+ ```
268
+
269
+ ```tsx
270
+ // Subscribe on component mount, clean up on unmount
271
+ function MyView({ model }: { model: MyModel }) {
272
+ const [version, setVersion] = useState(0);
273
+
274
+ useEffect(() => {
275
+ const onChange = () => setVersion(v => v + 1);
276
+ model.addEventListener("change", onChange);
277
+ return () => model.removeEventListener("change", onChange); // auto-unregistered on unmount
278
+ }, [model]);
279
+
280
+ const items = useMemo(() => computeItems(model), [model, version]);
281
+ // ...
282
+ }
283
+ ```
284
+
285
+ **Rationale:** three timing bugs (badge stuck at 0 / when stops working / refresh doesn't update the tree) all traced back to a module-level command handler mutating a mutable model, with React unable to perceive it. The model announces its own changes (`EventTarget`/`CustomEvent` are web standards; you don't need the shell's `Emitter`)—handlers only mutate the model and never touch React.
286
+
287
+ **When it applies:** a plugin has module-level command handlers that need to trigger a UI refresh after changing data.
288
+
289
+ **⚠️ Plugins must not `import { Emitter } from "@src/core/CoreEvents"`—that is a shell-internal implementation (plugin communication iron rule + ESLint `noCoreImportInPlugin` at error level). Plugin-owned models use the web-standard `EventTarget`; events between plugins, or between a plugin and the shell, go through `window.linkdesk.events` (see `07-plugin-to-plugin-communication.md`).**
290
+
291
+ ---
292
+
293
+ ## 9. System UI Overlays → linkdesk API (quickPick / notifications / dialog)
294
+
295
+ **❌ Forbidden:** hand-rolled picker overlays / `window.alert()` / `window.confirm()` / `import ... from "@src/core/..."`.
296
+
297
+ **✅ Right:**
298
+ ```tsx
299
+ // Picker—window.linkdesk.quickPick.show({ items, placeholder, prefix })
300
+ const picked = await window.linkdesk.quickPick.show({
301
+ placeholder: "Select target session",
302
+ items: [
303
+ { label: "Session A", description: "/dev/ttyUSB0" },
304
+ { label: "Session B", description: "/dev/ttyUSB1" },
305
+ ],
306
+ });
307
+
308
+ // Notification—window.linkdesk.notifications.show(message, { type })
309
+ await window.linkdesk.notifications.show("Connected", { type: "info" });
310
+ await window.linkdesk.notifications.show("Validation failed", { type: "error" });
311
+
312
+ // Confirm / alert / file picker—window.linkdesk.dialog
313
+ const ok = await window.linkdesk.dialog.confirm("Delete this session?");
314
+ await window.linkdesk.dialog.alert("Version conflict, skipped");
315
+ const file = await window.linkdesk.dialog.openFile({
316
+ filters: [{ name: "DXF files", extensions: ["dxf"] }],
317
+ });
318
+ ```
319
+
320
+ **Rationale:** all three are rendered uniformly by the in-pool host (QuickPickHost / **the bell wide notification panel** / DialogHost)—styles match the shell and scale with the theme and font size. Hand-rolled overlays = inconsistent style + `position: fixed` breaking under keep-alive. Full signatures are in `contracts/linkdesk.d.ts`.
321
+
322
+ > ⚠️ **Notifications are not "auto-vanishing floating cards"** (notification-surface unification and correction): the bottom-right narrow toast pipeline has been deleted entirely, and **the only notification surface = the status bar bell wide panel**. Three things authors need to know:
323
+ > 1. **Notifications don't pop a card, don't steal focus, and don't block interaction**—they go into the bell (unread count +1), and the user only sees them after opening it. Don't treat notifications as a "must be seen" channel: if the user has to decide on the spot → use `dialog.confirm` (modal, steals focus).
324
+ > 2. **Persistent notifications per source are quota-limited**—grouped by `options.source`, at most 5 persistent per group; beyond that, the oldest one from the same source is pushed out. A flood won't pile into a wall, but **don't count on notifications for long-term records either**.
325
+ > 3. **Keyboard reachability means "the panel is reachable", not "notifications are reachable"**—the bell can be focused and opened with the keyboard, everything inside the panel can be reached with Tab, and `Esc` closes it; but the panel **has no focus trap** (non-modal, focus can leave freely). **Don't write assumptions like "Tab gets you to my notification button"**—the user may never open the panel at all; and **don't count on a second surface**: the bell panel is the only notification face (user directive restated 2026-10-01 — the bottom-right "auto-vanishing card" was built twice and deleted twice).
326
+
327
+ **Notification action buttons (`actions` on `notifications.show`):** failure / user-action-required notifications can carry an `actions` button array—clicking runs through the **command system** (modeled after VS Code's `showErrorMessage(msg, { title, command })` actions). Command handlers are registered by the plugin itself (`commands.registerCommand`):
328
+
329
+ ```tsx
330
+ // Failure toast + [Retry]/[View dependencies]—command = a command the plugin registered itself
331
+ await window.linkdesk.notifications.show("Install failed: cannot connect to source", {
332
+ type: "error", // error toasts linger 8s (enough to read the diagnostics); info/warning linger 6s
333
+ actions: [
334
+ { id: "retry", label: "Retry", isPrimary: true, command: "myplugin.retryInstall" },
335
+ { id: "deps", label: "View dependencies", command: "myplugin.openDeps" },
336
+ ],
337
+ });
338
+ // Commands can take arguments—clicking runs command(...args)
339
+ await window.linkdesk.notifications.show("Save conflict", {
340
+ type: "warning",
341
+ actions: [{ label: "Force save", command: "myplugin.saveForce", args: [filePath] }],
342
+ });
343
+ ```
344
+
345
+ Button text = the final display text (the shell does not translate it a second time); `isPrimary: true` = primary button (accent), unset = secondary text button. **Not passing `actions` = no buttons today, zero behavioral change.** Full types are in `contracts/linkdesk.d.ts` (the `actions` of the `notifications.show` options).
346
+
347
+ **Progress notifications + persistent notifications + source identity:** `show` **always returns a handle** (it isn't only progress bars that get one). The three easiest things to get wrong:
348
+
349
+ ```tsx
350
+ // ① Progress notification—the handle drives the same single notification (it won't spawn N of them)
351
+ const h = await window.linkdesk.notifications.show("Downloading…", {
352
+ progress: true, // turns on a real progress bar; not passing percent = indeterminate animation
353
+ source: "myplugin", // see ③
354
+ });
355
+ await h.update("Downloading…", 42); // 0-100; passing only message keeps it indeterminate
356
+ await h.finish("Download complete"); // closes the progress bar, optionally adds a completion notification
357
+ // or await h.cancel(); // close it outright, no completion notification
358
+
359
+ // ② Persistent notification—doesn't auto-dismiss, waits for the user to click × (use for error diagnostics)
360
+ await window.linkdesk.notifications.show("Port is in use, please close other programs", {
361
+ type: "error",
362
+ persistent: true,
363
+ });
364
+
365
+ // ③ Source identity—the panel groups by it, 5 persistent slots per group
366
+ await window.linkdesk.notifications.show("Sync failed", { source: "myplugin" });
367
+ ```
368
+
369
+ **Three things you must know:**
370
+
371
+ 1. **The handle is the only key**: a notification **can only be updated/removed by the handle that created it**. A `show` with the same text elsewhere = another notification, and you can't retract theirs. To retract a persistent notification (e.g. a failed `persistent`), use its own handle or let the user click ×.
372
+ 2. **`source` must be self-reported**: the pool is a single process sharing one realm, all plugins share the same `window.linkdesk`, and preload **cannot** know which plugin issued this `show` ⇒ only the author can pass it explicitly. **Not passing it → everything lands in the "Other" group**; plugins pass their own plugin id, and the shell's own domains use `app.<domain>`.
373
+ 3. **`persistent` has a quota**: at most 5 persistent per group (by `source`); beyond that the oldest of the same source is pushed out and a summary hint is shown. **Persistent ≠ unlimited retention**—if you need retention, write your own file.
374
+
375
+ > The full **behavior contract** (not signatures—for signatures see `contracts/linkdesk.d.ts`) is in the `notifications` row of [`01-plugin-api-contract.md`](01-plugin-api-contract.md) §3.2—this section only covers usage, and that one is authoritative for semantics.
376
+
377
+ **Rich-content confirm dialogs (`dialog.confirmContent`):** use this when the confirm dialog needs **more than one line of text** (a form / list / screenshot / custom layout)—**the dialog is the shell (centered, masking, Esc, focus lock, click-mask to cancel) and your view draws the content** (modeled after VS Code's "the dialog is the shell, the plugin defines the content"):
378
+
379
+ ```tsx
380
+ // 1) First declare the view for this content in plugin.json (any contributes.views container works)
381
+ // 2) In code, address and open it by the "declared id"
382
+ const ok = await window.linkdesk.dialog.confirmContent({
383
+ pluginId: "myplugin", // the plugin the content belongs to (the shell uses this for composite addressing)
384
+ viewId: "myplugin.confirmImport", // declared id of the content view
385
+ title: "Confirm import", // fallback title—if the content view fails to resolve, the shell falls back to a plain-text confirm
386
+ message: "3 entries will be overwritten", // fallback body
387
+ payload: { files: ["a.ts", "b.ts"] }, // opaque payload: the shell doesn't interpret it, your view reads it itself
388
+ });
389
+ if (ok) { /* user confirmed */ } // false = cancelled / closed
390
+ ```
391
+
392
+ The other half—the content view (**another view in the same code**, reading the payload and stating a verdict):
393
+
394
+ ```tsx
395
+ // In your content view component—mounting opens it, reading once is enough (every new dialog is a fresh mount)
396
+ function MyConfirmContent() {
397
+ const data = window.linkdesk.dialogHost.current();
398
+ if (!data || data.open !== true) return null; // defensive: don't render blank
399
+ const payload = data.content?.payload as MyPayload;
400
+ return (
401
+ <div>
402
+ {/* The body layout and the buttons are entirely yours to draw */}
403
+ <button onClick={() => window.linkdesk.dialogHost.cancel()}>Cancel</button>
404
+ <button onClick={() => window.linkdesk.dialogHost.confirm()}>OK</button>
405
+ </div>
406
+ );
407
+ }
408
+ ```
409
+
410
+ **The fallback is hard**: if `viewId` can't be resolved (view not declared / the declaring plugin isn't installed) → the shell **falls back to a plain-text confirm** (using `title`/`message`), the dialog still appears and **never dies silently**. So don't skip `title`/`message`. The payload crosses IPC via structured clone, so only cloneable data can go in it (no functions/React elements). There are only two ways to settle: `dialogHost.confirm()` / `dialogHost.cancel()`—**don't close the dialog yourself with `setState`**; the shell won't recognize it.
411
+
412
+ ---
413
+
414
+ ## 10. Font Sizes → `--font-size-*` tokens + `--ui-scale` (measurement-system normalization)
415
+
416
+ **❌ Forbidden:** writing bare `px` for plugin text font sizes (`font-size: 14px`)—the `check-font-scale-audit` gate (`npm run check`) rejects it mechanically.
417
+
418
+ **✅ Right:** font sizes consume `var(--font-size-*)`; line-height is unitless (`1.5`) or `calc(... * var(--ui-scale))`; fixed upper bounds (input box/button/status bar heights) are written as `calc(Npx * var(--ui-scale))` to scale with the global setting. Unified global font-size scaling (the `app.uiFontScale` setting, 85–150%, always shown and always in effect).
419
+
420
+ **Scale table** (100% render = `--ui-scale: 1`; the engine computes the final px from the scale factor):
421
+
422
+ | Step | Base px | Meaning |
423
+ |---|---|---|
424
+ | `--font-size-2xs` | 11 | badges/paths |
425
+ | `--font-size-xs` | 12 | secondary text/buttons/stats |
426
+ | `--font-size-sm` | 13 | main UI text (aligned with VS Code's 13px) |
427
+ | `--font-size-md` | 14 | menus/tabs/file tree name |
428
+ | `--font-size-lg` | 16 | icon glyphs/content icons (paired with 14px text) |
429
+ | `--font-size-xl` | 18 | region titles |
430
+ | `--font-size-2xl` | 22 | row icons/large text |
431
+ | `--font-size-3xl` | 28 | pd-name |
432
+ | `--font-size-4xl` | 30 | welcome-title |
433
+
434
+ **Iron rules + boundaries (see the archive's §5 icon rulings / §6.2 monaco island decision):**
435
+ - **Standalone display icons do not scale with font size** (decorative/brand semantics, not directly adjacent to text)—`.icon-btn .plugin-icon--codicon` 24 / `.plugin-icon--emoji` 24 / `.hamburger-btn` 20 / hero-icon 48 / row icons 20, and so on; for whitelist exemptions see `scripts/check-font-scale-audit.mjs`.
436
+ - **Content-level font sizes go through `contributes.configuration`** (e.g. `editor.fontSize`)—large text areas/editor content are controlled by the plugin's own configuration and don't follow `--ui-scale`.
437
+ - **The monaco content island precedent**: editor content reads `editor.fontSize`, while chrome (status bar/breadcrumbs) follows the global setting—two orthogonal axes, each minding its own business.
438
+ - **Mapping rule**: migrating existing `NNpx` to the scale table goes "up one step"—`12→sm / 13→md / 11→xs / 10→2xs / 14→lg / 18→xl` (at 100% this enlarges to the new default baseline, aligned with VS Code).
439
+
440
+ ---
441
+
442
+ ## 11. The Token Contract—Six-Domain Matrix + Honest Boundaries + Data Discipline (.5)
443
+
444
+ > **In one line:** before writing UI, check the 11.1 six-domain matrix—forms/controls/surfaces written with `var(--*)` **follow the theme + glass + global scaling automatically**, with zero plugin awareness. Doing it right is driven by recommendations, doing it wrong shows red through the gate but only as a WARN, and bypassing it takes a knowing declaration via a standard eslint-disable (content/brand fixed colors are legitimately exempt—see 11.2).
445
+ > The gate = `linkdesk-plugin-sdk lint` (built into `@linkdesk/plugin-sdk`): the eslint rule leg + the three-check scanner leg, dual-track; all 15 items are **WARNs that never fail the build/upload**—advice, not a lockdown. Run it once at your project root; a violation shows red with self-explanatory fix text.
446
+
447
+ ### 11.1 The six-domain token matrix—authors can only write "follows automatically" if they know what variables exist
448
+
449
+ | Domain | var() keys (the full list always defers to `src/index.css`) | How authors write it | Gate coverage |
450
+ |---|---|---|---|
451
+ | **Color** | `--text-primary/--text-secondary/--text-muted` (the text-color source is controlled by fontTone) + `--bg-window/--bg-side-panel/--bg-card/--bg-input/--bg-selection` + `--accent/--accent-hover` | `color: var(--text-primary)` | `linkdesk/no-hardcoded-hex` |
452
+ | **Surface** | `--bg-*` surface fills + `--surface-radius` (follows the shell's global corner-radius slider) | `background: var(--bg-card)` | `linkdesk/no-hardcoded-hex` |
453
+ | **Radius** | `--radius-xs/sm/md/lg/xl/2xl` + `--surface-radius` | `border-radius: var(--radius-md)` | `linkdesk/no-hardcoded-radius` (bare px in border-radius is red) |
454
+ | **Glass** | `--glass-blur/--glass-saturate/--glass-tint/--glass-morph/--glass-specular…` (the full group in `src/index.css`) | `backdrop-filter: blur(var(--glass-blur)) …` | contract guidance—composite forms are beyond per-item gating |
455
+ | **Font size** | `--font-size-2xs … 4xl` + `--ui-scale` (the scaling axis for `app.uiFontScale`; the scale table is in §10) | `font-size: var(--font-size-md)` / em/rem | `check-font-scale` (the check leg—a bare px font size is red) |
456
+ | **Font family** | `--font-ui` / `--font-mono` | `font-family: var(--font-ui)` | contract guidance (authors may legitimately choose their own font) |
457
+
458
+ `var(--*)` = theme/glass/global scaling follow automatically, with zero plugin awareness—**this is exactly why the @linkdesk/ui control layer can be "follow without thinking"**—the controls are written entirely on tokens, so a plugin that does `npm i @linkdesk/ui` and consumes them follows along. Control reuse always imports from `@linkdesk/ui` (see §Quick Reference)—don't hand-roll wheels.
459
+
460
+ ### 11.2 Honest boundaries / knowing bypasses—content and brand colors can have their own sky
461
+
462
+ **Three gate tiers (07 §6):** recommended (copy it and you're right) / warning (15 self-explanatory items, red but **a WARN never fails**) / knowing bypass (a standard eslint-disable declaration with a reason). **No ecosystem can stop an author from hardcoding colors**—VS Code also has extensions that don't follow the theme. What the gate does is make "doing it right" the default and "doing it wrong" explicitly red but **knowingly bypassable**: a comment carrying a reason = the "proceed anyway" informed confirmation on a browser danger page, not silently switching off the light.
463
+
464
+ **Legitimate exemption categories:** var() fallback hex (`color: var(--x, #fff)` = a compliant form, not blocked) / color-picker swatches / canvas drawing / engine regions / **view-level exemption for content canvases**.
465
+
466
+ **The content vs. chrome boundary (empirically validated by the Angry Birds test):** a game / data visualization / canvas Main Area = **a content world, not UI chrome**—UI chrome follows the theme (var()/t()/@linkdesk/ui), while content can have its own sky (grass green / health-bar red / sky blue need not follow the theme). Authors **declare a view-level exemption once**, and the gate doesn't light up item by item inside content regions (item-by-item disables for the 5-10 hardcoded values in a game are far too noisy):
467
+
468
+ ```tsx
469
+ /* eslint-disable linkdesk/no-hardcoded-hex, linkdesk/no-hardcoded-radius -- content canvas: the game main area draws itself */
470
+ export function GameBoard() {
471
+ return <canvas /* draws blue sky, green grass, red health bar—a content world, not UI chrome */ />;
472
+ }
473
+ ```
474
+
475
+ ```tsx
476
+ // Line-level knowing bypass (a brand fixed-color badge—exempts only this line, other lines are still blocked)
477
+ // eslint-disable-next-line linkdesk/no-hardcoded-hex -- brand fixed-color badge
478
+ const PRO_BADGE = <span style={{ color: "#ff6b00" }}>PRO</span>;
479
+ ```
480
+
481
+ ```css
482
+ /* The same format in CSS (the check script recognizes it)—a color-picker swatch with a fixed value, exempt on this line */
483
+ /* eslint-disable-next-line linkdesk/no-hardcoded-hex -- color-picker swatch */
484
+ .swatch--brand { background: #ffd700; }
485
+ ```
486
+
487
+ **Semantics:** a line that hits an exemption goes **entirely silent** and doesn't light up (aligned with eslint's native suppress—after a disable declaration nothing is reported item by item); **no declaration = an unhandled deviation**, and `linkdesk-plugin-sdk lint` reports it with a normal WARN. **This is not new syntax**—it's the same format as the shell's existing `no-hardcoded-hex` error suggestion. **Backgrounds not being glassed holds inherently at the mechanism layer**—backdrop-filter only paints shell surface elements and is not applied to a plugin view's root node, so content the author draws is simply never glassed.
488
+
489
+ ### 11.3 Non-CSS engine adaptation—the translation bridge (self-rendering engines don't use CSS variables)
490
+
491
+ monaco-style self-rendering engines (canvas / WebGL / rich-text engines likewise) don't consume CSS variables—following the theme requires a **translation bridge**: subscribe to theme changes → translate into the engine's own theme API. Precedent: `src/services/theme-sync.ts` (it lives in **the editor plugin's own repo**, `Encaron/linkdesk-plugin-editor`—shipped plugin source is not in the shell repo):
492
+
493
+ ```ts
494
+ // Subscribe to theme changes (the event may fire before mount → register at top level or guard on active, see 11.5)
495
+ const off = window.linkdesk.events.on("theme:changed", () => {
496
+ engine.updateTheme(translateTheme()); // translate your tokens → the engine's theme object
497
+ });
498
+ ```
499
+
500
+ monaco's current opaque background and two-state (light/dark) following is **a transitional workaround, not a settled boundary**—full theme adaptation may come later.
501
+
502
+ ### 11.4 Plugin-private data channels—choosing a channel when you build your own settings UI / manage your own saves
503
+
504
+ When authors build their own settings UI or manage their own saves (without going through a shell settings-page declaration), pick the data landing spot by semantics:
505
+
506
+ | Channel | Good for | Example |
507
+ |---|---|---|
508
+ | `window.linkdesk.pluginState` (**preferred**) | plugin-managed saves—centralized caching + file persistence (a proper API: `get/set/onChange(pluginId, key)`) | game score / level progress / high-score board / skin preference |
509
+ | `window.linkdesk.configuration.set(key)` private namespace | follows settings semantics, readable by other plugins/themes, **must appear in the shell settings-page UI** (declaring contributes.configuration puts it there) | plugin parameters (declared = UI; undeclared = a purely private key that still persists when written) |
510
+ | `window.linkdesk.filesystem` | large files / binary / cross-plugin sharing | screenshot export / save files |
511
+ | `localStorage` | supplementary—in-pool temporary cache (no cross-machine, no shell management) | high-frequency temporary values within a session |
512
+
513
+ **Iron rule: private keys that don't declare `contributes.configuration` do not appear in the shell settings-page UI**—`config.set` writes and persists even without a schema (only enums get filtered), so authors who want the shell settings page declare a contribution, and those who want their own UI write private keys directly; the two don't interfere.
514
+
515
+ ### 11.5 Shell-discipline handoff list—each non-UI discipline sinks into the doc where it lands
516
+
517
+ | Discipline | Where it's specified |
518
+ |---|---|
519
+ | The plugin's only entry is `window.linkdesk.*`; **importing @src/core (including any @src subpath) is forbidden** | `01-plugin-api-contract.md` |
520
+ | Configuration: **subscribe, don't read once** (linkdesk.configuration is event-driven) | §3 of this file |
521
+ | linkdesk.events subscription **timing**—the event may fire before mount (IPC buffering) → register at top level or guard on active | `02-plugin-lifecycle.md` |
522
+ | **Don't hardcode other plugins' IDs** (differential behavior goes through plugin.json declaration fields, consumed via the Registry pattern) | `03-contributes-spec.md` |
523
+ | Configuration keys **must have a default** | `06-plugin-json-spec.md` |
524
+ | **Use only documented API namespaces** (don't casually hang undocumented `linkdesk.xxx` off the API) | `01-plugin-api-contract.md` |
525
+ | Controls always come from `@linkdesk/ui` (built-in controls are imported from the npm package; `@src/components/shared/*` is forbidden) | §Quick Reference of this file |
526
+
527
+ ---
528
+
529
+ ## 12. CSS Class Names—Prefix Your Own Elements; Don't "Borrow" Reserved Names
530
+
531
+ **One thing to remember first: the plugin view's stylesheet is not yours alone.** The same window loads the
532
+ host's styles, the shared components' (`@linkdesk/ui`) styles, and **every loaded plugin's** styles at once —
533
+ **class names are global identifiers**. Writing a class name claims that name; if someone else uses it too,
534
+ both stylesheets land on the same element.
535
+
536
+ **Three rules:**
537
+
538
+ 1. **Class names you give your own elements must start with your `pluginId` plus a hyphen**—
539
+ `settings-*`, `editor-*`, `file-tree-*` … (`pluginId` is the id you declare in `plugin.json`; every
540
+ official plugin does this). **Don't use abbreviations**: the `ms-` / `mpd-` shorthand style is **retired**—
541
+ an abbreviation guarantees nothing, and two plugins that each abbreviate to `ms-` collide. `pluginId` is
542
+ unique by construction (immutable once published), so deriving the prefix from it is free collision
543
+ protection.
544
+ 2. **`@keyframes` names take the prefix too** (`file-tree-fadeIn`), and **rename the `animation:` reference in
545
+ the same edit**—a keyframe name is a global identifier exactly like a class name: on a collision the later
546
+ definition wins and the earlier animation silently stops.
547
+ 3. **These names are reserved by the host—don't use them for your own elements** (if you do, the host's
548
+ styles will hit you):
549
+
550
+ | Source | Reserved names | Notes |
551
+ |---|---|---|
552
+ | The input-box utility the host **gives you** | `.ldk-input` | Input-box utility—**just use it** (it exists for your inputs). ⚠️ It is the **one** name in the whole `ldk-` family you're encouraged to **consume** (every other `ldk-` name means "hands off"; this one means "take it") |
553
+ | Shared component classes + host container classes | **the whole `ldk-` namespace**—today: `ldk-badge`, `ldk-button`, `ldk-combobox`, `ldk-mdv`, `ldk-selectbox`, `ldk-sle`, `ldk-slider`, `ldk-toggle`, `ldk-hint-card` (2026-09-19, hover hint card) (shared components), plus the host's own container classes such as `ldk-titlebar`, `ldk-input`, `ldk-setting-group` | Class names of the badge / button / combobox / Markdown container / select / string-list editor / slider / toggle components in `@linkdesk/ui`. **You don't have to memorize them**—remember one thing: **anything starting with `ldk-` belongs to the host itself (shared components + host UI containers), so don't put it on your own elements** (the one exception is `.ldk-input` on the row above: that one is **for you**) |
554
+
555
+ **`@keyframes` names work the same way**—the host already uses the animation names below, so avoid them when naming your own animations. A collision has the same consequence as a class name (the later definition wins, the earlier one is dropped), and it is equally **silent**: one of the two animations simply stops playing, with nothing in the console.
556
+
557
+ | Reserved keyframe names | Notes |
558
+ |---|---|
559
+ | `ldk-selectbox-in` | the shared select dropdown's entrance animation |
560
+ | `ldk-drop-zone-in` | the drop zone's entrance animation |
561
+ | `ldk-dropdown-card-in` | the dropdown card's entrance animation |
562
+ | `ldk-floating-panel-in` | the floating panel's entrance animation |
563
+ | `ldk-notif-icon-spin` | the notification icon's spin |
564
+ | `ldk-notif-progress-scan` | the notification progress scan |
565
+ | `ldk-rn-spin` | the release-notes page's refresh icon spin |
566
+ | `ldk-boot-mark-breath` | the boot brand screen's breathing |
567
+ | `ldk-view-skeleton-breath` | the content loading skeleton's breathing |
568
+ | `ldk-welcome-skeleton-breath` | the welcome recent list loading skeleton's breathing |
569
+ | `ldk-welcome-in` | the welcome page's entrance fade-up (its single authored moment) |
570
+
571
+ **The name you reference has to exist somewhere**—rule 2 above says "when you rename, change the reference in
572
+ the same commit"; this is the other half, and **the machine checks it**: the name you write in
573
+ `animation` / `animation-name` must either be defined by an `@keyframes` **in your own CSS** or be one of the
574
+ names in **the reserved table above** (referencing the host's animations is **legitimate consumption**—you will
575
+ not be flagged). Reference a name **nobody defined** and the animation **reports nothing, warns nothing, it
576
+ just does not run**—the symptom is "why isn't my animation working", while the console stays silent (other
577
+ plugins and the host are running in the same window, so it is hard to spot at a glance).
578
+ From `@linkdesk/plugin-sdk` **≥ 0.1.37**, the plugin lint reports these **dangling references** one by one
579
+ (**file name + line number + the name**); if you genuinely need a name the gate cannot see (say the animation
580
+ is injected at runtime), use a standard `eslint-disable` comment stating why.
581
+
582
+ > 🔧 **Maintainer note (authors can skip this)**—the **Reserved names** and **Reserved keyframe names** columns in the two tables above are **machine-read**: the gate
583
+ > in `npm run check` (`scripts/check-reserved-names-doc-sync.mjs`) cross-checks them **both ways** against the
584
+ > registry `packages/plugin-sdk/schemas/reserved-class-names.json`—every registry name must appear here, and
585
+ > every name here must either be registered (bare names) or a real `ldk-` name present in the host source.
586
+ > The keyframe table is cross-checked **both ways** against the registry's `keyframes` array in the same way.
587
+ > ⇒ **Editing these two columns is a public-surface change**: add/remove a name in **three places in one commit**—
588
+ > the registry plus these two tables in both language trees. Both columns hold **names only**; put prose in
589
+ > the "Notes" column.
590
+
591
+ **One more namespace rule**: your `pluginId` **must not start with `ldk-`**—the whole `ldk-` namespace belongs
592
+ to the host, so a plugin called `ldk-tools` would derive its prefix (`ldk-tools-*`) **straight into host
593
+ territory**, which also makes rule 1 meaningless. This constraint lives in the `plugin.json` schema, so your
594
+ editor flags it immediately.
595
+
596
+ **Want their look? Use their component**—`import { Button } from "@linkdesk/ui"`, don't hand-write its class
597
+ name (hand-writing bypasses the component, and you fall behind the moment it changes).
598
+
599
+ **Always use state classes in compound form**: `.your-class.active`, `.your-class.on` (never bare
600
+ `.active {}` or `.on {}`—that would also restyle same-named state elements in the host and in other plugins).
601
+
602
+ **A real example from this project**: using a host-reserved name as a "handy style name" on your own element
603
+ painted the background and the text the same color, so the text was swallowed by its own background — the UI
604
+ just looked like "a solid block". **No error**, just wrong, and hard to trace.
605
+
606
+ ### 12.1 Upgrading from an older `@linkdesk/ui`—the one thing you have to change yourself
607
+
608
+ Shared component class names now carry an `ldk-` prefix (as of `@linkdesk/ui` **0.2.0**). This affects exactly
609
+ one kind of code: rules in **your own plugin's CSS** that use a descendant selector to fine-tune a shared
610
+ component. **Nothing to do before you upgrade; when you upgrade, it's one prefix.**
611
+
612
+ - **When it hits you**: after `@linkdesk/ui` moves to **0.2.0**—**not before**. In older versions these
613
+ components' class names were bare (`.badge`), and the CSS shipped inside the package is consistent with the
614
+ components, so **if you don't upgrade, nothing breaks**. (A `^0.1.x` range will not cross over to `0.2.0` by
615
+ itself, so this only comes up on the upgrade you perform deliberately.)
616
+ - **What is affected**: descendant selectors in **your own plugin CSS** such as
617
+ `.control-bar .combobox { … }`, `.settings-slider-control .slider { … }`, `.changelog .mdv { … }`.
618
+ **The components' own styles are unaffected, and your own class names don't change.**
619
+ - **How to fix it**: add the `ldk-` prefix to **the part of the selector that points at the shared component**—
620
+ `.combobox` → `.ldk-combobox`, `.slider` → `.ldk-slider`, `.mdv` → `.ldk-mdv`, `.badge` → `.ldk-badge`,
621
+ `.selectbox-trigger` → `.ldk-selectbox-trigger`, `.combobox-field` → `.ldk-combobox-field`. **Family names
622
+ (suffixes like `-trigger` / `-field` / `-input`) take the prefix too.** Your own prefixes (`.control-bar`,
623
+ `.settings-*`) stay as they are. **After upgrading, grep your CSS for the eight old base names
624
+ `.badge`, `.button`, `.combobox`, `.mdv`, `.selectbox`, `.sle`, `.slider`, `.toggle`**: add the prefix where
625
+ the rule tunes a shared component, leave the rest alone.
626
+ - **Why it isn't automatically compatible**: this kind of mismatch **raises no error**—a selector that no
627
+ longer matches simply stops applying, so the UI looks "roughly right, just a bit off". Because it is silent,
628
+ we moved the names under the `ldk-` prefix and wrote this section.
629
+
630
+ ### 12.2 The prefix rules (§12 rules 1 and 2) are live—what about existing code?
631
+
632
+ **In one line: it keeps working unchanged, but the next time you touch that file is when you fix it.**
633
+
634
+ - **The official plugins have already been cleaned up under the new rules**—four plugins were renamed:
635
+ `file-tree` (v1.0.9), `settings` (v1.0.11), `serial-monitor` (v1.0.12) and `marketplace` (v1.0.33); their
636
+ bare class names and keyframe names now carry the `<pluginId>-` prefix. The remaining official plugin repos
637
+ had no bare definitions to begin with (their class names either already carry a prefix or they define none).
638
+ Measured against the official catalog, the audit reads **18/18 compliant**.
639
+ - **Third-party authors have no repository to change**: this rule governs only **the class and keyframe names
640
+ you write yourself**—it doesn't touch repo layout, your `pluginId`, or anyone else's code. You do **not**
641
+ need to cut a release for it.
642
+ - **Old unprefixed class names raise no error and don't stop working**—they work fine today. The cost is that
643
+ **the collision risk is still there**: if another plugin defines the same class name, both stylesheets land
644
+ on the same element (no error, just wrong-looking, and hard to trace).
645
+ - **Compliance is judged by the check that ships with your project**: a scaffolded project carries a strict
646
+ check leg (`npm run verify`) that scans your CSS for class names **bare-defined on your own elements** and
647
+ for `@keyframes` names, and fails them when they don't start with `<pluginId>-`. So the real action is
648
+ **rename them the next time you open that file**: `.panel {}` → `.myplugin-panel {}`, changing the CSS and
649
+ the JSX that uses it together (identifiers only—don't touch style values).
650
+
651
+ > Want to see whether your project has bare names right now? Run `npm run verify` in the project root.
652
+
653
+ ### 12.3 The host's input-box utility was renamed: `.input` → `.ldk-input` (2026-09-16)
654
+
655
+ **In one line: if your plugin wrote `className="input"`, change it to `className="ldk-input"`—the styling is identical, only the name changed.**
656
+
657
+ - **What changed**: the host used to call its input-box utility **`.input`** (no prefix—the only host public name without `ldk-`). That conflicted with rule 1 above ("every cross-party name carries a namespace") ⇒ it is now **`.ldk-input`**. The host's **setting-group card**, `.setting-group`, was renamed to **`.ldk-setting-group`** at the same time.
658
+ - **Who is affected**: **any plugin that wrote `className="input"` in its own JSX/TSX**—among the official plugins, `settings` and `serial-monitor` used it and were updated in the same release batch. **The fix is one place**: `className="input"` → `className="ldk-input"`; the same for concatenated forms (`"input my-input"` → `"ldk-input my-input"`). **Zero styling change**—same rule, same CSS variables, only the name.
659
+ - **What happens if you don't**: the input doesn't error; it simply **loses the host-provided appearance** (background / border / radius / padding) and looks like a browser-native input.
660
+ - **When you must change it**: as soon as you run on the **new shell**. The new shell version is **`0.2.0`**, and both official plugins now declare `minAppVersion: "0.2.0"` in `plugin.json`—declare the same value in your plugin and users on an older shell get a clear "requires app version ≥0.2.0" message instead of an unstyled input (see [04-distribution-format §minAppVersion](04-distribution-format.md) for the semantics).
661
+
662
+ ### 12.4 The rest of the shared components' class names took the `ldk-` prefix too (2026-09-16)
663
+
664
+ **In one line: same story as 12.1, just for the components that 12.1 didn't cover—if your own CSS tunes those components with descendant selectors, add the `ldk-` prefix when you upgrade.**
665
+
666
+ - **What changed**: §12.1 covered the eight base names of `@linkdesk/ui` (`badge` / `button` / `combobox` / `mdv` / `selectbox` / `sle` / `slider` / `toggle`) at **0.2.0**. The remaining components' class names—plus one `@keyframes` name—now carry the prefix too (**since the 2026-09-16 round**; for how to read the version line see [19-Component Cheatsheet §2.1](19-component-cheatsheet.md)):
667
+
668
+ | Old family | New family |
669
+ |---|---|
670
+ | `.colorpicker-*` | `.ldk-colorpicker-*` |
671
+ | `.ctx-*` | `.ldk-ctx-*` |
672
+ | `.form-row` | `.ldk-form-row` |
673
+ | `.inline-input`, `.inline-input--compact/--normal` | `.ldk-inline-input`, `.ldk-inline-input--compact/--normal` |
674
+ | `.number-input*` | `.ldk-number-input*` |
675
+ | `.segmented-radio`, `.segmented-radio__option/__label` | `.ldk-segmented-radio`, `.ldk-segmented-radio__option/__label` |
676
+ | `.sidebar-section*`, `.sidebar-pane-view`, `.sidebar-pane-sash` | `.ldk-sidebar-section*`, `.ldk-sidebar-section-pane-view`, `.ldk-sidebar-section-pane-sash` |
677
+ | `.theme-picker*`, `.theme-card`, `.theme-preview` | `.ldk-theme-picker*`, `.ldk-theme-picker-card`, `.ldk-theme-picker-preview` |
678
+ | `.tbadge` / `.tname` / `.pv-bar` / `.pv-dot` (theme-card internals) | `.ldk-theme-picker-badge` / `.ldk-theme-picker-name` / `.ldk-theme-picker-preview-bar` / `.ldk-theme-picker-preview-dot` |
679
+ | `@keyframes selectbox-in` | `@keyframes ldk-selectbox-in` |
680
+
681
+ - **Who is affected**: again **only your own CSS**'s descendant selectors that point at those components (e.g. `.settings-row:has(.theme-picker)`). **The components' own styling does not change, and your own class names stay as they are.** The whole point is that the shared components' names now all live in the `ldk-` namespace, whose rule you already know: **anything starting with `ldk-` belongs to the host—don't put it on your own elements** (the one exception is `.ldk-input`, the utility that is **for you**).
682
+ - **What happens if you don't**: exactly the silent failure described in 12.1—the selector just stops matching and those few rules quietly stop applying. **No error.**
683
+ - 🔴 **When the host renames a shared name or restyles a component, there is no code and no CSS for you to change** — components and styles are supplied by the shell pool (centralized supply, see [19-Component Cheatsheet §2](19-component-cheatsheet.md)): the same implementation follows the shell upgrade, so your UI stays consistent. The one thing to maintain is that your `@linkdesk/ui` dependency **stays on the current version line** (it decides what your local dev and types resolve to).
684
+ - ⛔ **Component styles never come from your source either**: a line like `import "@linkdesk/ui/index.css"` (or its dist / `@import` form) is failed by the SDK lint leg `linkdesk/no-ui-css-import`, with **no exemption exit** — baking the styles into your plugin means "the shell restyles once, the whole ecosystem follows" stops being true for you.
685
+ - **When you must change it**: when the shell you support moves to a version that contains this rename (how to read the version line: [19-Component Cheatsheet §2.1](19-component-cheatsheet.md) — ui version = shell version, one line). After upgrading, **grep your own CSS for the old families** in the table above: an official plugin (`settings`) had exactly one such spot and it was fixed in the same release batch.
686
+ - **You get the same ruler** (`@linkdesk/plugin-sdk` 0.1.40 onward): your repo's lint ships with a dangling-name check—when the host renames a shared name and you didn't follow, **your own CI calls it out** (usage and fixes in [16-naming-conventions §7.6](16-naming-conventions.md)).
687
+
688
+ ### 12.5 The **scope** of custom properties—`--x:` written under `:root` is written for the whole application
689
+
690
+ The three rules above govern **names**; this one governs **territory**. For custom properties (`--xxx`) there is exactly one rule:
691
+
692
+ > **Scope is the namespace.** The name is yours to choose; **which subtree it lives in** is what decides who it belongs to.
693
+
694
+ **① Document-level scope is the host's alone.** Declarations on `:root` / `html` / `body` / `[data-theme="…"]` / `*` are **visible to the entire document**—that is not your territory:
695
+
696
+ ```css
697
+ /* ❌ this declaration is visible to the whole document */
698
+ :root { --my-panel-gap: 8px; }
699
+
700
+ /* ✅ hang it under your own root class: scope = your subtree */
701
+ .my-plugin-root { --my-panel-gap: 8px; }
702
+ ```
703
+
704
+ **② Every other declaration hangs under one of your own classes.** Write `.your-class { --xxx: … }`—and note that **the name needs no prefix there**: a `--gap` under `:root` collides with someone else's, a `--gap` under `.my-plugin-root` cannot (the scope has already divided the territory).
705
+
706
+ **③ Nobody may define a `--ldk-*` custom property** (same rule as class names and keyframes—the whole `ldk-` namespace belongs to the host).
707
+
708
+ **Why this is nastier than a class-name collision**: most of the host's colors / radii / z-index layers are **provided by its stylesheets rather than written by code**. Write one of the host's contract names (say `--bg-card`) under `:root` and **you win**—the whole application's card background follows your value. And **switching themes may switch it back** (a theme overrides some of those names) ⇒ the symptom is "**works sometimes, breaks sometimes**", the hardest kind to diagnose.
709
+
710
+ **One self-check** (glance at it when your CSS is done): **"is my `--x:` written under `:root`?"** If yes ⇒ move it under your own root class.
711
+
712
+ **Migrating**—plugins that already define custom properties under `:root`:
713
+
714
+ | Case | Level | What to do |
715
+ |---|---|---|
716
+ | Name **carries** your own prefix (`--my-plugin-gap`) | 🟡 suggested | Move it under your own root class. The name is yours and nobody competes for it, but there is no reason for it to sit under `:root`—after the move its scope shrinks from the whole document to your own subtree |
717
+ | Name **carries no** prefix (`--gap`, `--bg-card`, …) | 🔴 required | It is live document-wide right now and may already be overriding the host's or another plugin's value ⇒ move it under your own root class (the name may stay as it is; **what changes is the scope**) |
718
+ | Name starts with `ldk-` | 🔴 required | Give it one of your own names—`ldk-` is the host's namespace |
719
+ | Written **under your own root class** | ✅ compliant | Nothing to do. Fine-tuning like `.your-root .ldk-x { --y: … }` is compliant too (one of your own classes appears in the selector) |
720
+
721
+ **How it is enforced mechanically**: run `npm run lint` in the plugin project root (or `npm run verify` in CI) and each occurrence is reported—🔴 turns CI red, 🟡 only prints. When "it works locally but CI is red", read this section first.
722
+
723
+ > 🔧 **Maintainer note (authors may skip)**: the rule text (including how the host registers its contract blocks and the floating-layer host exception) lives under `docs/02-Electron架构/插件生态与发布/01-插件独立构建/样式命名空间归一化/`; the shell side is guarded by `scripts/check-css-namespace.mjs`, the plugin side by the SDK's `check-css-namespace` leg (token scope is the third criterion of that same leg, sharing one disable-comment id with the class-name and keyframe criteria).
724
+
725
+ ### 12.6 The selector itself needs a "landing spot" too—**anchorless selectors are forbidden** (2026-09-16)
726
+
727
+ The five sections above govern **names** (class names / keyframes / custom properties). This one governs the **shape of the selector**—a rule that is even easier to overlook:
728
+
729
+ > **Class names and ids are "name anchors"; element / universal / attribute / pseudo-class / pseudo-element selectors are not.**
730
+ > The latter hit other people's elements **without sharing a single name with anyone.**
731
+
732
+ ```css
733
+ /* ❌ one rule rewrites *every* button in the document—including the host's and other plugins' */
734
+ button { border: none; }
735
+ * { box-sizing: border-box; }
736
+ #some-id { display: none; } /* an id is global and guessable too, and outranks classes */
737
+ :root { outline: none; } /* `:root` is an anchorless selector as well */
738
+
739
+ /* ✅ hang it under your own root class—same intent, landing spot limited to your own subtree */
740
+ .my-plugin-root button { border: none; }
741
+ ```
742
+
743
+ **Two rules** (both are **mechanically red** in `npm run lint` at the plugin project root / `npm run verify` in CI):
744
+
745
+ | Rule | Verdict | Why |
746
+ |---|---|---|
747
+ | **No anchorless selectors** | The selector has **no** `.class` or `#id` subject (element / universal / attribute / pseudo-class / pseudo-element; **top-level *and* qualified, including inside `@media`**) ⇒ 🔴 | It hits "every element of that kind in the document", regardless of who rendered it |
748
+ | **A cross-party hit must carry your own anchor** | The selector mentions an `ldk-*` class (**including a mention inside `:has(…)`**) but does **not** carry a `.<your pluginId>-*` class ⇒ 🔴 | `ldk-` is the host's namespace; **fine-tuning has to happen on your own territory** |
749
+
750
+ ⚠️ **The second rule does not forbid restyling shared components**—that is a **legitimate feature** (scoped tuning). It only requires you to **carry your own prefix as the anchor**:
751
+
752
+ ```css
753
+ /* ❌ targets the host's / shared components' elements with no landing spot of your own ⇒ red */
754
+ .ldk-toggle { transform: scale(1.1); }
755
+
756
+ /* ✅ the same intent, written on your own territory ⇒ compliant */
757
+ .my-plugin-root .ldk-toggle { transform: scale(1.1); }
758
+ ```
759
+
760
+ **Why it is worth remembering**: the host itself has **17** such "anchorless selectors" (`*` resets / `html`·`body` / `[data-theme]` / `*:focus-visible` / the scrollbar family / `input[type="number"]`·`select`)—they are a **deliberate shared baseline** that plugins rely on (and may override). Precisely because they exist, **your anchorless selector will hit them**: write `button { }` and the host's buttons plus every other plugin's buttons change with it.
761
+
762
+ **Migration**: **zero instances today**—a full re-check of the official plugins plus the in-repo fixture (the "anchorless S2 / cross-party S3" columns of `npm run audit:plugin-prefix -- --all`) is **0** ⇒ **you have nothing to change**; this rule is **preventive**.
763
+
764
+ > 🔧 **Maintainer note (authors may skip)**: the rule text (R0 scope / R1 host baseline / R2 / R3) plus the decision formulas and negative controls live in `docs/02-Electron架构/插件生态与发布/01-插件独立构建/样式命名空间归一化/32-任务-选择器形态轴门禁与落地.md`; the host side is guarded by criteria ⑩⑪ of `scripts/check-css-namespace.mjs` (plus the runtime mirror on axis ④ of the probe), and the plugin side by the **fourth and fifth criteria** of the SDK's `check-css-namespace` leg (`checks/selector-form.ts` for S2/S3, and `checks/keyframe-refs.ts` for dangling keyframe references—the latter in place since **2026-09-18**, SDK `≥ 0.1.37`).
765
+
766
+ ---
767
+
768
+ ## 13. Hover Hints → the `data-hint` attributes (or `<HintTip>`)
769
+
770
+ **That little bar that appears when the pointer rests on your button/icon is not drawn by the browser.**
771
+
772
+ The host ships one unified light hint (`HintTip`): light/dark theme, UI scaling, edge flipping, and the
773
+ keycap look for shortcuts are all decided in one place by the shell. **You do not import anything** to use
774
+ it—write attributes:
775
+
776
+ ```tsx
777
+ // ❌ native title: drawn by the browser; theme/scaling/keycaps never follow the shell (red since SDK >= 0.1.49)
778
+ <button title={t("Refresh")}>
779
+
780
+ // ✅ attribute form: swap title= for data-hint= (zero DOM structure change)
781
+ <button data-hint={t("Refresh")} aria-label={t("Refresh")}>
782
+
783
+ // ✅ with a shortcut: give the command id and the shell looks it up (name + keys come from that one table,
784
+ // so the hint bar / context menu / command palette always say the same thing)
785
+ <button data-hint-command="fileTree.refresh" aria-label={t("Refresh")}>
786
+
787
+ // ✅ reveal kind ("see the whole truncated text"): it must appear at once, don't make it wait
788
+ <div data-hint={fullPath} data-hint-delay="0">{truncated}</div>
789
+
790
+ // ✅ composite cases (you want to control the wrapper): the component form
791
+ import { HintTip } from "@linkdesk/ui";
792
+ <HintTip label={t("Refresh")} command="fileTree.refresh"><button …>…</button></HintTip>
793
+ ```
794
+
795
+ Four attributes, all written on your own DOM elements:
796
+
797
+ | Attribute | What it does |
798
+ |---|---|
799
+ | `data-hint` | The hint text (explain and reveal kinds share it—**the text is always yours**; the shell never ships sentences) |
800
+ | `data-hint-command` | Command id—the shell reads name and shortcut from the command table. **Same source** as the context menu / command palette (change it once, everything follows) |
801
+ | `data-hint-delay` | Intent delay in ms. Explain kind: **leave the default** (120 ms—prevents a flash while sweeping past); reveal kind: pass `"0"` |
802
+ | `data-hint-placement` | Preferred side: `top`/`bottom`/`left`/`right` (default `top`; flips automatically when it does not fit) |
803
+
804
+ **⚠️ Three rules**
805
+
806
+ 1. **Explain kind waits, reveal kind does not**—"see the whole truncated text" must be immediate; a command
807
+ explanation for an icon is exactly the case that should pause a moment.
808
+ 2. **No more native `title=`**: the SDK leg `linkdesk/no-native-title` (SDK >= 0.1.49) marks it red—`lint`
809
+ prints a red row and `ci-verify` fails. For the rare form where the hint renderer cannot reach (the
810
+ legitimate exception), write `// eslint-disable-next-line linkdesk/no-native-title -- reason` (a **reason
811
+ is mandatory**).
812
+ 3. **No buttons inside the bar**: a hint is a hint, not a menu (use `<ContextMenu>` for interaction); for a
813
+ **long text / title / footnote** or multi-line explanation use `HintCard`—that component is the one that
814
+ owns "long explanations with a footnote".
815
+
816
+ > 🔧 **Maintainer note (authors may skip)**: renderer = `src/components/shared/hint-tip/HintTipRenderer.tsx`
817
+ > (a single mount in the pool: delegated `pointerover`/`pointerout`/`focusin`/`focusout` plus an intent-delay
818
+ > state machine); the single source of truth for the attribute literals is `hintAttrs.ts` (⛔ never write a
819
+ > `"data-hint"` literal anywhere else); the master switch is the shell config `app.hint.enabled` (default on,
820
+ > visible in settings); the gates are three legs — shell-side `scripts/check-native-title.mjs` (legacy
821
+ > white-list ledger, new sites only) and the SDK leg `checks/no-native-title.ts` (same id, pinned to each
822
+ > other by the three 锚⑪ anchor sentences).
823
+
824
+ ---
825
+
826
+ ## Quick Reference
827
+
828
+ | What you want to do | Core facility | How to bring it in |
829
+ |---|---|---|
830
+ | Context menu | `<ContextMenu>` (open-string menuId) | `@linkdesk/ui` (ContextMenu) + a `plugin.json contributes.menus` declaration (or `window.linkdesk.menu.registerItems`, see §1) |
831
+ | Overlay/dialog | `createPortal` | `react-dom` (render into `document.body`, see §2) |
832
+ | Persistence | `window.linkdesk.configuration.get/set/onChange` | plugin communication iron rule—only `window.linkdesk.*` (see §3) |
833
+ | System picker | `window.linkdesk.quickPick.show` | uniform rendering by the in-pool QuickPickHost (see §9) |
834
+ | Notifications | `window.linkdesk.notifications.show` | uniform rendering by the in-pool **bell wide notification panel** (see §9; semantics in `01-plugin-api-contract.md` §3.2) |
835
+ | Confirm/alert/file picker | `window.linkdesk.dialog.confirm/alert/open/openFile` | uniform rendering by the in-pool DialogHost (see §9) |
836
+ | Rich-content confirm | `window.linkdesk.dialog.confirmContent({ pluginId, viewId, payload })` | the in-pool DialogHost renders the shell, **the content = a plugin-drawn view** (see §9) |
837
+ | Shortcuts (non-text keys) | `plugin.json contributes.keybindings` | — (putting text keys here = swallowing the whole pool, see §4.1) |
838
+ | Shortcuts (text keys / focus-bound keys) | container `onKeyDown` + `tabIndex` | pool-side self-handling, see §4.2 (document/window keydown is forbidden) |
839
+ | Hover hints | `data-hint` / `data-hint-command` / `data-hint-delay` attributes (or `<HintTip>`) | just write them on your own DOM elements — **no import needed** (see §13; a native `title=` is red) |
840
+ | Colors | CSS variables | `var(--xxx)`, list in `src/index.css` |
841
+ | Font sizes | CSS variables | `var(--font-size-*)` + `--ui-scale`, bare px forbidden (gate, see §10) |
842
+ | Six-domain token overview | see the §11.1 matrix | color/surface/radius/glass/font size/font family—`var(--*)` follows theme+glass+scaling automatically; full list in `src/index.css` |
843
+ | UI discipline gate | `linkdesk-plugin-sdk lint` | all 15 items are WARNs that never fail; a knowing bypass = a standard eslint-disable declaration (see §11.2) |
844
+ | Text | `t()` | `useTranslation()` from `react-i18next` |
845
+ | CSS class names / state classes | own prefix + host reserved-name list | see §12 (class names are global—all plugins share the document with the host) |
846
+ | Element / id selectors | must hang under your own root class | see §12.6 (an anchorless selector hits everyone's elements, name or no name) |
847
+ | Sidebar list selection | `onMouseDown` (not `onClick`) | aligned with VS Code Explorer—prevents lost events when a fast click crosses elements |
848
+
849
+ **Use these facilities when writing plugins; don't hand-roll. Even if you write one, it'll have to be torn out later—better to normalize from day one.**