@linkdesk/plugin-docs 0.1.0

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.
Files changed (49) hide show
  1. package/README.md +58 -0
  2. package/docs/00-readme.md +189 -0
  3. package/docs/01-plugin-api-contract.md +171 -0
  4. package/docs/02-plugin-lifecycle.md +348 -0
  5. package/docs/03-contributes-spec.md +800 -0
  6. package/docs/04-distribution-format.md +172 -0
  7. package/docs/05-ui-conventions.md +549 -0
  8. package/docs/06-plugin-json-spec.md +640 -0
  9. package/docs/07-plugin-to-plugin-communication.md +299 -0
  10. package/docs/08-view-container-api.md +405 -0
  11. package/docs/09-plugin-directory-layout.md +301 -0
  12. package/docs/10-building-a-settings-plugin.md +164 -0
  13. package/docs/11-authoring-themes.md +173 -0
  14. package/docs/12-readme-media-contract.md +74 -0
  15. package/docs/13-development-guide.md +259 -0
  16. package/docs/14-data-pipeline-command-conventions.md +173 -0
  17. package/docs/15-multi-repo-and-local-workspace.md +86 -0
  18. package/docs/16-naming-conventions.md +77 -0
  19. package/docs/17-region-map.md +225 -0
  20. package/docs/18-cross-region-wiring.md +192 -0
  21. package/docs/19-component-cheatsheet.md +108 -0
  22. package/docs/20-adding-a-setting.md +159 -0
  23. package/docs/themes/01-build-a-theme-plugin.md +150 -0
  24. package/docs/themes/02-theme-field-index.md +145 -0
  25. package/docs/zh/00-README.md +189 -0
  26. package/docs/zh/01-/346/217/222/344/273/266API/345/245/221/347/272/246.md +171 -0
  27. package/docs/zh/02-/346/217/222/344/273/266/347/224/237/345/221/275/345/221/250/346/234/237.md +348 -0
  28. package/docs/zh/03-/346/217/222/344/273/266contributes/350/247/204/350/214/203.md +800 -0
  29. package/docs/zh/04-/346/217/222/344/273/266/345/210/206/345/217/221/346/240/274/345/274/217.md +172 -0
  30. package/docs/zh/05-/346/217/222/344/273/266UI/345/206/231/346/263/225/350/247/204/347/272/246.md +549 -0
  31. package/docs/zh/06-plugin.json/350/247/204/350/214/203.md +640 -0
  32. package/docs/zh/07-/346/217/222/344/273/266/351/227/264/351/200/232/344/277/241.md +299 -0
  33. package/docs/zh/08-ViewContainer-/350/247/206/345/233/276/345/256/271/345/231/250API.md +403 -0
  34. package/docs/zh/09-/346/217/222/344/273/266/347/233/256/345/275/225/350/247/204/350/214/203.md +301 -0
  35. package/docs/zh/10-/345/246/202/344/275/225/351/200/240/344/270/200/344/270/252/350/256/276/347/275/256/346/217/222/344/273/266.md +164 -0
  36. package/docs/zh/11-/344/270/273/351/242/230/345/210/266/344/275/234.md +172 -0
  37. package/docs/zh/12-README/350/257/264/346/230/216/345/214/272/345/252/222/344/275/223/345/245/221/347/272/246.md +74 -0
  38. package/docs/zh/13-/346/217/222/344/273/266/345/274/200/345/217/221/346/214/207/345/215/227.md +259 -0
  39. package/docs/zh/14-/346/225/260/346/215/256/347/256/241/351/201/223/345/221/275/344/273/244/347/272/246/345/256/232.md +173 -0
  40. package/docs/zh/15-/345/244/232/344/273/223/345/274/200/345/217/221/344/270/216/346/234/254/345/234/260/345/267/245/344/275/234/345/214/272.md +86 -0
  41. package/docs/zh/16-/345/221/275/345/220/215/350/247/204/350/214/203.md +77 -0
  42. package/docs/zh/17-/345/214/272/345/237/237/345/234/260/345/233/276.md +225 -0
  43. package/docs/zh/18-/345/214/272/345/237/237/351/227/264/344/272/222/345/212/250.md +192 -0
  44. package/docs/zh/19-/347/273/204/344/273/266/351/200/237/346/237/245.md +108 -0
  45. package/docs/zh/20-/346/210/221/347/232/204/346/217/222/344/273/266/345/212/240/344/270/200/346/235/241/351/205/215/347/275/256/351/241/271.md +159 -0
  46. package/docs/zh/plugin.schema.json +687 -0
  47. package/docs/zh//344/270/273/351/242/230/01-/345/201/232/344/270/200/344/270/252/344/270/273/351/242/230/346/217/222/344/273/266.md +150 -0
  48. package/docs/zh//344/270/273/351/242/230/02-/344/270/273/351/242/230/345/255/227/346/256/265/351/200/237/346/237/245.md +145 -0
  49. package/package.json +20 -0
@@ -0,0 +1,301 @@
1
+ # Plugin Directory Layout Spec
2
+
3
+ > 2026-08-05. **Official plugin template β€” a third-party developer looking at any official plugin sees the same directory structure.**
4
+ > **2026-09-06 reconciliation with the implementation** (audit): flattened single root (no plugins/{builtin,user}) Β· shared controls via @linkdesk/ui Β· distribution = .linkdesk-plugin zip. References to the corresponding mechanisms have been removed from this page.
5
+ > πŸ”₯ **2026-09-11 adds three things**: β‘  the **"line ceiling" column for each file category** (until now this doc only governed directory semantics and never said how big is too big β€” plugin size was effectively in a double blind spot where "neither the spec nor the gate cares"); β‘‘ **`hooks/` directory + `utils/` boundary details**; β‘’ **the path-mirroring semantics of `__tests__/` carved in stone**. **The mechanical enforcement of the ceilings = the size gate in `npm run check`** (the tables in this section are authoritative).
6
+
7
+ ---
8
+
9
+ ## Standard directory structure
10
+
11
+ ```
12
+ my-plugin/
13
+ β”œβ”€ plugin.json # plugin declaration β€” the only required file
14
+ β”œβ”€ icon.svg # plugin icon (optional) β€” root directory or resources/, declared by the plugin.json `icon` field
15
+ β”œβ”€ README.md # plugin readme β€” the data source for the "Details" tab of the details page (strongly recommended)
16
+ β”œβ”€ CHANGELOG.md # changelog β€” the sole source of truth for the "Changelog" tab of the details page (strongly recommended)
17
+ β”œβ”€ i18n/ # translation files β€” one JSON per language (optional)
18
+ β”‚ └─ en.json # key = original text, value = translation
19
+ β”œβ”€ resources/ # static assets β€” icons/fonts/images (optional β€” declared as relative paths, the shell resolves them)
20
+ β”‚ └─ icon.png
21
+ └─ src/
22
+ β”œβ”€ index.tsx # entry β€” export default React component (≀120 lines, thin facade)
23
+ β”œβ”€ views/ # page-level components β€” one per ViewContainer view (≀150 lines)
24
+ β”‚ β”œβ”€ MainView.tsx
25
+ β”‚ └─ SettingsView.tsx
26
+ β”œβ”€ components/ # reusable UI components β€” referenced by views/ or externally (≀150 lines)
27
+ β”‚ └─ Toolbar.tsx
28
+ β”œβ”€ hooks/ # React hooks β€” `use*` prefix, one hook per file (≀150 lines)
29
+ β”‚ └─ useToolbarState.ts
30
+ β”œβ”€ services/ # business logic β€” data models, state management, API wrappers (≀200 lines)
31
+ β”‚ β”œβ”€ model.ts
32
+ β”‚ └─ api.ts
33
+ β”œβ”€ utils/ # pure-function utilities β€” no side effects, no instance state (≀150 lines)
34
+ β”‚ └─ format.ts
35
+ β”œβ”€ styles/ # CSS files β€” one .css per view/component, never inline (≀300 lines)
36
+ β”‚ β”œβ”€ MainView.css
37
+ β”‚ └─ Toolbar.css
38
+ └─ __tests__/ # tests β€” same name as the file under test + .test suffix, same relative path
39
+ β”œβ”€ services/
40
+ β”‚ └─ model.test.ts
41
+ └─ views/
42
+ └─ MainView.test.tsx
43
+ ```
44
+
45
+ ## `README.md` / `CHANGELOG.md` β€” readme and changelog
46
+
47
+ > πŸ”₯ **2026-09-11**. **Previously this doc didn't mention these two files once**, so "add a readme / add a changelog" had **no authoritative yardstick**. This section is that yardstick.
48
+
49
+ ### Division of labor and readers
50
+
51
+ | File | Feeds | What happens if it's missing |
52
+ |:--|:--|:--|
53
+ | **`README.md`** | The **Details** tab of the plugin details page (Markdown rendering, supports images / video / external links β€” see [12-readme-media-contract](12-readme-media-contract.md)) | The details page is **left with a single `description` line** |
54
+ | **`CHANGELOG.md`** | The **Changelog** tab of the plugin details page | That tab shows **"This plugin ships no changelog"** |
55
+
56
+ ### Fixed location β€” plugin root, path never declared
57
+
58
+ Both live in the **plugin root directory** (alongside `plugin.json`), with **fixed filenames**. They are **not written into `plugin.json` and no field is consulted** β€” the reader loads the in-package file by **fixed filename**.
59
+
60
+ > πŸ”΄ **Why this is carved in stone**: `plugin.json` once had `readme` / `changelog` fields, but **nothing ever read them** (the reader reads the **filenames** `README.md` / `CHANGELOG.md` directly). Keeping them around = keeping a **deceptive way of writing things**. **Removed 2026-09-11** β‡’ **any "record the readme / changelog inside `plugin.json`" pattern you see is stale material.**
61
+
62
+ ### The `CHANGELOG.md` format convention
63
+
64
+ The SDK's `publish` slices sections out of it to fill catalog entries, so **the section-heading format is constrained**:
65
+
66
+ ```markdown
67
+ # Changelog ← document title (content is free-form)
68
+
69
+ ## v1.0.0 (2026-09-11) ← πŸ”΄ version section heading: `## v<version>`
70
+ - Fixed such and such
71
+ - Added some capability
72
+
73
+ ## v0.9.0 (2026-08-01) ← older versions below, newest on top
74
+ - …
75
+ ```
76
+
77
+ - **The section heading must yield a parseable version number** β€” `## v1.0.0…` / `## 1.0.0…` both work (the `v` is optional), and **the version number must be exactly equal to `plugin.json`'s `version`**.
78
+ - **Unparseable version number β†’ that version's catalog entry is left blank** (**honestly blank, never guessed**).
79
+ - **The date goes in parentheses on the heading line** (`(2026-09-11)`) β€” **display only**.
80
+ - **Body text outside the heading = that version's change notes** β€” the raw Markdown is copied verbatim, no second-pass parsing.
81
+ - **Versions in descending order** (newest on top) β€” the details page renders in this order.
82
+
83
+ ### πŸ”΄ The "one concept, one place" iron rule
84
+
85
+ > **There is no `changelog` / `readme` field in `plugin.json`, and there never will be.**
86
+ > The changelog goes **only** in `CHANGELOG.md`; the readme goes **only** in `README.md` β€” one thing has **exactly one home**.
87
+
88
+ This must be **written down explicitly**: the old pattern still lingers in old commits, old docs, and old plugins, and **if it isn't spelled out, the next person will copy it back in**.
89
+
90
+ ### Coupling with the version number
91
+
92
+ Changing the contents of `README.md` / `CHANGELOG.md` **= a content change = you must bump `plugin.json.version`** and rebuild the distribution artifact β€” an installed user's copy is **frozen by version**, and the app only fills in what's missing and never refreshes what's installed (see [04-distribution-format Β§4](04-distribution-format.md)).
93
+
94
+ **`version` is the anchor for four places**: the version number in the `CHANGELOG.md` section heading ↔ `plugin.json.version` ↔ the catalog entry `versions[].version` ↔ `package.json.version` β€” **all four share one source**.
95
+
96
+ > The fourth place (`package.json.version`) is newly included: now that plugin source lives in its own separate repo, `package.json` is the **first thing a newcomer (or an AI) sees** when opening the repo β€” two version numbers coexisting and disagreeing guarantees someone bumps the wrong one, while both the publish chain and the content-fingerprint gate read `plugin.json.version` β‡’ **bumping the wrong one = silently ineffective**. Mechanical backstop = `scripts/check-plugin-version-sync.mjs` (hooked into `npm run check`, with a negative control).
97
+
98
+ ---
99
+
100
+ **⚠️ The plugin source directory produces no build artifacts (Vite dev chunks are build-internal and never land in `dist/`).** The distributed artifact = a single-file `<id>.linkdesk-plugin` zip built with plugin-sdk (containing `index.bundle.js` + `views/*.bundle.js` + a rewritten plugin.json; once the loader detects `index.bundle.js` it uses the bundle as the entry) β€” authors need not care about build artifacts, only about the source structure above; distribution details in [04-distribution-format](04-distribution-format.md).
101
+
102
+ ## Source location and the distribution artifact
103
+
104
+ > πŸ”₯ **2026-09-14**. This section answers a question that had never been written down before: **which repo does the plugin source live in?** How to lay out the local directory and how to create the repo β†’ [15-multi-repo-and-local-workspace](15-multi-repo-and-local-workspace.md).
105
+
106
+ 1. **The source of truth for source code = the plugin's own repo** (`github.com/<owner>/<repo>`), **not the shell repo**. The shell repo's `plugins/` allows only two kinds of things: **fixtures** (demos that don't ship, e.g. `panel-demo`) and **build artifacts** (`bundled-plugins/<id>.linkdesk-plugin`).
107
+ 2. **The semantics of `bundled-plugins/<id>.linkdesk-plugin` in the shell repo = the seed snapshot used for factory shipping**, with its version accounted for by `bundled-plugins.lock.json`. It is **not a second copy of the source** β€” if the source changes you must change it back in the plugin repo, then run the publish chain to refresh the seed.
108
+ 3. **The chain from source to a user's desktop**: plugin repo β†’ `npm run build` β†’ `<id>.linkdesk-plugin` (zip) β†’ GitHub Release asset β†’ catalog entry β†’ user install. **Not one step passes through the shell repo.**
109
+ 4. **Plugin identity (id) is immutable forever**; the display name (`name`) can change; the repo name can change β€” the three-way rule and all naming criteria β†’ [16-naming-conventions](16-naming-conventions.md).
110
+ 5. **There is exactly one source of truth for the version number inside a plugin = `plugin.json.version`**. `package.json.version` is not the source of truth, but must equal it (the version number is "one source in four places" β€” see [16-naming-conventions Β§5.1](16-naming-conventions.md)).
111
+
112
+ **Reconciliation with the `publish` implementation** (the spec must not contradict the tool): the publish target repo = the project's git remote `origin` (`getCurrentRepoRemote` in `packages/plugin-sdk/src/publish.ts`; not a git repo / no origin β†’ immediate error); the catalog is written to the **repo-root `marketplace.json`** (read-modify-write via the Contents API); `readmeUrl` / `versions[].changelog` are filled in automatically by publish from the project-root `README.md` / `CHANGELOG.md`.
113
+
114
+ ---
115
+
116
+ ## Static assets and icons
117
+
118
+ **Icon location:** the plugin root or `resources/` β€” declared by the `icon` field of `plugin.json`. A bare string = the built-in icon set (codicon name / `iconSource:"lucide"` allowlist name), e.g. `"icon": "FolderTree"`; a path = a file relative to the plugin directory, e.g. `"icon": "resources/icon.png"` (the serial-monitor official usage).
119
+
120
+ > ℹ️ **Spec convergence**: new plugins put icons and media **in `resources/` across the board** (see [12-readme-media-contract Β§3](12-readme-media-contract.md)). "The root directory works too" is a **technical fact** (the shell resolves whatever relative path you declare), **not the recommended pattern** β€” official templates all use `resources/`; match them.
121
+
122
+ **Reading assets (author's view = declare a relative path, the shell resolves it):** every asset path appearing in plugin.json declaration fields (`icon` / `contributes.views[].render` / the `assets/...` in a theme recipe json) is written **relative to the plugin directory** β€” at load/render time the shell resolves it into an absolute URL under the current protocol via `getPluginAssetPath(pluginId, path)` (works for both dev `http://localhost:1420` and packaged `file://`). **Authors import no path utilities and hand-build no URLs** (hard constraint 12 forbids authors writing absolute path literals such as `/assets/...`, `/resources/...` β€” those all blow up under packaged file://; working in dev is just a coincidence).
123
+
124
+ ```
125
+ resources/
126
+ β”œβ”€ icon.svg # plugin icon β€” pointed to by the plugin.json icon field
127
+ β”œβ”€ logo.png # details page / marketplace banner image
128
+ └─ manual.html # bundled docs (pointed to by the `docs` field)
129
+ ```
130
+
131
+ ---
132
+
133
+ ## Theme plugin directory (themes/ + assets/ β€” flattening into the root is forbidden)
134
+
135
+ > A theme = a pure-data plugin (`contributes.themes` declaration + recipe json + assets) that usually **produces no `src/` code**. The authoritative directory spec: [11-authoring-themes](11-authoring-themes.md) Β§2 β“ͺ.
136
+
137
+ ```
138
+ theme-myglass/
139
+ β”œβ”€ plugin.json # contributes.themes declaration β€” recipe json paths point under themes/
140
+ β”œβ”€ themes/ # the only home for recipe json β€” flattening into the plugin root is forbidden
141
+ β”‚ └─ myglass.json
142
+ β”œβ”€ assets/ # fonts (woff2/ttf) + background images (png/jpeg/webp) β€” relative paths from the json
143
+ β”‚ β”œβ”€ MyFont.woff2
144
+ β”‚ └─ bg.png
145
+ └─ resources/ # plugin icon, etc. (the general convention above)
146
+ ```
147
+
148
+ | Directory | What goes in it | Rule |
149
+ |:--|:--|:--|
150
+ | `themes/` | recipe json (`appearance` + `colorways[]`) | **flattening into the root is forbidden**; pointed to by `contributes.themes[].path`; one plugin may hold multiple recipe json files |
151
+ | `assets/` | fonts / background images | write relative paths `assets/...` in the json β†’ resolved by the shell's `getPluginAssetPath`; absolute paths forbidden (hard constraint 12) |
152
+ | `resources/` | plugin icon | the general convention ("Static assets and icons" above) |
153
+
154
+ A theme author who ships `src/` (e.g. custom UI/scripts) follows the general structure β€” a pure-data theme has no `src/`.
155
+
156
+ ---
157
+
158
+ ## Criteria for each file category
159
+
160
+ > πŸ”₯ **2026-09-11 adds the "line ceiling" column**. **The ceilings are mechanically enforced by the size gate in `npm run check`** β€” the table in this section is the author's first-hand basis. **Over the ceiling means you must split** (via feature-folder, see below).
161
+
162
+ | Directory | What goes in it | What doesn't | Line ceiling |
163
+ |:--|:--|:--|--:|
164
+ | **views/** | page-level React components β€” with their own route or a ViewContainer entry | toolbar buttons, status bar items (β†’ components/) | ≀150 |
165
+ | **components/** | reusable UI components β€” stateless/weakly-stateful components referenced from multiple places | logic that touches the filesystem directly (β†’ services/) | ≀150 |
166
+ | **hooks/** | React hooks β€” `use*` prefix, **one hook per file** | components (β†’ components/), services (β†’ services/) | ≀150 |
167
+ | **services/** | business logic, data models, API wrappers | JSX rendering code (β†’ views/ or components/) | ≀200 |
168
+ | **utils/** | pure-function utilities β€” side-effect-free, UI/business-agnostic general functions (formatting/parsing/math) | stateful / side-effecting logic (β†’ services/); React hooks (β†’ hooks/) | ≀150 |
169
+ | **styles/** | standalone .css files β€” one per view/component | inline style (hand-writing it is forbidden β€” use CSS variables) | ≀300 |
170
+ | **resources/** | static assets β€” icons/fonts/images/docs (declared as relative paths, resolved by the shell) | modules that get imported (β†’ src/) | β€” |
171
+ | **`src/` root singletons** | cross-layer shared type definitions (`types.ts`) / constants (`constants.ts`) | modules with logic (β†’ their role folders) | ≀150 |
172
+ | **`src/index.tsx`** | plugin entry (thin facade, registers contribution points) | β€” | ≀120 |
173
+ | **__tests__/** | Vitest tests β€” `<file under test>.test.ts(x)` | test helpers (β†’ `__tests__/helpers/`) | unlimited (>1000 lines: split by `describe` group into multiple files in the same folder) |
174
+
175
+ πŸ”΄ **The table above covers directories you write yourself** (`views`/`components`/`hooks`/`services`/`utils`/`styles`). **Creating another top-level directory = the gate errors out on the spot** (fail-loud: "unknown role folder") β€” this isn't there to block you, it's there to **force you to state explicitly "what role is this and how many lines does it get"**. The honest move is to **register it** (e.g. serial-monitor's `cm6/` = a pure-logic CodeMirror domain, registered at the 150 tier), **not** to move code into `utils/` to fit the table. **Before adding this to the spec, think hard about whether it really is a new kind of thing.**
176
+
177
+ πŸ”΄ **`.css` is always 300, no matter which directory it sits in** β€” a component's co-located styles (e.g. `views/SettingsView.css`) and CSS under `styles/` are measured with the same ruler.
178
+
179
+ πŸ”΄ **Aggregator tier (ceiling Γ—2) β€” two forms**: what the facade looks like depends on whether it carries a "basename constraint".
180
+
181
+ | Form | What it looks like | Who uses it |
182
+ |:--|:--|:--|
183
+ | **(a) Loose facade beside the folder** | a folder `X/` **exists alongside** the file `X.ts(x)` | `views/` β€” the filename = `contributes.views[].render`, **renaming it changes the artifact** β‡’ the facade can only stay beside the folder and can only keep the original name |
184
+ | **(b) Entry inside the folder** | the path is **`<roleDir>/<Feature>/index.ts(x)`** | `services/` / `components/` / `hooks/` / `utils/` β€” the service/component name is not any declared field (**no basename constraint**) β‡’ the facade is the folder's entry, with no extra loose file left in the root |
185
+
186
+ Both forms count at this tier **Γ—2** (`views`/`components`/`hooks`/`utils`β†’300 Β· `services`β†’400). **This is a relaxed ceiling, not a target** β€” the facade should still be as thin as possible, and **must not contain pure logic** (pure functions / data transforms / types must sink into submodules).
187
+
188
+ > ⚠️ **Don't treat "a folder with the same name" as the only criterion** β€” when you create `services/foo/index.ts` + submodules under `services/`, **the gate recognizes it as an aggregator** (form b). Conversely, under `views/` **do not** rename the facade to `index.tsx` β€” that changes the name `render` points at.
189
+
190
+ > **Handling overruns**: use a **feature-folder (same-named folder = aggregator + submodules)** β€” the facade keeps its original path and filename (**zero changes to external imports**) and submodules go into the same-named folder. **Splitting into multiple flat files within the same domain is forbidden.**
191
+
192
+ > πŸ”” **Folder-width yellow light (threshold 12) β€” a reminder only, never blocking**: when **a folder's direct children (files + subfolders) exceed 12**, `npm run check` prints a notice (**`check` still goes green**). It doesn't stop you, it just forces you to **take a look + give a one-line reason**. **Don't create 3-file fragment folders just to clear the light** β€” that's worse than flat files. A very wide folder == often means two or three distinct functional domains are hiding inside, which is worth a read.
193
+ >
194
+ > πŸ“Œ **How to read the gate**: the closing line prints the currently effective tiers (`tier A … ; tier B plugins/<id>/src by role table Β· tier C entry ≀120`). **If the plugin tier is ever turned off, that line becomes `⚠️ Plugin tier disabled β€” the plugin domain is currently unguarded`** β€” so **whether the gate is on duty is visible from the output alone**, with no need to read the script.
195
+
196
+ ### Decision flow
197
+
198
+ ```
199
+ Does this file contain JSX/React rendering?
200
+ β”œβ”€ Yes β†’ Is it a page corresponding to one ViewContainer?
201
+ β”‚ β”œβ”€ Yes β†’ views/
202
+ β”‚ └─ No β†’ components/
203
+ └─ No β†’ Is it a React hook (`use*` prefix)?
204
+ β”œβ”€ Yes β†’ hooks/ (one hook per file)
205
+ └─ No β†’ Does it operate on data/state/files/network?
206
+ β”œβ”€ Yes β†’ services/ (has side effects)
207
+ └─ No β†’ Is it a pure function (stateless, side-effect-free)?
208
+ β”œβ”€ Yes β†’ utils/
209
+ └─ No β†’ Is it CSS?
210
+ └─ Yes β†’ keep it with the view/component it serves (co-located is legal),
211
+ otherwise put it in styles/. **The gate goes by extension
212
+ (always 300) and doesn't care which directory it's in**
213
+ β”œβ”€ Yes β†’ __tests__/
214
+ └─ No β†’ src/ (root, special cases)
215
+ ```
216
+
217
+ ### πŸ”΄ The `utils/` boundary with `services/` and `hooks/` (added 2026-09-11)
218
+
219
+ `utils/` takes **pure functions only** β€” no instance state, no side effects, no React. **Two mechanical criteria**:
220
+
221
+ - **Has instance state / has side effects** (holds a `Map`/`Set`/buffer, reads or writes disk, sends IPC, maintains a singleton) β†’ **does not go in `utils/`, goes in `services/`**.
222
+ - **Is a React hook (`use*`)** β†’ **does not go in `utils/`, goes in `hooks/`**.
223
+
224
+ > **Lesson from the field**: `serial-monitor/src/utils/` once held both `RingBuffer.ts` (**a stateful class**) and `useSendData.ts` (**a React hook**) β€” neither belonged in `utils/`. This boundary was never carved in stone before, so authors could only guess.
225
+
226
+ ### πŸ”΄ `__tests__/` paths and naming (made explicit 2026-09-11)
227
+
228
+ **`__tests__/` is a plugin-layer convention and is always used** β€” shell-layer tests follow the shell's own structure (`src/**/` co-located next to the shell code), and **plugins do not adopt co-location** (that is the shell-layer approach). Plugin tests use Vitest.
229
+
230
+ **Naming**: `<file under test>.test.ts(x)` β€” **inside `__tests__/` keep the same relative path as the file under test**:
231
+
232
+ ```
233
+ src/services/model.ts β†’ src/__tests__/services/model.test.ts
234
+ src/views/MainView.tsx β†’ src/__tests__/views/MainView.test.tsx
235
+ src/views/Detail/state.ts β†’ src/__tests__/views/Detail/state.test.ts
236
+ ```
237
+
238
+ **Line count**: test files **are not subject to the size gate** (the gate skips `__tests__/`) β€” fixtures are naturally long, so no ceiling applies; **but tests over 1000 lines get split by `describe` group into multiple files in the same folder**.
239
+
240
+ > ⚠️ **The easiest place to trip when migrating existing tests**: once a test file sits one level deeper, **every relative import changes** (`./model` β†’ `../../services/model`). **The symptom of missing one is Vitest silently skipping the file (`0 test`) rather than erroring** β€” after migrating, verify the total case count hasn't dropped.
241
+
242
+ ---
243
+
244
+ ## Special cases β€” things allowed in the `src/` root
245
+
246
+ - **`index.tsx`** β€” the plugin entry, which must live in the `src/` root
247
+ - **Highly cohesive single-file plugins** (≀3 files total) β€” subdirectories are not mandatory
248
+ - **Cross-layer shared type definitions** (e.g. `types.ts`) β€” in the `src/` root, imported by multiple subdirectories
249
+
250
+ ---
251
+
252
+ ## The `i18n/` translation directory
253
+
254
+ A plugin ships its own translation files, one JSON per target language. key = the original plugin UI string (using the author's native language is recommended), value = the translation.
255
+
256
+ ```
257
+ i18n/
258
+ β”œβ”€ en.json ← { "εœ¨ζ–‡δ»Άζ ‘δΈ­ζ˜Ύη€Ί": "Reveal in File Tree" }
259
+ └─ ja.json ← { "εœ¨ζ–‡δ»Άζ ‘δΈ­ζ˜Ύη€Ί": "フゑむルツγƒͺーで葨瀺" }
260
+ ```
261
+
262
+ **Declaration:** the `contributes.i18n` field of `plugin.json` declares the path of each language file:
263
+ ```json
264
+ "contributes": {
265
+ "i18n": { "en": "i18n/en.json", "ja": "i18n/ja.json" }
266
+ }
267
+ ```
268
+
269
+ **You don't need to write a fallback file for the author's native language** β€” a key with no translation is returned as-is by `parseMissingKeyHandler`: a Chinese plugin doesn't need a `zh.json`, and a pure-English or pure-French plugin likewise doesn't need a fallback file for English or French β€” the key is the original text, and a missing translation silently falls back to displaying the key itself.
270
+
271
+ **What gets translated:** `title`/`description` in `plugin.json` (for commands, settings, view container names) + UI strings passed to `t()` in `.tsx`.
272
+
273
+ **Language-switch behavior:** the shell automatically loads each plugin's `contributes.i18n` β†’ registers it into i18next β†’ takes effect immediately on a language switch, with no restart. Just call `t()` at render time; no `namespace` argument is required β€” translations are registered in the global `"translation"` namespace.
274
+
275
+ ---
276
+
277
+ ## Naming conventions
278
+
279
+ - **Filenames:** PascalCase (components), camelCase (non-components), kebab-case.css (styles)
280
+ - **Test files:** `<file under test>.test.ts(x)` β€” placed in `__tests__/`, **keeping the same relative path as the file under test** (see "`__tests__/` paths and naming" above)
281
+ - **CSS files:** same name as the component being styled β€” `MainView.tsx` β†’ `MainView.css`
282
+
283
+ ---
284
+
285
+ ## Compared with VS Code
286
+
287
+ VS Code extensions have no mandatory directory structure, but the official examples follow a similar convention:
288
+
289
+ | VS Code | LinkDesk |
290
+ |:--|:--|
291
+ | `src/extension.ts` | `src/index.tsx` |
292
+ | `src/commands/` | none β€” commands are registered in `index.tsx` |
293
+ | `src/views/` | `src/views/` β€” identical |
294
+ | `src/test/` | `src/__tests__/` β€” Vitest's double-underscore convention |
295
+ | `media/` | `src/styles/` β€” LinkDesk keeps everything under src |
296
+ | `package.nls.json` / `l10n/` | `i18n/` β€” LinkDesk keys are the original Chinese text and only target-language JSON is provided |
297
+
298
+ ---
299
+
300
+ > **← Previous chapter:** `08-view-container-api.md`
301
+ > **← Index:** `00-readme.md`
@@ -0,0 +1,164 @@
1
+ # How to Build a Settings Plugin
2
+
3
+ > 2026-08-22 Β· **2026-09-06 reconciliation with the implementation** (flattened single root + shared controls moved to @linkdesk/ui). **For third-party plugin authors.** Want your plugin to give users a "settings UI"? No shell changes needed β€” just declare a plugin with `factoryRole: "settings"`. This is **a complete replacement for the entire settings UI**, not one more settings item inside it.
4
+
5
+ ## What this is
6
+
7
+ **A settings plugin = a whole settings interface.** A plugin declaring `factoryRole: "settings"` coexists with the official settings plugin:
8
+
9
+ - The user opens settings (`Ctrl+,` / the gear icon) β†’ they land in the UI of the **currently active set** (never switched = the official set)
10
+ - Multiple sets can be installed β†’ each settings UI has a **shared area** at the top listing all N sets (including itself); click a set to switch to it
11
+ - The active-set choice is **persisted**, surviving restarts
12
+
13
+ Key mental model: **a settings plugin's UI is just a renderer; the data always lives in one place.** Every set's UI calls the same `window.linkdesk.configuration` API and sees the same data β€” switching sets only swaps the renderer, the data doesn't move. This isn't a "private vs. public data" distinction, it's about **consistency**: everyone sees the same thing.
14
+
15
+ ## Minimal declaration β€” three steps in plugin.json
16
+
17
+ Follow the official settings plugin (= the `plugin.json` in **the settings plugin's own repo**, `Encaron/linkdesk-plugin-settings`; the shipped plugin's source is no longer in the shell repo):
18
+
19
+ ```jsonc
20
+ {
21
+ "$schema": "../../public/schemas/plugin.schema.json",
22
+ "name": "Pretty Settings", // plugin name β€” this is what the shared-area button shows (goes through t())
23
+ "version": "1.0.0",
24
+ "icon": "resources/icon.png",
25
+ // omit core β€” uninstallable; core: true means the UI has no uninstall button (an anti-mistake-deletion flag, not a category)
26
+ "factoryRole": "settings", // β‘  the key β€” declares you are a member of the "settings set" family
27
+ "entry": "src/index.tsx", // tab entry (appearsIn.tabBar requires entry)
28
+ "appearsIn": { "iconBar": "bottom", "tabBar": true },
29
+ "tabBehavior": { "singleton": true }, // singleton β€” switching won't open a duplicate if it's already open
30
+ "contributes": {
31
+ "viewsContainers": {
32
+ "settings": { "title": "Settings", "location": "auxiliarybar" } // β‘‘ view container
33
+ },
34
+ "views": {
35
+ "settings": [
36
+ { "id": "settings", "title": "Settings", "render": "src/views/SettingsView.tsx", "order": 0 }
37
+ ]
38
+ },
39
+ "floatingPanel": { "viewId": "settings" } // β‘’ floating panel form (optional)
40
+ }
41
+ }
42
+ ```
43
+
44
+ All three key declarations are required: **`factoryRole: "settings"`** (puts you in the shared-area candidate list) + **`contributes.views`** (the actual render component) + **`floatingPanel`** (the `Ctrl+,` fallback form).
45
+
46
+ ## Data API shape β€” everything goes through `window.linkdesk.*`
47
+
48
+ Settings plugins are **forbidden from `import @src/core/...`** (the plugin communication iron rule + ESLint `noCoreImportInPlugin`). All data is in the public API:
49
+
50
+ | What you want | Call | Return shape |
51
+ |------|------|------|
52
+ | All configuration groups | `window.linkdesk.configuration.getConfigurationContributions()` | `[pluginId, { title, properties }][]` (named type `LinkDeskConfigurationContribution`) |
53
+ | Merged schema | `window.linkdesk.configuration.getSchema()` | `LinkDeskConfigSchema` β€” includes `type/default/description/enum/enumDescriptions` + **`uiHint`/`minimum`/`maximum`/`renderHint`/`dependsOn`** (type completions; the basis on which the official controls switch their colors) |
54
+ | Read/write/subscribe to configuration | `configuration.get/set/onChange` | the general API, usable by any plugin |
55
+ | Settings-page-specific refresh | `configuration.onDidChangeConfiguration(cb)` | config changes β†’ cb(key, value), UI refreshes live |
56
+ | Jump to a configuration group | `configuration.consumeSettingsGroup()` / `onRequestSettingsGroup(cb)` | switch groups on open |
57
+ | Scroll to a setting | `configuration.consumeScrollToSetting()` / `onRequestScrollToSetting(cb)` | scroll it into position on open |
58
+ | Keybindings page data | `window.linkdesk.keybindings.getKeybindings()` | `Keybinding[]` (the data source for the keybindings UI) |
59
+ | Theme picker | `window.linkdesk.commands.executeCommand("theme.pick")` | opens the theme QuickPick (two-stage: recipe β†’ colorway) |
60
+ | Language picker | `window.linkdesk.commands.executeCommand("workbench.action.selectLanguage")` | opens the language QuickPick |
61
+ | Plugin install/uninstall refresh | `window.linkdesk.configuration.onPluginLifecycleChange(cb)` | plugin installed/uninstalled β†’ cb, re-fetch candidates / button disappears |
62
+
63
+ **The `settings.json` filename constant is part of the data contract.** The official settings plugin's "Open as JSON" button locates the on-disk file like this:
64
+
65
+ ```ts
66
+ const dir = await window.linkdesk.path?.appDataDir?.();
67
+ const filePath = dir ? window.linkdesk.path.join(dir, "settings.json") : "";
68
+ ```
69
+
70
+ The filename is simply `settings.json`, with no shell-side map β€” copy it as-is.
71
+
72
+ ## Shared controls β€” `@linkdesk/ui`
73
+
74
+ A settings UI's shared controls live in the **`@linkdesk/ui`** package (consolidated there β€” third parties `npm i @linkdesk/ui` and import directly; **`import @src/core/...` is forbidden, and so is `@src/components/...`**):
75
+
76
+ `ContextMenu` Β· `InlineInput` Β· `SelectBox` Β· `Toggle` Β· `ColorPicker` Β· `FontFamilySelect` Β· `FilePathInput` Β· `NumberInput` Β· `Slider` Β· `Combobox` Β· `FormRow` Β· `SegmentedRadio` Β· `ThemePicker` Β· `PluginIcon` Β· shared hooks (`useDebouncedInput` / `useClipboardKeys`, etc.)
77
+
78
+ ```tsx
79
+ import { InlineInput, SelectBox, FormRow } from "@linkdesk/ui";
80
+ ```
81
+
82
+ > The official settings implementation (`src/views/SettingsView.tsx`, in the settings plugin's own repo) imports from `@linkdesk/ui` β€” copy the import line as-is, no extra project configuration needed.
83
+
84
+ ## The composition layer is free-form β€” same data, laid out however you like
85
+
86
+ The data API only determines "what data exists"; **the layout is your free play**. Current references:
87
+
88
+ - **Official settings** (repo `Encaron/linkdesk-plugin-settings`, core:true) = group tree on the left + form on the right + a flat switch bar on top β€” the only settings set in service right now (the old `settings-demo` reference implementation has been retired; for composing from scratch see approach 1/2 below)
89
+ - Your own settings set can be arranged however you like: banner header + card sections (every configuration group = a card, with a role pill row + keycap cards for keybindings) + a bottom-right pill for switching sets β€” all fine (the design source for form two = the factory-role coexistence mockup `01-ε½’ζ€δΈ€ε½’ζ€δΊŒ-ε€ζ‚εœΊζ™―ε›Ύ.html`)
90
+
91
+ Composition dimensions: group navigation / search box / control rendering / "Open as JSON" / the keybindings subpage / banner header / card sections β€” each of these can be built, skipped, or moved.
92
+
93
+ ## Switching the active set β€” shared-area buttons + whole-plugin-side set switching
94
+
95
+ Each settings plugin's top shared area renders **buttons for all N sets (including itself)**, with the active set highlighted. Clicking to switch = **whole-plugin-side set switching** with zero shell changes:
96
+
97
+ ```ts
98
+ async function handleSettingsSwitch(targetId: string) {
99
+ await window.linkdesk.factorySlots.setActive("settings", targetId); // β‘  persist to disk
100
+ if (tabId) {
101
+ // β‘‘ tab form: close this set's tab β†’ open the target set (singleton dedup focuses it if it already exists)
102
+ await window.linkdesk.tabs.close(tabId).catch(() => {});
103
+ await window.linkdesk.tabs.create(targetId).catch(() => {});
104
+ } else {
105
+ // β‘’ floating panel form: switch in place β€” candidate viewId composite addressing, the shell replaces the panel content compositely
106
+ const target = settingsCandidates.find((c) => c.pluginId === targetId);
107
+ if (target?.viewId) {
108
+ await window.linkdesk.panel.revealFloating(target.viewId, target.pluginId).catch(() => {});
109
+ } else {
110
+ await window.linkdesk.tabs.create(targetId).catch(() => {}); // no floating panel declared β†’ fall back to opening a tab
111
+ }
112
+ }
113
+ }
114
+ ```
115
+
116
+ The component receives `tabId` in its `{ isActive, tabId }` props (injected by the shell; `undefined` for a floating panel with no tab β†’ takes the floating-panel switch-in-place branch). `settingsCandidates` comes from `factorySlots.list("settings")` β€” each candidate carries a `viewId` (that set's `contributes.floatingPanel.viewId`, used for composite addressing when switching in place). The optional pluginId on `panel.revealFloating(viewId, pluginId?)` was added later β€” when two sets with the same viewId coexist, passing pluginId hits the target set precisely.
117
+
118
+ The number of shared-area buttons is **derived from the live set at runtime** β€” delete any set β†’ `onPluginLifecycleChange` β†’ re-fetch β†’ the button disappears automatically.
119
+
120
+ ## Approach 1: Copy the official plugin (fastest)
121
+
122
+ Copy the official settings plugin's directory (repo `Encaron/linkdesk-plugin-settings`) wholesale into your project root and change only:
123
+
124
+ 1. `plugin.json` β€” `name`/`description`; **remove `core: true`** (otherwise the UI has no uninstall entry point); for new UI copy see the i18n section below
125
+ 2. Append your own style to `src/views/SettingsView.css` β€” **but override rules must hang off your own root class**, see "πŸ”₯ CSS scoping iron rule" below
126
+
127
+ The official settings plugin has **zero `@src/core` imports** (two historical `@src/core` dependencies were eliminated along the way: `getFilePath` β†’ self-derived from `path.appDataDir`; `useConfigurationIpc` β†’ calls `window.linkdesk.configuration.*` directly), so a copy is self-contained.
128
+
129
+ ## Approach 2: Compose from scratch (an entirely different canvas)
130
+
131
+ Don't copy the official settings plugin's component structure β€” **the components depend only on the data API + `@linkdesk/ui` shared controls, and the layout is entirely yours**: banner header, card grid, role pill row, keycap cards for keybindings, a floating pill in the bottom-right β€” arrange them however you want (data API shapes in the table above, controls in the "Shared controls" section).
132
+
133
+ > Reference path: `src/views/SettingsView.tsx` in the official settings plugin repo is a minimal settings-set skeleton; for an entirely different canvas, write your own `SettingsView.tsx` from scratch and point `contributes.views[].render` at it.
134
+
135
+ ## πŸ”₯ CSS scoping iron rule
136
+
137
+ **Two settings sets' CSS is injected into the same Pool document.** If your override rules use bare shared classes (e.g. `.settings-form .settings-row`, `.settings-role-switch--gen`), they will fight the official set's rules of the same kind β€” last injected wins, and the official set gets polluted by your styles (bug 2 measured on real hardware: the demo's card bubbles leaked into the official set β€” the lesson still stands).
138
+
139
+ The structural fix = **your own dedicated root-class namespace** (use your own pluginId, e.g. `.my-settings`):
140
+
141
+ - Put a dedicated class on the root element (`.my-settings`) and hang every override/rule you add off it: `.my-settings .settings-row { ... }`
142
+ - Rules then match only your own subtree β†’ the official set is unaffected; and you get "style self-containment" for free (whether the official set's CSS loads or not doesn't affect you)
143
+ - Prefix your own new component classes too (`.ms-*`); don't use bare names (`.keycap` must also hang off `.my-settings .keycap`)
144
+
145
+ ## New i18n copy (the i18n audit gate)
146
+
147
+ New UI copy goes through `t("<original Chinese text>")`; the i18n audit in `npm run check` requires **every new key to have an English translation**, otherwise it goes red. A settings plugin just declares its translation file in `contributes`:
148
+
149
+ ```jsonc
150
+ "contributes": {
151
+ "i18n": { "en": "i18n/en.json" },
152
+ // ...
153
+ }
154
+ ```
155
+
156
+ `i18n/en.json` = `{ "δΈ­ζ–‡εŽŸζ–‡": "English" }` (zh isn't needed β€” Chinese keys have a built-in fallback).
157
+
158
+ ## Verification
159
+
160
+ - `npm run check` all green (tsc + ESLint zero warnings + vitest)
161
+ - On real hardware: run `npm run dev` in **your own project root** (or build a zip and install it into `{userData}/plugins`) β†’ restart β†’ the icon bar shows up β†’ open settings β†’ the shared area shows the new button β†’ click to switch β†’ persistence survives a restart
162
+ - Uninstallable and reinstallable (uninstallable β‡’ reinstallable = the very definition of plugin-ness)
163
+
164
+ > Reference implementation: repo `Encaron/linkdesk-plugin-settings` (the core:true official settings set, whose UI has no uninstall entry point).