@michengai/dsh-codex-ui 2.0.5 → 2.0.6

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/lib/client.js CHANGED
@@ -74,6 +74,7 @@ window.__ModuleLoader__.load({
74
74
  settingsSkin: `${CODEX_UI_API_BASE}/settings-skin`,
75
75
  composer: `${CODEX_UI_API_BASE}/composer`,
76
76
  sidebar: `${CODEX_UI_API_BASE}/sidebar`,
77
+ sections: `${CODEX_UI_API_BASE}/sections`,
77
78
  theme: `${CODEX_UI_API_BASE}/theme`
78
79
  });
79
80
  //#endregion
@@ -3059,6 +3060,18 @@ html[data-dsh-glass] body:not([data-ds-dark-theme]) .dcu-section-card{background
3059
3060
  "settings.noResults": "没有匹配的设置分类",
3060
3061
  "input.historyHint": "↑↓ 翻历史",
3061
3062
  "about.nav": "Codex UI",
3063
+ "sections.pinned": "置顶",
3064
+ "sections.default": "项目",
3065
+ "sections.menu": "分区",
3066
+ "sections.pin": "置顶",
3067
+ "sections.unpin": "取消置顶",
3068
+ "sections.rename": "重命名",
3069
+ "sections.remove": "移除分区",
3070
+ "sections.writePending": "工作区移动尚未完成,后续操作正在等待宿主响应。",
3071
+ "sections.writeAborted": "工作区移动未完成,已自动撤销。",
3072
+ "sections.new": "新建分区",
3073
+ "sections.newName": "新分区名称",
3074
+ "sections.settings": "分区设置",
3062
3075
  "about.title": "Codex UI",
3063
3076
  "about.viewProject": "GitHub",
3064
3077
  "about.feedback": "问题反馈",
@@ -3214,6 +3227,18 @@ html[data-dsh-glass] body:not([data-ds-dark-theme]) .dcu-section-card{background
3214
3227
  "settings.noResults": "No matching settings categories",
3215
3228
  "input.historyHint": "↑↓ History",
3216
3229
  "about.nav": "Codex UI",
3230
+ "sections.pinned": "Pinned",
3231
+ "sections.default": "Projects",
3232
+ "sections.menu": "Section",
3233
+ "sections.pin": "Pin",
3234
+ "sections.unpin": "Unpin",
3235
+ "sections.rename": "Rename",
3236
+ "sections.remove": "Remove section",
3237
+ "sections.writePending": "Workspace move is still pending host response.",
3238
+ "sections.writeAborted": "Workspace move was not completed and was aborted.",
3239
+ "sections.new": "New section",
3240
+ "sections.newName": "Section name",
3241
+ "sections.settings": "Section settings",
3217
3242
  "about.title": "Codex UI",
3218
3243
  "about.viewProject": "GitHub",
3219
3244
  "about.feedback": "Issues",
@@ -4872,7 +4897,7 @@ html[data-dsh-glass-float] [data-shortcut-modal="settings"]:has(> [class*="optio
4872
4897
  */
4873
4898
  const CODEX_UI_NAV_MARKER = "data-dcu-nav-icon";
4874
4899
  const NAV_ROW_SELECTOR = "[role=\"dialog\"] nav button, [data-shortcut-modal=\"settings\"] nav button";
4875
- const STYLE_ID = "dcu-settings-nav-icon-style";
4900
+ const STYLE_ID$1 = "dcu-settings-nav-icon-style";
4876
4901
  const ICON_MASK_URL = `url("data:image/svg+xml,${encodeURIComponent("<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 16 16\"><rect x=\"1.5\" y=\"2\" width=\"13\" height=\"12\" rx=\"2\" stroke=\"black\" stroke-width=\"1.3\" fill=\"none\"/><line x1=\"5.5\" y1=\"2\" x2=\"5.5\" y2=\"14\" stroke=\"black\" stroke-width=\"1.3\"/><line x1=\"5.5\" y1=\"5.5\" x2=\"14.5\" y2=\"5.5\" stroke=\"black\" stroke-width=\"1.3\"/></svg>")}")`;
4877
4902
  const NAV_ICON_CSS = `
4878
4903
  [${CODEX_UI_NAV_MARKER}="codex-ui"] > svg { display: none !important; }
@@ -4893,9 +4918,9 @@ html[data-dsh-glass-float] [data-shortcut-modal="settings"]:has(> [class*="optio
4893
4918
  }
4894
4919
  `;
4895
4920
  function ensureStyle(doc) {
4896
- if (doc.getElementById(STYLE_ID) !== null) return;
4921
+ if (doc.getElementById(STYLE_ID$1) !== null) return;
4897
4922
  const style = doc.createElement("style");
4898
- style.id = STYLE_ID;
4923
+ style.id = STYLE_ID$1;
4899
4924
  style.textContent = NAV_ICON_CSS;
4900
4925
  (doc.head ?? doc.documentElement).appendChild(style);
4901
4926
  }
@@ -4943,7 +4968,7 @@ html[data-dsh-glass-float] [data-shortcut-modal="settings"]:has(> [class*="optio
4943
4968
  doc.querySelectorAll(`[${CODEX_UI_NAV_MARKER}="codex-ui"]`).forEach((btn) => {
4944
4969
  btn.removeAttribute(CODEX_UI_NAV_MARKER);
4945
4970
  });
4946
- doc.getElementById(STYLE_ID)?.remove();
4971
+ doc.getElementById(STYLE_ID$1)?.remove();
4947
4972
  };
4948
4973
  }
4949
4974
  //#endregion
@@ -5690,7 +5715,7 @@ html[data-dsh-glass-float] [data-shortcut-modal="settings"]:has(> [class*="optio
5690
5715
  /** 宿主固定的入口:始终常驻,不参与收纳与拖动。 */
5691
5716
  const FIXED_PANEL_IDS = ["plugins"];
5692
5717
  const SIDEBAR_LAYOUT_KEY = "michengai.codex-ui.sidebar-layout.v1";
5693
- const isStringArray = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
5718
+ const isStringArray$1 = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
5694
5719
  /** 解析持久化内容;格式不符时返回 undefined,由调用方回退默认布局。 */
5695
5720
  function parseLayout(raw) {
5696
5721
  if (raw === null || raw === "") return void 0;
@@ -5698,7 +5723,7 @@ html[data-dsh-glass-float] [data-shortcut-modal="settings"]:has(> [class*="optio
5698
5723
  const data = JSON.parse(raw);
5699
5724
  if (typeof data !== "object" || data === null) return void 0;
5700
5725
  const { pinned, more } = data;
5701
- if (!isStringArray(pinned) || !isStringArray(more)) return void 0;
5726
+ if (!isStringArray$1(pinned) || !isStringArray$1(more)) return void 0;
5702
5727
  return {
5703
5728
  pinned,
5704
5729
  more
@@ -6573,31 +6598,46 @@ html[data-dsh-glass-float] [data-shortcut-modal="settings"]:has(> [class*="optio
6573
6598
  cursor: grabbing !important;
6574
6599
  }
6575
6600
 
6576
- /* 拖拽放置指示线 */
6577
- .dcu-sb-row[data-drag-over="before"]::before {
6601
+ /*
6602
+ * 拖拽放置指示线:完全照搬宿主工作区树的落点线画法
6603
+ * (12px 高的带子里,左端一个 5x7 的箭头 + 从 x=4 起、高 2px 的横线,颜色用宿主 business 状态色)。
6604
+ * 这样侧栏导航和工作区树的落点线是同一个视觉语言,不再是两种粗细/两种颜色。
6605
+ */
6606
+ .dcu-sb-row[data-drag-over="before"]::before,
6607
+ .dcu-sb-row[data-drag-over="after"]::after {
6578
6608
  content: "";
6579
6609
  position: absolute;
6580
- top: -1px;
6581
- left: 6px;
6582
- right: 6px;
6583
- height: 2px;
6584
- border-radius: 1px;
6585
- background: var(--dsw-alias-brand-primary, #4176e6);
6610
+ left: 0;
6611
+ right: 0;
6612
+ height: 12px;
6586
6613
  pointer-events: none;
6587
6614
  z-index: 10;
6615
+ background:
6616
+ linear-gradient(
6617
+ 55deg,
6618
+ transparent calc(50% - 1px),
6619
+ var(--dsw-alias-state-business-primary, var(--dsw-alias-brand-primary, #4176e6)) calc(50% - 1px) calc(50% + 1px),
6620
+ transparent calc(50% + 1px)
6621
+ )
6622
+ 0 0 / 5px 7px no-repeat,
6623
+ linear-gradient(
6624
+ 125deg,
6625
+ transparent calc(50% - 1px),
6626
+ var(--dsw-alias-state-business-primary, var(--dsw-alias-brand-primary, #4176e6)) calc(50% - 1px) calc(50% + 1px),
6627
+ transparent calc(50% + 1px)
6628
+ )
6629
+ 0 5px / 5px 7px no-repeat,
6630
+ linear-gradient(var(--dsw-alias-state-business-primary, var(--dsw-alias-brand-primary, #4176e6)) 0 0) 4px 5px /
6631
+ calc(100% - 4px) 2px no-repeat;
6632
+ }
6633
+
6634
+ /* 12px 的带子里,横线落在第 5~7px,所以上移 6px 让横线正好压在行边界上。 */
6635
+ .dcu-sb-row[data-drag-over="before"]::before {
6636
+ top: -6px;
6588
6637
  }
6589
6638
 
6590
6639
  .dcu-sb-row[data-drag-over="after"]::after {
6591
- content: "";
6592
- position: absolute;
6593
- bottom: -1px;
6594
- left: 6px;
6595
- right: 6px;
6596
- height: 2px;
6597
- border-radius: 1px;
6598
- background: var(--dsw-alias-brand-primary, #4176e6);
6599
- pointer-events: none;
6600
- z-index: 10;
6640
+ bottom: -6px;
6601
6641
  }
6602
6642
 
6603
6643
  .dcu-sb-row[data-drag-over="onto"] {
@@ -6672,7 +6712,7 @@ html[data-dsh-glass-float] [data-shortcut-modal="settings"]:has(> [class*="optio
6672
6712
  flex-shrink: 0;
6673
6713
  margin-left: auto;
6674
6714
  color: var(--dsw-alias-label-tertiary, #888);
6675
- transition: transform 200ms cubic-bezier(0.2, 0, 0, 1);
6715
+ transition: transform 150ms var(--ds-ease-in-out, cubic-bezier(0.2, 0, 0, 1));
6676
6716
  pointer-events: none;
6677
6717
  }
6678
6718
 
@@ -6684,7 +6724,7 @@ html[data-dsh-glass-float] [data-shortcut-modal="settings"]:has(> [class*="optio
6684
6724
  display: grid;
6685
6725
  grid-template-rows: 0fr;
6686
6726
  opacity: 0;
6687
- transition: grid-template-rows 220ms cubic-bezier(0.2, 0, 0, 1), opacity 160ms ease;
6727
+ transition: grid-template-rows 220ms cubic-bezier(0.2, 0, 0, 1), opacity 220ms cubic-bezier(0.2, 0, 0, 1);
6688
6728
  overflow: hidden;
6689
6729
  -webkit-app-region: no-drag !important;
6690
6730
  }
@@ -6692,7 +6732,9 @@ html[data-dsh-glass-float] [data-shortcut-modal="settings"]:has(> [class*="optio
6692
6732
  .dcu-sb-accordion.dcu-sb-accordion-open {
6693
6733
  grid-template-rows: 1fr;
6694
6734
  opacity: 1;
6695
- overflow: visible;
6735
+ /* 保持 hidden:1fr 已经是内容自然高度,切成 visible 会让内容在动画第一帧就整块露出来,
6736
+ 看起来「没有展开动画」。 */
6737
+ overflow: hidden;
6696
6738
  }
6697
6739
 
6698
6740
  .dcu-sb-accordion[aria-hidden="true"] {
@@ -6708,7 +6750,7 @@ html[data-dsh-glass-float] [data-shortcut-modal="settings"]:has(> [class*="optio
6708
6750
  }
6709
6751
 
6710
6752
  .dcu-sb-accordion.dcu-sb-accordion-open .dcu-sb-accordion-content {
6711
- overflow: visible;
6753
+ overflow: hidden;
6712
6754
  }
6713
6755
 
6714
6756
  .dcu-sb-empty-drop-hint {
@@ -6897,6 +6939,1733 @@ html[data-dsh-glass-float] [data-shortcut-modal="settings"]:has(> [class*="optio
6897
6939
  };
6898
6940
  }
6899
6941
  //#endregion
6942
+ //#region src/client/sidebar/sections/model.ts
6943
+ /**
6944
+ * 工作区「分区」模型(纯函数,不触碰 DOM 与存储)。
6945
+ *
6946
+ * 分区是插件层的视图结构:宿主的工作区注册表仍是唯一事实来源,
6947
+ * 分区只决定「谁排在谁旁边」。因此模型里的分组成员顺序就是最终要写入宿主的顺序,
6948
+ * `flattenSections` 的结果与宿主 `workspaces` 的排列应当逐项一致。
6949
+ *
6950
+ * 不变式:
6951
+ * - 始终包含内置分区 `pinned`(置顶)与兜底分区 `default`(项目),且各只有一份;
6952
+ * - `default` 永远排在最后,`pinned` 可被拖到任意位置(Codex 同样允许);
6953
+ * - 一个工作区最多出现在一个分区里,未知工作区在归一化时被丢弃。
6954
+ */
6955
+ /** 内置「置顶」分区 id:可拖动、可重命名,但不能删除。 */
6956
+ const PINNED_SECTION_ID = "pinned";
6957
+ /** 兜底「项目」分区 id:固定最后,成员是尚未归类的工作区。 */
6958
+ const DEFAULT_SECTION_ID = "default";
6959
+ /** 新建用户的默认分区结构:置顶 + 项目,没有自定义分区。 */
6960
+ function createSectionsState() {
6961
+ return { sections: [{
6962
+ id: PINNED_SECTION_ID,
6963
+ name: "置顶",
6964
+ ids: []
6965
+ }, {
6966
+ id: DEFAULT_SECTION_ID,
6967
+ name: "项目",
6968
+ ids: []
6969
+ }] };
6970
+ }
6971
+ /** 判断是否内置分区(置顶与兜底),内置分区不允许删除。 */
6972
+ function isBuiltinSection(id) {
6973
+ return id === "pinned" || id === "default";
6974
+ }
6975
+ const isStringArray = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
6976
+ /**
6977
+ * 解析持久化内容。
6978
+ * 结构不合法时返回 `undefined`,由调用方回退默认结构(与侧栏布局解析风格一致)。
6979
+ */
6980
+ function parseSections(raw) {
6981
+ if (raw === null || raw === void 0 || raw === "") return void 0;
6982
+ try {
6983
+ const data = JSON.parse(raw);
6984
+ if (typeof data !== "object" || data === null) return void 0;
6985
+ const sections = data.sections;
6986
+ if (!Array.isArray(sections)) return void 0;
6987
+ const parsed = [];
6988
+ for (const item of sections) {
6989
+ if (typeof item !== "object" || item === null) return void 0;
6990
+ const record = item;
6991
+ if (typeof record.id !== "string" || record.id === "") return void 0;
6992
+ if (typeof record.name !== "string") return void 0;
6993
+ if (!isStringArray(record.ids)) return void 0;
6994
+ parsed.push({
6995
+ id: record.id,
6996
+ name: record.name,
6997
+ ids: record.ids.slice()
6998
+ });
6999
+ }
7000
+ return { sections: parsed };
7001
+ } catch {
7002
+ return;
7003
+ }
7004
+ }
7005
+ /** 序列化为持久化字符串。 */
7006
+ function serializeSections(state) {
7007
+ return JSON.stringify({ sections: state.sections });
7008
+ }
7009
+ /**
7010
+ * 用当前实际存在的工作区集合校正分区结构:
7011
+ * - 丢弃已删除的工作区、跨分区重复项(保留首次出现)与重复分区 id;
7012
+ * - 补齐缺失的内置分区,`default` 固定到最后;
7013
+ * - 名称空白的内置分区回退默认名。
7014
+ *
7015
+ * @param state - 待校正的结构。
7016
+ * @param knownIds - 宿主当前存在的工作区 id;省略时只做结构校正,不按存在性裁剪(启动早期宿主可能还没就绪)。
7017
+ * @returns 新的、满足不变式的结构。
7018
+ */
7019
+ function normalizeSections(state, knownIds) {
7020
+ const known = knownIds === void 0 ? void 0 : new Set(knownIds);
7021
+ const seenIds = /* @__PURE__ */ new Set();
7022
+ const seenSections = /* @__PURE__ */ new Set();
7023
+ const sections = [];
7024
+ for (const section of state.sections) {
7025
+ if (seenSections.has(section.id)) continue;
7026
+ seenSections.add(section.id);
7027
+ const ids = [];
7028
+ for (const id of section.ids) {
7029
+ if (seenIds.has(id)) continue;
7030
+ if (known !== void 0 && !known.has(id)) continue;
7031
+ seenIds.add(id);
7032
+ ids.push(id);
7033
+ }
7034
+ const canonical = defaultNameFor(section.id);
7035
+ const name = canonical !== "" ? canonical : section.name.trim();
7036
+ sections.push({
7037
+ id: section.id,
7038
+ name,
7039
+ ids
7040
+ });
7041
+ }
7042
+ if (!seenSections.has("pinned")) sections.unshift({
7043
+ id: PINNED_SECTION_ID,
7044
+ name: defaultNameFor(PINNED_SECTION_ID),
7045
+ ids: []
7046
+ });
7047
+ const defaultIndex = sections.findIndex((section) => section.id === DEFAULT_SECTION_ID);
7048
+ if (defaultIndex === -1) sections.push({
7049
+ id: DEFAULT_SECTION_ID,
7050
+ name: defaultNameFor(DEFAULT_SECTION_ID),
7051
+ ids: []
7052
+ });
7053
+ else if (defaultIndex !== sections.length - 1) {
7054
+ const [fallback] = sections.splice(defaultIndex, 1);
7055
+ sections.push(fallback);
7056
+ }
7057
+ return { sections };
7058
+ }
7059
+ /** 内置分区的默认名称。 */
7060
+ function defaultNameFor(id) {
7061
+ if (id === "pinned") return "置顶";
7062
+ if (id === "default") return "项目";
7063
+ return "";
7064
+ }
7065
+ /** 查找某个工作区所属分区 id。 */
7066
+ function sectionOf(state, workspaceId) {
7067
+ for (const section of state.sections) if (section.ids.includes(workspaceId)) return section.id;
7068
+ }
7069
+ /** 按分区顺序摊平出的工作区顺序,即应当写入宿主的顺序。 */
7070
+ function flattenSections(state) {
7071
+ const order = [];
7072
+ for (const section of state.sections) order.push(...section.ids);
7073
+ return order;
7074
+ }
7075
+ /**
7076
+ * 把工作区放进指定分区。
7077
+ *
7078
+ * @param state - 当前结构。
7079
+ * @param workspaceId - 目标工作区。
7080
+ * @param sectionId - 目标分区。
7081
+ * @param index - 分区内插入位置;省略时追加到分区末尾。
7082
+ * @returns 新的结构;分区不存在时原样返回。
7083
+ */
7084
+ function assignWorkspace(state, workspaceId, sectionId, index) {
7085
+ if (state.sections.find((section) => section.id === sectionId) === void 0) return state;
7086
+ const sections = state.sections.map((section) => ({
7087
+ id: section.id,
7088
+ name: section.name,
7089
+ ids: section.ids.filter((id) => id !== workspaceId)
7090
+ }));
7091
+ const next = sections.find((section) => section.id === sectionId);
7092
+ const at = index === void 0 ? next.ids.length : Math.max(0, Math.min(index, next.ids.length));
7093
+ next.ids.splice(at, 0, workspaceId);
7094
+ return { sections };
7095
+ }
7096
+ /** 新建自定义分区,插到兜底分区之前。 */
7097
+ function createSection(state, id, name) {
7098
+ const sections = state.sections.map((section) => ({
7099
+ ...section,
7100
+ ids: section.ids.slice()
7101
+ }));
7102
+ const defaultIndex = sections.findIndex((section) => section.id === DEFAULT_SECTION_ID);
7103
+ const at = defaultIndex === -1 ? sections.length : defaultIndex;
7104
+ sections.splice(at, 0, {
7105
+ id,
7106
+ name,
7107
+ ids: []
7108
+ });
7109
+ return { sections };
7110
+ }
7111
+ /** 重命名分区;名称为空时忽略。 */
7112
+ function renameSection(state, sectionId, name) {
7113
+ if (isBuiltinSection(sectionId)) return state;
7114
+ const trimmed = name.trim();
7115
+ if (trimmed === "") return state;
7116
+ return { sections: state.sections.map((section) => section.id === sectionId ? {
7117
+ ...section,
7118
+ name: trimmed,
7119
+ ids: section.ids.slice()
7120
+ } : section) };
7121
+ }
7122
+ /**
7123
+ * 删除自定义分区,成员并入兜底分区末尾。
7124
+ * 内置分区(置顶、项目)不可删除,原样返回。
7125
+ */
7126
+ function deleteSection(state, sectionId) {
7127
+ if (isBuiltinSection(sectionId)) return state;
7128
+ const removed = state.sections.find((section) => section.id === sectionId);
7129
+ if (removed === void 0) return state;
7130
+ return { sections: state.sections.filter((section) => section.id !== sectionId).map((section) => section.id === "default" ? {
7131
+ ...section,
7132
+ ids: [...section.ids, ...removed.ids]
7133
+ } : {
7134
+ ...section,
7135
+ ids: section.ids.slice()
7136
+ }) };
7137
+ }
7138
+ /**
7139
+ * 用宿主的最新顺序校正归属(用户在原生树上直接拖动项目后调用)。
7140
+ *
7141
+ * 判定方式:把新旧顺序做前后缀比较,找出唯一被移动的项;它归入「新位置上方最近的邻居」所属分区,
7142
+ * 没有上方邻居时归入下方邻居的分区,两侧都没有则落到兜底分区。
7143
+ * 其余项保持原归属。返回结构的分区摊平结果与新顺序逐项一致。
7144
+ *
7145
+ * @param state - 拖动前的结构。
7146
+ * @param order - 宿主当前的完整工作区顺序。
7147
+ * @returns 校正后的结构与是否发生变化。
7148
+ */
7149
+ function reconcileHostOrder(state, order) {
7150
+ const assignments = /* @__PURE__ */ new Map();
7151
+ for (const section of state.sections) for (const id of section.ids) assignments.set(id, section.id);
7152
+ let added = false;
7153
+ for (const id of order) if (!assignments.has(id)) {
7154
+ assignments.set(id, DEFAULT_SECTION_ID);
7155
+ added = true;
7156
+ }
7157
+ const sections = state.sections.map((section) => {
7158
+ const ids = order.filter((id) => assignments.get(id) === section.id);
7159
+ return {
7160
+ id: section.id,
7161
+ name: section.name,
7162
+ ids
7163
+ };
7164
+ });
7165
+ const changed = added || sections.some((section, index) => {
7166
+ const before = state.sections[index];
7167
+ if (before === void 0 || before.ids.length !== section.ids.length) return true;
7168
+ return before.ids.some((id, i) => id !== section.ids[i]);
7169
+ });
7170
+ return {
7171
+ state: { sections },
7172
+ changed
7173
+ };
7174
+ }
7175
+ //#endregion
7176
+ //#region src/client/sidebar/sections/motion.ts
7177
+ /**
7178
+ * 分区事务的布局动效:宿主仍拥有所有项目节点,只在一次最终布局上做块级 FLIP。
7179
+ * 普通原生拖拽不进入此流程;不调用 React 实例或宿主私有动画方法。
7180
+ */
7181
+ var SectionLayoutMotion = class {
7182
+ list;
7183
+ positions = /* @__PURE__ */ new Map();
7184
+ animations = /* @__PURE__ */ new Set();
7185
+ constructor(list) {
7186
+ this.list = list;
7187
+ for (const element of Array.from(list.children)) if (element instanceof HTMLElement) this.positions.set(element, element.getBoundingClientRect());
7188
+ }
7189
+ /** 合并标题与成员最终布局,在同一绘制前替换本次排序的行级位移。 */
7190
+ play(layout) {
7191
+ for (const row of Array.from(this.list.querySelectorAll("[data-row-key]"))) for (const animation of row.getAnimations?.() ?? []) {
7192
+ const effect = animation.effect;
7193
+ if (typeof effect?.getKeyframes === "function" && effect.getKeyframes().some((frame) => frame.transform !== void 0)) animation.cancel();
7194
+ }
7195
+ layout();
7196
+ if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return Promise.resolve();
7197
+ const finished = Array.from(this.list.children).flatMap((element) => {
7198
+ if (!(element instanceof HTMLElement) || typeof element.animate !== "function") return [];
7199
+ const before = this.positions.get(element);
7200
+ const after = element.getBoundingClientRect();
7201
+ if (after.height === 0) return [];
7202
+ if (before === void 0 || before.height === 0) return [{
7203
+ element,
7204
+ keyframes: [{ opacity: 0 }, { opacity: 1 }]
7205
+ }];
7206
+ const dx = before.left - after.left;
7207
+ const dy = before.top - after.top;
7208
+ if (dx === 0 && dy === 0) return [];
7209
+ return [{
7210
+ element,
7211
+ keyframes: [{ transform: `translate(${dx}px, ${dy}px)` }, { transform: "none" }]
7212
+ }];
7213
+ }).map(({ element, keyframes }) => {
7214
+ const animation = element.animate(keyframes, {
7215
+ duration: 200,
7216
+ easing: "ease-out"
7217
+ });
7218
+ this.animations.add(animation);
7219
+ return animation.finished.catch(() => {}).then(() => {
7220
+ animation.cancel();
7221
+ this.animations.delete(animation);
7222
+ });
7223
+ });
7224
+ return Promise.all(finished).then(() => {});
7225
+ }
7226
+ /** 卸载时取消本实例创建的动画,释放对宿主节点的引用。 */
7227
+ dispose() {
7228
+ for (const animation of this.animations) animation.cancel();
7229
+ this.animations.clear();
7230
+ this.positions.clear();
7231
+ }
7232
+ };
7233
+ //#endregion
7234
+ //#region src/client/sidebar/sections/order.ts
7235
+ /**
7236
+ * 生成一次性排序计划,不根据宿主中间帧反复纠偏。
7237
+ * 显式操作只允许移动给定的项目;启动恢复才允许调整整表。
7238
+ */
7239
+ function planWorkspaceMoves(current, desired, workspaceIds) {
7240
+ const order = current.slice();
7241
+ const moves = [];
7242
+ const move = (workspaceId, beforeWorkspaceId) => {
7243
+ if (!order.includes(workspaceId)) return;
7244
+ const next = order.filter((id) => id !== workspaceId);
7245
+ const at = beforeWorkspaceId === void 0 ? next.length : next.indexOf(beforeWorkspaceId);
7246
+ if (at < 0) return;
7247
+ next.splice(at, 0, workspaceId);
7248
+ if (next.every((id, index) => id === order[index])) return;
7249
+ moves.push({
7250
+ workspaceId,
7251
+ beforeWorkspaceId
7252
+ });
7253
+ order.splice(0, order.length, ...next);
7254
+ };
7255
+ if (workspaceIds !== void 0) {
7256
+ const moving = new Set(workspaceIds);
7257
+ for (let index = desired.length - 1; index >= 0; index -= 1) {
7258
+ const id = desired[index];
7259
+ if (moving.has(id)) move(id, desired[index + 1]);
7260
+ }
7261
+ } else for (let index = 0; index < desired.length; index += 1) if (order[index] !== desired[index]) move(desired[index], order[index]);
7262
+ return moves;
7263
+ }
7264
+ let transport = {
7265
+ async load() {
7266
+ try {
7267
+ const response = await fetch(CODEX_UI_API_ENDPOINTS.sections, {
7268
+ credentials: "same-origin",
7269
+ headers: { accept: "application/json" }
7270
+ });
7271
+ if (!response.ok) return null;
7272
+ const text = await response.text();
7273
+ return text.trim() === "" ? null : text;
7274
+ } catch {
7275
+ return null;
7276
+ }
7277
+ },
7278
+ async save(body) {
7279
+ try {
7280
+ return (await fetch(CODEX_UI_API_ENDPOINTS.sections, {
7281
+ method: "POST",
7282
+ credentials: "same-origin",
7283
+ headers: { "content-type": "application/json" },
7284
+ body
7285
+ })).ok;
7286
+ } catch {
7287
+ return false;
7288
+ }
7289
+ }
7290
+ };
7291
+ /**
7292
+ * 读取宿主里的分区文档。
7293
+ *
7294
+ * @returns 原始 JSON 文本;读取失败时返回 `null`,调用方按默认结构启动,不影响侧栏渲染。
7295
+ */
7296
+ async function loadSectionsDocument() {
7297
+ return transport.load();
7298
+ }
7299
+ let pending;
7300
+ let timer;
7301
+ let inFlight;
7302
+ async function flush() {
7303
+ const body = pending;
7304
+ pending = void 0;
7305
+ if (body === void 0) return;
7306
+ if (!await transport.save(body) && pending === void 0) {
7307
+ pending = body;
7308
+ scheduleSave();
7309
+ }
7310
+ }
7311
+ /** 立刻把待写内容发出去(切换页面、卸载时使用)。 */
7312
+ async function flushSectionsSave() {
7313
+ if (timer !== void 0) {
7314
+ window.clearTimeout(timer);
7315
+ timer = void 0;
7316
+ }
7317
+ inFlight = flush();
7318
+ await inFlight;
7319
+ inFlight = void 0;
7320
+ }
7321
+ function scheduleSave() {
7322
+ if (timer !== void 0) window.clearTimeout(timer);
7323
+ timer = window.setTimeout(() => {
7324
+ timer = void 0;
7325
+ if (inFlight !== void 0) return;
7326
+ inFlight = flush().finally(() => {
7327
+ inFlight = void 0;
7328
+ });
7329
+ }, 350);
7330
+ }
7331
+ /**
7332
+ * 排队保存分区文档(350ms 合并连续操作,避免拖动时每次移动都打一次请求)。
7333
+ *
7334
+ * @param body - 完整文档 JSON。
7335
+ */
7336
+ function scheduleSectionsSave(body) {
7337
+ pending = body;
7338
+ scheduleSave();
7339
+ }
7340
+ //#endregion
7341
+ //#region src/client/sidebar/sections/index.ts
7342
+ /** 分区标题行的标记属性,样式与测试都靠它定位。 */
7343
+ const SECTION_HEADER_ATTR = "data-dcu-ws-section";
7344
+ /** 追加在项目行菜单里的入口标记。 */
7345
+ const MENU_ITEM_ATTR = "data-dcu-ws-section-item";
7346
+ const HEADER_CLASS = "dcu-ws-section";
7347
+ const STYLE_ID = "michengai-codex-ui-sections-styles";
7348
+ /** 各分区的折叠状态(与本文件的分区数据分键存放)。 */
7349
+ const COLLAPSED_STORAGE_KEY = "michengai.codex-ui.workspace-sections-collapsed.v1";
7350
+ /**
7351
+ * 分区标题、菜单与拖拽指示线的样式。
7352
+ * 只吃宿主主题变量,随明暗与主题切换自动跟随;宿主变量缺失时回退中性色。
7353
+ */
7354
+ const SECTIONS_CSS = `
7355
+ .dcu-ws-section{display:flex;align-items:center;gap:4px;height:30px;margin:8px 2px 2px;padding:0 4px 0 var(--dcu-section-lead,6px);font-size:12px;letter-spacing:.2px;color:var(--dsw-alias-label-tertiary,rgba(127,127,127,.95));-webkit-app-region:no-drag;cursor:pointer;border-radius:6px}
7356
+ .dcu-ws-section:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.10))}
7357
+ .dcu-ws-section-label{flex:0 0 auto;max-width:70%;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
7358
+ /* 展开/收起三角与宿主项目行同构:16×20 的 slot,里面是 14px 的实心三角,展开旋转 90°。 */
7359
+ .dcu-ws-section-chevron{display:inline-flex;align-items:center;justify-content:center;flex:none;width:16px;height:20px;color:var(--dsw-alias-label-caption,var(--dsw-alias-label-tertiary,#888))}
7360
+ .dcu-ws-section-chevron svg{display:block;transition:transform .15s var(--ds-ease-in-out,cubic-bezier(.2,0,0,1))}
7361
+ .dcu-ws-section[data-open='true'] .dcu-ws-section-chevron svg{transform:rotate(90deg)}
7362
+ .dcu-ws-section-grow{flex:1 1 auto}
7363
+ .dcu-ws-section-input{flex:1 1 auto;min-width:0;height:22px;padding:0 6px;border-radius:5px;font:inherit;font-size:12.5px;color:var(--dsw-alias-label-primary,inherit);background:var(--dsw-alias-bg-layer-2,rgba(127,127,127,.14));border:.5px solid var(--dsw-alias-border-l3,rgba(127,127,127,.4));outline:none}
7364
+ .dcu-ws-section-editing{margin:4px 2px;padding-left:0}
7365
+ /* 分区成员不加缩进:项目行以下全是宿主自己的排版(会话行、缩进变量都在里面),
7366
+ 这里再补 padding 会把整个项目块连同会话一起右移,跟原生不一致。成员标记只用于折叠隐藏。 */
7367
+ [data-dcu-section-member]{transition:max-height 180ms var(--ds-ease-in-out,cubic-bezier(.2,0,0,1)),opacity 180ms var(--ds-ease-in-out,cubic-bezier(.2,0,0,1))}
7368
+ [data-dcu-section-hidden='true']{display:none !important}
7369
+ .dcu-ws-section-actions{display:flex;gap:2px;opacity:.55;transition:opacity .12s ease;flex:none}
7370
+ .dcu-ws-section:hover .dcu-ws-section-actions,.dcu-ws-section:focus-within .dcu-ws-section-actions{opacity:1}
7371
+ .dcu-ws-section-action{width:22px;height:22px;border:0;border-radius:50%;background:transparent;color:inherit;font:inherit;font-size:12px;line-height:1;cursor:pointer;display:grid;place-items:center}
7372
+ .dcu-ws-section-action:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.16))}
7373
+ [data-sidebar-collapsed='true'] .dcu-ws-section{display:none !important}
7374
+ .dcu-ws-section-menu{position:fixed;z-index:1000;min-width:184px;max-width:280px;overflow-y:auto;overscroll-behavior:contain;scrollbar-width:thin;padding:4px;display:flex;flex-direction:column;gap:2px;border:none;border-radius:var(--dsw-radius-md,8px);background:var(--dsw-menu-surface-fill,var(--dsw-alias-surface-overlay,#1e1e22));backdrop-filter:var(--dsw-menu-backdrop-filter,blur(40px) saturate(150%));-webkit-backdrop-filter:var(--dsw-menu-backdrop-filter,blur(40px) saturate(150%));box-shadow:var(--dsw-elevation-prominent,0 6px 20px rgba(0,0,0,.45));color:var(--dsw-alias-label-primary,#ededed)}
7375
+ /* 父菜单与二级菜单之间有一小段空隙:铺一条透明桥,指针穿过去时不会触发离开事件。 */
7376
+ .dcu-ws-section-menu[data-flyout='true']::before{content:'';position:absolute;top:0;bottom:0;left:-6px;width:8px}
7377
+ .dcu-ws-section-menu button{display:flex;align-items:center;gap:8px;width:100%;min-height:28px;padding:6px 10px;text-align:left;border:0;border-radius:var(--dsw-radius-sm,6px);background:transparent;color:inherit;font:inherit;font-size:13px;line-height:20px;cursor:pointer;transition:background-color .12s ease}
7378
+ .dcu-ws-section-menu .dcu-ws-section-menu-icon{display:grid;place-items:center;width:16px;height:16px;flex:none;color:var(--dsw-alias-label-secondary,#a1a1a6)}
7379
+ .dcu-ws-section-menu .dcu-ws-section-menu-icon:empty{display:none}
7380
+ .dcu-ws-section-menu .dcu-ws-section-menu-label{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
7381
+ .dcu-ws-section-menu button:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.08))}
7382
+ .dcu-ws-section-menu button[aria-current='true']{color:var(--dsw-alias-state-business-primary,#4176e6)}
7383
+ .dcu-ws-section[data-dcu-section-fixed='true']{cursor:default}
7384
+ /* 跨分区拖拽拦截时以 CSS 隐藏宿主落点线,绝不侵入修改宿主 React 的 DOM className;移回合法区自然恢复 */
7385
+ body[data-dcu-drag-blocked='true'] [class*="workspaceDropBefore"]::before,
7386
+ body[data-dcu-drag-blocked='true'] [class*="workspaceDropAfter"]::after,
7387
+ body[data-dcu-drag-blocked='true'] [class*="dropBefore"]::before,
7388
+ body[data-dcu-drag-blocked='true'] [class*="dropAfter"]::after{display:none !important}
7389
+
7390
+ `;
7391
+ /** 注入分区样式;已存在时复用(样式与组件生命周期解耦,卸载不摘除)。 */
7392
+ function injectStyles() {
7393
+ if (document.getElementById(STYLE_ID) !== null) return;
7394
+ const style = document.createElement("style");
7395
+ style.id = STYLE_ID;
7396
+ style.textContent = SECTIONS_CSS;
7397
+ document.head.appendChild(style);
7398
+ }
7399
+ /** 内置分区的显示名走本地化;用户改过名则用用户的名字。 */
7400
+ function localizeBuiltinName(sectionId, storedName, text) {
7401
+ if (sectionId === "pinned") return text("sections.pinned", "置顶");
7402
+ if (sectionId === "default") return text("sections.default", "项目");
7403
+ return storedName;
7404
+ }
7405
+ const MENU_CLASS = "dcu-ws-section-menu";
7406
+ /** 从行节点上读出工作区 id:`data-row-key="workspace:<id>"`,未分组桶为空串。 */
7407
+ function workspaceIdOfRow(row) {
7408
+ const key = row.getAttribute("data-row-key");
7409
+ if (key === null || !key.startsWith("workspace:")) return void 0;
7410
+ const id = key.slice(10);
7411
+ return id === "" ? void 0 : id;
7412
+ }
7413
+ /**
7414
+ * 列表是否属于侧栏的「工作区」区块。
7415
+ *
7416
+ * 频道、定时等页签下也会出现树形列表,只有同时满足下面三条才算工作区,避免把分区标题塞进别的列表:
7417
+ * 不在 rail(侧栏收起)形态里、同一区域的区块标题带有多颗操作按钮、列表里确有项目行。
7418
+ */
7419
+ function isWorkspaceRegion(list) {
7420
+ if (list.querySelector("[data-row-key^=\"workspace:\"]") === null) return false;
7421
+ let node = list.parentElement;
7422
+ for (let level = 0; level < 4 && node !== null; level += 1) {
7423
+ const header = node.querySelector("[class*=\"sectionHeader\"]");
7424
+ if (header !== null) {
7425
+ const actions = header.querySelector("[class*=\"headerActions\"]");
7426
+ if (actions !== null && actions.querySelectorAll("button").length >= 2) return true;
7427
+ }
7428
+ node = node.parentElement;
7429
+ }
7430
+ return false;
7431
+ }
7432
+ /** 收集原生列表里的项目分组块,按 DOM 顺序。 */
7433
+ function collectProjectBlocks(root, list) {
7434
+ const container = list ?? findWorkspaceList(root);
7435
+ if (container === void 0) return [];
7436
+ const blocks = [];
7437
+ for (const row of Array.from(root.querySelectorAll("[data-row-key^=\"workspace:\"]"))) {
7438
+ const workspaceId = workspaceIdOfRow(row);
7439
+ if (workspaceId === void 0) continue;
7440
+ const block = blockOf(row, container);
7441
+ if (block !== null) blocks.push({
7442
+ workspaceId,
7443
+ block
7444
+ });
7445
+ }
7446
+ return blocks;
7447
+ }
7448
+ /**
7449
+ * 找到承载全部项目行的滚动列表。
7450
+ *
7451
+ * 宿主结构是 `div[role=tree].list > div.groupSection > span > div[data-row-key]`,
7452
+ * 直接取 `row.parentElement.parentElement` 只会拿到第一个分组块内部,标题就会全挤在最上面。
7453
+ * 这里改成语义判定:从第一行向上找到「同时包含所有行」的祖先。
7454
+ */
7455
+ function findWorkspaceList(root) {
7456
+ const rows = Array.from(root.querySelectorAll("[data-row-key^=\"workspace:\"]")).filter((row) => workspaceIdOfRow(row) !== void 0);
7457
+ if (rows.length === 0) return void 0;
7458
+ const first = rows[0];
7459
+ const last = rows[rows.length - 1];
7460
+ let node = first.parentElement;
7461
+ let treeCandidate;
7462
+ let anyCandidate;
7463
+ while (node !== null) {
7464
+ if (node.contains(last) && isWorkspaceRegion(node)) {
7465
+ if (node.getAttribute("role") === "tree") treeCandidate = node;
7466
+ else anyCandidate = node;
7467
+ }
7468
+ node = node.parentElement;
7469
+ }
7470
+ return treeCandidate ?? anyCandidate;
7471
+ }
7472
+ /** 行所属的分组块:行到列表之间、父节点就是列表的那一层。 */
7473
+ function blockOf(row, list) {
7474
+ let node = row instanceof HTMLElement ? row : null;
7475
+ while (node !== null && node.parentElement !== list) node = node.parentElement;
7476
+ return node;
7477
+ }
7478
+ /**
7479
+ * 观察并驱动工作区分区。
7480
+ *
7481
+ * @param ctx - 客户端根 Context。
7482
+ * @returns 释放函数;卸载后标题、监听与在途写入全部撤销。
7483
+ */
7484
+ let activeInstance;
7485
+ function observeWorkspaceSections(ctx, translate) {
7486
+ if (typeof document === "undefined") return () => {};
7487
+ const text = (key, fallback) => {
7488
+ try {
7489
+ const value = translate?.(key, fallback);
7490
+ return value === void 0 || value === "" ? fallback : value;
7491
+ } catch {
7492
+ return fallback;
7493
+ }
7494
+ };
7495
+ injectStyles();
7496
+ activeInstance?.();
7497
+ let disposed = false;
7498
+ let state = createSectionsState();
7499
+ /** 分区文档是否已从宿主导入;未导入前不渲染标题、不做顺序写入。 */
7500
+ let sectionsLoaded = false;
7501
+ let list;
7502
+ let baselineSet = false;
7503
+ let activeUpdate;
7504
+ let writeGen = 0;
7505
+ let waitNotice;
7506
+ let noticeTimer;
7507
+ const clearWriteWait = () => {
7508
+ writeGen += 1;
7509
+ if (noticeTimer !== void 0) window.clearTimeout(noticeTimer);
7510
+ noticeTimer = void 0;
7511
+ waitNotice?.remove();
7512
+ waitNotice = void 0;
7513
+ };
7514
+ const showAbortedNotice = () => {
7515
+ if (disposed || list?.parentElement === null || list === void 0) return;
7516
+ clearWriteWait();
7517
+ waitNotice = document.createElement("div");
7518
+ waitNotice.setAttribute("data-dcu-sections-wait", "aborted");
7519
+ waitNotice.setAttribute("role", "alert");
7520
+ waitNotice.textContent = text("sections.writeAborted", "工作区移动未完成,已自动撤销。");
7521
+ waitNotice.style.cssText = "padding: 8px 12px; font-size: 12px; color: var(--dsw-alias-text-danger, #ef4444);";
7522
+ list.parentElement.insertBefore(waitNotice, list);
7523
+ const notice = waitNotice;
7524
+ noticeTimer = window.setTimeout(() => {
7525
+ noticeTimer = void 0;
7526
+ if (waitNotice === notice) {
7527
+ notice.remove();
7528
+ waitNotice = void 0;
7529
+ }
7530
+ }, 4e3);
7531
+ };
7532
+ const insertWorkspace = async (service, workspaceId, beforeWorkspaceId) => {
7533
+ const curGen = ++writeGen;
7534
+ const timer8s = window.setTimeout(() => {
7535
+ if (disposed || writeGen !== curGen || list?.parentElement === null || list === void 0) return;
7536
+ waitNotice?.remove();
7537
+ waitNotice = document.createElement("div");
7538
+ waitNotice.setAttribute("data-dcu-sections-wait", "");
7539
+ waitNotice.setAttribute("role", "status");
7540
+ waitNotice.textContent = text("sections.writePending", "工作区移动尚未完成,后续操作正在等待宿主响应。");
7541
+ waitNotice.style.cssText = "padding: 8px 12px; font-size: 12px; color: var(--dsw-alias-text-secondary, inherit);";
7542
+ list.parentElement.insertBefore(waitNotice, list);
7543
+ }, 8e3);
7544
+ let timer20s;
7545
+ try {
7546
+ await Promise.race([service.insertBefore(workspaceId, beforeWorkspaceId), new Promise((_, reject) => {
7547
+ timer20s = window.setTimeout(() => {
7548
+ if (writeGen === curGen) reject(/* @__PURE__ */ new Error("宿主响应超时 (20s)"));
7549
+ }, 2e4);
7550
+ })]);
7551
+ } finally {
7552
+ window.clearTimeout(timer8s);
7553
+ if (timer20s !== void 0) window.clearTimeout(timer20s);
7554
+ if (writeGen === curGen) {
7555
+ waitNotice?.remove();
7556
+ waitNotice = void 0;
7557
+ }
7558
+ }
7559
+ };
7560
+ const updates = [];
7561
+ let committedState = state;
7562
+ let wired = false;
7563
+ let syncing = false;
7564
+ let rafId = 0;
7565
+ let observer;
7566
+ let unsubscribe;
7567
+ const headers = /* @__PURE__ */ new Map();
7568
+ let menuHost;
7569
+ /** 当前二级菜单的锚点(「分区」那一行),悬停重复触发时用来去重。 */
7570
+ let assignAnchor;
7571
+ const workspaces = () => {
7572
+ const service = ctx.get?.("workspaces");
7573
+ if (service === void 0 || service === null) return void 0;
7574
+ const candidate = service;
7575
+ if (typeof candidate.insertBefore !== "function" || candidate.list === void 0) return void 0;
7576
+ return candidate;
7577
+ };
7578
+ const knownIds = () => {
7579
+ const service = workspaces();
7580
+ if (service === void 0) return [];
7581
+ try {
7582
+ return service.list.getSnapshot().items.map((item) => item.workspaceId);
7583
+ } catch {
7584
+ return [];
7585
+ }
7586
+ };
7587
+ const domOrder = () => collectProjectBlocks(list ?? document, list).map((block) => block.workspaceId);
7588
+ /**
7589
+ * 从宿主导入分区文档。
7590
+ *
7591
+ * 宿主读不到(接口未就绪、首次运行)时按默认结构启动:只有「置顶 + 项目」两个内置分区,
7592
+ * 首次同步会把宿主现有工作区顺序采纳进「项目」,与以前的全新安装行为一致。
7593
+ */
7594
+ async function loadStateFromHost() {
7595
+ let raw = null;
7596
+ try {
7597
+ raw = await loadSectionsDocument();
7598
+ } catch {
7599
+ raw = null;
7600
+ }
7601
+ state = normalizeSections(parseSections(raw) ?? { sections: [] });
7602
+ committedState = state;
7603
+ sectionsLoaded = true;
7604
+ scheduleSync();
7605
+ }
7606
+ /** 分区文档写回宿主;失败不阻塞界面,下一次用户操作会再触发保存。 */
7607
+ function persist(value = state) {
7608
+ if (!sectionsLoaded) return;
7609
+ scheduleSectionsSave(serializeSections(value));
7610
+ }
7611
+ function commit(next) {
7612
+ commitExplicit(next, []);
7613
+ }
7614
+ /** 保留显式移动身份;在宿主确认且真实列表到位之前,不提前修改标题和折叠标记。 */
7615
+ function commitExplicit(next, workspaceIds) {
7616
+ if (disposed) return;
7617
+ state = next;
7618
+ updates.push({
7619
+ next,
7620
+ workspaceIds,
7621
+ rpcDone: false
7622
+ });
7623
+ startNextUpdate();
7624
+ }
7625
+ function ensureHeader(sectionId, name) {
7626
+ let header = headers.get(sectionId);
7627
+ if (header !== void 0 && header.isConnected) {
7628
+ const label = header.querySelector(`.${HEADER_CLASS}-label`);
7629
+ const next = localizeBuiltinName(sectionId, name, text);
7630
+ if (label !== null && label.textContent !== next) label.textContent = next;
7631
+ return header;
7632
+ }
7633
+ header = document.createElement("div");
7634
+ header.className = HEADER_CLASS;
7635
+ header.setAttribute(SECTION_HEADER_ATTR, sectionId);
7636
+ if (isBuiltinSection(sectionId)) header.setAttribute("data-dcu-section-fixed", "true");
7637
+ header.draggable = false;
7638
+ header.tabIndex = 0;
7639
+ header.dataset.open = collapsed[sectionId] === true ? "false" : "true";
7640
+ const label = document.createElement("span");
7641
+ label.className = `${HEADER_CLASS}-label`;
7642
+ label.textContent = localizeBuiltinName(sectionId, name, text);
7643
+ header.appendChild(label);
7644
+ const chevron = document.createElement("span");
7645
+ chevron.className = `${HEADER_CLASS}-chevron`;
7646
+ chevron.innerHTML = iconChevron();
7647
+ header.appendChild(chevron);
7648
+ const grow = document.createElement("span");
7649
+ grow.className = `${HEADER_CLASS}-grow`;
7650
+ header.appendChild(grow);
7651
+ const actions = document.createElement("span");
7652
+ actions.className = `${HEADER_CLASS}-actions`;
7653
+ actions.appendChild(buildHeaderActionButton(sectionId, name));
7654
+ header.appendChild(actions);
7655
+ header.addEventListener("click", (event) => {
7656
+ if (event.target instanceof Element && event.target.closest(`.${HEADER_CLASS}-actions`) !== null) return;
7657
+ toggleSection(sectionId);
7658
+ });
7659
+ header.addEventListener("keydown", (event) => {
7660
+ if (event.key === "Enter" || event.key === " ") {
7661
+ event.preventDefault();
7662
+ toggleSection(sectionId);
7663
+ }
7664
+ });
7665
+ headers.set(sectionId, header);
7666
+ return header;
7667
+ }
7668
+ /** 分区标题右侧的 `···`:直接克隆宿主项目行的原生图标按钮,样式与宿主完全一致。 */
7669
+ function buildHeaderActionButton(sectionId, name) {
7670
+ const hostButton = document.querySelector("[data-row-key^=\"workspace:\"] [class*=\"rowActions\"] button");
7671
+ let button;
7672
+ if (hostButton !== null) {
7673
+ button = hostButton.cloneNode(true);
7674
+ button.removeAttribute("aria-keyshortcuts");
7675
+ button.removeAttribute("tabindex");
7676
+ } else {
7677
+ button = document.createElement("button");
7678
+ button.className = `${HEADER_CLASS}-action`;
7679
+ button.textContent = "···";
7680
+ }
7681
+ button.setAttribute("type", "button");
7682
+ button.setAttribute("aria-label", `${name} ${text("sections.settings", "分区设置")}`);
7683
+ button.addEventListener("click", (event) => {
7684
+ event.preventDefault();
7685
+ event.stopPropagation();
7686
+ openSectionMenu(sectionId, button);
7687
+ });
7688
+ return button;
7689
+ }
7690
+ function toggleSection(sectionId) {
7691
+ const header = headers.get(sectionId);
7692
+ const collapse = !(header?.dataset.open === "false");
7693
+ collapsed[sectionId] = collapse;
7694
+ persistCollapsed();
7695
+ if (header !== void 0) header.dataset.open = collapse ? "false" : "true";
7696
+ animateSectionMembers(sectionId, collapse);
7697
+ scheduleSync();
7698
+ }
7699
+ /** 正在做折叠动画的分区:这段时间里 placeHeaders 不要改写成员的显示状态。 */
7700
+ const animatingSections = /* @__PURE__ */ new Set();
7701
+ /** 每个分区最近一次折叠动画的代号,用来丢弃过期回调。 */
7702
+ const animationGeneration = /* @__PURE__ */ new Map();
7703
+ /**
7704
+ * 折叠/展开动画。
7705
+ *
7706
+ * 成员是宿主的分组块,不能包容器,所以对块本身做 max-height 过渡(经典稳妥做法):
7707
+ * 先量出当前高度写成具体 px,再过渡到 0;展开反向。用 max-height 而不是 `height:auto`
7708
+ * 是因为宿主块内部有自己的布局,auto 插值在逐帧重排时会互相压住(表现为项目文件夹重叠)。
7709
+ */
7710
+ function animateSectionMembers(sectionId, collapse) {
7711
+ const blocks = Array.from(document.querySelectorAll(`[data-dcu-section-member="${sectionId}"]`));
7712
+ if (blocks.length === 0) return;
7713
+ const generation = (animationGeneration.get(sectionId) ?? 0) + 1;
7714
+ animationGeneration.set(sectionId, generation);
7715
+ animatingSections.add(sectionId);
7716
+ for (const block of blocks) {
7717
+ if (!block.isConnected) continue;
7718
+ if (collapse) {
7719
+ block.removeAttribute("data-dcu-section-hidden");
7720
+ block.style.overflow = "hidden";
7721
+ const height = block.offsetHeight;
7722
+ block.style.maxHeight = `${height}px`;
7723
+ block.style.opacity = "1";
7724
+ block.offsetHeight;
7725
+ block.style.maxHeight = "0px";
7726
+ block.style.opacity = "0";
7727
+ } else {
7728
+ block.removeAttribute("data-dcu-section-hidden");
7729
+ block.style.overflow = "hidden";
7730
+ block.style.maxHeight = "0px";
7731
+ block.style.opacity = "0";
7732
+ block.offsetHeight;
7733
+ const targetHeight = Math.max(block.scrollHeight, block.offsetHeight || 40);
7734
+ block.style.maxHeight = `${targetHeight}px`;
7735
+ block.style.opacity = "1";
7736
+ }
7737
+ }
7738
+ window.setTimeout(() => {
7739
+ if (animationGeneration.get(sectionId) !== generation) return;
7740
+ blocks.forEach((block) => {
7741
+ if (!block.isConnected) return;
7742
+ block.style.removeProperty("max-height");
7743
+ block.style.removeProperty("overflow");
7744
+ block.style.removeProperty("opacity");
7745
+ if (collapse) block.setAttribute("data-dcu-section-hidden", "true");
7746
+ else block.removeAttribute("data-dcu-section-hidden");
7747
+ });
7748
+ animatingSections.delete(sectionId);
7749
+ scheduleSync();
7750
+ }, 210);
7751
+ }
7752
+ function readCollapsed() {
7753
+ try {
7754
+ const raw = window.localStorage.getItem(COLLAPSED_STORAGE_KEY);
7755
+ if (raw === null) return {};
7756
+ const parsed = JSON.parse(raw);
7757
+ return typeof parsed === "object" && parsed !== null ? parsed : {};
7758
+ } catch {
7759
+ return {};
7760
+ }
7761
+ }
7762
+ function persistCollapsed() {
7763
+ try {
7764
+ window.localStorage.setItem(COLLAPSED_STORAGE_KEY, JSON.stringify(collapsed));
7765
+ } catch {}
7766
+ }
7767
+ /** 上一次算对齐时的(标题数+列宽)组合,避免每帧量 rect。 */
7768
+ let lastAlignKey = "";
7769
+ /** 把标题按分区顺序放到各自第一个分组块前面;空分区贴着下一个分区显示。 */
7770
+ function placeHeaders(blocks, layoutState = state) {
7771
+ if (blocks.length === 0) return;
7772
+ const target = blocks[0].block.parentElement;
7773
+ if (target === null) return;
7774
+ const ungrouped = Array.from(list?.querySelectorAll("[data-row-key=\"workspace:\"]") ?? []).map((row) => row instanceof HTMLElement ? blockOf(row, list) : null).find((block) => block !== null);
7775
+ const byId = new Map(blocks.map((item) => [item.workspaceId, item.block]));
7776
+ let reference = null;
7777
+ for (let index = layoutState.sections.length - 1; index >= 0; index -= 1) {
7778
+ const section = layoutState.sections[index];
7779
+ const first = section.ids.map((id) => byId.get(id)).find((block) => block !== void 0);
7780
+ if (first !== void 0) reference = first;
7781
+ else if (section.id === "default" && ungrouped !== void 0) reference = ungrouped;
7782
+ const header = ensureHeader(section.id, section.name);
7783
+ if (header.parentElement !== target || header.nextElementSibling !== reference) target.insertBefore(header, reference);
7784
+ reference = header;
7785
+ }
7786
+ const memberOf = /* @__PURE__ */ new Map();
7787
+ for (const section of layoutState.sections) for (const id of section.ids) memberOf.set(id, section.id);
7788
+ for (const block of blocks) {
7789
+ const sectionId = memberOf.get(block.workspaceId);
7790
+ if (sectionId === void 0) {
7791
+ block.block.removeAttribute("data-dcu-section-member");
7792
+ block.block.removeAttribute("data-dcu-section-hidden");
7793
+ continue;
7794
+ }
7795
+ block.block.setAttribute("data-dcu-section-member", sectionId);
7796
+ if (animatingSections.has(sectionId)) continue;
7797
+ if (headers.get(sectionId)?.dataset.open === "false") block.block.setAttribute("data-dcu-section-hidden", "true");
7798
+ else {
7799
+ block.block.removeAttribute("data-dcu-section-hidden");
7800
+ block.block.style.removeProperty("max-height");
7801
+ block.block.style.removeProperty("overflow");
7802
+ block.block.style.removeProperty("opacity");
7803
+ }
7804
+ }
7805
+ const alignKey = `${headers.size}:${list?.clientWidth ?? 0}`;
7806
+ const label = document.querySelector("[class*=\"sectionLabel\"]");
7807
+ const firstHeader = headers.get(layoutState.sections[0]?.id ?? "pinned");
7808
+ if (label !== null && firstHeader !== void 0 && alignKey !== lastAlignKey) {
7809
+ lastAlignKey = alignKey;
7810
+ const lead = Math.max(0, Math.round(label.getBoundingClientRect().left - firstHeader.getBoundingClientRect().left));
7811
+ for (const header of headers.values()) header.style.setProperty("--dcu-section-lead", `${lead}px`);
7812
+ }
7813
+ if (ungrouped !== void 0) {
7814
+ ungrouped.setAttribute("data-dcu-section-member", DEFAULT_SECTION_ID);
7815
+ if (!animatingSections.has("default")) {
7816
+ if (headers.get("default")?.dataset.open === "false") ungrouped.setAttribute("data-dcu-section-hidden", "true");
7817
+ else {
7818
+ ungrouped.removeAttribute("data-dcu-section-hidden");
7819
+ ungrouped.style.removeProperty("max-height");
7820
+ ungrouped.style.removeProperty("overflow");
7821
+ ungrouped.style.removeProperty("opacity");
7822
+ }
7823
+ }
7824
+ }
7825
+ for (const [id, header] of Array.from(headers.entries())) if (!layoutState.sections.some((section) => section.id === id)) {
7826
+ header.remove();
7827
+ headers.delete(id);
7828
+ }
7829
+ }
7830
+ /** 列表不在工作区视图(频道、定时、rail 收起)时摘掉标题,避免串到别的列表里。 */
7831
+ function detachHeaders() {
7832
+ for (const header of headers.values()) header.remove();
7833
+ headers.clear();
7834
+ }
7835
+ function closeSectionMenu() {
7836
+ menuHost?.remove();
7837
+ menuHost = void 0;
7838
+ assignAnchor = void 0;
7839
+ }
7840
+ /**
7841
+ * 分区自己的菜单面板。
7842
+ * 宿主菜单的底色画在它内部的 viewport 上、外壳是全透明的,克隆外壳拿不到样式;
7843
+ * 这里直接用宿主主题令牌画一张同风格的菜单,图标仍用宿主图标组件渲染。
7844
+ */
7845
+ function openHostPanel(anchor, items, flyoutFrom) {
7846
+ closeSectionMenu();
7847
+ const parentMenu = flyoutFrom?.isConnected === true ? flyoutFrom : anchor.closest("[role=\"menu\"]");
7848
+ let panel;
7849
+ let viewport;
7850
+ if (parentMenu !== null && parentMenu !== void 0) {
7851
+ panel = parentMenu.cloneNode(false);
7852
+ panel.classList.add(MENU_CLASS);
7853
+ const material = parentMenu.querySelector("[class*=\"material\"]");
7854
+ if (material !== null) panel.appendChild(material.cloneNode(true));
7855
+ const vp = parentMenu.querySelector("[role=\"presentation\"], [class*=\"viewport\"]");
7856
+ if (vp !== null) {
7857
+ viewport = vp.cloneNode(false);
7858
+ panel.appendChild(viewport);
7859
+ } else viewport = panel;
7860
+ } else if (hostMenuShellTemplate !== void 0) {
7861
+ panel = hostMenuShellTemplate.cloneNode(false);
7862
+ panel.classList.add(MENU_CLASS);
7863
+ if (hostMenuViewportTemplate !== void 0) {
7864
+ viewport = hostMenuViewportTemplate.cloneNode(false);
7865
+ panel.appendChild(viewport);
7866
+ } else viewport = panel;
7867
+ } else {
7868
+ panel = document.createElement("div");
7869
+ panel.className = MENU_CLASS;
7870
+ panel.setAttribute("role", "menu");
7871
+ viewport = panel;
7872
+ }
7873
+ const sampleRow = parentMenu?.querySelector("[class*=\"itemWrap\"]") ?? hostMenuRowTemplate;
7874
+ const sampleRef = sampleRow?.querySelector("button[role=\"menuitem\"]") ?? void 0;
7875
+ for (const item of items) {
7876
+ const row = buildMenuRow(sampleRef, item.icon, item.label, "", sampleRow);
7877
+ if (row !== null) {
7878
+ row.querySelector("button")?.addEventListener("click", (event) => {
7879
+ event.preventDefault();
7880
+ event.stopPropagation();
7881
+ item.onSelect();
7882
+ });
7883
+ viewport.appendChild(row);
7884
+ } else {
7885
+ const button = document.createElement("button");
7886
+ button.type = "button";
7887
+ button.setAttribute("role", "menuitem");
7888
+ const icon = document.createElement("span");
7889
+ icon.className = `${MENU_CLASS}-icon`;
7890
+ icon.innerHTML = item.icon;
7891
+ const label = document.createElement("span");
7892
+ label.className = `${MENU_CLASS}-label`;
7893
+ label.textContent = item.label;
7894
+ button.append(icon, label);
7895
+ button.addEventListener("click", (event) => {
7896
+ event.preventDefault();
7897
+ event.stopPropagation();
7898
+ item.onSelect();
7899
+ });
7900
+ viewport.appendChild(button);
7901
+ }
7902
+ }
7903
+ let leaveTimer;
7904
+ const cancelLeave = () => {
7905
+ if (leaveTimer === void 0) return;
7906
+ window.clearTimeout(leaveTimer);
7907
+ leaveTimer = void 0;
7908
+ };
7909
+ panel.addEventListener("mouseenter", cancelLeave);
7910
+ panel.addEventListener("mouseleave", () => {
7911
+ cancelLeave();
7912
+ leaveTimer = window.setTimeout(() => {
7913
+ leaveTimer = void 0;
7914
+ closeSectionMenu();
7915
+ }, 180);
7916
+ });
7917
+ panel.addEventListener("pointerdown", (event) => event.stopPropagation());
7918
+ panel.addEventListener("mousedown", (event) => event.stopPropagation());
7919
+ if (parentMenu !== null && parentMenu !== void 0) {
7920
+ parentMenu.appendChild(panel);
7921
+ panel.dataset.flyout = "true";
7922
+ panel.style.left = "0px";
7923
+ panel.style.top = "0px";
7924
+ const rect = anchor.getBoundingClientRect();
7925
+ const width = panel.offsetWidth || 196;
7926
+ const height = panel.offsetHeight || 120;
7927
+ const parentRect = parentMenu.getBoundingClientRect();
7928
+ let left = parentRect.right + 2;
7929
+ if (left + width > window.innerWidth - 10) left = Math.max(10, parentRect.left - width - 4);
7930
+ const maxHeight = Math.max(140, Math.min(360, window.innerHeight - 20));
7931
+ panel.style.maxHeight = `${maxHeight}px`;
7932
+ let top = rect.top - 4;
7933
+ if (top + Math.min(height, maxHeight) > window.innerHeight - 10) top = Math.max(10, window.innerHeight - Math.min(height, maxHeight) - 10);
7934
+ panel.style.left = `${left}px`;
7935
+ panel.style.top = `${top}px`;
7936
+ } else {
7937
+ document.body.appendChild(panel);
7938
+ panel.style.left = "0px";
7939
+ panel.style.top = "0px";
7940
+ const rect = anchor.getBoundingClientRect();
7941
+ const width = panel.offsetWidth || 196;
7942
+ const height = panel.offsetHeight || 120;
7943
+ panel.style.left = `${Math.max(8, Math.min(rect.left + 4, window.innerWidth - width - 8))}px`;
7944
+ panel.style.top = `${Math.max(8, Math.min(rect.bottom + 4, window.innerHeight - height - 8))}px`;
7945
+ }
7946
+ menuHost = panel;
7947
+ }
7948
+ function openSectionMenu(sectionId, anchor) {
7949
+ const section = state.sections.find((item) => item.id === sectionId);
7950
+ if (section === void 0) return;
7951
+ const builtin = sectionId === "pinned" || sectionId === "default";
7952
+ const items = [];
7953
+ if (!builtin) items.push({
7954
+ label: text("sections.rename", "重命名"),
7955
+ icon: iconEdit(),
7956
+ onSelect: () => {
7957
+ closeSectionMenu();
7958
+ startRename(sectionId);
7959
+ }
7960
+ });
7961
+ items.push({
7962
+ label: text("sections.new", "新建分区"),
7963
+ icon: iconPlus(),
7964
+ onSelect: () => {
7965
+ closeSectionMenu();
7966
+ startCreateSection();
7967
+ }
7968
+ });
7969
+ if (!builtin) items.push({
7970
+ label: text("sections.remove", "移除分区"),
7971
+ icon: iconClose(),
7972
+ onSelect: () => {
7973
+ closeSectionMenu();
7974
+ headers.get(sectionId)?.remove();
7975
+ headers.delete(sectionId);
7976
+ commitExplicit(deleteSection(state, sectionId), section.ids);
7977
+ }
7978
+ });
7979
+ openHostPanel(anchor, items);
7980
+ }
7981
+ /** 标题原地改名:只把标签换成输入框,不碰宿主节点。 */
7982
+ let editingInput;
7983
+ function startRename(sectionId) {
7984
+ const header = headers.get(sectionId);
7985
+ const label = header?.querySelector(`.${HEADER_CLASS}-label`);
7986
+ if (header === void 0 || label === null || label === void 0) return;
7987
+ const section = state.sections.find((item) => item.id === sectionId);
7988
+ if (section === void 0) return;
7989
+ label.style.display = "none";
7990
+ const input = document.createElement("input");
7991
+ input.className = `${HEADER_CLASS}-input`;
7992
+ input.value = section.name;
7993
+ input.maxLength = 24;
7994
+ header.insertBefore(input, label);
7995
+ input.focus();
7996
+ input.select();
7997
+ editingInput = input;
7998
+ const finish = (commitValue) => {
7999
+ if (editingInput !== input) return;
8000
+ editingInput = void 0;
8001
+ const value = input.value.trim();
8002
+ input.remove();
8003
+ label.style.display = "";
8004
+ if (commitValue && value !== "") commit(renameSection(state, sectionId, value));
8005
+ };
8006
+ input.addEventListener("keydown", (event) => {
8007
+ if (event.key === "Enter") {
8008
+ event.preventDefault();
8009
+ finish(true);
8010
+ } else if (event.key === "Escape") {
8011
+ event.preventDefault();
8012
+ finish(false);
8013
+ }
8014
+ });
8015
+ input.addEventListener("blur", () => finish(true));
8016
+ }
8017
+ /** 新建分区:在列表里插一行输入框,回车创建(宿主 web 里 window.prompt 被禁用,所以不用 prompt)。 */
8018
+ function startCreateSection(workspaceId) {
8019
+ const host = findWorkspaceList(document);
8020
+ if (host === void 0) return;
8021
+ const row = document.createElement("div");
8022
+ row.className = `${HEADER_CLASS} ${HEADER_CLASS}-editing`;
8023
+ const input = document.createElement("input");
8024
+ input.className = `${HEADER_CLASS}-input`;
8025
+ input.placeholder = text("sections.newName", "新分区名称");
8026
+ input.maxLength = 24;
8027
+ row.appendChild(input);
8028
+ const lastHeader = Array.from(headers.values()).at(-1);
8029
+ if (lastHeader !== void 0 && lastHeader.parentElement === host) host.insertBefore(row, lastHeader.nextSibling);
8030
+ else host.insertBefore(row, host.firstChild);
8031
+ input.focus();
8032
+ let done = false;
8033
+ const finish = (commitValue) => {
8034
+ if (done) return;
8035
+ done = true;
8036
+ const value = input.value.trim();
8037
+ row.remove();
8038
+ if (!commitValue || value === "") return;
8039
+ const id = `s${Date.now().toString(36)}`;
8040
+ const created = createSection(state, id, value);
8041
+ if (workspaceId === void 0) commit(created);
8042
+ else commitExplicit(assignWorkspace(created, workspaceId, id), [workspaceId]);
8043
+ };
8044
+ input.addEventListener("keydown", (event) => {
8045
+ if (event.key === "Enter") {
8046
+ event.preventDefault();
8047
+ finish(true);
8048
+ } else if (event.key === "Escape") {
8049
+ event.preventDefault();
8050
+ finish(false);
8051
+ }
8052
+ });
8053
+ input.addEventListener("blur", () => finish(true));
8054
+ }
8055
+ function onKeydownToCloseSectionMenu(event) {
8056
+ if (event.key !== "Escape" || menuHost === void 0) return;
8057
+ closeSectionMenu();
8058
+ }
8059
+ function onPointerdownToCloseSectionMenu(event) {
8060
+ if (menuHost === void 0) return;
8061
+ if (event.target instanceof Node && menuHost.contains(event.target)) return;
8062
+ closeSectionMenu();
8063
+ }
8064
+ document.addEventListener("keydown", onKeydownToCloseSectionMenu, true);
8065
+ document.addEventListener("pointerdown", onPointerdownToCloseSectionMenu, true);
8066
+ /**
8067
+ * 保留项目之间的原生拖拽排序,同时严格禁止跨分区拖拽(跨分区转移全靠菜单操作)。
8068
+ *
8069
+ * 1. 同分区内部:完全放行宿主原生的拖拽排序事件,顺序变化由 reconcileHostOrder 自动持久化。
8070
+ * 2. 跨分区或分区标题:在捕获阶段拦截 dragover 与 drop,显示禁止符号,阻止跨分区落点。
8071
+ */
8072
+ let draggingWorkspaceId;
8073
+ let draggingSectionId;
8074
+ /**
8075
+ * 跨分区拖拽拦截时切换 body 标记。
8076
+ * 由 CSS 控制宿主伪元素显隐,完全不触碰宿主 DOM className,
8077
+ * 移回同分区时落点线瞬时自然恢复,且避免 60Hz 遍历整个 DOM 树。
8078
+ */
8079
+ function setDragBlocked(blocked) {
8080
+ if (blocked) {
8081
+ if (!document.body.hasAttribute("data-dcu-drag-blocked")) document.body.setAttribute("data-dcu-drag-blocked", "true");
8082
+ } else if (document.body.hasAttribute("data-dcu-drag-blocked")) document.body.removeAttribute("data-dcu-drag-blocked");
8083
+ }
8084
+ function onWorkspaceDragStart(event) {
8085
+ setDragBlocked(false);
8086
+ const target = event.target;
8087
+ if (!(target instanceof Element)) return;
8088
+ const row = target.closest("[data-row-key^=\"workspace:\"]");
8089
+ if (row === null) return;
8090
+ const workspaceId = (row.getAttribute("data-row-key") ?? "").slice(10);
8091
+ if (!workspaceId) return;
8092
+ draggingWorkspaceId = workspaceId;
8093
+ draggingSectionId = sectionOf(state, workspaceId);
8094
+ }
8095
+ function onWorkspaceDragOver(event) {
8096
+ if (draggingWorkspaceId === void 0 || draggingSectionId === void 0) return;
8097
+ const target = event.target;
8098
+ if (!(target instanceof Element)) return;
8099
+ if (target.closest(`.${HEADER_CLASS}`) !== null) {
8100
+ if (event.dataTransfer) event.dataTransfer.dropEffect = "none";
8101
+ setDragBlocked(true);
8102
+ event.stopPropagation();
8103
+ return;
8104
+ }
8105
+ let targetWorkspaceId;
8106
+ const targetRow = target.closest("[data-row-key^=\"workspace:\"]");
8107
+ if (targetRow !== null) targetWorkspaceId = (targetRow.getAttribute("data-row-key") ?? "").slice(10);
8108
+ else {
8109
+ const rowInGroup = target.closest("[class*=\"groupSection\"]")?.querySelector("[data-row-key^=\"workspace:\"]");
8110
+ if (rowInGroup) targetWorkspaceId = (rowInGroup.getAttribute("data-row-key") ?? "").slice(10);
8111
+ }
8112
+ if (targetWorkspaceId !== void 0 && targetWorkspaceId !== "") {
8113
+ if (sectionOf(state, targetWorkspaceId) !== draggingSectionId) {
8114
+ if (event.dataTransfer) event.dataTransfer.dropEffect = "none";
8115
+ setDragBlocked(true);
8116
+ event.stopPropagation();
8117
+ } else {
8118
+ event.preventDefault();
8119
+ if (event.dataTransfer) event.dataTransfer.dropEffect = "move";
8120
+ setDragBlocked(false);
8121
+ }
8122
+ }
8123
+ }
8124
+ function onWorkspaceDrop(event) {
8125
+ setDragBlocked(false);
8126
+ if (draggingWorkspaceId === void 0 || draggingSectionId === void 0) return;
8127
+ const target = event.target;
8128
+ if (!(target instanceof Element)) return;
8129
+ if (target.closest(`.${HEADER_CLASS}`) !== null) {
8130
+ event.preventDefault();
8131
+ event.stopPropagation();
8132
+ return;
8133
+ }
8134
+ const targetRow = target.closest("[data-row-key^=\"workspace:\"]");
8135
+ if (targetRow !== null) {
8136
+ const targetWorkspaceId = (targetRow.getAttribute("data-row-key") ?? "").slice(10);
8137
+ if (sectionOf(state, targetWorkspaceId) !== draggingSectionId) {
8138
+ event.preventDefault();
8139
+ event.stopPropagation();
8140
+ }
8141
+ }
8142
+ }
8143
+ function onWorkspaceDragEnd() {
8144
+ setDragBlocked(false);
8145
+ draggingWorkspaceId = void 0;
8146
+ draggingSectionId = void 0;
8147
+ }
8148
+ document.addEventListener("dragstart", onWorkspaceDragStart, true);
8149
+ document.addEventListener("dragover", onWorkspaceDragOver, true);
8150
+ document.addEventListener("drop", onWorkspaceDrop, true);
8151
+ document.addEventListener("dragend", onWorkspaceDragEnd, true);
8152
+ /**
8153
+ * 项目行 `···` 按钮:宿主的行内操作区里**第一颗**按钮。
8154
+ * 操作区还有一颗「新建会话」按钮,且两颗按钮的 aria-label 都随语言变化,
8155
+ * 所以按位置(`rowActions` 容器的第一个 button)识别,不依赖文案。
8156
+ */
8157
+ function projectRowOfMenuButton(target) {
8158
+ const button = target.closest("button");
8159
+ if (button === null) return null;
8160
+ const row = button.closest("[data-row-key^=\"workspace:\"]");
8161
+ if (row === null) return null;
8162
+ const actions = row.querySelector("[class*=\"rowActions\"]");
8163
+ if (actions === null || !actions.contains(button)) return null;
8164
+ return actions.querySelector("button") === button ? row : null;
8165
+ }
8166
+ /**
8167
+ * 项目行 `···` 一按下就记下目标工作区。
8168
+ *
8169
+ * 宿主的菜单在 **pointerdown** 阶段就挂载(不是 click),等到 click 再注入必然晚一帧以上,
8170
+ * 用户看到的就是「菜单先出来,置顶/分区过一会儿才冒出来」。
8171
+ * 键盘回车没有 pointerdown,所以保留 click 兜底。
8172
+ */
8173
+ function prepareMenuInjection(target) {
8174
+ if (target.closest("[role=\"menu\"]") !== null) return;
8175
+ if (target.closest("[data-row-key^=\"session:\"]") !== null) {
8176
+ assigningWorkspaceId = void 0;
8177
+ return;
8178
+ }
8179
+ const row = projectRowOfMenuButton(target);
8180
+ if (row === null) {
8181
+ assigningWorkspaceId = void 0;
8182
+ return;
8183
+ }
8184
+ assigningWorkspaceId = workspaceIdOfRow(row);
8185
+ injectMenuEntry();
8186
+ }
8187
+ function onPointerdownToPrepareMenu(event) {
8188
+ if (event.target instanceof Element) prepareMenuInjection(event.target);
8189
+ }
8190
+ function onClickToPrepareMenu(event) {
8191
+ if (event.target instanceof Element) prepareMenuInjection(event.target);
8192
+ }
8193
+ document.addEventListener("pointerdown", onPointerdownToPrepareMenu, true);
8194
+ document.addEventListener("click", onClickToPrepareMenu, true);
8195
+ /**
8196
+ * 用宿主自己的图标组件渲染出静态 SVG。
8197
+ * 手绘图标在描边粗细、圆角与视觉重心上永远差一档,直接复用宿主原语才能和原生菜单项完全同源。
8198
+ */
8199
+ const iconCache = /* @__PURE__ */ new Map();
8200
+ function hostIconMarkup(name, size = 16) {
8201
+ const cached = iconCache.get(name);
8202
+ if (cached !== void 0) return cached;
8203
+ const Component = _deepseek_ai_dsh_client_ui_primitives[name];
8204
+ if (typeof Component !== "function") {
8205
+ iconCache.set(name, "");
8206
+ return "";
8207
+ }
8208
+ let markup = "";
8209
+ const host = document.createElement("div");
8210
+ try {
8211
+ (0, react_dom.render)((0, react.createElement)(Component, {
8212
+ size,
8213
+ "aria-hidden": true
8214
+ }), host);
8215
+ markup = host.innerHTML;
8216
+ } catch {
8217
+ markup = "";
8218
+ } finally {
8219
+ (0, react_dom.unmountComponentAtNode)(host);
8220
+ }
8221
+ iconCache.set(name, markup);
8222
+ return markup;
8223
+ }
8224
+ /**
8225
+ * 图标全部取自宿主 primitives(RC 版本就有这些名字,别再自己画、也别依赖 sprite):
8226
+ * `IconPinOutlineRegular` / `IconPinFillRegular` / `IconChecklistOutlineRegular` /
8227
+ * `IconCheckOutlineRegular` / `IconPlusOutlineRegular` / `IconEditOutlineRegular` /
8228
+ * `IconCloseOutlineRegular` / `IconTriangleRightFillRegular`。
8229
+ */
8230
+ const iconPin = () => hostIconMarkup("IconPinOutlineRegular");
8231
+ const iconPinned = () => hostIconMarkup("IconPinFillRegular");
8232
+ const iconSection = () => hostIconMarkup("IconChecklistOutlineRegular");
8233
+ const iconPlus = () => hostIconMarkup("IconPlusOutlineRegular");
8234
+ /** 分区展开箭头:和宿主项目行同一颗 `IconTriangleRightFillRegular`,展开时旋转 90°。 */
8235
+ const iconChevron = () => hostIconMarkup("IconTriangleRightFillRegular");
8236
+ const iconEdit = () => hostIconMarkup("IconEditOutlineRegular");
8237
+ const iconClose = () => hostIconMarkup("IconCloseOutlineRegular");
8238
+ /**
8239
+ * 按宿主菜单项的行结构复制一行,保证图标槽、字号、悬停与危险态样式完全一致。
8240
+ * 宿主一行是 `div > button[role=menuitem](span 图标 + span 文案)`,因此克隆整行最稳。
8241
+ */
8242
+ function buildMenuRow(reference, icon, label, attribute, template, tailIcon) {
8243
+ const wrapper = template ?? reference?.parentElement;
8244
+ if (wrapper === void 0 || wrapper === null) return null;
8245
+ const row = wrapper.cloneNode(true);
8246
+ row.querySelectorAll("button").forEach((button) => {
8247
+ if (button !== row.querySelector("button")) button.remove();
8248
+ });
8249
+ const button = row.querySelector("button");
8250
+ if (button === null) return null;
8251
+ button.removeAttribute("disabled");
8252
+ button.style.opacity = "";
8253
+ button.style.cursor = "";
8254
+ if (attribute !== "") button.setAttribute(attribute, "true");
8255
+ button.querySelectorAll("[class*=\"shortcut\"], [aria-keyshortcuts]").forEach((el) => el.remove());
8256
+ const spans = Array.from(button.querySelectorAll(":scope > span"));
8257
+ const iconSlot = spans[0];
8258
+ const labelSlot = button.querySelector("[class*=\"itemLabel\"], [class*=\"label\"]") ?? spans.slice(1).find((span) => span.children.length === 0 || span.textContent !== "") ?? spans[spans.length - 1];
8259
+ if (iconSlot === void 0 || labelSlot === void 0 || iconSlot === labelSlot) return null;
8260
+ spans.forEach((span) => {
8261
+ if (span !== iconSlot && span !== labelSlot) span.remove();
8262
+ });
8263
+ iconSlot.innerHTML = icon;
8264
+ labelSlot.textContent = label;
8265
+ if (tailIcon !== void 0 && tailIcon !== "") {
8266
+ const tail = document.createElement("span");
8267
+ tail.style.marginLeft = "auto";
8268
+ tail.style.opacity = "0.65";
8269
+ tail.style.display = "inline-flex";
8270
+ tail.style.alignItems = "center";
8271
+ tail.innerHTML = tailIcon;
8272
+ button.appendChild(tail);
8273
+ }
8274
+ return row;
8275
+ }
8276
+ function injectMenuEntry(attempt = 0) {
8277
+ if (disposed) return;
8278
+ if (assigningWorkspaceId === void 0) return;
8279
+ if (document.querySelector(`[data-dcu-ws-section-item]`) !== null) return;
8280
+ const menus = Array.from(document.querySelectorAll("[role=\"menu\"]")).filter((item) => !isOwnPanel(item));
8281
+ const rendered = menus.filter((menu) => menu.querySelector("button[role=\"menuitem\"]") !== null);
8282
+ const menu = rendered[rendered.length - 1] ?? (hostMenuRowTemplate === void 0 ? void 0 : menus[menus.length - 1]);
8283
+ if (menu === void 0) {
8284
+ if (attempt < 6) window.setTimeout(() => injectMenuEntry(attempt + 1), 20);
8285
+ return;
8286
+ }
8287
+ const menuItemsText = Array.from(menu.querySelectorAll("button[role=\"menuitem\"]")).map((b) => b.textContent ?? "").join(" ");
8288
+ if (menuItemsText.includes("置顶会话") || menuItemsText.includes("分叉会话") || menuItemsText.includes("删除会话") || menuItemsText.includes("Session ID") || menuItemsText.includes("移动到工作区")) {
8289
+ assigningWorkspaceId = void 0;
8290
+ return;
8291
+ }
8292
+ const reference = Array.from(menu.querySelectorAll("button[role=\"menuitem\"]")).find((button) => button.closest("[role=\"menu\"]") === menu);
8293
+ const template = hostMenuRowTemplate;
8294
+ let container = reference?.parentElement?.parentElement;
8295
+ if (container === void 0 || container === null) {
8296
+ if (template === void 0) return;
8297
+ container = menu.firstElementChild ?? menu;
8298
+ }
8299
+ if (reference !== void 0 && template === void 0) {
8300
+ hostMenuSurface = menu;
8301
+ hostMenuClassName = menu.className;
8302
+ hostMenuShellTemplate = menu.cloneNode(false);
8303
+ const viewport = reference.parentElement?.parentElement;
8304
+ hostMenuViewportTemplate = viewport === void 0 || viewport === null ? void 0 : viewport.cloneNode(false);
8305
+ }
8306
+ if (reference !== void 0 && hostMenuRowTemplate === void 0 && !isOwnPanel(reference)) {
8307
+ hostMenuRowTemplate = reference.parentElement?.cloneNode(true);
8308
+ hostMenuSurface = menu;
8309
+ hostMenuClassName = menu.className;
8310
+ hostMenuShellTemplate = menu.cloneNode(false);
8311
+ const viewport = reference.parentElement?.parentElement;
8312
+ hostMenuViewportTemplate = viewport === void 0 || viewport === null ? void 0 : viewport.cloneNode(false);
8313
+ }
8314
+ const workspaceId = assigningWorkspaceId;
8315
+ if (workspaceId === void 0) return;
8316
+ const pinned = sectionOf(state, workspaceId) === PINNED_SECTION_ID;
8317
+ const pinRow = buildMenuRow(reference, pinned ? iconPinned() : iconPin(), text(pinned ? "sections.unpin" : "sections.pin", pinned ? "取消置顶" : "置顶"), MENU_ITEM_ATTR, hostMenuRowTemplate);
8318
+ const sectionRow = buildMenuRow(reference, iconSection(), text("sections.menu", "分区"), MENU_ITEM_ATTR, hostMenuRowTemplate, "<svg viewBox=\"0 0 16 16\" width=\"12\" height=\"12\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M6 12L10 8L6 4\"/></svg>");
8319
+ /**
8320
+ * 插到宿主菜单行所在的同一个父亲里、紧挨在第一条宿主行之前。
8321
+ *
8322
+ * 归档插件就是这么做的:先拿到宿主行的外层 wrapper,再把克隆行插进「wrapper 的父亲」。
8323
+ * 这样我们的行和宿主的行是亲兄弟,共用同一块菜单表面;换成自己猜容器的话,
8324
+ * 某些布局下(桌面端)拿到的会是外壳层,行就被渲染成一个独立浮层。
8325
+ */
8326
+ const hostWrap = reference?.parentElement ?? null;
8327
+ const hostParent = hostWrap?.parentElement ?? container;
8328
+ const insertBeforeNode = hostWrap !== null && hostWrap.parentElement === hostParent ? hostWrap : container.firstChild;
8329
+ if (pinRow !== null) {
8330
+ pinRow.querySelector("button")?.addEventListener("click", (event) => {
8331
+ event.preventDefault();
8332
+ event.stopPropagation();
8333
+ closeMenusByEscape();
8334
+ commitExplicit(assignWorkspace(state, workspaceId, pinned ? DEFAULT_SECTION_ID : PINNED_SECTION_ID), [workspaceId]);
8335
+ });
8336
+ hostParent.insertBefore(pinRow, insertBeforeNode);
8337
+ }
8338
+ if (sectionRow !== null) {
8339
+ const anchorButton = sectionRow.querySelector("button");
8340
+ if (anchorButton !== null) {
8341
+ let hoverTimer;
8342
+ const cancelHover = () => {
8343
+ if (hoverTimer === void 0) return;
8344
+ window.clearTimeout(hoverTimer);
8345
+ hoverTimer = void 0;
8346
+ };
8347
+ anchorButton.addEventListener("mouseenter", () => {
8348
+ cancelHover();
8349
+ hoverTimer = window.setTimeout(() => {
8350
+ hoverTimer = void 0;
8351
+ if (menuHost !== void 0 && assignAnchor === anchorButton) return;
8352
+ openAssignMenu(anchorButton, menu);
8353
+ }, 90);
8354
+ });
8355
+ anchorButton.addEventListener("mouseleave", () => {
8356
+ cancelHover();
8357
+ hoverTimer = window.setTimeout(() => {
8358
+ hoverTimer = void 0;
8359
+ if (assignAnchor === anchorButton) closeSectionMenu();
8360
+ }, 180);
8361
+ });
8362
+ anchorButton.addEventListener("click", (event) => {
8363
+ event.preventDefault();
8364
+ event.stopPropagation();
8365
+ cancelHover();
8366
+ openAssignMenu(anchorButton, menu);
8367
+ });
8368
+ }
8369
+ hostParent.insertBefore(sectionRow, pinRow?.nextSibling ?? insertBeforeNode);
8370
+ }
8371
+ }
8372
+ /** 让宿主菜单按它自己的 Escape 语义关闭,避免我们自己猜关闭逻辑。 */
8373
+ function closeMenusByEscape() {
8374
+ document.dispatchEvent(new KeyboardEvent("keydown", {
8375
+ key: "Escape",
8376
+ bubbles: true,
8377
+ cancelable: true
8378
+ }));
8379
+ }
8380
+ let assigningWorkspaceId;
8381
+ let hostMenuSurface;
8382
+ /** 宿主菜单表面与菜单行的克隆模板:分区菜单复用它们,样式才与原生一致。 */
8383
+ let hostMenuClassName;
8384
+ let hostMenuRowTemplate;
8385
+ /** 宿主菜单的外壳与内容容器:真正的底色/模糊画在 viewport 上,必须整层复用。 */
8386
+ let hostMenuShellTemplate;
8387
+ let hostMenuViewportTemplate;
8388
+ let collapsed = readCollapsed();
8389
+ function openAssignMenu(anchor, parentMenu) {
8390
+ assignAnchor = anchor;
8391
+ const workspaceId = assigningWorkspaceId;
8392
+ if (workspaceId === void 0) return;
8393
+ const current = sectionOf(state, workspaceId);
8394
+ /**
8395
+ * 只列「能移动过去」的目标:
8396
+ * - 当前所在的分区不列(移到自己那儿没意义);
8397
+ * - 置顶也不列——父菜单里已经有独立的一行「置顶 / 取消置顶」,重复出现只会让人犹豫。
8398
+ */
8399
+ const items = state.sections.filter((section) => section.id !== current && section.id !== "pinned").map((section) => ({
8400
+ label: section.name,
8401
+ icon: iconSection(),
8402
+ onSelect: () => {
8403
+ closeSectionMenu();
8404
+ closeMenusByEscape();
8405
+ commitExplicit(assignWorkspace(state, workspaceId, section.id), [workspaceId]);
8406
+ }
8407
+ }));
8408
+ items.push({
8409
+ label: text("sections.new", "新建分区"),
8410
+ icon: iconPlus(),
8411
+ onSelect: () => {
8412
+ closeSectionMenu();
8413
+ closeMenusByEscape();
8414
+ startCreateSection(workspaceId);
8415
+ }
8416
+ });
8417
+ openHostPanel(anchor, items, parentMenu);
8418
+ }
8419
+ /** 新增项目进入默认分区,删除项目及时裁剪;不改变既有成员的显式归属。 */
8420
+ function withHostWorkspaces(value, ids) {
8421
+ let next = normalizeSections(value, ids);
8422
+ for (const id of ids) if (sectionOf(next, id) === void 0) next = assignWorkspace(next, id, DEFAULT_SECTION_ID);
8423
+ return next;
8424
+ }
8425
+ /** 一次只执行一个确定的计划;请求未结束时绝不超时重发同一条写入。 */
8426
+ function startNextUpdate() {
8427
+ if (disposed || activeUpdate !== void 0) return;
8428
+ const update = updates.shift();
8429
+ if (update === void 0) return;
8430
+ update.next = withHostWorkspaces(update.next, knownIds());
8431
+ if (updates.length === 0) state = update.next;
8432
+ activeUpdate = update;
8433
+ if (list !== void 0) update.motion = new SectionLayoutMotion(list);
8434
+ const service = workspaces();
8435
+ const write = async () => {
8436
+ if (service === void 0) throw new Error("工作区服务未就绪");
8437
+ const desired = flattenSections(update.next);
8438
+ for (const move of planWorkspaceMoves(knownIds(), desired, update.workspaceIds)) {
8439
+ if (disposed || activeUpdate !== update) return;
8440
+ await insertWorkspace(service, move.workspaceId, move.beforeWorkspaceId);
8441
+ }
8442
+ if (disposed || activeUpdate !== update) return;
8443
+ update.rpcDone = true;
8444
+ syncNow();
8445
+ };
8446
+ write().catch(() => {
8447
+ if (disposed || activeUpdate !== update) return;
8448
+ console.warn("[codex-ui:sections] 工作区移动失败,已撤销未确认的分区操作。");
8449
+ showAbortedNotice();
8450
+ updates.length = 0;
8451
+ update.motion?.dispose();
8452
+ activeUpdate = void 0;
8453
+ state = committedState;
8454
+ scheduleSync();
8455
+ });
8456
+ scheduleSync();
8457
+ }
8458
+ function scheduleSync() {
8459
+ if (disposed || rafId !== 0) return;
8460
+ rafId = window.requestAnimationFrame(() => {
8461
+ rafId = 0;
8462
+ syncNow();
8463
+ });
8464
+ }
8465
+ /** 缓存宿主菜单的表面类名与行结构,供分区菜单复用(任意宿主菜单都可以当模板)。 */
8466
+ /** 是不是我们自己画的面板(分区菜单)。宿主菜单模板绝不能取自它。 */
8467
+ function isOwnPanel(element) {
8468
+ return element instanceof Element && element.closest(`.${MENU_CLASS}`) !== null;
8469
+ }
8470
+ function cacheHostMenuTemplate() {
8471
+ if (hostMenuRowTemplate !== void 0 && hostMenuRowTemplate.isConnected) return;
8472
+ const menu = Array.from(document.querySelectorAll("[role=\"menu\"]")).find((item) => item.querySelector("button[role=\"menuitem\"]") !== null && !isOwnPanel(item) && item.closest("[data-shortcut-modal=\"settings\"]") === null);
8473
+ const reference = menu?.querySelector("button[role=\"menuitem\"]");
8474
+ const wrapper = reference?.parentElement;
8475
+ if (menu === void 0 || reference === void 0 || wrapper === void 0 || wrapper === null) return;
8476
+ menu.className;
8477
+ hostMenuRowTemplate = wrapper.cloneNode(true);
8478
+ hostMenuShellTemplate = menu.cloneNode(false);
8479
+ const viewport = wrapper.parentElement;
8480
+ hostMenuViewportTemplate = viewport === null ? void 0 : viewport.cloneNode(false);
8481
+ }
8482
+ function syncNow() {
8483
+ if (disposed || syncing) return;
8484
+ cacheHostMenuTemplate();
8485
+ if (!sectionsLoaded) return;
8486
+ const next = findWorkspaceList(document);
8487
+ if (next === void 0) {
8488
+ detachHeaders();
8489
+ return;
8490
+ }
8491
+ list = next;
8492
+ if (!wired) {
8493
+ wired = true;
8494
+ subscribeWorkspaces();
8495
+ startObserver();
8496
+ }
8497
+ syncing = true;
8498
+ try {
8499
+ const order = domOrder();
8500
+ const ids = knownIds();
8501
+ const update = activeUpdate;
8502
+ if (update !== void 0) {
8503
+ if (update.rpcDone && sameVisibleOrder(ids, order)) {
8504
+ const normalized = withHostWorkspaces(update.next, ids);
8505
+ if (!sameOrder(flattenSections(normalized), flattenSections(update.next))) {
8506
+ const original = new Set(flattenSections(update.next));
8507
+ update.next = reconcileHostOrder(normalized, ids).state;
8508
+ state = withHostWorkspaces(state, ids);
8509
+ update.motion?.dispose();
8510
+ update.motion = void 0;
8511
+ update.layoutDone = false;
8512
+ const additions = ids.filter((id) => !original.has(id));
8513
+ const moves = planWorkspaceMoves(ids, flattenSections(update.next), additions);
8514
+ if (moves.length > 0) {
8515
+ const service = workspaces();
8516
+ if (service === void 0) throw new Error("工作区服务未就绪");
8517
+ update.rpcDone = false;
8518
+ (async () => {
8519
+ for (const move of moves) await insertWorkspace(service, move.workspaceId, move.beforeWorkspaceId);
8520
+ if (activeUpdate !== update || disposed) return;
8521
+ update.rpcDone = true;
8522
+ scheduleSync();
8523
+ })().catch(() => {
8524
+ console.warn("[codex-ui:sections] 同步新工作区顺序失败。");
8525
+ if (activeUpdate !== update || disposed) return;
8526
+ updates.length = 0;
8527
+ activeUpdate = void 0;
8528
+ state = committedState;
8529
+ scheduleSync();
8530
+ });
8531
+ return;
8532
+ }
8533
+ }
8534
+ }
8535
+ const desired = flattenSections(update.next);
8536
+ if (!sameOrder(ids, desired) || !sameVisibleOrder(desired, order)) return;
8537
+ if (!update.layoutDone) {
8538
+ update.layoutDone = true;
8539
+ const layout = () => placeHeaders(collectProjectBlocks(list, list), update.next);
8540
+ const finished = update.motion?.play(layout);
8541
+ if (finished === void 0) layout();
8542
+ (finished ?? Promise.resolve()).then(() => {
8543
+ if (disposed || activeUpdate !== update) return;
8544
+ update.motionDone = true;
8545
+ syncNow();
8546
+ });
8547
+ }
8548
+ if (update.rpcDone && update.motionDone) {
8549
+ committedState = update.next;
8550
+ state = update.next;
8551
+ persist(committedState);
8552
+ activeUpdate = void 0;
8553
+ startNextUpdate();
8554
+ }
8555
+ return;
8556
+ }
8557
+ if (!sameVisibleOrder(ids, order) || order.length === 0) return;
8558
+ const before = serializeSections(state);
8559
+ state = normalizeSections(state, ids);
8560
+ if (!baselineSet) {
8561
+ baselineSet = true;
8562
+ for (const id of ids) if (sectionOf(state, id) === void 0) state = assignWorkspace(state, id, DEFAULT_SECTION_ID);
8563
+ committedState = state;
8564
+ if (!sameOrder(flattenSections(state), ids)) {
8565
+ commitExplicit(state);
8566
+ return;
8567
+ }
8568
+ } else state = reconcileHostOrder(state, ids).state;
8569
+ committedState = state;
8570
+ if (serializeSections(state) !== before) persist();
8571
+ placeHeaders(collectProjectBlocks(list, list));
8572
+ } finally {
8573
+ syncing = false;
8574
+ }
8575
+ }
8576
+ /** 可见行必须是快照的有序子集;未渲染的项目仍由完整快照维护。 */
8577
+ function sameVisibleOrder(all, visible) {
8578
+ const shown = new Set(visible);
8579
+ return shown.size === visible.length && sameOrder(all.filter((id) => shown.has(id)), visible);
8580
+ }
8581
+ /** 两个顺序是否逐项一致。 */
8582
+ function sameOrder(left, right) {
8583
+ return left.length === right.length && left.every((id, index) => id === right[index]);
8584
+ }
8585
+ function startObserver() {
8586
+ observer = new MutationObserver((mutations) => {
8587
+ if (disposed) return;
8588
+ if (assigningWorkspaceId !== void 0 && document.querySelector(`[data-dcu-ws-section-item]`) === null) {
8589
+ for (const mutation of mutations) for (const node of Array.from(mutation.addedNodes)) if (node instanceof Element && (node.matches("[role=\"menu\"]") || node.querySelector("[role=\"menu\"]") !== null)) {
8590
+ injectMenuEntry();
8591
+ return;
8592
+ }
8593
+ }
8594
+ let touched = false;
8595
+ for (const mutation of mutations) {
8596
+ for (const node of Array.from(mutation.addedNodes)) {
8597
+ if (node instanceof Element && node.closest(`.${HEADER_CLASS}`) !== null) continue;
8598
+ touched = true;
8599
+ break;
8600
+ }
8601
+ if (touched) break;
8602
+ if (mutation.type === "childList") {
8603
+ touched = true;
8604
+ break;
8605
+ }
8606
+ }
8607
+ if (touched) {
8608
+ if (activeUpdate !== void 0) syncNow();
8609
+ else scheduleSync();
8610
+ }
8611
+ });
8612
+ observer.observe(document.body, {
8613
+ childList: true,
8614
+ subtree: true
8615
+ });
8616
+ }
8617
+ function subscribeWorkspaces() {
8618
+ const service = workspaces();
8619
+ if (service === void 0) return;
8620
+ try {
8621
+ unsubscribe = service.list.subscribe(() => scheduleSync());
8622
+ } catch {
8623
+ unsubscribe = void 0;
8624
+ }
8625
+ }
8626
+ const boot = window.setInterval(() => {
8627
+ if (disposed) return;
8628
+ if (findWorkspaceList(document) === void 0) return;
8629
+ window.clearInterval(boot);
8630
+ scheduleSync();
8631
+ }, 200);
8632
+ loadStateFromHost();
8633
+ scheduleSync();
8634
+ const dispose = () => {
8635
+ if (disposed) return;
8636
+ disposed = true;
8637
+ if (activeInstance === dispose) activeInstance = void 0;
8638
+ window.clearInterval(boot);
8639
+ if (rafId !== 0) window.cancelAnimationFrame(rafId);
8640
+ observer?.disconnect();
8641
+ clearWriteWait();
8642
+ updates.length = 0;
8643
+ activeUpdate?.motion?.dispose();
8644
+ activeUpdate = void 0;
8645
+ document.removeEventListener("dragstart", onWorkspaceDragStart, true);
8646
+ document.removeEventListener("dragover", onWorkspaceDragOver, true);
8647
+ document.removeEventListener("drop", onWorkspaceDrop, true);
8648
+ document.removeEventListener("dragend", onWorkspaceDragEnd, true);
8649
+ document.removeEventListener("keydown", onKeydownToCloseSectionMenu, true);
8650
+ document.removeEventListener("pointerdown", onPointerdownToCloseSectionMenu, true);
8651
+ document.removeEventListener("pointerdown", onPointerdownToPrepareMenu, true);
8652
+ document.removeEventListener("click", onClickToPrepareMenu, true);
8653
+ unsubscribe?.();
8654
+ closeSectionMenu();
8655
+ flushSectionsSave();
8656
+ for (const header of headers.values()) header.remove();
8657
+ headers.clear();
8658
+ document.body.removeAttribute("data-dcu-dragging-section-target");
8659
+ document.body.removeAttribute("data-dcu-drag-blocked");
8660
+ for (const block of Array.from(document.querySelectorAll("[data-dcu-section-member]"))) {
8661
+ block.removeAttribute("data-dcu-section-member");
8662
+ block.removeAttribute("data-dcu-section-hidden");
8663
+ }
8664
+ };
8665
+ activeInstance = dispose;
8666
+ return dispose;
8667
+ }
8668
+ //#endregion
6900
8669
  //#region src/client/index.ts
6901
8670
  const inject = [
6902
8671
  "slots",
@@ -6916,6 +8685,26 @@ html[data-dsh-glass-float] [data-shortcut-modal="settings"]:has(> [class*="optio
6916
8685
  const t = ctx.locale.bind(NS);
6917
8686
  ctx.effect(() => observeTheme(ctx), "michengai-codex-ui: theme & appearance");
6918
8687
  ctx.effect(() => observeSidebarNav(ctx), "michengai-codex-ui: sidebar navigation");
8688
+ ctx.effect(() => {
8689
+ let stop;
8690
+ let cancelled = false;
8691
+ checkSidebarEnabled().then((enabled) => {
8692
+ if (cancelled || !enabled) return;
8693
+ const translate = (key, fallback) => {
8694
+ try {
8695
+ const value = t(key);
8696
+ return typeof value === "string" && value !== "" && value !== key ? value : fallback ?? key;
8697
+ } catch {
8698
+ return fallback ?? key;
8699
+ }
8700
+ };
8701
+ stop = observeWorkspaceSections(ctx, translate);
8702
+ });
8703
+ return () => {
8704
+ cancelled = true;
8705
+ stop?.();
8706
+ };
8707
+ }, "michengai-codex-ui: workspace sections");
6919
8708
  ctx.effect(() => observeComposerEnhancements(ctx), "michengai-codex-ui: composer enhancements");
6920
8709
  ctx.effect(() => observeSettingsSkin(), "michengai-codex-ui: official settings skin");
6921
8710
  ctx.effect(() => observeSettingsNavIcon(() => t("about.nav")), "michengai-codex-ui: settings nav icon");