@linkdesk/plugin-docs 0.1.60 → 0.1.61

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.
package/docs/00-readme.md CHANGED
@@ -25,6 +25,7 @@
25
25
  | **Build a theme** (no code) | [themes/01-build-a-theme-plugin](themes/01-build-a-theme-plugin.md) | → [themes/02-theme-field-index](themes/02-theme-field-index.md) |
26
26
  | **Add a setting to my plugin** | [20-adding-a-setting](20-adding-a-setting.md) | → [03-contributes-spec](03-contributes-spec.md) |
27
27
  | **Let AI / keybindings / the Command Palette operate my plugin** | [21-command-ification-spec](21-command-ification-spec.md) | → [03-contributes-spec §3.1](03-contributes-spec.md) (every `commands` field) |
28
+ | **Add an item to a menu (context menu / gear / hamburger)** | [22-menu-contribution-points](22-menu-contribution-points.md) | → [21-command-ification-spec](21-command-ification-spec.md) (make it a command first) |
28
29
  | **Make several regions work together** (sidebar selection → main area switch → status bar update) | [18-cross-region-wiring](18-cross-region-wiring.md) | → [07-plugin-to-plugin-communication](07-plugin-to-plugin-communication.md) |
29
30
  | **Look up the API** (what can I call) | [01-plugin-api-contract §3](01-plugin-api-contract.md) (the entry table for the three API surfaces) | → the SDK package README cheatsheet / `linkdesk.d.ts` |
30
31
  | **Use the UI parts the shell provides** | [19-component-cheatsheet](19-component-cheatsheet.md) | → [05-ui-conventions](05-ui-conventions.md) |
@@ -179,6 +180,7 @@ Full story → [04-distribution-format §Listing Is Two Steps](04-distribution-f
179
180
  | **19** | **[19-component-cheatsheet](19-component-cheatsheet.md)** | **Which UI parts the shell provides**, and when to use which |
180
181
  | **20** | **[20-adding-a-setting](20-adding-a-setting.md)** | The minimal approach: declare one → it appears on the settings page automatically → read it in code |
181
182
  | **21** | **[21-command-ification-spec](21-command-ification-spec.md)** | **Let AI/keybindings/the Command Palette operate my plugin** — how to turn actions into commands, plus the author checklist |
183
+ | **22** | **[22-menu-contribution-points](22-menu-contribution-points.md)** | **Put an action into one of the host's menus** — the 14 slots, the `group`/`when` conventions, and the public context-key table |
182
184
  | **T1** | **[themes/01-build-a-theme-plugin](themes/01-build-a-theme-plugin.md)** | The theme-authoring walkthrough (no code) |
183
185
  | **T2** | **[themes/02-theme-field-index](themes/02-theme-field-index.md)** | A cross-index of recipe fields and CSS variables |
184
186
 
@@ -94,7 +94,7 @@ async function list(): Promise<FileEntry[]> {
94
94
  | **notifications** | **The only notification surface is the wide status bar bell panel** (the narrow bottom-right toast path was deleted wholesale) — no cards popping up, no focus stealing, no blocking; the unread count increments and the user only sees it after clicking. **Don't treat it as a "must be seen" channel**: when the user has to decide right now → `dialog.confirm`. **`show` always returns a handle** (`{ update, finish, cancel }` — **and not only when `progress:true`**); **a notification can only be updated/removed by the handle that created it**, and a `show` with the same text elsewhere = a different notification. `progress:true` turns on a real progress bar: `update(msg, percent?)` gives a determinate 0-100 bar, while omitting percent = an indeterminate animation; `finish(msg?)` closes it and optionally adds a completion notification; `cancel` just closes it with nothing added. `persistent:true` = stays put and doesn't auto-dismiss (for error diagnostics), waiting for the user to click ×. **The persistent quota is bucketed by `source`, 5 each**; overflow evicts the oldest from that same source and shows a summary hint (persistent ≠ archived — write your own file if you want a record). `source` = **the machine-read attribution key, containing no human copy** (the shell resolves the human-readable name) — ⚠️ **it cannot be injected automatically**: the pool is a single-process shared realm and all plugins share one `window.linkdesk`, so the preload has no way to know which plugin's tree issued this `show` ⇒ **only the author can explicitly report their own plugin id** (the shell's own domains use `app.<domain>`); **omit it → everything lands in the "Other" group**. `actions` clicks go through the shell's `executeCommand(command, args)`, with the handler self-registered by the plugin |
95
95
  | **dialog** | `confirm`/`alert`/`open`/`openFile` = shell-rendered modal dialogs (they take focus, with a focus lock). **`confirmContent(options)`** = **rich-content confirmation** — the dialog is still the shell (centered/scrim/Esc/focus lock/click-scrim-to-cancel) while **the content = a plugin-drawn view** (`pluginId` + `viewId` declarative addressing + an opaque `payload`, matching VS Code's "the dialog is the shell, the content is the plugin's"). **How the content side reads it**: once the view mounts, get data through `dialogHost.current?.content?.payload` (`open !== true` → `null`, defensive so you don't get a blank screen); **there are only two settlement paths, `dialogHost.confirm` / `dialogHost.cancel`** (don't close the dialog yourself — the shell won't recognize it). **The fallback is hard**: if `viewId` can't be resolved (undeclared / declaring plugin not installed) → the shell **falls back to a plain text confirmation** (using `title`/`message`); the dialog still appears and never dies silently ⇒ so don't omit `title`/`message`. `payload` crosses IPC by structured clone ⇒ only cloneable data can go in it |
96
96
  | **search** | Full-text search/replace — `searchFiles(opts)` is a single call-and-response executed by the shell/main process over IPC (zero local scanning on the plugin side); the request/result shapes follow the contract's `SearchWireOptions`/`SearchWireResult` |
97
- | **encoding** | The encoding detect/convert trio (handled by the main process EncodingService): `detect(buffer)` guesses the encoding name / `decode(buffer, encoding)` bytes→text / `encode(text, encoding)` text→bytes — `Uint8Array` in and out |
97
+ | **encoding** | The encoding detect/convert quartet (handled by the main process EncodingService): `detect(buffer)` guesses the encoding name / `decode(buffer, encoding)` bytes→text / `encode(text, encoding)` text→bytes / `isBinary(buffer)` decides whether the bytes are binary (`Promise<boolean>`) — `Uint8Array` in and out. **Binary detection belongs to the shell, a single source of truth**: a plugin that reads a file and intends to render it as text asks `isBinary` before calling `decode` instead of guessing from the extension (extensions lie, content does not). `isBinary` is a **later addition**: older hosts don't have it, so feature-detect before calling (`lk.encoding?.isBinary`) and fall back to the plain-text path when it is missing |
98
98
  | **update** | **Read-only update state**: `getState()` returns the host's full update state-machine snapshot (a nine-state discriminated union — `uninitialized`/`disabled`/`idle`/`checking`/`available`/`downloading`/`downloaded`/`updating`/`ready`; the payloads follow the contract's `UpdateState`); it **never throws** (the service always has a state). For "About"-style plugins to display version/update progress — **read-only**: triggering download/install is the shell's own business (the host's `update.*` command segment; plugins don't add commands to it) |
99
99
 
100
100
  **Shell broadcast events (plugins can subscribe via `events.on`):**
@@ -793,6 +793,28 @@ useEffect(() => {
793
793
 
794
794
  > **The `pluginId` is declared by the top-level `pluginId` field** (it must be written explicitly; do **not** write it under `contributes`). When it is not declared it falls back to "the project directory name" — the fallback path is kept only for legacy third-party plugins outside the repo, and **new plugins always declare it explicitly** (directory names and repository names are free-form, so relying on the fallback means your identity drifts with the name, and none of the five consequences reports an error). See [16-naming-conventions](16-naming-conventions.md).
795
795
 
796
+ #### Once you hold an associated file: check for binary before deciding how to display it
797
+
798
+ `fileAssociations` only answers "this extension is yours" — it does **not** promise the file's contents are text. A pdf, an image, an archive can all land in your hands. The shell has already done the detection for you: once you have read the bytes as a `Uint8Array`, ask `lk.encoding.isBinary(buffer)` first. If it says true, don't force a text rendering — `decode` would only produce garbage, and the user will think your plugin is broken.
799
+
800
+ ```ts
801
+ const buffer = await lk.filesystem.readBinaryFile(path);
802
+ // Detection belongs to the shell (one source of truth); older hosts lack this
803
+ // surface, so feature-detect and fall back to the plain-text path.
804
+ const probe = lk.encoding as { isBinary?: (b: Uint8Array) => Promise<boolean> };
805
+ const isBinary = typeof probe.isBinary === "function" ? await probe.isBinary(buffer) : false;
806
+ if (isBinary) {
807
+ // Render your own "can't show this as text" placeholder — don't splash garbage at the user.
808
+ return;
809
+ }
810
+ const text = await lk.encoding.decode(buffer, await lk.encoding.detect(buffer));
811
+ ```
812
+
813
+ - **Detection belongs to the shell — don't build a second one**: `isBinary` samples the file header heuristically (including BOM and UTF-16 special cases). Extensions lie, content does not — the criterion lives in exactly one place.
814
+ - **Degrade on older hosts**: `isBinary` is a later addition that older hosts do not have. Write it as a feature probe (the `lk.encoding?.isBinary?.` form) and fall back to today's plain-text path when it is missing — the garbling is unchanged, but that is the older host's existing behaviour, not something your plugin just introduced.
815
+ - **Draw the notice yourself**: both the placeholder and the way out are drawn by your plugin (the shell does not pre-build a "binary notice" component — no shared UI is frozen before a second real consumer exists). Give the user a path forward: point them at a plugin that can handle the file, or say in the notice what the file should be opened with.
816
+ - **Don't let a save destroy the file**: when a file is binary, don't allow saving — one save would rewrite the original bytes as UTF-8 text and corrupt the binary file on the spot.
817
+
796
818
  ### 3.14 `statusBar` — status bar entries (a top-level field)
797
819
 
798
820
  ```json
@@ -113,7 +113,7 @@ The `entry` field → the loader automatically recognizes this as a view plugin.
113
113
  | `contributes.keybindings` | — | registered into KeybindingRegistry → global keyboard listening |
114
114
  | `contributes.themes` | theme | registered into ThemeRegistry → theme browser |
115
115
  | `contributes.languages` | language | registered into LanguageRegistry |
116
- | `contributes.fileAssociations` | — | registered into FileAssociationService → double-clicking a file opens it automatically |
116
+ | `contributes.fileAssociations` | — | registered into FileAssociationService → double-clicking a file opens it automatically; an entry may declare `role` (e.g. `"text-fallback"`, see below) |
117
117
  | `contributes.floatingPanel` | — | Declares that the view can be displayed in a floating panel inside the shell — viewId references an already-registered view; without the declaration there is no "Open in Floating Panel" context-menu item; optional `defaultForm`/`formKey` fix or offer the **first-open form** |
118
118
 
119
119
  **A plugin can declare several contributions at once.** A view plugin, for example, can have `entry` + `sidebar` + `statusBar` + `contributes.configuration` + `contributes.commands` — each is registered independently and does not affect the others.
@@ -634,6 +634,54 @@ function CadView() {
634
634
  }
635
635
  ```
636
636
 
637
+ #### contributes.fileAssociations — file associations and role declarations
638
+
639
+ Declares "which extensions' files are opened by me". When the user double-clicks such a file (or opens it from the file tree or the command line), the shell routes it to your plugin per this table and opens it in **your** tab.
640
+
641
+ ```json
642
+ {
643
+ "contributes": {
644
+ "fileAssociations": [
645
+ { "extension": "dxf", "displayName": "CAD drawing" },
646
+ { "extension": "stl", "command": "cad.importStl" }
647
+ ]
648
+ }
649
+ }
650
+ ```
651
+
652
+ | Field | Required | Notes |
653
+ |:--|:--:|:--|
654
+ | `extension` | ✅ | Extension — **without the dot** (`dxf` / `ts`); case-insensitive (the shell lower-cases it) |
655
+ | `command` | — | Which of your commands to run on open; omit to use the framework's default open action |
656
+ | `displayName` | — | The name shown in the "Open with…" picker |
657
+ | `role` | — | **Role declaration** (see below). The first version defines only `"text-fallback"` |
658
+
659
+ **Several plugins may declare the same extension** (your `ts` coexists with someone else's `ts`) — the shell does not pick a winner for you; the user picks from "Open with…", and the default is **whichever plugin activated first**. So declaring is **not** a takeover; it means "I can open it too".
660
+
661
+ ##### `role` — how to become the default text editor
662
+
663
+ The shell **does not know, and must not know, any plugin id** (iron law ② of the shell) — "when no plugin declares a file's kind, which tab should open it" is answered by plugins **self-declaring a role**:
664
+
665
+ ```json
666
+ {
667
+ "contributes": {
668
+ "fileAssociations": [
669
+ { "extension": "txt", "role": "text-fallback" },
670
+ { "extension": "ts", "role": "text-fallback" },
671
+ { "extension": "json", "role": "text-fallback" }
672
+ ]
673
+ }
674
+ }
675
+ ```
676
+
677
+ - **`role` attaches to the entry** (each entry carries its own — which is also why **an entry must carry `extension`**), but it is **recorded per plugin**: declaring 45 entries with `"text-fallback"` still makes you **one** holder (you cannot crowd ahead of others by sheer entry count).
678
+ - **The badge is a nomination, not a takeover.** The order in which the shell resolves "who should open this" is **① user override table → ② plugins declaring that extension (activation order, ties broken by pluginId lexicographically) → ③ the text-fallback holder (this role) → ④ none of the above ⇒ the shell's prompt page**.
679
+ - ⇒ **You never have to guess anyone's name**: to take over the text fallback slot, declare `role: "text-fallback"`; installing a second holder **never silently drifts** the current default (it merely joins the candidates, and the user can pick explicitly).
680
+ - ⇒ **Uninstalling all holders** is safe too: the file has no owner and no fallback ⇒ the shell shows its prompt page and ⛔ never hands you the id of a plugin that does not exist.
681
+ - ⚠️ **Binary files are not yours**: whether a file can be read as text is judged by **the shell** (`EncodingService.isBinary`, a single source of truth), while which extensions are yours is decided by **your declaration** — ⛔ do not add `pdf` / `jpg` to your list to grab the reader plugins' turf.
682
+
683
+ > To show/hide a **context menu** item by extension (e.g. "only for `.md`"), read the public context keys `resourceExtname` / `resourceIsFile` — see [22-menu-contribution-points](22-menu-contribution-points.md).
684
+
637
685
  ---
638
686
 
639
687
  ### The `tabBehavior` field
@@ -118,6 +118,7 @@ The table below is **reconciled name by name** against it (gate `scripts/check-r
118
118
  | Host appearance sentinel | `followTheme` | The "follow the theme" sentinel of a mix source — **it is not an id**, so don't try to shadow it with a plugin id |
119
119
  | Host-only context key (plugins **must not** set) | `activeEditor`、`editorCount`、`editorHasSelection`、`inputFocus`、`settingsActiveIsBuiltin`、`settingsSlotFilled`、`sidebarPosition`、`updateActionable`、`updateButtonLabel` | Set one of these at runtime over IPC and the host logs a `console.error` **naming you** (the value is still written: these are state, not registrations, so the runtime cannot tell who came first) |
120
120
  | Shared-contract context key (plugins **may** set) | `settingKey`、`settingFollowTheme`、`settingModified`、`settingResetsToDefault`、`settingHasTitle` | These five are a **public contract**: the official `settings` plugin writes them, host commands read them in `when` clauses — use them as specified, don't change their meaning (`settingHasTitle` = the row declared a `title`; it gates the gear item "copy setting name") |
121
+ | Shared-contract context key (plugins **may** set) | `resourceExtname`、`resourceIsFile` | **File-context public keys** (added 2026-10-05): the writer is the official `file-tree` (injected on right-click for the target node), and the readers are **any plugin's menu `when`** — `resourceExtname` is the **lowercase extension including the dot** (`.md`), `resourceIsFile` is a boolean. ⚠️ With no file context (right-click on a root node or on empty space) both are **undefined** — don't test against an empty string (in `when`, treat "undefined" as "does not match"). See the "Menu contribution points" guide |
121
122
 
122
123
  **How to check yourself** (from your own repo): once `@linkdesk/plugin-sdk` is installed, your repo's `verify` runs four ownership legs (command ids / config keys / appearance ids / context keys); whichever one you violate is reported with its location plus the suggested fix, **"should start with `<pluginId>.`"**.
123
124
 
@@ -0,0 +1,237 @@
1
+ # 22 — Menu contribution points (put your action into one of the host's menus)
2
+
3
+ > 🌐 **中文版(维护者面)→ [../03-插件制造/22-菜单贡献点.md](https://github.com/Encaron/linkdesk/blob/electron/docs/03-插件制造/22-菜单贡献点.md)**
4
+ >
5
+ > 2026-10-05 · **In one line**: **you declare "which slot, under what condition, running which command" in `plugin.json`** —
6
+ > the host changes no code for you, and you import no host module (**strings are the contract**).
7
+ > This page is a **spec plus an author self-check**; the per-field schema lives in [06-plugin.json-spec](06-plugin-json-spec.md),
8
+ > the discipline of turning actions into commands in [21-command-ification-spec](21-command-ification-spec.md),
9
+ > and command-id ownership in [16-naming-conventions](16-naming-conventions.md) §7.
10
+
11
+ ---
12
+
13
+ ## 1. Minimal working example (three things must hold at once)
14
+
15
+ ```json
16
+ {
17
+ "contributes": {
18
+ "commands": [
19
+ { "id": "my-plugin.exportMd", "title": "Export as HTML" }
20
+ ],
21
+ "menus": {
22
+ "fileContext": [
23
+ { "command": "my-plugin.exportMd", "when": "resourceExtname == '.md'", "group": "1_navigation" }
24
+ ]
25
+ }
26
+ }
27
+ }
28
+ ```
29
+
30
+ | # | Condition | What happens when it fails |
31
+ |:--:|:--|:--|
32
+ | ① | The command is **declared** in `contributes.commands` | The item renders but does nothing when clicked (rendering uses the command's `title`; running uses its handler) |
33
+ | ② | The slot id is a **value** (`fileContext`), not a member name (`FileContext`) | It **silently disappears**: the host registry has no such key and nothing errors. The `check-menu-slot-case` gate catches exactly this case (differing only in letter case) |
34
+ | ③ | The `when` expression evaluates to true | The item is hidden (an unparseable `when` is treated as "do not show" — the safe side) |
35
+
36
+ After editing `plugin.json`, **reactivate the plugin** (restart the app, or disable and enable it) — contributions are read at activation.
37
+
38
+ ---
39
+
40
+ ## 2. Slots (MenuId): the 14 host registration points
41
+
42
+ The slot id is the **key** in `contributes.menus`; the value is the **value** of a host `MENU_SLOTS` constant (lower camelCase).
43
+
44
+ | Slot value | Where it appears | Common `when` keys | Notes |
45
+ |:--|:--|:--|:--|
46
+ | `commandPalette` | The Ctrl+Shift+P command palette | — | ⚠️ **No host renderer reads it today**: palette entries come from `contributes.commands` (filtered by each command's own `when`), so items you post here are invisible — treat it as a **reserved slot** |
47
+ | `tabContext` | Right-click on a tab in the tab bar | — | The host posts its own "close / close others / pin…" items here; yours merge with them |
48
+ | `panelViewContext` | Right-click on the bottom panel's tab strip | — | The position/alignment submenus and the view-visibility list are injected dynamically by the host |
49
+ | `editorContext` | Right-click inside a tab's **content area** (terminal receive area, editor…) | — | Aimed at "the thing currently open", not at a file |
50
+ | `extensionGear` | The bottom gear menu (global action entry) | — | Always visible to the user — use sparingly |
51
+ | `marketplaceItemGear` | The gear on **each entry** in the plugin marketplace | — | Per-plugin actions (enable/disable/uninstall are the host's own items) |
52
+ | `menuBar` | The ☰ hamburger menu bar | — | Items with `group: "panel"` merge into the hamburger's "Panel" group (see §4) |
53
+ | `panel` | The hamburger's "Panel" group (dedicated slot) | — | Equivalent to the row above with `group:"panel"` — pick one |
54
+ | `fileContext` | Right-click on a node in the file tree | `resourceExtname` · `resourceIsFile` | The main battleground for "show by extension", see §5 |
55
+ | `cardContext` | Right-click on a card | — | — |
56
+ | `quickSendContext` | Right-click on the quick-send pill | — | — |
57
+ | `iconBar` | Right-click on the icon bar | — | — |
58
+ | `settingItemGear` | The hover gear on **each row** of the settings page | `settingKey` · `settingFollowTheme` · `settingModified` · `settingResetsToDefault` · `settingHasTitle` | These five are the settings-row public contract keys, see §5 |
59
+ | `viewTitleContext` | Right-click on a sidebar/right-sidebar **view title** | — | Collapse/expand/hide/reset-position are posted by the host |
60
+
61
+ **A `—` in the "Common `when` keys" column is not "no keys exist"** — it means there are no **public contract** keys there.
62
+ In those slots you can only use host-only flags (`activeEditor` and friends: **read-only, plugins must not set them**)
63
+ or your own `<pluginId>.*` flags.
64
+
65
+ > The "Where it appears" column is taken from the host's `MENU_SLOTS` constant table (the host's **intent**) —
66
+ > if a live reading disagrees, trust the live reading and tell us.
67
+
68
+ > 🔴 **`MenuId` is an open string**: you may invent a slot id of your own (say `my-plugin.palette`) and nothing errors —
69
+ > but **no renderer will read it** unless your own plugin does (`menu.getItems("my-plugin.palette")`).
70
+ > Posting into a host slot makes your item appear in a host menu; a self-made slot is a plugin-internal mechanism.
71
+
72
+ ---
73
+
74
+ ## 3. Item fields
75
+
76
+ | Field | Required | Meaning |
77
+ |:--|:--:|:--|
78
+ | `command` | ✅ | The command id to run. **A parent item with `children` may leave it empty** (a parent only expands a submenu and runs nothing; use `label` as its text) |
79
+ | `label` | — | Overrides the command's `title` (display text). **Required for a parent item (no `command`)** |
80
+ | `group` | — | Group name (see §4). Default = the fallback group |
81
+ | `when` | — | Visibility condition (see §5). Default = always shown |
82
+ | `order` | — | Sort weight within a group, **lower comes first**, default `100` |
83
+ | `children` | — | Submenu, any depth. **The parent expands on hover** (`children: []` plus a pool-side `resolveChildren` gives a dynamic submenu — advanced usage) |
84
+
85
+ ```jsonc
86
+ // Shorthand: a bare string element means { "command": "…" }
87
+ "menus": { "fileContext": ["my-plugin.exportMd"] }
88
+ ```
89
+
90
+ ### Submenu example
91
+
92
+ ```jsonc
93
+ {
94
+ "menus": {
95
+ "fileContext": [
96
+ {
97
+ "command": "", // a parent runs no command
98
+ "label": "My tools",
99
+ "group": "3_creation",
100
+ "when": "resourceExtname == '.md'",
101
+ "children": [
102
+ { "command": "my-plugin.exportMd" },
103
+ { "command": "my-plugin.wordCount" }
104
+ ]
105
+ }
106
+ ]
107
+ }
108
+ }
109
+ ```
110
+
111
+ ---
112
+
113
+ ## 4. `group` and ordering (what the menu ends up looking like)
114
+
115
+ Rendering happens in two steps, **both done by the host** — you only supply `group` and `order`:
116
+
117
+ 1. **Sort**: take every item in that slot (the host's own, other plugins', yours) and sort by `order` ascending (default `100`).
118
+ 2. **Group**: merge by `group`, **drawing a divider between groups**; the order of groups = **the position of the group's earliest item in the sorted result** (i.e. "first appearance", **not** alphabetical).
119
+
120
+ ⇒ To place "my group" after "navigation", give your group a **larger `order`**; the group *name* itself does not sort.
121
+
122
+ **Naming convention (context menus: `fileContext` / `tabContext` / `editorContext` / `cardContext`)** — use
123
+ `<number>_<meaning>` bucket names; the number decides the order, the word is for humans:
124
+
125
+ | Conventional bucket | What goes in it |
126
+ |:--|:--|
127
+ | `1_navigation` | Open, open in new tab, reveal in system, open in terminal, open with… |
128
+ | `2_editing` | Cut, copy, copy path, paste… |
129
+ | `3_creation` | New file, new folder, new terminal… |
130
+ | `4_modify` | Rename, move… |
131
+ | `5_search` | Find in folder… |
132
+ | `6_workspace` | Workspace/root-scoped actions (close folder…) |
133
+
134
+ **Two special group names**:
135
+
136
+ - `delete` — danger styling (red). **Keep destructive actions in a group of their own** (the shared `ContextMenu` only looks at this one group name to pick the danger colour).
137
+ - The fallback group — what an item joins when it has no `group`; a divider is still drawn between it and explicit groups.
138
+
139
+ > ⚠️ Group names are **free-form strings**: Chinese names work too (several settings-page plugins use them).
140
+ > The table above is the **cross-plugin convention** — your group sits in the same menu as everyone else's,
141
+ > and mismatched naming just adds meaningless dividers.
142
+
143
+ ### Merging into `menuBar` / `panel`
144
+
145
+ Posting into the `menuBar` or `panel` slot with `group: "panel"` merges the items into the hamburger's **"Panel" group**
146
+ (where the host keeps its "open/collapse panel" entry; plugin items follow it). This is the only special rule for those two slots.
147
+
148
+ ---
149
+
150
+ ## 5. `when`: conditional visibility
151
+
152
+ `when` is a small expression that **judges context keys in the host** (values written at runtime by the host or by another plugin).
153
+
154
+ | Syntax | Example | Meaning |
155
+ |:--|:--|:--|
156
+ | Bare key | `file-tree.itemIsFile` | True when the value is **truthy** (undefined = false) |
157
+ | `==` / `!=` | `resourceExtname == '.md'` | String comparison; empty and undefined compare as the empty string (see the pitfalls) |
158
+ | `=~` | `resourceExtname =~ '\\.md$'` | Regular expression (**case-sensitive**, run as a plain JS `RegExp`) |
159
+ | `in` | `activeEditor in ['terminal', 'editor']` | Set membership |
160
+ | `&&` / `\|\|` / `!` / `( )` | `resourceIsFile && !file-tree.inputFocus` | Boolean combination (`!` binds tightest, then `&&`, then `\|\|`) |
161
+ | `true` / `false` | `when: "false"` | Constants (`false` = never show; useful as a placeholder) |
162
+
163
+ ### 🔴 Two pitfalls you must know
164
+
165
+ **Pitfall 1 — literals need (single) quotes.**
166
+ The parser only accepts `'…'` (and numbers) as literals. Writing `resourceExtname == .md` without quotes **fails to parse**,
167
+ the `when` is treated as "do not show", the menu item **silently disappears**, and the only trace is one
168
+ `when 表达式解析失败` line in the console.
169
+
170
+ ```jsonc
171
+ "when": "resourceExtname == .md" // ❌ parse failure → the item never appears
172
+ "when": "resourceExtname == '.md'" // ✅
173
+ "when": "resourceExtname =~ '\\.md$'" // ✅ regexes need quotes too (escape `\` as `\\` in JSON)
174
+ ```
175
+
176
+ **Pitfall 2 — `== ''` also matches "undefined".**
177
+ `==` is implemented as `String(value ?? "")`, so **a key that was never written** and **a key whose value is the empty string**
178
+ cannot be told apart. To mean "there is a file context", do not write `resourceExtname != ''` (that is false when undefined either) —
179
+ use the boolean key:
180
+
181
+ ```jsonc
182
+ "when": "resourceExtname == '.md'" // ✅ undefined → "" ≠ ".md" → hidden
183
+ "when": "resourceIsFile" // ✅ undefined → false
184
+ "when": "resourceExtname != ''" // ❌ false when undefined; reads fine but is ambiguous
185
+ ```
186
+
187
+ ### Which keys you may use
188
+
189
+ | Key | Value | Written by | Notes |
190
+ |:--|:--|:--|:--|
191
+ | `resourceExtname` | The extension **lower-cased, including the dot** (`.md` / `.txt`); **undefined for a file without an extension or a dotfile** | The official `file-tree` | Injected on right-click for the target node; also **undefined** when right-clicking a root node or empty space |
192
+ | `resourceIsFile` | Boolean; undefined for a root node or empty space | The official `file-tree` | Whether the right-clicked target is a file or a folder |
193
+ | `settingKey` · `settingFollowTheme` · `settingModified` · `settingResetsToDefault` · `settingHasTitle` | Strings/booleans | The official `settings` | Public contract keys of the settings-row gear slot (`settingItemGear`) |
194
+ | `activeEditor` · `editorCount` · `editorHasSelection` · `inputFocus` · `sidebarPosition` · … | See the ledger | **The host** | **Read-only**; plugins must not set them (full list in [16-naming-conventions](16-naming-conventions.md) §7 and the SDK's `schemas/host-reserved.json`) |
195
+ | `<your pluginId>.*` | Whatever you decide | **You** | Your private flags. ⛔ Never without the prefix (the SDK's `check-context-ownership` fails it) |
196
+
197
+ **Flags you write yourself** (so the host or another plugin can read them in a `when`, or for your own menus):
198
+
199
+ ```ts
200
+ await window.linkdesk.contextKey.set("my-plugin.previewOpen", true);
201
+ // when: "my-plugin.previewOpen"
202
+ ```
203
+
204
+ > ⚠️ A context key is **a key in a global registry**: writing someone else's name without a prefix **silently overrides their state**
205
+ > (their `when` flickers, and neither side reports an error). The prefix rule and its consequences are in
206
+ > [16-naming-conventions](16-naming-conventions.md) §7, and the gate runs inside your own `npm run verify`.
207
+
208
+ ---
209
+
210
+ ## 6. Command-ownership discipline
211
+
212
+ A menu item **only references a command id**, so rule number one is always:
213
+
214
+ 1. **Your command ids must carry your own prefix** (`my-plugin.`) — rationale and gate in
215
+ [16-naming-conventions](16-naming-conventions.md) §7 and [21-command-ification-spec](21-command-ification-spec.md)
216
+ (everything you can do in the UI should be a command).
217
+ 2. **⛔ Never reference another plugin's command.** Their commands are their implementation detail: if they rename, uninstall,
218
+ or disable, your item **silently stops working** (or worse, throws when clicked). For cross-plugin work, go through a
219
+ **declarative contract** (they declare a public command, or use [07-plugin-to-plugin-communication](07-plugin-to-plugin-communication.md)).
220
+ The only exception is a **host-public command** (the `theme.*` / `view.*` / `app.*` ones the docs say you may call).
221
+ 3. **Visible text must be translatable.** An item shows the command's `title` (or its own `label`) — those strings belong in your
222
+ repo's `i18n/en.json` (key = the Chinese source string), per [09-plugin-directory-layout](09-plugin-directory-layout.md);
223
+ leg ⑧ of `npm run verify` counts them.
224
+
225
+ ---
226
+
227
+ ## 7. Self-check (in this order when an item does not show up)
228
+
229
+ | Symptom | Most likely cause | How to confirm |
230
+ |:--|:--|:--|
231
+ | Not a single item of mine in the slot | The slot key was written as the member name (`FileContext`) | The `check-menu-slot-case` gate (inside `npm run lint` / `verify`); or look at your `plugin.json` and check the key is lower camelCase |
232
+ | Appears sometimes, not others | The `when` is false | Re-run the `when` in the debug entry, or look for `when 表达式解析失败` in the console |
233
+ | Appears but does nothing when clicked | The command was never registered (declared in `contributes.commands` but no pool-side `registerCommand`) | See [21-command-ification-spec](21-command-ification-spec.md) §2 "two legs" |
234
+ | My item sorts first/last and loses to others | `order` defaults to `100` and other groups are smaller | Adjust `order` or rename the group (group order = first appearance) |
235
+ | A "missing your repo's prefix" report | A command id / config key / appearance id / context key lacks the `<pluginId>.` prefix | `npm run verify` reports the site and suggests a name (see [16-naming-conventions](16-naming-conventions.md) §7) |
236
+
237
+ **One command runs every author-side gate**: `npm run verify` (lint + cross-plugin imports + dictionary + declaration consistency + test coverage + …).
@@ -25,6 +25,7 @@
25
25
  | **做一个主题**(不写代码) | [主题/01-做一个主题插件](主题/01-做一个主题插件.md) | → [主题/02-主题字段速查](主题/02-主题字段速查.md) |
26
26
  | **给我的插件加一条配置项** | [20-我的插件加一条配置项](20-我的插件加一条配置项.md) | → [03-插件contributes规范](03-插件contributes规范.md) |
27
27
  | **让 AI / 快捷键 / 命令面板也能操作我的插件** | [21-插件命令化规范](21-插件命令化规范.md) | → [03-插件contributes规范 §3.1](03-插件contributes规范.md)(`commands` 全字段) |
28
+ | **往某个菜单(右键/齿轮/汉堡)里加一项** | [22-菜单贡献点](22-菜单贡献点.md) | → [21-插件命令化规范](21-插件命令化规范.md)(先把动作做成命令) |
28
29
  | **让几个区域联动**(侧栏选中 → 主区切换 → 状态栏更新) | [18-区域间互动](18-区域间互动.md) | → [07-插件间通信](07-插件间通信.md) |
29
30
  | **查 API**(能调什么) | [01-插件API契约 §三](01-插件API契约.md)(三处 API 面的入口表) | → SDK 包内 README 速查表 / `linkdesk.d.ts` |
30
31
  | **用壳提供的 UI 零件** | [19-组件速查](19-组件速查.md) | → [05-插件UI写法规约](05-插件UI写法规约.md) |
@@ -179,6 +180,7 @@ npm run publish # 发布到你自己的 GitHub 仓(上
179
180
  | **19** | **[19-组件速查](19-组件速查.md)** | **壳提供了哪些 UI 零件**、什么时候用哪个 |
180
181
  | **20** | **[20-我的插件加一条配置项](20-我的插件加一条配置项.md)** | 最小做法:声明一条 → 设置页自动出现 → 代码里读 |
181
182
  | **21** | **[21-插件命令化规范](21-插件命令化规范.md)** | **让 AI/快捷键/命令面板能操作我的插件**——动作做成命令的规范 + 作者检查清单 |
183
+ | **22** | **[22-菜单贡献点](22-菜单贡献点.md)** | **把一个动作放进宿主的菜单**——14 个槽位清单 + `group`/`when` 约定 + 公共 context key 表 |
182
184
  | **T1** | **[主题/01-做一个主题插件](主题/01-做一个主题插件.md)** | 做主题的动线(零代码) |
183
185
  | **T2** | **[主题/02-主题字段速查](主题/02-主题字段速查.md)** | 配方字段与 CSS 变量的对照索引 |
184
186
 
@@ -94,7 +94,7 @@ async function list(): Promise<FileEntry[]> {
94
94
  | **notifications** | **唯一通知面 = 状态栏铃铛宽面板**(右下窄 toast 链路已整删)——不弹卡、不抢焦点、不挡操作;未读计数 +1,用户点开才看见。**别把它当「必须被看见」的通道**:要用户当场决定 → `dialog.confirm`。**`show` 一律返回句柄**(`{ update, finish, cancel }`,——**不是只有 `progress:true` 才有**);**一条通知只能被创建它的那个句柄更新/删除**,别处同文案 `show` = 另一条。`progress:true` 开真进度条:`update(msg, percent?)` 给 0-100 确定条、不传 percent = 不定态动画;`finish(msg?)` 关掉并可选补完成通知;`cancel` 直接关掉不补。`persistent:true` = 长驻不自动消失(错误诊断类),等用户点 ×。**常驻配额按 `source` 分桶各 5 条**,超出顶掉同来源最老的并给汇总提示(长驻 ≠ 留档,要留档写自己的文件)。`source` = **机器读的归属键、不含人类文案**(人类可读名壳解析)——⚠️ **做不到自动注入**:池是单进程共享 realm,所有插件共用一个 `window.linkdesk`,preload 无从知道这次 `show` 是哪个插件的树发的 ⇒ **只能作者显式报自己的插件 id**(壳自身域用 `app.<域>`);**不传 → 全落「其他」组**。`actions` 点击走壳 `executeCommand(command, args)`,handler 插件自注册 |
95
95
  | **dialog** | `confirm`/`alert`/`open`/`openFile` = 壳渲染的模态框(抢焦点、有焦点锁)。**`confirmContent(options)`** = **富内容确认**——对话框仍是壳(居中/遮罩/Esc/焦点锁/点遮罩取消),**内容 = 插件自绘视图**(`pluginId` + `viewId` 声明寻址 + 不透明 `payload`,对标 VS Code「对话框是壳、内容插件定」)。**内容侧读法**:视图挂载后经 `dialogHost.current?.content?.payload` 取数(`open !== true` → `null`,防御不白屏);**结算只有 `dialogHost.confirm` / `dialogHost.cancel` 两条路**(别自己关弹窗,壳不认)。**兜底是硬的**:`viewId` 解析不出(未声明/声明插件没装)→ 壳**回落纯文字确认框**(用 `title`/`message`),弹窗照出、不静默死 ⇒ `title`/`message` 别省。`payload` 过 IPC 结构化克隆 ⇒ 只能放可克隆数据 |
96
96
  | **search** | 全文搜索/替换——`searchFiles(opts)` 一发一收,经 IPC 由壳/主进程执行(插件侧零本地扫描);请求/结果形状以契约 `SearchWireOptions`/`SearchWireResult` 为准 |
97
- | **encoding** | 编码检测/转换三件套(主进程 EncodingService 代办):`detect(buffer)` 猜编码名 / `decode(buffer, encoding)` 字节→文本 / `encode(text, encoding)` 文本→字节——`Uint8Array` 进出 |
97
+ | **encoding** | 编码检测/转换四件套(主进程 EncodingService 代办):`detect(buffer)` 猜编码名 / `decode(buffer, encoding)` 字节→文本 / `encode(text, encoding)` 文本→字节 / `isBinary(buffer)` 判是否二进制(`Promise<boolean>`)——`Uint8Array` 进出。**二进制判定归壳、一处真相源**:读盘后要当文本渲染的插件先问 `isBinary` 再 `decode`,别自己按扩展名猜(扩展名会骗人,内容不会)。`isBinary` 是**后加的面**:老宿主没有它 ⇒ 调用前判存在(`lk.encoding?.isBinary`),缺了就按纯文本路径走 |
98
98
  | **update** | **只读更新态**:`getState()` 返回宿主更新状态机全量快照(`uninitialized`/`disabled`/`idle`/`checking`/`available`/`downloading`/`downloaded`/`updating`/`ready` 九态判别联合,载荷以契约 `UpdateState` 为准);**永不抛**(服务必然有态)。供「关于」类插件展示版本/更新进度——**只读**:触发下载/安装是壳自己的事(宿主 `update.*` 命令段,插件不补命令) |
99
99
 
100
100
  **壳广播事件(插件可订阅,走 `events.on`):**
@@ -781,6 +781,27 @@ useEffect(() => {
781
781
 
782
782
  > **pluginId 由顶层 `pluginId` 字段声明**(起要求显式写;`contributes` 下**不写**)。不声明时退回「项目目录名」兜底——兜底路径保留只为兼容仓外存量第三方插件,**新插件一律显式声明**(目录名/仓库名是自由的,靠兜底 = 身份跟着名字漂,且五条后果全不报错)。规则见 [16-命名规范](16-命名规范.md)。
783
783
 
784
+ #### 拿到关联文件后:先判二进制,再决定怎么显示
785
+
786
+ `fileAssociations` 只回答「这个扩展名归你」,**不保证文件内容是文本**——pdf、图片、压缩包都可能落到你手上。壳替你把判定做完了:读盘拿到 `Uint8Array` 之后先问一句 `lk.encoding.isBinary(buffer)`,判真就别硬当文本渲染——`decode` 出来的只会是乱码,而用户会以为是你的插件坏了。
787
+
788
+ ```ts
789
+ const buffer = await lk.filesystem.readBinaryFile(path);
790
+ // 判定归壳(一处真相源);老宿主没有这个面 ⇒ 特征探测 + 退回纯文本路径
791
+ const probe = lk.encoding as { isBinary?: (b: Uint8Array) => Promise<boolean> };
792
+ const isBinary = typeof probe.isBinary === "function" ? await probe.isBinary(buffer) : false;
793
+ if (isBinary) {
794
+ // 渲染自己的「无法作为文本显示」占位——别把乱码泼给用户
795
+ return;
796
+ }
797
+ const text = await lk.encoding.decode(buffer, await lk.encoding.detect(buffer));
798
+ ```
799
+
800
+ - **判定归壳,别自己再来一份**:`isBinary` 采样文件头做启发式判定(含 BOM 与 UTF-16 的特异处理)——扩展名会骗人、内容不会,判据只此一处。
801
+ - **老宿主降级**:`isBinary` 是后加的面,老宿主上没有;写成特征探测(`lk.encoding?.isBinary?.` 形态),缺了就照旧走纯文本路径——乱码照旧,但那是旧宿主的既有表现,不是新引入的问题。
802
+ - **提示块自绘**:占位与出路都由你的插件画(壳不预造「二进制提示」组件——没有第二个真实消费方之前不固化共享 UI)。给用户一条可走的路:换一个能处理它的插件,或在提示里说清这个文件该用什么打开。
803
+ - **别让保存毁文件**:判定为二进制就别允许保存——一次保存会把原始字节覆写成 UTF-8 文本,二进制文件当场损坏。
804
+
784
805
  ### 3.14 `statusBar`——状态栏条目(顶层字段)
785
806
 
786
807
  ```json
@@ -113,7 +113,7 @@ my-plugin/
113
113
  | `contributes.keybindings` | — | 注册到 KeybindingRegistry → 全局键盘监听 |
114
114
  | `contributes.themes` | theme | 注册到 ThemeRegistry → 主题浏览器 |
115
115
  | `contributes.languages` | language | 注册到 LanguageRegistry |
116
- | `contributes.fileAssociations` | — | 注册到 FileAssociationService → 双击文件自动打开 |
116
+ | `contributes.fileAssociations` | — | 注册到 FileAssociationService → 双击文件自动打开;条目可挂牌 `role`(如 `"text-fallback"`,见下) |
117
117
  | `contributes.floatingPanel` | — | 声明视图可在壳内悬浮面板显示——viewId 引用已注册视图;未声明则无「在悬浮面板中打开」右键;可选 `defaultForm`/`formKey` 定/选**首开形态** |
118
118
 
119
119
  **插件可同时声明多种贡献。** 比如一个视图插件可以有 `entry` + `sidebar` + `statusBar` + `contributes.configuration` + `contributes.commands`——全部独立注册,互不影响。
@@ -631,6 +631,54 @@ function CadView() {
631
631
  }
632
632
  ```
633
633
 
634
+ #### contributes.fileAssociations —— 文件关联与角色挂牌
635
+
636
+ 声明「哪些扩展名的文件交给我打开」。用户双击这类文件(或从文件树、命令行打开)时,壳按这张表路由到你的插件,在**你的标签页**里打开。
637
+
638
+ ```json
639
+ {
640
+ "contributes": {
641
+ "fileAssociations": [
642
+ { "extension": "dxf", "displayName": "CAD 图纸" },
643
+ { "extension": "stl", "command": "cad.importStl" }
644
+ ]
645
+ }
646
+ }
647
+ ```
648
+
649
+ | 字段 | 必需 | 说明 |
650
+ |:--|:--:|:--|
651
+ | `extension` | ✅ | 扩展名——**不带点**(`dxf` / `ts`);大小写不敏感(壳统一转小写) |
652
+ | `command` | — | 打开时执行你的哪个命令;缺省走框架的文件打开动作 |
653
+ | `displayName` | — | 在「打开方式…」选择器里显示的名字 |
654
+ | `role` | — | **角色挂牌**(见下)。首版只定义 `"text-fallback"` |
655
+
656
+ **同一扩展名可以多家声明**(你声明的 `ts` 与别人的 `ts` 并存)——壳不替你判给谁,用户从「打开方式…」里挑;默认取**先激活的那家**。所以声明**不是抢占**,是「我也能开」。
657
+
658
+ ##### `role`:怎么成为「默认文本编辑器」
659
+
660
+ 壳**不知道也不该知道**任何插件 id(壳的铁律②)——「某类文件没有任何插件声明时,开哪个标签页」这件事,靠插件**自报角色**:
661
+
662
+ ```json
663
+ {
664
+ "contributes": {
665
+ "fileAssociations": [
666
+ { "extension": "txt", "role": "text-fallback" },
667
+ { "extension": "ts", "role": "text-fallback" },
668
+ { "extension": "json", "role": "text-fallback" }
669
+ ]
670
+ }
671
+ }
672
+ ```
673
+
674
+ - **`role` 依附于条目**(每条自己带,也正因此**条目必须带 `extension`**),但**按插件记名**——你声明 45 条带 `"text-fallback"`,仍然只算**一个**挂牌者(不会因为条数多而挤到别人前面)。
675
+ - **牌 = 提名,不是夺权**:壳解析「该开谁」的顺序是 **① 用户覆盖表 → ② 声明了该扩展名的插件(激活序优先,同序按 pluginId 字典序)→ ③ 文本兜底挂牌者(本角色)→ ④ 都没有 ⇒ 壳的提示页**。
676
+ - ⇒ **你不需要猜别人叫什么**:想接管文本兜底位,声明 `role: "text-fallback"` 即可;装上第二家挂牌者**不会静默漂移**当前默认(它只是进了候选,用户可显式改选)。
677
+ - ⇒ **卸光挂牌者**也不崩:文件没有归属 + 没有兜底 ⇒ 壳显示提示页,⛔ 不会塞给你一个不存在的插件。
678
+ - ⚠️ **二进制文件不归你**:「这个文件能不能当文本看」由**壳**判定(`EncodingService.isBinary` 一处真相源),「哪些扩展名归我」由**你的声明**决定——⛔ 别把 `pdf` / `jpg` 加进扩展名单去抢阅读器插件的地盘。
679
+
680
+ > 想让**右键菜单**按扩展名显隐(如「仅对 `.md` 出现」),读公共 context key `resourceExtname` / `resourceIsFile`——见 [22-菜单贡献点](22-菜单贡献点.md)。
681
+
634
682
  ---
635
683
 
636
684
  ### `tabBehavior` 字段
@@ -120,6 +120,7 @@ node_modules/@linkdesk/plugin-sdk/schemas/host-reserved.json
120
120
  | 宿主外观哨兵值 | `followTheme` | 混搭来源的「跟随主题」哨兵——**它不是 id**,别拿一个插件 id 去顶它 |
121
121
  | 宿主专用旗子(插件**禁设**) | `activeEditor`、`editorCount`、`editorHasSelection`、`inputFocus`、`settingsActiveIsBuiltin`、`settingsSlotFilled`、`sidebarPosition`、`updateActionable`、`updateButtonLabel` | 你在运行时经 IPC 设它,宿主会 `console.error` **点名你**(值照写:旗子是状态不是注册,运行时拿不到「谁是先者」) |
122
122
  | 宿主公开约定旗子(插件**可设**) | `settingKey`、`settingFollowTheme`、`settingModified`、`settingResetsToDefault`、`settingHasTitle` | 这 5 个是**公开约定面**:官方 `settings` 插件写、宿主命令的 `when` 读——照约定用,别改语义(`settingHasTitle` = 该行声明了 `title`,门控齿轮「复制设置名称」) |
123
+ | 宿主公开约定旗子(插件**可设**) | `resourceExtname`、`resourceIsFile` | **文件上下文公共键**(2026-10-05 新增):写的人是**官方 `file-tree`**(右键时按目标节点注入)、读的人是**任意插件的菜单 `when`**——`resourceExtname` 是**带点小写**扩展名(`.md`),`resourceIsFile` 是布尔。⚠️ 无文件上下文(根节点/空白处右键)时两者**未定义**,别拿空串判(写 `when` 时按「未定义 ⇒ 不成立」用)。详见「菜单贡献点」篇 |
123
124
 
124
125
  **怎么自查**(你自己的仓里就能跑):装上 `@linkdesk/plugin-sdk` 后,你仓里的 `verify` 会跑四条归属腿
125
126
  (命令 id / 配置键 / 外观 id / 上下文旗子);哪条犯了会直接报点并给出**「应以 `<pluginId>.` 开头」**的改法。
@@ -0,0 +1,227 @@
1
+ # 22 — 菜单贡献点(把你的动作放进宿主的某个菜单)
2
+
3
+ > 🌐 **English version(作者面主显)→ [../03-plugin-authoring/22-menu-contribution-points.md](https://github.com/Encaron/linkdesk/blob/electron/docs/03-plugin-authoring/22-menu-contribution-points.md)**
4
+ >
5
+ > 2026-10-05 · **一句话**:**你在 `plugin.json` 里声明「哪个槽位、什么条件、跑哪条命令」,菜单项就出现在那里**——
6
+ > 壳不因你改一行代码,你也不用 `import` 壳的任何模块(**字符串即契约**)。
7
+ > 本文是**规范 + 作者自查清单**;条目字段的 schema 定义在 [06-plugin.json规范](06-plugin.json规范.md),
8
+ > 动作做成命令的纪律在 [21-插件命令化规范](21-插件命令化规范.md),命令 id 的命名归属在 [16-命名规范](16-命名规范.md) §七。
9
+
10
+ ---
11
+
12
+ ## 一、最小可用(三件事同时成立才看得见)
13
+
14
+ ```json
15
+ {
16
+ "contributes": {
17
+ "commands": [
18
+ { "id": "my-plugin.exportMd", "title": "导出为 HTML" }
19
+ ],
20
+ "menus": {
21
+ "fileContext": [
22
+ { "command": "my-plugin.exportMd", "when": "resourceExtname == '.md'", "group": "1_navigation" }
23
+ ]
24
+ }
25
+ }
26
+ }
27
+ ```
28
+
29
+ | # | 条件 | 不满足时会怎样 |
30
+ |:--:|:--|:--|
31
+ | ① | `contributes.commands` 里**声明过**这条命令 | 菜单项渲染出来,但点下去什么也不发生(渲染用的是命令的 `title`,跑的是命令的 handler) |
32
+ | ② | 槽位 id 写的是**值**(`fileContext`),不是成员名(`FileContext`) | **静默消失**:那个键在壳注册表里查不到,不报任何错。门禁 `check-menu-slot-case` 专拦这一种(只差大小写) |
33
+ | ③ | `when` 求值为真 | 项隐藏(`when` 解析失败也按「不显示」处理——安全侧) |
34
+
35
+ 改完 `plugin.json` 要**让插件重新激活**(重启应用 / 禁用再启用)才会生效——贡献点是激活时读的。
36
+
37
+ ---
38
+
39
+ ## 二、槽位(MenuId):14 个宿主注册点
40
+
41
+ 槽位 id 就是 `contributes.menus` 的**键**,值是宿主 `MENU_SLOTS` 常量的**值**(小驼峰)。
42
+
43
+ | 槽位值 | 出现在哪 | 常用 when 键 | 备注 |
44
+ |:--|:--|:--|:--|
45
+ | `commandPalette` | Ctrl+Shift+P 命令面板 | — | ⚠️ **当前无宿主渲染方**:面板条目来自 `contributes.commands`(按命令自己的 `when` 过滤)⇒ 投进本槽的条目看不见;当作**预留槽位** |
46
+ | `tabContext` | 标签栏里某个标签的右键 | — | 宿主自己往这里投「关闭/关闭其他/固定…」,插件项与之合并 |
47
+ | `panelViewContext` | 底部面板的标签栏右键 | — | 位置/对齐子菜单 + 视图显隐清单由壳动态注入 |
48
+ | `editorContext` | 标签页**内容区**右键(终端接收区、编辑器…) | — | 面向「当前打开的东西」,不是面向文件 |
49
+ | `extensionGear` | 底部齿轮菜单(全局操作入口) | — | 常驻入口,慎用(用户每次都看得到) |
50
+ | `marketplaceItemGear` | 插件市场里**每个条目**的齿轮 | — | per-plugin 操作(启用/禁用/卸载是壳自己的项) |
51
+ | `menuBar` | ☰ 汉堡菜单栏 | — | `group: "panel"` 的条目会归并进汉堡里的「面板」分组(见 §四) |
52
+ | `panel` | 汉堡里的「面板」分组(专用槽) | — | 与上一行 `menuBar` + `group:"panel"` 等效,二选一 |
53
+ | `fileContext` | 文件树节点右键 | `resourceExtname` · `resourceIsFile` | 按扩展名显隐的主战场,见 §五 |
54
+ | `cardContext` | 卡片右键 | — | — |
55
+ | `quickSendContext` | 快捷发送药丸右键 | — | — |
56
+ | `iconBar` | 图标栏右键 | — | — |
57
+ | `settingItemGear` | 设置页**每一行**的 hover 齿轮 | `settingKey` · `settingFollowTheme` · `settingModified` · `settingResetsToDefault` · `settingHasTitle` | 这五个是设置行的公开约定键,见 §五 |
58
+ | `viewTitleContext` | 侧栏/右栏**视图标题**右键 | — | 折叠/展开/隐藏/重置位置由壳投 |
59
+
60
+ **「常用 when 键」列的 `—` 不是「没有键可用」**,而是「没有**公共约定**的键」——
61
+ 你在这些槽位里只能用宿主专用旗子(`activeEditor` 等,⛔ 插件禁设、只读)或你自己的 `<pluginId>.*` 旗子。
62
+
63
+ > 上表的「出现在哪」列取自壳的 `MENU_SLOTS` 常量表(宿主**意图**)——真机读数与它对不上时,以运行结果为准并反馈给我们。
64
+
65
+ > 🔴 **`MenuId` 是开放字符串**:你可以自造一个槽位 id(比如 `my-plugin.palette`),壳不会报错——
66
+ > 但**没有渲染方会读它**,除非你自己的插件去读(`menu.getItems("my-plugin.palette")`)。
67
+ > 往宿主槽位投条目才会出现在宿主菜单里;自造槽位是插件内部机制。
68
+
69
+ ---
70
+
71
+ ## 三、条目字段
72
+
73
+ | 字段 | 必填 | 说明 |
74
+ |:--|:--:|:--|
75
+ | `command` | ✅ | 要跑的命令 id。**有 `children` 的父项可以为空**(父项只展开子菜单,不跑命令,此时用 `label` 当显示文本) |
76
+ | `label` | — | 覆盖命令的 `title`(显示文本)。**父项(无 `command`)必填** |
77
+ | `group` | — | 分组名(见 §四)。缺省 = 兜底组 |
78
+ | `when` | — | 显隐条件(见 §五)。缺省 = 恒显示 |
79
+ | `order` | — | 同组内排序权重,**越小越靠前**,缺省 `100` |
80
+ | `children` | — | 子菜单,可任意深度。**父项 hover 展开**(`children: []` 空数组 + 池侧 `resolveChildren` 可以做动态子菜单,属于高级用法) |
81
+
82
+ ```jsonc
83
+ // 简写:数组元素直接写字符串 = { "command": "…" }
84
+ "menus": { "fileContext": ["my-plugin.exportMd"] }
85
+ ```
86
+
87
+ ### 子菜单示例
88
+
89
+ ```jsonc
90
+ {
91
+ "menus": {
92
+ "fileContext": [
93
+ {
94
+ "command": "", // 父项不跑命令
95
+ "label": "我的工具",
96
+ "group": "3_creation",
97
+ "when": "resourceExtname == '.md'",
98
+ "children": [
99
+ { "command": "my-plugin.exportMd" },
100
+ { "command": "my-plugin.wordCount" }
101
+ ]
102
+ }
103
+ ]
104
+ }
105
+ }
106
+ ```
107
+
108
+ ---
109
+
110
+ ## 四、`group` 与排序(决定菜单长什么样)
111
+
112
+ 菜单渲染分两步,**都是壳做的**,你只提供 `group` 与 `order`:
113
+
114
+ 1. **排序**:取该槽位全部条目(含壳自己的、别的插件的),按 `order` 升序(缺省 `100`)。
115
+ 2. **分组**:按 `group` 归并,**组之间画一条分隔线**;组的先后 = **该组内最靠前的条目在排序结果里的位置**(即「首现顺序」,**不是**字母序)。
116
+
117
+ ⇒ 想让「我的组」排在「导航组」后面,就给你的组一个**更大的 `order`**;组名本身不参与排序。
118
+
119
+ **命名约定(上下文菜单:`fileContext` / `tabContext` / `editorContext` / `cardContext`)**——用
120
+ `<序号>_<语义>` 的桶名,序号决定先后,语义给人看:
121
+
122
+ | 约定桶名 | 放什么 |
123
+ |:--|:--|
124
+ | `1_navigation` | 打开、在新标签打开、在系统中显示、在终端打开、打开方式… |
125
+ | `2_editing` | 剪切、复制、复制路径、粘贴… |
126
+ | `3_creation` | 新建文件、新建文件夹、新建终端… |
127
+ | `4_modify` | 重命名、移动… |
128
+ | `5_search` | 在此文件夹中查找… |
129
+ | `6_workspace` | 与工作区/根相关的操作(关闭文件夹…) |
130
+
131
+ **两个特殊组名**:
132
+
133
+ - `delete` —— 危险样式(红色)。**删除类操作建议单独成组**(默认 `ContextMenu` 只按这一个组名判危险色)。
134
+ - 缺省组 —— 没写 `group` 时归入,与显式组之间照样画分隔线。
135
+
136
+ > ⚠️ 组名是**自由字符串**:写中文(设置页的若干插件就这么写)也能跑,但上面这张表是**跨插件协调的约定**——
137
+ > 你的组要和别人的组拼在同一个菜单里,命名不一致就会多出几条没意义的分隔线。
138
+
139
+ ### `menuBar` / `panel` 的归并
140
+
141
+ 往 `menuBar` 或 `panel` 槽位投条目、并把 `group` 写成 `"panel"`,会**归并进汉堡菜单的「面板」分组**
142
+ (壳在那里放「打开/折叠面板」的招牌;插件条目跟在后面)。这是这两个槽位唯一的特殊约定。
143
+
144
+ ---
145
+
146
+ ## 五、`when`:条件显隐
147
+
148
+ `when` 是一个小型表达式,**判定的是宿主里的 context key**(键值由壳或别的插件在运行时写)。
149
+
150
+ | 语法 | 例 | 说明 |
151
+ |:--|:--|:--|
152
+ | 裸键 | `file-tree.itemIsFile` | 值为**真值**即成立(未定义 = 不成立) |
153
+ | `==` / `!=` | `resourceExtname == '.md'` | 字符串比较,空/未定义按空串比(见下面的坑) |
154
+ | `=~` | `resourceExtname =~ '\\.md$'` | 正则匹配(**区分大小写**,按 JS `RegExp` 原样执行) |
155
+ | `in` | `activeEditor in ['terminal', 'editor']` | 集合成员 |
156
+ | `&&` / `||` / `!` / `( )` | `resourceIsFile && !file-tree.inputFocus` | 布尔组合(`!` 优先级最高,`&&` 高于 `\|\|`) |
157
+ | `true` / `false` | `when: "false"` | 常量(`false` = 恒隐藏,留占位用) |
158
+
159
+ ### 🔴 两个必须知道的坑
160
+
161
+ **坑 1 —— 字面量要加引号(单引号)。**
162
+ 解析器只认 `'…'`(和数字)当字面量。写成 `resourceExtname == .md`(不加引号)**解析失败** ⇒
163
+ `when` 按「不显示」处理,菜单项**静默消失**,只在控制台留一行 `when 表达式解析失败`。
164
+
165
+ ```jsonc
166
+ "when": "resourceExtname == .md" // ❌ 解析失败 → 项永不出现
167
+ "when": "resourceExtname == '.md'" // ✅
168
+ "when": "resourceExtname =~ '\\.md$'" // ✅ 正则也要引号(JSON 里反斜杠要转义成 `\\`)
169
+ ```
170
+
171
+ **坑 2 —— `== ''` 会把「未定义」也判成真。**
172
+ `==` 内部是 `String(值 ?? "")`,所以**没写过这个键**和**值就是空串**无法区分。
173
+ 想看「有文件上下文」,不要写 `resourceExtname != ''`(未定义时它也是 false),用布尔键:
174
+
175
+ ```jsonc
176
+ "when": "resourceExtname == '.md'" // ✅ 未定义 → "" ≠ ".md" → 不显示
177
+ "when": "resourceIsFile" // ✅ 未定义 → 不成立
178
+ "when": "resourceExtname != ''" // ❌ 未定义时 != 不成立,看着对但语义含糊
179
+ ```
180
+
181
+ ### 能用哪些键
182
+
183
+ | 键 | 取值 | 谁写 | 说明 |
184
+ |:--|:--|:--|:--|
185
+ | `resourceExtname` | **带点小写**扩展名(`.md` / `.txt`);**无扩展名或点开头文件 = 未定义** | 官方 `file-tree` | 文件树右键时按目标节点注入;根节点/空白处右键也**未定义** |
186
+ | `resourceIsFile` | 布尔;根节点/空白处右键 = 未定义 | 官方 `file-tree` | 右键目标是文件还是文件夹 |
187
+ | `settingKey` · `settingFollowTheme` · `settingModified` · `settingResetsToDefault` · `settingHasTitle` | 字符串/布尔 | 官方 `settings` | 设置行齿轮槽位(`settingItemGear`)的公开约定面 |
188
+ | `activeEditor` · `editorCount` · `editorHasSelection` · `inputFocus` · `sidebarPosition` · … | 见账 | **宿主** | **只读**,插件禁设(完整清单见 [16-命名规范](16-命名规范.md) §七 与 SDK 包内 `schemas/host-reserved.json`) |
189
+ | `<你的 pluginId>.*` | 你自己定 | **你自己** | 你的私有旗子。⛔ 不能不带前缀(SDK 的 `check-context-ownership` 判红) |
190
+
191
+ **你自己写的旗子**(供宿主/别的插件的 `when` 读,或供你自己的菜单用):
192
+
193
+ ```ts
194
+ await window.linkdesk.contextKey.set("my-plugin.previewOpen", true);
195
+ // when: "my-plugin.previewOpen"
196
+ ```
197
+
198
+ > ⚠️ context key 是**全局名册的键**:不带前缀就写别人的名字 = 静默顶掉别人的状态(`when` 时隐时现,两边都不报错)。
199
+ > 前缀规则与后果见 [16-命名规范](16-命名规范.md) §七,门禁跑在你自己的 `npm run verify` 里。
200
+
201
+ ---
202
+
203
+ ## 六、命令归属纪律
204
+
205
+ 菜单项**只引用命令 id**,所以第 1 条永远是:
206
+
207
+ 1. **命令 id 必须带你自己的前缀**(`my-plugin.`)——理由与门禁见 [16-命名规范](16-命名规范.md) §七
208
+ + [21-插件命令化规范](21-插件命令化规范.md)(界面上能做的每件事都该有一条命令)。
209
+ 2. **⛔ 不引用别的插件的命令。** 别人的命令是别人的实现细节:他改名、他卸载、他禁用,你的菜单项就**静默失效**
210
+ (或者更坏——点下去报错)。要跨插件协作,走**声明式契约**(对方声明命令为公开面,或走 [07-插件间通信](07-插件间通信.md))。
211
+ 唯一例外是**宿主公开命令**(`theme.*` / `view.*` / `app.*` 等文档明示可调的那些)。
212
+ 3. **可见文案要能翻译。** 菜单项显示的是命令的 `title`(或条目自己的 `label`)——这些串要进本仓
213
+ `i18n/en.json`(key = 中文原文),规则见 [09-插件目录规范](09-插件目录规范.md);`npm run verify` 第 ⑧ 段会数。
214
+
215
+ ---
216
+
217
+ ## 七、自查(看不到菜单项时按这个顺序查)
218
+
219
+ | 现象 | 最可能的原因 | 怎么确认 |
220
+ |:--|:--|:--|
221
+ | 整个槽位一条我的项都没有 | 槽位键写成了成员名(`FileContext`) | 门禁 `check-menu-slot-case`(`npm run lint` / `verify` 里);或搜你的 `plugin.json` 看键是不是小驼峰 |
222
+ | 有时出现有时不出现 | `when` 为假 | 复制 `when` 到命令面板的调试入口 / 看控制台有没有「when 表达式解析失败」 |
223
+ | 出现了但点了没反应 | 命令没注册(只声明了 `contributes.commands`,池侧没 `registerCommand`) | 见 [21-插件命令化规范](21-插件命令化规范.md) §二「两条腿」 |
224
+ | 我的项排在最后/最前,压不过别人 | `order` 缺省 `100`,别人的组更小 | 调 `order` 或换组名(组序 = 首现顺序) |
225
+ | 报「不带本仓归属」 | 命令 id / 配置键 / 外观 id / context key 少了 `<pluginId>.` 前缀 | `npm run verify` 会报点并给出建议名(见 [16-命名规范](16-命名规范.md) §七) |
226
+
227
+ **一条命令跑完全部作者侧门禁**:`npm run verify`(lint + 跨插件 import + 字典 + 声明自洽 + 测试覆盖 + …)。
@@ -477,14 +477,15 @@
477
477
  },
478
478
  "fileAssociations": {
479
479
  "type": "array",
480
- "description": "File associations — file extension → plugin routing (consumed by the main-process plugin-manifest-loader). Declare only the extension plus an optional open command; this plugin's own pluginId comes from the top-level `pluginId` field (see the top-level pluginId description for the directory-name fallback).",
480
+ "description": "File associations — file extension → plugin routing (consumed by the main-process plugin-manifest-loader). Declare only the extension plus an optional open command or role; this plugin's own pluginId comes from the top-level `pluginId` field (see the top-level pluginId description for the directory-name fallback).",
481
481
  "items": {
482
482
  "type": "object",
483
483
  "required": ["extension"],
484
484
  "properties": {
485
485
  "extension": { "type": "string", "description": "File extension — without the dot, e.g. dxf / stl / step" },
486
486
  "command": { "type": "string", "description": "Optional — command ID to run when opening a file with this extension" },
487
- "displayName": { "type": "string", "description": "Optional — display name in the 'Open with…' picker" }
487
+ "displayName": { "type": "string", "description": "Optional — display name in the 'Open with…' picker" },
488
+ "role": { "type": "string", "enum": ["text-fallback"], "description": "Optional — role declaration, attached to this specific entry. \"text-fallback\": this plugin is a candidate for the shell's default text editor fallback (used when no plugin declares the file's extension). The shell picks the active holder; installing a second holder never silently drifts the current default. First version defines only \"text-fallback\"." }
488
489
  },
489
490
  "additionalProperties": false
490
491
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@linkdesk/plugin-docs",
3
- "version": "0.1.60",
3
+ "version": "0.1.61",
4
4
  "description": "LinkDesk 插件作者文档(离线包)——作者面文档树的发布产物(英文 `docs/03-plugin-authoring` 在包根、中文 `docs/03-插件制造` 在 `zh/`):从零学会做一个插件(导览 / 三档动线 / 区域地图 / 组件速查 / 主题 / API 入口)。",
5
5
  "type": "module",
6
6
  "files": [