@aiti-ai/ext-shared 0.0.0-stage → 0.1.11

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 (131) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +36 -2
  3. package/agent-accounts.test.mjs +227 -0
  4. package/agent-accounts.ts +324 -0
  5. package/agent-capability-contract.test.mjs +129 -0
  6. package/agent-interaction.test.mjs +194 -0
  7. package/agent-interaction.ts +340 -0
  8. package/agent-launch.test.mjs +262 -0
  9. package/agent-spawn-env.test.mjs +169 -0
  10. package/agent-spawn-env.ts +548 -0
  11. package/aiti-editor-inject.mjs +49 -0
  12. package/backend-queue.test.mjs +336 -0
  13. package/backend-queue.ts +469 -0
  14. package/blob-save-route.ts +128 -0
  15. package/cbc-model-catalog.ts +86 -0
  16. package/check-client.mjs +273 -0
  17. package/check-ext-globals.mjs +144 -0
  18. package/controlled-login-dialog.mjs +270 -0
  19. package/controlled-login.mjs +398 -0
  20. package/controlled-login.test.mjs +466 -0
  21. package/convert-saveas.test.mjs +39 -0
  22. package/convert-saveas.ts +170 -0
  23. package/copy-client-bundle.mjs +39 -0
  24. package/cursor-cli-store.ts +377 -0
  25. package/dedupe-fetch.test.mjs +71 -0
  26. package/dedupe-fetch.ts +58 -0
  27. package/deploy-commit.mjs +52 -0
  28. package/dev-pack.mjs +246 -0
  29. package/dock-icons.ts +127 -0
  30. package/esbuild-bin.test.mjs +53 -0
  31. package/esbuild-bin.ts +66 -0
  32. package/exec-async.test.mjs +86 -0
  33. package/exec-async.ts +179 -0
  34. package/ext-display-names.ts +91 -0
  35. package/ext-entry-contracts.test.mjs +131 -0
  36. package/ext-float-dock-core.test.mjs +348 -0
  37. package/ext-float-dock-core.ts +783 -0
  38. package/ext-float-dock-lite.ts +52 -0
  39. package/ext-float-dock.test.mjs +286 -0
  40. package/ext-float-dock.ts +740 -0
  41. package/ext-icons-deploy.mjs +24 -0
  42. package/ext-lazy.test.mjs +186 -0
  43. package/ext-lazy.tsx +183 -0
  44. package/ext-model-state.test.mjs +272 -0
  45. package/ext-model-state.ts +324 -0
  46. package/ext-protocol.mjs +113 -0
  47. package/ext-protocol.test.mjs +88 -0
  48. package/ext-session-usage.test.mjs +219 -0
  49. package/ext-session-usage.ts +507 -0
  50. package/external-cli-governance.ts +153 -0
  51. package/git-ops-client/api.mjs +56 -0
  52. package/git-ops-client/branch-panel.tsx +987 -0
  53. package/git-ops-client/i18n.mjs +328 -0
  54. package/host-tools-allow.test.mjs +46 -0
  55. package/host-tools-allow.ts +84 -0
  56. package/icons/alert.svg +1 -0
  57. package/icons/bookmark.svg +1 -0
  58. package/icons/bot.svg +1 -0
  59. package/icons/chart-column.svg +1 -0
  60. package/icons/check-circle.svg +1 -0
  61. package/icons/clipboard-list.svg +1 -0
  62. package/icons/clock.svg +1 -0
  63. package/icons/coffee.svg +1 -0
  64. package/icons/edit.svg +1 -0
  65. package/icons/eye.svg +1 -0
  66. package/icons/git-branch.svg +1 -0
  67. package/icons/git-commit-horizontal.svg +1 -0
  68. package/icons/globe.svg +1 -0
  69. package/icons/history.svg +1 -0
  70. package/icons/import.svg +1 -0
  71. package/icons/inbox.svg +1 -0
  72. package/icons/key-round.svg +1 -0
  73. package/icons/layout-grid.svg +1 -0
  74. package/icons/mail.svg +1 -0
  75. package/icons/message-circle.svg +1 -0
  76. package/icons/message-square.svg +1 -0
  77. package/icons/meter-vertical.svg +1 -0
  78. package/icons/mic.svg +1 -0
  79. package/icons/monitor.svg +1 -0
  80. package/icons/pen-line.svg +1 -0
  81. package/icons/plug.svg +1 -0
  82. package/icons/radio-dot.svg +1 -0
  83. package/icons/radio.svg +1 -0
  84. package/icons/refresh.svg +1 -0
  85. package/icons/rocket.svg +1 -0
  86. package/icons/search.svg +1 -0
  87. package/icons/shield.svg +1 -0
  88. package/icons/sparkles.svg +1 -0
  89. package/icons/square-kanban.svg +1 -0
  90. package/icons/terminal.svg +1 -0
  91. package/icons/users.svg +1 -0
  92. package/icons/volume-2.svg +1 -0
  93. package/icons/wand.svg +1 -0
  94. package/icons/wrench.svg +1 -0
  95. package/icons/x-circle.svg +1 -0
  96. package/icons/x.svg +1 -0
  97. package/ignore-semantics.ts +76 -0
  98. package/lazy-loading-metrics.mjs +61 -0
  99. package/new-session-cwd.test.mjs +389 -0
  100. package/new-session-cwd.ts +253 -0
  101. package/open-viewer-window.ts +65 -0
  102. package/overlay-back-client.test.mjs +123 -0
  103. package/overlay-back-client.ts +87 -0
  104. package/package.json +65 -4
  105. package/pi-fork-rpc/README.md +12 -0
  106. package/pi-fork-rpc/cli-resolve.test.mjs +42 -0
  107. package/pi-fork-rpc/cli-resolve.ts +79 -0
  108. package/pi-fork-rpc/remote-queue.test.mjs +100 -0
  109. package/pi-fork-rpc/remote-queue.ts +140 -0
  110. package/pi-fork-rpc/spec.ts +106 -0
  111. package/pi-fork-rpc/wire.test.mjs +260 -0
  112. package/pi-fork-rpc/wire.ts +367 -0
  113. package/popup-anchor.ts +45 -0
  114. package/provider-priority-contract.test.mjs +55 -0
  115. package/reconcile-deps.mjs +41 -0
  116. package/reload-instances.mjs +60 -0
  117. package/seed-tool.test.mjs +95 -0
  118. package/seed-tool.ts +88 -0
  119. package/session-recycle.ts +109 -0
  120. package/shared-copy-sync.test.mjs +115 -0
  121. package/soffice-locate.ts +171 -0
  122. package/soffice-panel.ts +239 -0
  123. package/sync-dir.mjs +91 -0
  124. package/sync-dir.test.mjs +101 -0
  125. package/sync-gate.test.mjs +93 -0
  126. package/sync-mirror.test.mjs +85 -0
  127. package/task-list.test.mjs +91 -0
  128. package/task-list.ts +118 -0
  129. package/test-rm-rf.mjs +33 -0
  130. package/ui-dialogs.test.mjs +198 -0
  131. package/ui-dialogs.ts +310 -0
@@ -0,0 +1,740 @@
1
+ /**
2
+ * _shared/ext-float-dock.ts — aiti-float dock 的扩展侧 **全量面**(重 UI:DockBody、
3
+ * 头行工具条 hooks、faces 工厂)。状态机(present store)已下沉
4
+ * ./ext-float-dock-core.ts(零 react);壳用薄层 ./ext-float-dock-lite.ts(usePresent/
5
+ * useGate + 状态机小 API)——拆包扩展的薄壳 import lite,不连带本文件的 UI 层
6
+ * (P1-3,方案 pi-web-eager-ext-split-plan.md §6)。
7
+ *
8
+ * 本文件保持历史导入面不变:re-export core(状态机)+ lite(hooks),未拆包扩展
9
+ * 照旧 `import { usePresent, DockBody, ... } from "../../../_shared/ext-float-dock"`。
10
+ * 红线(dock 方案 §3.5):gate 是唯一渲染开关——扩展不得再以自有 state 直接
11
+ * 控制浮窗/嵌入两 face 的显隐。
12
+ */
13
+ import { useEffect, useState, createElement as h } from "react";
14
+ import { clampToViewport, fixedOrigin } from "./popup-anchor";
15
+ import { DOCK_ICON_NODES, DOCK_ICON_SVG_ROOT_PROPS, type DockIconName } from "./dock-icons";
16
+
17
+ /** 图标元素(React/h 版;dock-icons 单一数据源):stroke=2 线稿、currentColor。
18
+ * 与 DOM 版 createDockIconSvg(core appendDockIconRow 内)同图形同尺寸。 */
19
+ export function dockIconEl(name: DockIconName, size = 16): unknown {
20
+ return h("svg", { width: size, height: size, ...DOCK_ICON_SVG_ROOT_PROPS, "aria-hidden": "true" },
21
+ ...DOCK_ICON_NODES[name].map((n, i) => h(n.tag, { key: i, ...n.attrs })));
22
+ }
23
+
24
+ /* ── 左栏区块 zone 泛化(sidebar 统一 dock 方案 §3.8)──
25
+ * 纯状态层(present store + 折叠/排序/头行 store)在 ./ext-float-dock-core.ts
26
+ * (零 react——aiti-float DockStack 同源消费);这里 re-export 全量兼容面。
27
+ * 规范 zone 值 = `sidebar:<itemKey>`,旧值 "sidebar-explorer" 永远兼容读。 */
28
+ export {
29
+ type DockZone, type PresentState, type BlockAlign,
30
+ type DockHeaderAction, type DockHeaderState, type DockHeaderCommands, type DockMenuItem,
31
+ type DockHeaderRegistration, type DockHeaderStore, type DockHeaderVisibility,
32
+ type DockIconRowItem, type PositionMenuItem,
33
+ sidebarZoneOf, isSidebarDockState, splitBlockAlign,
34
+ SIDEBAR_DROP_ZONE, resolveDropZone,
35
+ SIDEBAR_COLLAPSE_PREFIX, SIDEBAR_ORDER_KEY,
36
+ SIDEBAR_COLLAPSE_EVENT, SIDEBAR_ORDER_EVENT, SIDEBAR_MOVE_EVENT, FLOAT_INSTALLED_EVENT,
37
+ readBlockCollapsed, writeBlockCollapsed, seedBlockCollapsedDefault,
38
+ readDockOrder, writeDockOrder,
39
+ effectiveBlockOrder, moveBlockKey, migrateLegacyCollapseKeys,
40
+ createDockHeaderStore, localDockHeaderStore, DOCK_HEADER_PENDING_TTL,
41
+ // present 状态机(P1-3 自本文件下沉 core)
42
+ present, presentState, onPresentChange, dockPref,
43
+ openFloat, closePanel, dockTo, dockToSidebar, undockToFloat,
44
+ setDockPref, clearDockPref, seedDockDefault, declareDockZones,
45
+ positionMenuItems, positionMenuModel, declareDockWindowOpener, dockWindowOpenerOf, DOCK_ZONE_LABELS,
46
+ } from "./ext-float-dock-core";
47
+ // hooks 薄层(P1-3 自本文件下沉 lite)
48
+ export { usePresent, useGate } from "./ext-float-dock-lite";
49
+ import {
50
+ isSidebarDockState,
51
+ readBlockCollapsed, writeBlockCollapsed,
52
+ readDockOrder, localDockHeaderStore, FLOAT_INSTALLED_EVENT,
53
+ SIDEBAR_COLLAPSE_EVENT, SIDEBAR_ORDER_EVENT, SIDEBAR_MOVE_EVENT, SIDEBAR_DROP_EVENT,
54
+ floatApi, closePanel, positionMenuModel, seedDockDefault, declareDockZones, DOCK_ZONE_LABELS,
55
+ } from "./ext-float-dock-core";
56
+ import { usePresent, useGate } from "./ext-float-dock-lite";
57
+ import type { DockHeaderAction, DockHeaderCommands, DockHeaderState, DockHeaderStore, DockMenuItem, DockIconRowItem } from "./ext-float-dock-core";
58
+
59
+
60
+ /* ── 左栏区块栈:折叠/排序/迁移的 React 绑定见文件尾(useBlockCollapsed/useDockOrder);
61
+ * 纯状态层在 ./ext-float-dock-core.ts。此处只留位置菜单项构建(依赖 present 动作糖)。── */
62
+
63
+ export function usePosition(itemKey: string, zones: DockZone[], defaultZone?: DockZone) {
64
+ const state = usePresent(itemKey);
65
+ return { state, zones, defaultZone, labels: DOCK_ZONE_LABELS };
66
+ }
67
+
68
+
69
+ /** 停靠 face 头行(chrome="section",左栏区块统一头行 v4):展开箭头 + 标题 + 计数 +
70
+ * **单一 ⋮ 功能菜单按钮**(折叠/位置/上移/下移/移除/关闭按上下文显隐——方案评审 6 拍板
71
+ * 「禁多按钮多位置差异」,⇱⇲✕ 三钮收编进一个菜单)。chrome="tab"(右栏 TabBar)v3.1 起
72
+ * **不渲染头行**——页签行已有 ⇱(位置菜单)+ ✕,双击 = 拉回浮窗。 */
73
+ /* ── dock 头工具条:服务/本地 store 探测 + hooks(v3;方案 §2.3/§2.7) ── */
74
+
75
+ /** 当前 store:aiti-float 服务(跨 bundle 单例)优先;缺席回落本地 store(同 bundle)。 */
76
+ export function headerStore(): DockHeaderStore {
77
+ const api = floatApi() as (FloatApi & { dockHeader?: DockHeaderStore }) | null;
78
+ const svc = api?.dockHeader;
79
+ return svc && typeof svc.register === "function" ? svc : localDockHeaderStore();
80
+ }
81
+
82
+ /** 请求 dock 头命令(face 按钮 → 内容实现):命中即执行;未命中 → 展开区块 + 排队(TTL 10s)。 */
83
+ export function requestDockCommand(itemKey: string, actionId: string, payload?: unknown): boolean {
84
+ return headerStore().request(itemKey, actionId, payload);
85
+ }
86
+
87
+ /** store 上线重解析 tick(服务安装事件):hook/订阅把它计入 effect 依赖即可换绑。 */
88
+ export function useDockHeaderStoreTick(): number {
89
+ const [tick, setTick] = useState(0);
90
+ useEffect(() => {
91
+ const on = () => setTick((v) => v + 1);
92
+ window.addEventListener(FLOAT_INSTALLED_EVENT, on);
93
+ return () => window.removeEventListener(FLOAT_INSTALLED_EVENT, on);
94
+ }, []);
95
+ return tick;
96
+ }
97
+
98
+ /** 内容注册命令实现(每次渲染更新引用;卸载清空)。 */
99
+ export function useDockCommands(itemKey: string | undefined, commands: DockHeaderCommands | null): void {
100
+ const tick = useDockHeaderStoreTick();
101
+ useEffect(() => {
102
+ if (!itemKey) return;
103
+ try { headerStore().register(itemKey, { commands }); } catch { /* ignore */ }
104
+ });
105
+ useEffect(() => {
106
+ if (!itemKey) return;
107
+ return () => { try { headerStore().register(itemKey, { commands: null }); } catch { /* ignore */ } };
108
+ }, [itemKey, tick]);
109
+ }
110
+
111
+ /** 内容上报状态(active/done/root 等纯数据;签名变化才通知)。 */
112
+ export function useDockHeaderState(itemKey: string | undefined, state: DockHeaderState | null): void {
113
+ const tick = useDockHeaderStoreTick();
114
+ useEffect(() => {
115
+ if (!itemKey) return;
116
+ try { headerStore().register(itemKey, { state }); } catch { /* ignore */ }
117
+ });
118
+ useEffect(() => {
119
+ if (!itemKey) return;
120
+ return () => { try { headerStore().register(itemKey, { state: null }); } catch { /* ignore */ } };
121
+ }, [itemKey, tick]);
122
+ }
123
+
124
+ /** 内容注册 ⋮ 菜单附加项(head/sep/item;复杂文件操作菜单等)。 */
125
+ export function useDockHeaderMenuItems(itemKey: string | undefined, menuItems: DockMenuItem[] | null): void {
126
+ const tick = useDockHeaderStoreTick();
127
+ useEffect(() => {
128
+ if (!itemKey) return;
129
+ try { headerStore().register(itemKey, { menuItems }); } catch { /* ignore */ }
130
+ });
131
+ useEffect(() => {
132
+ if (!itemKey) return;
133
+ return () => { try { headerStore().register(itemKey, { menuItems: null }); } catch { /* ignore */ } };
134
+ }, [itemKey, tick]);
135
+ }
136
+
137
+ /** face 读取内容上报的状态(订阅重渲染)。 */
138
+ export function useDockHeaderStateOf(itemKey: string | undefined): DockHeaderState {
139
+ const tick = useDockHeaderStoreTick();
140
+ const [, setVer] = useState(0);
141
+ useEffect(() => {
142
+ if (!itemKey) return;
143
+ const s = headerStore();
144
+ return s.subscribe(itemKey, () => setVer((v) => v + 1));
145
+ }, [itemKey, tick]);
146
+ return itemKey ? headerStore().stateOf(itemKey) : {};
147
+ }
148
+
149
+ /** DockBody 内部:订阅本 itemKey 的 actions/menuItems(签名变化触发重渲染)。 */
150
+ function useDockHeaderStoreData(itemKey: string): { actions: DockHeaderAction[] | null; menuItems: DockMenuItem[] | null; hasCommands: boolean } {
151
+ const tick = useDockHeaderStoreTick();
152
+ const [, setVer] = useState(0);
153
+ useEffect(() => {
154
+ const s = headerStore();
155
+ return s.subscribe(itemKey, () => setVer((v) => v + 1));
156
+ }, [itemKey, tick]);
157
+ const s = headerStore();
158
+ return { actions: s.actionsOf(itemKey), menuItems: s.menuItemsOf(itemKey), hasCommands: !!s.commandsOf(itemKey) };
159
+ }
160
+
161
+ /** 合并按钮来源:face prop 优先 + 服务/本地 store 补位(按 id 去重,保持声明序)。 */
162
+ function mergeHeaderActions(local: DockHeaderAction[] | null | undefined, fromStore: DockHeaderAction[] | null): DockHeaderAction[] {
163
+ const out: DockHeaderAction[] = [];
164
+ const seen = new Set<string>();
165
+ for (const a of [...(local ?? []), ...(fromStore ?? [])]) {
166
+ if (!a || typeof a.id !== "string" || seen.has(a.id)) continue;
167
+ seen.add(a.id);
168
+ out.push(a);
169
+ }
170
+ return out;
171
+ }
172
+
173
+ /** 菜单渲染行(内部统一形态;head/sep/item)。 */
174
+ type DockMenuRow =
175
+ | { type: "head"; label: string }
176
+ | { type: "sep" }
177
+ | { type: "item"; label: string; icon?: unknown; badge?: number | string; hint?: string; active?: boolean; alwaysRun?: boolean; disabled?: boolean; run: () => void }
178
+ | { type: "icons"; label?: string; icon?: unknown; items: DockIconRowItem[] };
179
+
180
+ /** 停靠面板头行(chrome="section",左栏区块统一头行 v3):展开箭头 + 标题位 +
181
+ * **声明式业务按钮**(自适应宽度;放不下自动进 ⋮「工具」组)+ **常驻 detach**(位置菜单)+
182
+ * **单一 ⋮ 功能菜单**(工具溢出 / 内容注册菜单项 / 区块操作三段;长菜单可滚)。
183
+ * chrome="tab"(右栏 TabBar)不渲染头行——页签行已有 ⇱ + ✕。
184
+ * 折叠保挂:内容注册过命令(曾挂载)时,折叠保留 children(display:none)——头行按钮
185
+ * 状态准确、点击零等待;未注册则折叠不挂载(保住懒加载)。 */
186
+ export function DockBody(props: {
187
+ itemKey: string;
188
+ zone?: DockZone;
189
+ title?: string;
190
+ /** "section":统一 ⋮ 头行(左栏区块);"tab":无头行(控件在宿主 TabBar 页签上) */
191
+ chrome?: "section" | "tab";
192
+ /** 可停靠位置全集(detach 位置菜单;缺省 [zone]——单 zone 面板无需传) */
193
+ zones?: DockZone[];
194
+ /** 扩展声明默认落位(菜单尾标「默认」,纯展示) */
195
+ defaultZone?: DockZone;
196
+ /** 区块身份(折叠/排序记忆 key;缺省 = itemKey) */
197
+ blockKey?: string;
198
+ /** 折叠态外部受控(DockStack 容器传入) */
199
+ collapsed?: boolean;
200
+ onToggleCollapsed?: (next: boolean) => void;
201
+ /** 计数徽标(如子代理数) */
202
+ count?: number;
203
+ /** 常驻区块(reserved):无 detach/关闭菜单项;可带 onRemove(多实例「移除本实例」) */
204
+ kind?: "dockable" | "reserved";
205
+ /** 多实例区块「移除本实例」 */
206
+ onRemove?: () => void;
207
+ /** 「关闭」动作覆盖(缺省 closePanel(itemKey)) */
208
+ onClose?: () => void;
209
+ /** 「新窗口打开」能力(可选):提供时位置菜单优先出该项(图标排最前,B 图形);
210
+ * 不提供则回退注册表(declareDockWindowOpener),仍无则不显示(不支持的面板)。 */
211
+ onNewWindow?: () => void;
212
+ /** 扩展附加菜单项(钉住等多实例专属动作;插在区块操作段) */
213
+ extraMenuItems?: Array<{ label: string; icon?: unknown; hint?: string; active?: boolean; alwaysRun?: boolean; run: () => void }>;
214
+ /** 标题位自定义(如文件夹的目录切换器);提供时替换标题文本(title 仍用于 aria/兜底) */
215
+ renderTitle?: () => unknown;
216
+ /** 声明式头行按钮(face 本地声明;与服务/本地 store 注册的 buttons 合并,prop 优先按 id 去重) */
217
+ headerActions?: DockHeaderAction[];
218
+ children: any;
219
+ }) {
220
+ const { itemKey, zone, title, chrome = "section", zones, defaultZone, children } = props;
221
+ const kind = props.kind ?? "dockable";
222
+ const blockKey = props.blockKey ?? itemKey;
223
+ const selfCollapsed = useState<boolean>(() => readBlockCollapsed(blockKey));
224
+ const collapsed = props.collapsed ?? selfCollapsed[0];
225
+ // 外部折叠变更(旧 key 迁移 / 跨 tab / 容器)→ 同步自持态(受控 props 时不跟随)
226
+ const setSelfCollapsed = selfCollapsed[1];
227
+ useEffect(() => {
228
+ if (props.collapsed !== undefined) return;
229
+ const sync = () => setSelfCollapsed(readBlockCollapsed(blockKey));
230
+ window.addEventListener(SIDEBAR_COLLAPSE_EVENT, sync);
231
+ window.addEventListener("storage", sync);
232
+ return () => { window.removeEventListener(SIDEBAR_COLLAPSE_EVENT, sync); window.removeEventListener("storage", sync); };
233
+ }, [blockKey, props.collapsed]);
234
+ const setCollapsed = (next: boolean) => {
235
+ setSelfCollapsed(next);
236
+ writeBlockCollapsed(blockKey, next); // 单一事实源 + 广播(Stack 同步栈格 flex)
237
+ props.onToggleCollapsed?.(next);
238
+ };
239
+ // ── store 数据(内容注册的 actions/menuItems;签名变化重渲染)──
240
+ const storeData = useDockHeaderStoreData(itemKey);
241
+ // ⋮ 主菜单 / ⇱ 位置菜单共用一套 fixed 弹层(v3:菜单可能很长——maxHeight+overflowY,
242
+ // 内部滚动豁免「任意容器滚动即关」;点外 mousedown / 菜单外滚动仍关)。
243
+ const [menu, setMenu] = useState<{ kind: "position" | "main"; anchor: HTMLElement } | null>(null);
244
+ const [menuEl, setMenuEl] = useState<HTMLElement | null>(null);
245
+ const [menuBtnEl, setMenuBtnEl] = useState<HTMLElement | null>(null);
246
+ const [posBtnEl, setPosBtnEl] = useState<HTMLElement | null>(null);
247
+ const [menuPos, setMenuPos] = useState<{ left: number; top: number } | null>(null);
248
+ useEffect(() => {
249
+ if (!menu || !menuEl || !menu.anchor) return;
250
+ const b = menu.anchor.getBoundingClientRect();
251
+ const m = menuEl.getBoundingClientRect();
252
+ const gap = 4, pad = 8;
253
+ let top = b.bottom + gap;
254
+ const below = window.innerHeight - pad - top;
255
+ const above = b.top - gap - pad;
256
+ if (m.height > below && above > below) top = b.top - gap - m.height; // 上翻
257
+ const c = clampToViewport(b.right - m.width, top, m.width, m.height, pad);
258
+ const o = fixedOrigin(menuEl);
259
+ const next = { left: c.left - o.x, top: c.top - o.y };
260
+ setMenuPos((cur) => (cur && cur.left === next.left && cur.top === next.top) ? cur : next);
261
+ }, [menu, menuEl]);
262
+ useEffect(() => {
263
+ if (!menu) return;
264
+ const onDown = (e: any) => {
265
+ const t = e.target as Node | null;
266
+ if (t && menuEl?.contains(t)) return;
267
+ if (t && menu.anchor?.contains(t)) return;
268
+ setMenu(null);
269
+ };
270
+ const onScroll = (e: any) => {
271
+ // 菜单内部滚动豁免(长菜单必须可滚);菜单外任意容器滚动即关(fixed 弹层滞留旧位=错位)
272
+ if (menuEl && e.target instanceof Node && menuEl.contains(e.target)) return;
273
+ setMenu(null);
274
+ };
275
+ document.addEventListener("mousedown", onDown);
276
+ window.addEventListener("scroll", onScroll, true);
277
+ return () => {
278
+ document.removeEventListener("mousedown", onDown);
279
+ window.removeEventListener("scroll", onScroll, true);
280
+ };
281
+ }, [menu, menuEl]);
282
+ // ── 自适应:头行可用宽度 → 可见业务按钮数(ResizeObserver + window resize;无轮询)──
283
+ const [headerEl, setHeaderEl] = useState<HTMLElement | null>(null);
284
+ const [fitCount, setFitCount] = useState(4);
285
+ useEffect(() => {
286
+ if (!headerEl) return;
287
+ const calc = () => {
288
+ const w = headerEl.clientWidth || 0;
289
+ if (w <= 0) return;
290
+ // 固定占用估算:padding16 + 箭头22 + 标题最小56 + detach24 + ⋮24 + 间隙12
291
+ const fixed = 154;
292
+ const n = Math.max(0, Math.min(6, Math.floor((w - fixed) / 27)));
293
+ setFitCount((cur) => (cur === n ? cur : n));
294
+ };
295
+ calc();
296
+ let ro: any = null;
297
+ try { if (typeof ResizeObserver === "function") { ro = new ResizeObserver(calc); ro.observe(headerEl); } } catch { /* ignore */ }
298
+ window.addEventListener("resize", calc);
299
+ return () => { try { if (ro) ro.disconnect(); } catch { /* ignore */ } window.removeEventListener("resize", calc); };
300
+ }, [headerEl]);
301
+ const state = usePresent(itemKey);
302
+ const allZones = zones && zones.length ? zones : (zone ? [zone] : []);
303
+ const showDetach = kind === "dockable" && chrome === "section" && allZones.length > 0;
304
+ // .ts 文件(跨扩展共享不保证 jsx-runtime)→ 用 createElement 而非 JSX 语法
305
+ const btnBase: any = {
306
+ background: "none", border: "none", color: "var(--text-muted, #888)", cursor: "pointer",
307
+ fontSize: 11, lineHeight: 1, padding: "2px 5px", flexShrink: 0, fontFamily: "inherit",
308
+ };
309
+ // ── 业务按钮:合并来源 → 折叠过滤 visibility → 自适应截断(其余进 ⋮「工具」组)──
310
+ const allActions = mergeHeaderActions(props.headerActions, storeData.actions);
311
+ const eligible = allActions.filter((a) => !collapsed || (a.visibility ?? "always") !== "expanded");
312
+ const shownActions = eligible.slice(0, fitCount);
313
+ const overflowActions = eligible.slice(fitCount);
314
+ const actionBtn = (a: DockHeaderAction) => h("button", {
315
+ key: a.id, type: "button", title: a.title, "aria-label": a.title, disabled: a.disabled === true,
316
+ style: {
317
+ ...btnBase, position: "relative" as const,
318
+ color: a.done ? "var(--ok, #4ade80)" : a.active ? "var(--accent, #2563eb)" : "var(--text-muted, #888)",
319
+ opacity: a.disabled ? 0.5 : 1, cursor: a.disabled ? "default" : "pointer",
320
+ },
321
+ onClick: (e: any) => { if (a.disabled !== true) a.onClick(e); },
322
+ },
323
+ a.icon ? h("span", { style: { display: "inline-flex", alignItems: "center", justifyContent: "center" } }, a.icon) : h("span", { style: { fontSize: 12, fontWeight: 700, lineHeight: 1 } }, "•"),
324
+ (a.badge !== undefined && a.badge !== null && a.badge !== "") ? h("span", {
325
+ style: { position: "absolute" as const, top: -5, right: -4, fontSize: 9, lineHeight: "13px", color: "var(--text-muted, #888)", background: "var(--bg-panel, #1a1a1a)", border: "1px solid var(--border, #444)", borderRadius: 7, padding: "0 3px" },
326
+ }, String(a.badge)) : null);
327
+ // ── ⋮ 主菜单(三段:工具溢出 / 内容注册菜单项 / 区块操作)──
328
+ const buildMainMenu = (): DockMenuRow[] => {
329
+ const out: DockMenuRow[] = [];
330
+ if (overflowActions.length > 0) {
331
+ out.push({ type: "head", label: "工具" });
332
+ for (const a of overflowActions) out.push({ type: "item", label: a.title, icon: a.icon, badge: a.badge, active: a.active, alwaysRun: true, disabled: a.disabled, run: a.onClick });
333
+ }
334
+ if (storeData.menuItems && storeData.menuItems.length > 0) {
335
+ if (out.length > 0) out.push({ type: "sep" });
336
+ for (const m of storeData.menuItems) {
337
+ if (m.kind === "head") out.push({ type: "head", label: m.label });
338
+ else if (m.kind === "sep") out.push({ type: "sep" });
339
+ else out.push({ type: "item", label: m.label, icon: m.icon, hint: m.hint, active: m.active, alwaysRun: m.alwaysRun, disabled: m.disabled, run: m.run });
340
+ }
341
+ }
342
+ const ops: DockMenuRow[] = [];
343
+ if (chrome === "section") {
344
+ // 单行「移动」(2026-09-15 用户拍板回归 §3.5 图标排形态):行首对角双箭头图标(move-diagonal-2,
345
+ // 左上+右下)+ 行名呈 icon+text,与区块段其余行呼应;右侧 chevron-up/down 即时上移/下移。
346
+ ops.push({ type: "icons", label: "移动", icon: dockIconEl("move-diagonal-2", 13), items: [
347
+ { key: "move-up", icon: "chevron-up", label: "上移", run: () => requestBlockMove(blockKey, -1) },
348
+ { key: "move-down", icon: "chevron-down", label: "下移", run: () => requestBlockMove(blockKey, 1) },
349
+ ] });
350
+ }
351
+ if (kind === "reserved" && typeof props.onRemove === "function") {
352
+ ops.push({ type: "item", label: "移除本实例", icon: dockIconEl("trash", 13), run: () => props.onRemove!() });
353
+ }
354
+ if (Array.isArray(props.extraMenuItems)) {
355
+ for (const m of props.extraMenuItems) ops.push({ type: "item", label: m.label, icon: m.icon, hint: m.hint, active: m.active, alwaysRun: m.alwaysRun, run: m.run });
356
+ }
357
+ if (kind === "dockable" && chrome === "section") {
358
+ ops.push({ type: "item", label: "关闭", icon: dockIconEl("x", 13), run: () => (props.onClose ? props.onClose() : closePanel(itemKey)) });
359
+ }
360
+ if (ops.length > 0) {
361
+ if (out.length > 0) out.push({ type: "sep" });
362
+ out.push({ type: "head", label: "区块" });
363
+ out.push(...ops);
364
+ }
365
+ return out;
366
+ };
367
+ const positionRows: DockMenuRow[] = menu?.kind === "position"
368
+ // v5 图标排(方案 §3.4):统一模型(浮窗 → 各停靠位)+ 一行无歧义方位图标
369
+ ? [{ type: "icons" as const, label: "停靠方位", items: positionMenuModel(itemKey, allZones, defaultZone, state, { onNewWindow: props.onNewWindow }) }]
370
+ : [];
371
+ const menuRows: DockMenuRow[] = menu?.kind === "position" ? positionRows : (menu?.kind === "main" ? buildMainMenu() : []);
372
+ const renderMenuRow = (it: DockMenuRow, i: number) => {
373
+ if (it.type === "sep") return h("div", { key: `sep-${i}`, style: { height: 1, background: "var(--border, #444)", margin: "3px 4px", opacity: 0.7, flexShrink: 0 } });
374
+ if (it.type === "head") return h("div", { key: `head-${i}`, style: { fontSize: 10, color: "var(--text-dim, #888)", fontWeight: 600, padding: "4px 10px 2px", letterSpacing: 0.3, userSelect: "none", whiteSpace: "nowrap" as const } }, it.label);
375
+ // v5 图标排(方案 §3.4/§3.5):一行「名称 + 右对齐图标组」(参照菜单样式:名称左、
376
+ // 图标右对齐;当前态高亮锁定、默认位圆点、hover tooltip);数值与 DOM 版一致。
377
+ if (it.type === "icons") return h("div", {
378
+ key: `icons-${i}`, role: "group", "data-ext-dock-icon-row": "1",
379
+ style: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, padding: "5px 10px", flexShrink: 0 },
380
+ },
381
+ it.label ? h("span", { key: "label", "data-ext-dock-icon-row-label": "1",
382
+ // 行首图标(可选):带图标 = 动作行(正文字色,与其余 icon+text 行同款);
383
+ // 无图标 = 纯说明名(dim,位置菜单「停靠方位」标题原样)。
384
+ style: { display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12,
385
+ color: it.icon ? "var(--text, #ddd)" : "var(--text-dim, #888)", flexShrink: 0, userSelect: "none" as const, whiteSpace: "nowrap" as const } },
386
+ it.icon ? h("span", { style: { display: "inline-flex", flexShrink: 0 } }, it.icon) : null,
387
+ it.label) : null,
388
+ h("div", { key: "group", "data-ext-dock-icon-group": "1",
389
+ style: { display: "flex", gap: 6, marginLeft: "auto", flexShrink: 0 } },
390
+ ...it.items.map((x, j) => {
391
+ const isRadio = x.active === true || x.active === false;
392
+ const tip = x.isDefault ? `${x.label}(默认)` : x.label;
393
+ return h("button", {
394
+ key: `icon-${j}`, type: "button",
395
+ role: isRadio ? "menuitemradio" : "menuitem",
396
+ ...(isRadio ? { "aria-checked": x.active ? "true" : "false" } : {}),
397
+ title: tip, "aria-label": tip, "data-ext-dock-icon": x.key,
398
+ style: {
399
+ position: "relative" as const, width: 28, height: 28, display: "inline-flex", alignItems: "center", justifyContent: "center",
400
+ border: "none", borderRadius: 6, padding: 0, fontFamily: "inherit",
401
+ cursor: x.active ? "default" : "pointer",
402
+ background: x.active ? "var(--bg-selected, #2a2a2a)" : "none",
403
+ color: x.active ? "var(--accent, #2563eb)" : "var(--text-muted, #888)",
404
+ },
405
+ onClick: () => { if (x.active) return; setMenu(null); x.run(); },
406
+ onMouseEnter: (e: any) => { if (!x.active) { e.currentTarget.style.background = "var(--bg-hover, #262626)"; e.currentTarget.style.color = "var(--text, #ddd)"; } },
407
+ onMouseLeave: (e: any) => { if (!x.active) { e.currentTarget.style.background = "none"; e.currentTarget.style.color = "var(--text-muted, #888)"; } },
408
+ },
409
+ dockIconEl(x.icon, 16),
410
+ x.isDefault ? h("span", { key: "dot", "data-ext-dock-icon-default": "1", style: { position: "absolute" as const, top: 3, right: 3, width: 4, height: 4, borderRadius: "50%", background: "var(--accent, #2563eb)", pointerEvents: "none" as const } }) : null,
411
+ );
412
+ })),
413
+ );
414
+ const disabled = it.disabled === true;
415
+ const locked = it.active === true && it.alwaysRun !== true;
416
+ return h("button", {
417
+ key: `item-${i}`, type: "button", role: "menuitem", disabled,
418
+ style: {
419
+ background: "none", border: "none", cursor: disabled || locked ? "default" : "pointer", fontSize: 12,
420
+ padding: "6px 12px", textAlign: "left" as const, borderRadius: 6, fontFamily: "inherit",
421
+ color: it.active ? "var(--accent, #2563eb)" : "var(--text, #ddd)", display: "flex", alignItems: "center", gap: 6,
422
+ opacity: disabled ? 0.5 : 1, flexShrink: 0,
423
+ },
424
+ onClick: () => { setMenu(null); if (!locked) it.run(); },
425
+ onKeyDown: (e: any) => { if (e.key === "Escape") setMenu(null); },
426
+ },
427
+ it.icon ? h("span", { style: { width: 14, display: "inline-flex", justifyContent: "center", flexShrink: 0 } }, it.icon) : null,
428
+ (it.active ? "✓ " : "") + it.label,
429
+ it.badge !== undefined && it.badge !== null && it.badge !== "" ? h("span", { style: { marginLeft: "auto", fontSize: 10, color: "var(--text-muted, #888)", border: "1px solid var(--border, #444)", borderRadius: 6, padding: "0 4px" } }, String(it.badge)) : null,
430
+ it.hint ? h("span", { style: { marginLeft: "auto", fontSize: 10, color: "var(--text-muted, #888)", border: "1px solid var(--border, #444)", borderRadius: 4, padding: "0 4px" } }, it.hint) : null,
431
+ );
432
+ };
433
+ const menuNode = menu ? h("div", {
434
+ ref: setMenuEl,
435
+ role: "menu",
436
+ style: {
437
+ position: "fixed", zIndex: 2147483600, background: "var(--bg-panel, #1a1a1a)",
438
+ border: "1px solid var(--border, #444)", borderRadius: 8, padding: 4, display: "flex", flexDirection: "column", gap: 2,
439
+ boxShadow: "0 8px 24px rgba(0,0,0,0.4)", minWidth: menu?.kind === "position" ? 190 : 150, maxWidth: "calc(100vw - 16px)",
440
+ // 长菜单滚动契约(v3):视口内可滚 + 防滚动穿透(内部滚动不触发「容器滚动即关」)
441
+ maxHeight: "min(70vh, calc(100vh - 16px))", overflowY: "auto" as const, overscrollBehavior: "contain" as const,
442
+ // 首帧离屏(布局期测量后落位,绘制前同步无闪烁)
443
+ ...(menuPos ? { left: menuPos.left, top: menuPos.top } : { left: -99999, top: -99999 }),
444
+ },
445
+ onMouseLeave: () => setMenu(null),
446
+ }, menuRows.map(renderMenuRow)) : null;
447
+ const toggleCollapsed = () => setCollapsed(!collapsed);
448
+ // 排序 v2:头行 = HTML5 拖拽把手。dragged key 双通道传递:dataTransfer(跨 bundle,
449
+ // drop 阶段可读)+ 模块级 dragKey(同 bundle 实时读——dragover 阶段 dataTransfer 受
450
+ // 保护读不到,用于抑制自拖高亮;自拖拽必然同 bundle,故可靠)。drop 前/后半区决定
451
+ // 插入位;键盘路径 = ⋮ 上移/下移。
452
+ const onDragStart = (e: any) => {
453
+ if (e.target && typeof e.target.closest === "function" && e.target.closest("button")) { e.preventDefault(); return; }
454
+ dragKey = blockKey;
455
+ try {
456
+ e.dataTransfer.setData("application/x-pi-dock", blockKey);
457
+ e.dataTransfer.effectAllowed = "move";
458
+ } catch { /* ignore */ }
459
+ };
460
+ const isDockDrag = (e: any) => { try { return [...(e.dataTransfer?.types ?? [])].includes("application/x-pi-dock"); } catch { return false; } };
461
+ const dropMark = (e: any, on: boolean) => {
462
+ const el = e.currentTarget as HTMLElement;
463
+ if (!el) return;
464
+ el.classList.remove("pi-dock-drop-before", "pi-dock-drop-after");
465
+ if (on) el.classList.add((e.clientY - el.getBoundingClientRect().top) < el.getBoundingClientRect().height / 2 ? "pi-dock-drop-before" : "pi-dock-drop-after");
466
+ };
467
+ const onDrop = (e: any) => {
468
+ if (!isDockDrag(e)) return;
469
+ e.preventDefault();
470
+ const el = e.currentTarget as HTMLElement;
471
+ el.classList.remove("pi-dock-drop-before", "pi-dock-drop-after");
472
+ let dragged = "";
473
+ try { dragged = e.dataTransfer.getData("application/x-pi-dock") || ""; } catch { /* ignore */ }
474
+ if (!dragged) dragged = dragKey || "";
475
+ if (!dragged || dragged === blockKey) return;
476
+ const r = el.getBoundingClientRect();
477
+ requestBlockDrop(dragged, blockKey, (e.clientY - r.top) < r.height / 2);
478
+ };
479
+ const headerProps: any = { ref: setHeaderEl, style: { display: "flex", alignItems: "center", gap: 4, padding: "4px 8px", borderBottom: "1px solid var(--border, #333)", flexShrink: 0, minWidth: 0 }, onClick: (e: any) => { if (e.target && typeof e.target.closest === "function" && e.target.closest("button")) return; toggleCollapsed(); } };
480
+ if (chrome === "section") {
481
+ headerProps.draggable = true;
482
+ headerProps.title = "拖动排序";
483
+ headerProps.onDragStart = onDragStart;
484
+ headerProps.onDragOver = (e: any) => { if (isDockDrag(e) && dragKey !== blockKey) { e.preventDefault(); e.dataTransfer.dropEffect = "move"; dropMark(e, true); } };
485
+ headerProps.onDragLeave = (e: any) => { try { if (e.relatedTarget && e.currentTarget.contains(e.relatedTarget)) return; } catch { /* ignore */ } dropMark(e, false); };
486
+ headerProps.onDrop = onDrop;
487
+ headerProps.onDragEnd = () => {
488
+ dragKey = null;
489
+ document.querySelectorAll(".pi-dock-drop-before, .pi-dock-drop-after").forEach((el) => el.classList.remove("pi-dock-drop-before", "pi-dock-drop-after"));
490
+ };
491
+ }
492
+ const titleNode = props.renderTitle
493
+ ? h("span", { style: { minWidth: 0, flex: "0 1 auto", display: "inline-flex", alignItems: "center" } }, props.renderTitle())
494
+ : h("span", { style: { fontSize: 11, fontWeight: 600, color: "var(--text-muted, #999)", letterSpacing: "0.04em", textTransform: "uppercase" as const, flex: "0 1 auto", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" as const, minWidth: 0 } }, title ?? "");
495
+ // 折叠保挂(v3):内容注册过命令(曾挂载)→ 折叠保留 children(隐藏),按钮状态与命令即时可用
496
+ const keepAlive = collapsed && storeData.hasCommands;
497
+ return h("div", {
498
+ "data-ext-float-dock-body": itemKey,
499
+ "data-ext-item": itemKey,
500
+ "data-ext-dock-block": blockKey,
501
+ // 根上带声明属性:TabBar ⇱ 菜单在 face 挂载时可直接读(注册表兜底优先)
502
+ "data-ext-float-dock": allZones.join(" "),
503
+ ...(defaultZone ? { "data-ext-float-dock-default": defaultZone } : {}),
504
+ // 注册按钮数(e2e/调试断言用):当前头行可见 / 溢出
505
+ "data-ext-dock-actions": String(shownActions.length),
506
+ "data-ext-dock-actions-overflow": String(overflowActions.length),
507
+ style: { display: "flex", flexDirection: "column", height: "100%", minHeight: 0, overflow: "hidden", position: "relative" },
508
+ },
509
+ chrome === "section" && h("div", headerProps,
510
+ h("button", {
511
+ type: "button", title: collapsed ? "展开" : "折叠", "aria-label": (title ?? "区块") + (collapsed ? " 展开" : " 折叠"),
512
+ "aria-expanded": collapsed ? "false" : "true", style: { ...btnBase, display: "flex", alignItems: "center" },
513
+ onClick: toggleCollapsed,
514
+ },
515
+ h("svg", { width: 9, height: 9, viewBox: "0 0 10 10", fill: "none", stroke: "currentColor", strokeWidth: 1.8, strokeLinecap: "round", strokeLinejoin: "round",
516
+ style: { transform: collapsed ? "none" : "rotate(90deg)", transition: "transform 0.15s", flexShrink: 0 } },
517
+ h("polyline", { points: "3 2 7 5 3 8" })),
518
+ ),
519
+ titleNode,
520
+ typeof props.count === "number" && h("span", { style: { color: "var(--text-dim, #777)", fontWeight: 400, fontSize: 10, flexShrink: 0 } }, `(${props.count})`),
521
+ h("span", { style: { flex: 1, minWidth: 0 } }),
522
+ ...shownActions.map(actionBtn),
523
+ showDetach ? h("span", { style: { position: "relative", display: "inline-flex", flexShrink: 0 } },
524
+ h("button", {
525
+ ref: setPosBtnEl, type: "button", title: "切换停靠位置", "aria-label": "切换停靠位置", "aria-haspopup": "menu",
526
+ "aria-expanded": menu?.kind === "position" ? "true" : "false",
527
+ style: { ...btnBase, fontSize: 12 },
528
+ onClick: () => { if (menu?.kind === "position") setMenu(null); else { setMenuPos(null); setMenu({ kind: "position", anchor: posBtnEl ?? menuBtnEl! }); } },
529
+ }, "⇱"),
530
+ menu?.kind === "position" ? menuNode : null,
531
+ ) : null,
532
+ h("span", { style: { position: "relative", display: "inline-flex", flexShrink: 0 } },
533
+ h("button", { ref: setMenuBtnEl, type: "button", title: "区块操作", "aria-label": "区块操作", "aria-haspopup": "menu", "aria-expanded": menu?.kind === "main" ? "true" : "false",
534
+ style: { ...btnBase, fontSize: 12, fontWeight: 700 },
535
+ onClick: () => { if (menu?.kind === "main") { setMenu(null); } else { setMenuPos(null); setMenu({ kind: "main", anchor: menuBtnEl! }); } },
536
+ onKeyDown: (e: any) => { if (e.key === "Escape" && menu?.kind === "main") setMenu(null); } }, "⋮"),
537
+ menu?.kind === "main" ? menuNode : null,
538
+ ),
539
+ ),
540
+ (!collapsed || keepAlive) && h("div", { style: { flex: collapsed ? "0 0 0" : 1, minHeight: 0, overflow: "hidden", display: collapsed ? "none" : "flex", flexDirection: "column" } }, children),
541
+ );
542
+ }
543
+
544
+ /** ⋮ 菜单「上移/下移」请求广播(全栈键集只有 DockStack 容器知道——容器监听落位)。 */
545
+ export function requestBlockMove(blockKey: string, delta: number): void {
546
+ try { window.dispatchEvent(new CustomEvent(SIDEBAR_MOVE_EVENT, { detail: { key: blockKey, delta } })); } catch { /* ignore */ }
547
+ }
548
+
549
+ /** 排序 v2:拖拽落点请求广播(dragged 移到 target 前/后;容器监听落位)。 */
550
+ export function requestBlockDrop(dragged: string, target: string, before: boolean): void {
551
+ try { window.dispatchEvent(new CustomEvent(SIDEBAR_DROP_EVENT, { detail: { key: dragged, target, before } })); } catch { /* ignore */ }
552
+ }
553
+
554
+ /** 当前拖拽中的区块 key(同 bundle 实时读;跨 bundle 落位走 dataTransfer)。 */
555
+ let dragKey: string | null = null;
556
+
557
+ /* 拖放落点高亮样式(一次性注入;DOM API 加类,React 重渲染不冲) */
558
+ if (typeof document !== "undefined" && !document.getElementById("pi-dock-dnd-css")) {
559
+ try {
560
+ const st = document.createElement("style");
561
+ st.id = "pi-dock-dnd-css";
562
+ st.textContent = "[data-ext-dock-block][draggable=true] { cursor: grab; }"
563
+ + ".pi-dock-drop-before { box-shadow: inset 0 2px 0 var(--accent, #2563eb); }"
564
+ + ".pi-dock-drop-after { box-shadow: inset 0 -2px 0 var(--accent, #2563eb); }";
565
+ document.head.appendChild(st);
566
+ } catch { /* ignore */ }
567
+ }
568
+
569
+ /** 折叠态 hook(区块栈容器/外部同步用):localStorage 单一事实源 + 变更事件订阅。 */
570
+ export function useBlockCollapsed(blockKey: string): [boolean, (next: boolean) => void] {
571
+ const [collapsed, setCollapsed] = useState<boolean>(() => readBlockCollapsed(blockKey));
572
+ useEffect(() => {
573
+ const sync = () => setCollapsed(readBlockCollapsed(blockKey));
574
+ sync();
575
+ window.addEventListener(SIDEBAR_COLLAPSE_EVENT, sync);
576
+ window.addEventListener("storage", sync);
577
+ return () => { window.removeEventListener(SIDEBAR_COLLAPSE_EVENT, sync); window.removeEventListener("storage", sync); };
578
+ }, [blockKey]);
579
+ return [collapsed, (next: boolean) => writeBlockCollapsed(blockKey, next)];
580
+ }
581
+
582
+ /** 排序持久化 hook(DockStack 容器用):readDockOrder + 变更事件订阅。 */
583
+ export function useDockOrder(): string[] {
584
+ const [order, setOrder] = useState<string[]>(() => readDockOrder());
585
+ useEffect(() => {
586
+ const sync = () => setOrder(readDockOrder());
587
+ sync();
588
+ window.addEventListener(SIDEBAR_ORDER_EVENT, sync);
589
+ window.addEventListener("storage", sync);
590
+ return () => { window.removeEventListener(SIDEBAR_ORDER_EVENT, sync); window.removeEventListener("storage", sync); };
591
+ }, []);
592
+ return order;
593
+ }
594
+
595
+ /** 左栏停靠 gate(v4 泛化):docked:sidebar:* 族(含旧 sidebar-explorer)任意落位即真。
596
+ * 返回当前落位 zone(sidebar:<itemKey> | sidebar-explorer),未停靠返回 null。 */
597
+ export function useGateSidebar(itemKey: string): string | null {
598
+ const state = usePresent(itemKey);
599
+ if (!isSidebarDockState(state)) return null;
600
+ return state === "docked:sidebar-explorer" ? "sidebar-explorer" : state.slice("docked:".length);
601
+ }
602
+
603
+ /** 左栏区块注册项(统一区块注册语义糖):dockable 面板以 sidebar:* 为默认位时的
604
+ * sidebarExplorerDock 注册条目(meta 携 title/priority——DockStack 排序默认序消费)。
605
+ * face 门控 = useGateSidebar(sidebar 族任意落位渲染),头行走统一 DockBody。 */
606
+ export function sidebarBlockItem(opts: {
607
+ key: string; // 完整 itemKey "extId:itemId"(= 注册复合 id 约定)
608
+ title: string;
609
+ priority?: number; // 默认序(项目0→任务1→文件2→停靠3+)
610
+ zones?: DockZone[]; // 位置全集(sidebar 族自动并入;右栏显式声明)
611
+ defaultZone?: DockZone;
612
+ renderContent: () => any;
613
+ }) {
614
+ const zones: DockZone[] = opts.zones?.length ? opts.zones : [sidebarZoneOf(opts.key)];
615
+ if (opts.defaultZone) seedDockDefault(opts.key, opts.defaultZone);
616
+ else seedDockDefault(opts.key, zones.find((z) => z === "sidebar-explorer" || z.startsWith("sidebar:")) ?? zones[0]);
617
+ declareDockZones(opts.key, zones, opts.defaultZone);
618
+ const itemId = opts.key.includes(":") ? opts.key.slice(opts.key.indexOf(":") + 1) : opts.key;
619
+ const SidebarFace = () => {
620
+ const dockedZone = useGateSidebar(opts.key);
621
+ if (!dockedZone) return null;
622
+ return h(DockBody, {
623
+ itemKey: opts.key, title: opts.title, chrome: "section" as const,
624
+ zones, defaultZone: opts.defaultZone, kind: "dockable" as const,
625
+ }, opts.renderContent());
626
+ };
627
+ return { id: itemId, render: SidebarFace, meta: { title: opts.title, priority: opts.priority } };
628
+ }
629
+
630
+ /* ── createDockFaces 工厂(v3 §2-F,G5 接入降本):一个调用注册浮窗 + 各停靠面 ──
631
+ *
632
+ * const faces = createDockFaces({ key: "my-ext:main", title: "我的面板",
633
+ * zones: ["right-panel"], defaultZone: "right-panel", renderContent: () => <MyContent/> });
634
+ * registerItems("dialogs", faces.dialogsItems);
635
+ * registerItems("rightFileDock", faces.rightFileDock);
636
+ * registerItems("sidebarExplorerDock", faces.sidebarExplorerDock);
637
+ *
638
+ * 打开入口仍由扩展调 openFloat(key)。浮窗壳 = 标准遮罩 + 面板(头行标题+✕ + 滚动体);
639
+ * 自带头行 UI 的内容可关 chrome(头行仍需自己调 closePanel(key))。
640
+ * 特例(git-review pages⇄dock 二面 / doc-center embedded)不走工厂,维持手写。 */
641
+ export function createDockFaces(opts: {
642
+ key: string; // 完整 itemKey "extId:itemId"(= 注册 id 约定,防 dock tab 链断裂)
643
+ title: string;
644
+ zones: DockZone[];
645
+ defaultZone?: DockZone;
646
+ renderContent: () => any; // 两面共用内容(ReactNode 工厂)
647
+ /** 浮窗面板附加 data-ext-float-* 属性(w/h/full/min-w/pos…),如 { "data-ext-float-w": 760 } */
648
+ floatAttrs?: Record<string, unknown>;
649
+ /** 浮窗面板内联样式兑底(未装 float 时生效) */
650
+ floatStyle?: Record<string, unknown>;
651
+ /** 浮窗面宽度/高度(style 与 data-ext-float-w/-h 同步声明;缺省 760×560) */
652
+ w?: number; hh?: number;
653
+ /** 标准 chrome 头行(标题+✕);内容自带头行时传 false(自己调 closePanel) */
654
+ chrome?: boolean;
655
+ /** dialogs item id(缺省 = key 第一个冒号后的 itemId 部分) */
656
+ itemId?: string;
657
+ /** 左栏区块默认序(meta.priority → DockStack 有效序;项目0→任务1→文件2→停靠3+) */
658
+ priority?: number;
659
+ }) {
660
+ const { key, title, zones, defaultZone, renderContent } = opts;
661
+ const itemId = opts.itemId ?? (key.includes(":") ? key.slice(key.indexOf(":") + 1) : key);
662
+ const w = opts.w ?? 760;
663
+ const hh = opts.hh ?? 560;
664
+ if (defaultZone) seedDockDefault(key, defaultZone); // 首次 open 直达默认位(§2-B)+ 注册表默认位
665
+ declareDockZones(key, zones, defaultZone); // TabBar ⇱ 菜单 zones 全集(v3.1)
666
+ const dockAttrs: Record<string, unknown> = { "data-ext-float-dock": zones.join(" ") };
667
+ if (defaultZone) dockAttrs["data-ext-float-dock-default"] = defaultZone;
668
+
669
+ const FloatFace = () => {
670
+ const gate = useGate(key, "float");
671
+ if (!gate) return null;
672
+ return h("div", {
673
+ style: { position: "fixed", inset: 0, zIndex: 311, background: "rgba(0,0,0,0.35)", display: "flex", alignItems: "center", justifyContent: "center" },
674
+ onClick: () => closePanel(key),
675
+ },
676
+ h("div", {
677
+ "data-ext-float": "1",
678
+ "data-ext-float-key": key,
679
+ ...dockAttrs,
680
+ ...(opts.floatAttrs ?? {}),
681
+ style: {
682
+ position: "fixed", width: `min(${w}px, 94vw)`, height: `min(${hh}px, 84vh)`,
683
+ display: "flex", flexDirection: "column", overflow: "hidden",
684
+ background: "var(--bg-panel, #1a1a1a)", border: "1px solid var(--border, #444)",
685
+ borderRadius: 12, boxShadow: "0 18px 60px rgba(0,0,0,0.4)", color: "var(--text, #ddd)",
686
+ ...(opts.floatStyle ?? {}),
687
+ },
688
+ onClick: (e: any) => e.stopPropagation(),
689
+ },
690
+ opts.chrome !== false && h("div", { style: { display: "flex", alignItems: "center", gap: 8, padding: "10px 14px 6px", flexShrink: 0 } },
691
+ h("h3", { style: { margin: 0, fontSize: 14, fontWeight: 600, flex: 1 } }, title),
692
+ h("button", { type: "button", "aria-label": "关闭", title: "关闭", onClick: () => closePanel(key),
693
+ style: { background: "none", border: "none", color: "var(--text-muted, #888)", cursor: "pointer", fontSize: 14, padding: "2px 8px", fontFamily: "inherit" } }, "✕"),
694
+ ),
695
+ h("div", { style: { flex: 1, minHeight: 0, overflow: "auto", display: "flex", flexDirection: "column" } }, renderContent()),
696
+ ),
697
+ );
698
+ };
699
+
700
+ const makeDockFace = (zone: DockZone, chrome: "section" | "tab") => () => {
701
+ // v4:左栏 face 门控放宽为 sidebar 族(docked:sidebar:* 任意区块位,兼容旧
702
+ // sidebar-explorer——用户 dockpref 持久化旧值时照样渲染);头行 zone 由状态推导。
703
+ if (zone === "sidebar-explorer") {
704
+ const dockedZone = useGateSidebar(key);
705
+ if (!dockedZone) return null;
706
+ return h(DockBody, { itemKey: key, zone, title, chrome, zones, defaultZone }, renderContent());
707
+ }
708
+ const docked = useGate(key, { dock: zone });
709
+ if (!docked) return null;
710
+ return h(DockBody, { itemKey: key, zone, title, chrome, zones, defaultZone }, renderContent());
711
+ };
712
+
713
+ const hasSidebarZone = zones.some((z) => z === "sidebar-explorer" || z.startsWith("sidebar:"));
714
+ return {
715
+ dialogsItems: [{ id: itemId, render: FloatFace }],
716
+ // ⚠ dock item 注册 raw itemId(宿主 registerItems 自动拼 extId:itemId = itemKey),
717
+ // 与状态机 key 一致(demo/doc-center/git-review 同款约定;id: key 会拼出双前缀断链)
718
+ rightFileDock: zones.includes("right-panel")
719
+ ? [{ id: itemId, render: makeDockFace("right-panel", "tab"), meta: { title } }]
720
+ : [],
721
+ // v4:meta.priority 透传(DockStack 默认序:项目0→任务1→文件2→停靠3+;用户改序后失效)
722
+ sidebarExplorerDock: hasSidebarZone
723
+ ? [{ id: itemId, render: makeDockFace("sidebar-explorer", "section"), meta: { title, ...(opts.priority !== undefined ? { priority: opts.priority } : {}) } }]
724
+ : [],
725
+ };
726
+ }
727
+
728
+ /* flash 样式(一次性注入;docked 态重复 open 的容器高亮,2s 自删 class) */
729
+ if (typeof document !== "undefined" && !document.getElementById("piwe-dock-flash-css")) {
730
+ try {
731
+ const st = document.createElement("style");
732
+ st.id = "piwe-dock-flash-css";
733
+ st.textContent = "@keyframes piwe-dock-flash-kf { 0%,100% { box-shadow: none; } 30% { box-shadow: inset 0 0 0 2px var(--accent, #2563eb); } }"
734
+ + ".piwe-dock-flash { animation: piwe-dock-flash-kf 2s ease; }";
735
+ document.head.appendChild(st);
736
+ } catch { /* ignore */ }
737
+ }
738
+
739
+ /* ── React 绑定(各扩展 bundle 自带 react;不引 react 的调用方直接用下面的 usePresent/useGate/DockBody) ── */
740
+