dsh-nav-fold 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js ADDED
@@ -0,0 +1,1883 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "dsh-nav-fold",
3
+ factory: (require) => {
4
+ var module = { exports: {} };
5
+ var exports = module.exports;
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
+ "use strict";
8
+ /**
9
+ * dsh-nav-fold · 浏览器半
10
+ *
11
+ * 把左侧栏顶部「功能入口」列表(ui-sidebar 声明的 sidebar.panellist 区域)做成
12
+ * 三态可折叠——展开 / 紧凑图标网格 / 收起,并记住状态。
13
+ *
14
+ * 控件位置:挂在**被折叠的那一组行**的末尾(nav 的最后一个子节点),因为它的作用
15
+ * 对象就是上面那几行,不是会话列表、也不是设置区。
16
+ *
17
+ * 两种控件模型(在「设置 → 功能入口折叠」里切换,存 localStorage):
18
+ * - segmented:三档选择器,语义恒定、任意两档直达、当前档高亮(默认)
19
+ * - cycle:单按钮循环,点一下进下一档
20
+ * 56px 图标轨里两种模型都退化成单个 收起⇄展开 循环按钮(轨道放不下排布)。
21
+ *
22
+ * 边界(设计取舍见 README「设计边界」段):
23
+ * - 不读写官方 panelPins(外壳闭包私有内存,重载即重置)
24
+ * - 不改官方行:只在命中的 nav 上加属性,并追加一个自有控制条节点
25
+ * - 定位失败只 warn 一次并保持原生 UI
26
+ */
27
+ const react = require("react");
28
+
29
+ /** 插件名(cordis 插件标识) */
30
+ const name = "nav-fold";
31
+ /** 版本号:必须与 package.json.version 一致(有单测守着) */
32
+ const PLUGIN_VERSION = "0.2.0";
33
+ /** 设置分区 / 控制条占用者 id */
34
+ const ENTRY_ID = "nav-fold";
35
+ /** 注入样式表的幂等标记 */
36
+ const STYLE_ID = "dsh-nav-fold";
37
+ /** localStorage:显示档位(桌面桶) */
38
+ const STORAGE_MODE = "dsh-nav-fold/v1/mode";
39
+ /** localStorage:显示档位(窄屏 / 手机桶) */
40
+ const STORAGE_MODE_NARROW = "dsh-nav-fold/v1/mode-narrow";
41
+ /** localStorage:自动档开关 */
42
+ const STORAGE_AUTO = "dsh-nav-fold/v1/auto";
43
+ /** localStorage:收起态要保留的行(按标签文本) */
44
+ const STORAGE_KEEP = "dsh-nav-fold/v1/keep";
45
+ /** localStorage:被标题行模型临时改写掉的档位(切回去时还原) */
46
+ const STORAGE_STASH = "dsh-nav-fold/v1/mode-stash";
47
+ /** localStorage:控件模型 */
48
+ const STORAGE_MODEL = "dsh-nav-fold/v1/model";
49
+ /** 命中导航元素的标记属性,三态值写在这个属性上 */
50
+ const NAV_ATTR = "data-navfold";
51
+ /** 自有控制条的标记属性 */
52
+ const BAR_ATTR = "data-navfold-bar";
53
+ /** 三态顺序即单按钮循环顺序 */
54
+ const MODES = ["expanded", "compact", "hidden"];
55
+ /** 控件模型 */
56
+ const MODELS = ["segmented", "cycle", "header"];
57
+ /** 设置菜单里显示的名字(与包名 dsh-nav-fold 同一词根;品牌名不翻译) */
58
+ const SETTINGS_LABEL = "nav-fold 导航折叠";
59
+ /** locale 命名空间 */
60
+ const NS = "dsh-nav-fold";
61
+
62
+ /** 文案字典:zh 是 key 来源,en 镜像全部 key */
63
+ const DICT = {
64
+ zh: {
65
+ "label": SETTINGS_LABEL,
66
+ "density.expanded.label": "文字",
67
+ "density.expanded.title": "显示为文字行(展开)",
68
+ "density.compact.label": "图标",
69
+ "density.compact.title": "显示为紧凑图标网格",
70
+ "density.hidden.label": "收起",
71
+ "density.hidden.title": "收起功能入口(只留第一行与更多)",
72
+ "cycle.expanded": "展开为文字行",
73
+ "cycle.compact": "切换为紧凑图标网格",
74
+ "cycle.hidden": "收起功能入口(只留第一行与更多)",
75
+ "bar.aria": SETTINGS_LABEL + ":显示方式",
76
+ "bar.title": "功能入口显示方式",
77
+ "bar.all": "全部",
78
+ "bar.all.title": "全部功能入口",
79
+ "popover.label": "功能入口",
80
+ "badge.text": "已收起 {hidden}",
81
+ "badge.title": "已收起 {hidden} 个入口,保留 {kept} 个(在设置里增减)",
82
+ "mode.expanded": "文字行",
83
+ "mode.compact": "图标网格",
84
+ "mode.hidden": "已收起",
85
+ "settings.hint": "{label}:把左侧栏顶部那组入口折叠成图标网格或收起,把高度还给会话列表。当前档位:{mode}。",
86
+ "settings.hint.segmented": "三档选择器下,按钮高亮表示当前档位。",
87
+ "settings.hint.cycle": "单按钮循环下,图标就是当前档,点一下换成下一档。",
88
+ "settings.model.group": "控制条样式",
89
+ "settings.model.segmented.title": "三档选择器",
90
+ "settings.model.segmented.desc": "文字 / 图标 / 收起 三个按钮并列,点哪个是哪个",
91
+ "settings.model.cycle.title": "单按钮循环",
92
+ "settings.model.cycle.desc": "一个按钮,点一下换成下一档(文字 → 图标 → 收起)",
93
+ "settings.model.header.title": "标题行",
94
+ "settings.model.header.desc": "整组收成一行「功能入口」标题,点标题展开或收起;图标网格档不可用",
95
+ "header.label": "功能入口",
96
+ "header.collapse": "收起功能入口",
97
+ "header.expand": "展开功能入口",
98
+ "settings.auto.group": "自动档",
99
+ "settings.auto.on.title": "自动档:开",
100
+ "settings.auto.on.desc": "窗口够窄(<768)或够矮(<760)时,第一次打开直接进图标档",
101
+ "settings.auto.off.title": "自动档:关",
102
+ "settings.auto.off.desc": "始终用你选过的档位(没选过就是文字行)",
103
+ "settings.auto.hint": "自动档只决定「第一次打开时用哪档」:手动点过控制条之后以你的选择为准,并按桌面 / 手机分别记住。",
104
+ "settings.keep.hint": "一个都不选就默认保留第一行。",
105
+ "settings.keep.empty": "还没读到侧栏入口——等界面渲染完再打开这里",
106
+ "settings.summary.entries": "{n} 个入口",
107
+ "settings.keptCount": "保留 {kept}/{total}",
108
+ "settings.model.title": "控制条样式",
109
+ "settings.model.desc": "三档并列点选;单按钮点一下换成下一档。",
110
+ "settings.auto.title": "自动档",
111
+ "settings.auto.desc": "首次打开时窗口够窄(<768)或够矮(<760)进图标档;手动选过以你为准。",
112
+ "settings.keep.title": "收起时保留",
113
+ "settings.keep.all": "全部",
114
+ "settings.keep.none": "清空",
115
+ "settings.restore": "恢复默认",
116
+ "settings.restore.confirm": "再点一次确认",
117
+ "settings.rail.hint": "56px 图标轨里两种样式都会收成一个图标,点一下换档。"
118
+ },
119
+ en: {
120
+ "label": SETTINGS_LABEL,
121
+ "density.expanded.label": "Text",
122
+ "density.expanded.title": "Show as full text rows",
123
+ "density.compact.label": "Icons",
124
+ "density.compact.title": "Show as a compact icon grid",
125
+ "density.hidden.label": "Collapse",
126
+ "density.hidden.title": "Collapse the launchers (keep the first row and More)",
127
+ "cycle.expanded": "Expand to text rows",
128
+ "cycle.compact": "Switch to the compact icon grid",
129
+ "cycle.hidden": "Collapse the launchers (keep the first row and More)",
130
+ "bar.aria": SETTINGS_LABEL + ": display style",
131
+ "bar.title": "Launcher display style",
132
+ "bar.all": "All",
133
+ "bar.all.title": "All launchers",
134
+ "popover.label": "Launchers",
135
+ "badge.text": "{hidden} collapsed",
136
+ "badge.title": "{hidden} launchers collapsed, {kept} kept (change it in Settings)",
137
+ "mode.expanded": "text rows",
138
+ "mode.compact": "icon grid",
139
+ "mode.hidden": "collapsed",
140
+ "settings.hint": "{label}: fold the sidebar launcher list into an icon grid or collapse it, giving the height back to sessions. Current: {mode}.",
141
+ "settings.hint.segmented": "With the segmented control the highlighted button is the current state.",
142
+ "settings.hint.cycle": "With the cycle button the icon is the current state; click to advance.",
143
+ "settings.model.group": "Control style",
144
+ "settings.model.segmented.title": "Segmented",
145
+ "settings.model.segmented.desc": "Three buttons — text / icons / collapse; click one to go there",
146
+ "settings.model.cycle.title": "Cycle button",
147
+ "settings.model.cycle.desc": "One button; click to advance (text → icons → collapse)",
148
+ "settings.model.header.title": "Header row",
149
+ "settings.model.header.desc": "Fold the whole group into one launcher header you click to expand or collapse",
150
+ "header.label": "Launchers",
151
+ "header.collapse": "Collapse the launchers",
152
+ "header.expand": "Expand the launchers",
153
+ "settings.auto.group": "Automatic",
154
+ "settings.auto.on.title": "Automatic: on",
155
+ "settings.auto.on.desc": "First open collapses to icons when the window is under 768 wide or 760 tall",
156
+ "settings.auto.off.title": "Automatic: off",
157
+ "settings.auto.off.desc": "Always use your last choice (text rows when there is none)",
158
+ "settings.auto.hint": "Automatic only picks the very first state; once you click the control bar your choice wins, remembered per desktop / mobile.",
159
+ "settings.keep.hint": "None selected keeps the first row.",
160
+ "settings.keep.empty": "No launcher rows seen yet — open this again once the UI has rendered",
161
+ "settings.summary.entries": "{n} entries",
162
+ "settings.keptCount": "{kept}/{total} kept",
163
+ "settings.model.title": "Control style",
164
+ "settings.model.desc": "Segmented picks directly; the cycle button advances one step.",
165
+ "settings.auto.title": "Automatic",
166
+ "settings.auto.desc": "First open uses icons when the window is under 768 wide or 760 tall; your own choice wins after that.",
167
+ "settings.keep.title": "Kept while collapsed",
168
+ "settings.keep.all": "All",
169
+ "settings.keep.none": "None",
170
+ "settings.restore": "Restore defaults",
171
+ "settings.restore.confirm": "Click again to confirm",
172
+ "settings.rail.hint": "In the 56px rail both styles reduce to a single icon you click to advance."
173
+ }
174
+ };
175
+
176
+ /**
177
+ * 取一条文案。
178
+ * @param dict - 字典。
179
+ * @param key - key。
180
+ * @returns 文案(缺失时回退为 key)。
181
+ */
182
+ function dictText(dict, key) {
183
+ return dict && typeof dict[key] === "string" ? dict[key] : key;
184
+ }
185
+
186
+ /**
187
+ * 占位符替换({name})。
188
+ * @param text - 模板。
189
+ * @param params - 变量。
190
+ * @returns 结果文本。
191
+ */
192
+ function formatText(text, params) {
193
+ if (!params) return text;
194
+ return String(text).replace(/\{(\w+)\}/g, (whole, name) => (params[name] === undefined ? whole : String(params[name])));
195
+ }
196
+
197
+ /** 当前翻译函数;locale 服务可用时被换成 bound 版本 */
198
+ let t = (key, params) => formatText(dictText(DICT.zh, key), params);
199
+ /** 与外壳自身抽屉断点一致 */
200
+ const NARROW_QUERY = "(max-width: 767px)";
201
+ /** 定位重扫的节流窗口 */
202
+ const RESCAN_MS = 150;
203
+ /** 侧栏收成 56px 图标轨时,控制条只留图标 */
204
+ const ICON_ONLY_WIDTH = 120;
205
+ /** 首屏宽限:React 还没渲染出侧栏时的“找不到”不算结构变更 */
206
+ const WARN_AFTER_MS = 3000;
207
+ /** 自动档:窗口高度低于这个值就进图标档(宽度另有 767 断点) */
208
+ const AUTO_HEIGHT_PX = 760;
209
+
210
+ /** 图标(16 网格,stroke 走 currentColor) */
211
+ const CHEVRON_UP = ["M4 10.5 8 6.5l4 4"];
212
+ const CHEVRON_DOWN = ["M4 6.5 8 10.5l4-4"];
213
+ const LIST_ICON = ["M2.5 4h11", "M2.5 8h11", "M2.5 12h11"];
214
+ const ALL_ICON = ["M3 3.5h10v10H3z", "M5.5 8l1.8 1.8L10.8 6.3"];
215
+ const NONE_ICON = ["M3 3.5h10v10H3z", "M5.8 10.2 10.2 5.8", "M10.2 10.2 5.8 5.8"];
216
+ const GRID_ICON = ["M2.5 2.5h4.2v4.2h-4.2z", "M9.3 2.5h4.2v4.2h-4.2z", "M2.5 9.3h4.2v4.2h-4.2z", "M9.3 9.3h4.2v4.2h-4.2z"];
217
+ const TEXT_ICON = ["M2.5 4h11", "M2.5 8h11", "M2.5 12h7"];
218
+ const CYCLE_ICON = ["M3 8a5 5 0 0 1 8.5-3.5L13 6", "M13 3v3h-3", "M13 8a5 5 0 0 1-8.5 3.5L3 10", "M3 13v-3h3"];
219
+
220
+ /** 每档的图标(文案走 t()) */
221
+ const DENSITY_ICON = {
222
+ expanded: TEXT_ICON,
223
+ compact: GRID_ICON,
224
+ hidden: CHEVRON_UP
225
+ };
226
+
227
+ /**
228
+ * 某一档的图标。
229
+ * @param mode - 档位。
230
+ * @returns 图标路径。
231
+ */
232
+ function densityIcon(mode) {
233
+ return DENSITY_ICON[mode] || TEXT_ICON;
234
+ }
235
+
236
+ /**
237
+ * 某一档的按钮短名。
238
+ * @param mode - 档位。
239
+ * @returns 短名。
240
+ */
241
+ function densityLabel(mode) {
242
+ return t("density." + mode + ".label");
243
+ }
244
+
245
+ /**
246
+ * 某一档的 tooltip。
247
+ * @param mode - 档位。
248
+ * @returns 说明。
249
+ */
250
+ function densityTitle(mode) {
251
+ return t("density." + mode + ".title");
252
+ }
253
+
254
+ /**
255
+ * 折叠表现全部收在自有命名空间下:只作用于带 data-navfold 属性的那一个 nav。
256
+ * 紧凑态用 clip 隐藏文字而不是 display:none,保留无障碍名与 tooltip。
257
+ */
258
+ const CSS_TEXT = [
259
+ "/* dsh-nav-fold v" + PLUGIN_VERSION + ":功能入口三态(只作用于被打标的 nav) */",
260
+ 'nav[data-navfold="compact"]{display:grid!important;grid-template-columns:repeat(auto-fit,minmax(34px,1fr));gap:2px;align-content:start;justify-items:stretch}',
261
+ 'nav[data-navfold="compact"]>button{position:relative!important;justify-content:center!important;padding:0!important;min-height:32px!important;height:32px!important}',
262
+ 'nav[data-navfold="compact"]>button>span+span{position:absolute!important;width:1px!important;height:1px!important;margin:-1px!important;padding:0!important;overflow:hidden!important;clip-path:inset(50%)!important;white-space:nowrap!important;border:0!important}',
263
+ 'nav[data-navfold="compact"]>span{display:flex!important;align-items:center;position:relative}',
264
+ 'nav[data-navfold="compact"]>span>button{position:relative!important;justify-content:center!important;padding:0!important;min-height:32px!important;height:32px!important;width:100%!important}',
265
+ 'nav[data-navfold="compact"]>span>button>span+span{position:absolute!important;width:1px!important;height:1px!important;margin:-1px!important;padding:0!important;overflow:hidden!important;clip-path:inset(50%)!important;white-space:nowrap!important;border:0!important}',
266
+ 'nav[data-navfold="hidden"]>button:not([data-navfold-keep]){display:none!important}',
267
+ // rc.2 起每个入口多一层 div.panelEntry:同一套表现要按包裹层再写一遍
268
+ 'nav[data-navfold="compact"]>div:not([' + BAR_ATTR + ']){display:flex!important;min-width:0}',
269
+ 'nav[data-navfold="compact"]>div:not([' + BAR_ATTR + '])>button{flex:1!important;position:relative!important;justify-content:center!important;padding:0!important;min-height:32px!important;height:32px!important;border-radius:8px!important}',
270
+ 'nav[data-navfold="compact"]>div:not([' + BAR_ATTR + '])>button>span+span{position:absolute!important;width:1px!important;height:1px!important;margin:-1px!important;padding:0!important;overflow:hidden!important;clip:rect(0 0 0 0)!important;white-space:nowrap!important;border:0!important}',
271
+ 'nav[data-navfold="compact"]>div:not([' + BAR_ATTR + '])>button:not([class*="panelRow"]){display:none!important}',
272
+ 'nav[data-navfold="hidden"]>div:not([data-navfold-keep]):not([' + BAR_ATTR + ']){display:none!important}',
273
+ "nav[data-navfold]>[" + BAR_ATTR + "] [data-navfold-count]{margin-right:2px;font-variant-numeric:tabular-nums;opacity:.8}",
274
+ "nav[data-navfold]>[" + BAR_ATTR + "]{display:flex;align-items:center;justify-content:flex-end;gap:2px;height:22px;margin-top:2px;padding:0 2px;font-size:11px;line-height:1;color:var(--dsw-alias-label-tertiary,#8a8a8a)}",
275
+ 'nav[data-navfold="compact"]>[' + BAR_ATTR + "]{grid-column:1/-1}",
276
+ "nav[data-navfold]>[" + BAR_ATTR + "] button{display:inline-flex;align-items:center;gap:3px;height:20px;padding:0 5px;border:1px solid transparent;border-radius:6px;background:transparent;color:inherit;font:inherit;cursor:pointer}",
277
+ "nav[data-navfold]>[" + BAR_ATTR + "] button:hover{background:var(--dsw-alias-bg-layer-2,rgba(128,128,128,.14));color:var(--dsw-alias-label-secondary,#555)}",
278
+ 'nav[data-navfold]>[' + BAR_ATTR + '] button[aria-pressed="true"]{background:var(--dsw-alias-bg-layer-2,rgba(128,128,128,.16));color:var(--dsw-alias-label-primary,#111)}',
279
+ "nav[data-navfold]>[" + BAR_ATTR + "] button:focus-visible{outline:2px solid var(--dsw-alias-accent,currentColor);outline-offset:1px}",
280
+ "nav[data-navfold]>[" + BAR_ATTR + "] button[data-navfold-action=\"cycle\"]{padding:0 10px}",
281
+ "nav[data-navfold]>[" + BAR_ATTR + "][data-navfold-icononly]{justify-content:center;padding:0;margin-top:4px}",
282
+ "nav[data-navfold]>[" + BAR_ATTR + "][data-navfold-icononly] [data-navfold-label]{display:none}",
283
+ // 设置面板控件:状态样式只写在 CSS 里(内联混用 border 简写/长写会被 React diff 清成黑色)
284
+ "[data-navfold-model]{border:1px solid transparent;background:transparent;color:var(--dsw-alias-label-secondary,#666);border-radius:6px;cursor:pointer}",
285
+ "[data-navfold-model]:hover{background:var(--dsw-alias-bg-layer-2,rgba(128,128,128,.12))}",
286
+ '[data-navfold-model][aria-checked="true"]{background:var(--dsw-alias-bg-layer-1,#fff);color:var(--dsw-alias-label-primary,#111);border-color:var(--dsw-alias-label-tertiary,rgba(0,0,0,.28));font-weight:600;box-shadow:0 1px 2px rgba(0,0,0,.06)}',
287
+ "[data-navfold-auto]{position:relative;width:38px;height:22px;padding:0;border:none;border-radius:999px;background:var(--dsw-alias-border-l2,rgba(0,0,0,.15));cursor:pointer;flex:0 0 auto}",
288
+ '[data-navfold-auto][aria-checked="true"]{background:var(--dsw-alias-accent,#4d6bfe)}',
289
+ "[data-navfold-auto]>span{position:absolute;top:3px;left:3px;width:16px;height:16px;border-radius:999px;background:#fff;transition:left .12s ease}",
290
+ '[data-navfold-auto][aria-checked="true"]>span{left:19px}',
291
+ "[data-navfold-keep-row]{display:inline-flex;align-items:center;gap:4px;padding:3px 8px;border-radius:6px;border:1px solid var(--dsw-alias-border-l2,rgba(0,0,0,.15));background:transparent;color:var(--dsw-alias-label-primary,#111);font-size:12px;line-height:1.5;cursor:pointer}",
292
+ "[data-navfold-keep-row]:hover{border-color:var(--dsw-alias-label-tertiary,rgba(0,0,0,.3))}",
293
+ '[data-navfold-keep-row][aria-pressed="true"]{border-color:var(--dsw-alias-accent,#4d6bfe);background:var(--dsw-alias-bg-layer-2,rgba(77,107,254,.10))}',
294
+ '[data-navfold-keep-row]>span[aria-hidden="true"]{font-size:11px;color:var(--dsw-alias-accent,#4d6bfe)}',
295
+ "nav[data-navfold]>[" + BAR_ATTR + "][data-navfold-header]{justify-content:flex-start;height:34px;margin:0 0 2px;padding:0 2px}",
296
+ "nav[data-navfold]>[" + BAR_ATTR + "][data-navfold-header] button{display:inline-flex;align-items:center;gap:6px;width:100%;height:30px;padding:0 6px;border:none;border-radius:8px;background:transparent;color:var(--dsw-alias-label-primary,#111);font-size:13px;cursor:pointer;justify-content:flex-start}",
297
+ "nav[data-navfold]>[" + BAR_ATTR + "][data-navfold-header] button:hover{background:var(--dsw-alias-bg-layer-2,rgba(128,128,128,.12))}",
298
+ "[data-navfold-header-count]{color:var(--dsw-alias-label-tertiary,#8a8a8a);font-size:12px;font-variant-numeric:tabular-nums}",
299
+ "[data-navfold-popover]{position:fixed;z-index:2147483000;min-width:180px;max-height:60vh;overflow:auto;display:grid;gap:2px;padding:6px;border-radius:10px;border:1px solid var(--dsw-alias-border-l2,rgba(0,0,0,.15));background:var(--dsw-alias-bg-layer-1,#fff);box-shadow:0 8px 24px rgba(0,0,0,.16)}",
300
+ "[data-navfold-popover] button{display:flex;align-items:center;gap:8px;width:100%;padding:6px 8px;border:none;border-radius:6px;background:transparent;color:var(--dsw-alias-label-primary,#111);font-size:12px;text-align:left;cursor:pointer}",
301
+ "[data-navfold-popover] button:hover{background:var(--dsw-alias-bg-layer-2,rgba(128,128,128,.14))}",
302
+ "[data-navfold-micro]{padding:2px 6px;border:none;border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary,#777);font-size:12px;cursor:pointer}",
303
+ "[data-navfold-micro]:hover{background:var(--dsw-alias-bg-layer-2,rgba(128,128,128,.12))}",
304
+ "[data-navfold-restore]{padding:3px 10px;border-radius:6px;border:1px solid var(--dsw-alias-border-l2,rgba(0,0,0,.15));background:transparent;color:var(--dsw-alias-label-secondary,#666);font-size:12px;cursor:pointer}",
305
+ "[data-navfold-restore]:hover{background:var(--dsw-alias-bg-layer-2,rgba(128,128,128,.12))}",
306
+ '[data-navfold-restore="confirm"]{border-color:var(--dsw-alias-state-error-primary,#d14343);color:var(--dsw-alias-state-error-primary,#d14343)}'
307
+ ].join("\n");
308
+
309
+ /** 运行时单例 */
310
+ const runtime = {
311
+ nav: null,
312
+ bar: null,
313
+ mode: "expanded",
314
+ model: "segmented",
315
+ auto: true,
316
+ narrow: false,
317
+ keep: [],
318
+ totals: { kept: 1, total: 0 },
319
+ signature: "",
320
+ observer: null,
321
+ resize: null,
322
+ viewportHandler: null,
323
+
324
+ timer: 0,
325
+ warned: false,
326
+ iconOnly: false,
327
+ mountedAt: 0,
328
+ listeners: new Set(),
329
+ popover: null,
330
+ headerDrift: 0,
331
+ modeStash: null,
332
+ confirmReset: false,
333
+ resetTimer: 0
334
+ };
335
+
336
+ /* ───────────────────────── 纯函数(可单测) ───────────────────────── */
337
+
338
+ /**
339
+ * 三态循环:展开 → 紧凑 → 收起 → 展开。
340
+ * @param mode - 当前档位。
341
+ * @returns 下一档位。
342
+ */
343
+ function nextMode(mode) {
344
+ const at = MODES.indexOf(mode);
345
+ return MODES[(at + 1) % MODES.length];
346
+ }
347
+
348
+ /**
349
+ * 决定启动档位:该设备桶的存档优先;否则手机一律图标档,桌面再按自动档看窗口高度。
350
+ * @param stored - 该桶的存档。
351
+ * @param narrow - 是否窄屏。
352
+ * @param height - 视口高度。
353
+ * @param auto - 自动档是否开启。
354
+ * @returns 合法档位。
355
+ */
356
+ function pickInitialMode(stored, narrow, height, auto) {
357
+ if (typeof stored === "string" && MODES.indexOf(stored) !== -1) return stored;
358
+ if (narrow) return "compact";
359
+ if (auto && autoWantsCompact(false, height)) return "compact";
360
+ return "expanded";
361
+ }
362
+
363
+ /**
364
+ * 自动档开关的存档解析。
365
+ * @param stored - localStorage 原始值。
366
+ * @returns 是否开启。
367
+ */
368
+ function resolveAuto(stored) {
369
+ return stored !== "off";
370
+ }
371
+
372
+ /**
373
+ * 决定控件模型:已存值优先,否则三档选择器。
374
+ * @param stored - localStorage 里的原始值。
375
+ * @returns 合法模型。
376
+ */
377
+ function resolveModel(stored) {
378
+ return typeof stored === "string" && MODELS.indexOf(stored) !== -1 ? stored : "segmented";
379
+ }
380
+
381
+ /**
382
+ * 当前设备桶该用哪个 localStorage 键。
383
+ * @param narrow - 是否窄屏。
384
+ * @returns 存储键。
385
+ */
386
+ function modeKey(narrow) {
387
+ return narrow ? STORAGE_MODE_NARROW : STORAGE_MODE;
388
+ }
389
+
390
+ /**
391
+ * 自动档:窗口够矮(或本来就在窄屏)时该不该进图标档。
392
+ * @param narrow - 是否命中窄屏断点。
393
+ * @param height - 视口高度。
394
+ * @returns 是否应该自动进图标档。
395
+ */
396
+ function autoWantsCompact(narrow, height) {
397
+ if (narrow) return true;
398
+ return typeof height === "number" && height > 0 && height < AUTO_HEIGHT_PX;
399
+ }
400
+
401
+ /** 是不是我们自己的控制条。 */
402
+ function isOwnBar(el) {
403
+ return !!el && el !== runtime.bar && typeof el.getAttribute === "function" && el.getAttribute(BAR_ATTR) !== null;
404
+ }
405
+
406
+ /**
407
+ * 在包裹层里找行按钮(不依赖 querySelector,假 DOM 与真 DOM 都能跑)。
408
+ * rc.2 起结构是 div.panelEntry > button.panelRow,Tooltip 不额外包一层。
409
+ * @param host - 包裹层元素。
410
+ * @returns 行按钮或 null。
411
+ */
412
+ function findRowButton(host) {
413
+ if (!host || !host.children) return null;
414
+ const kids = host.children;
415
+ for (let i = 0; i < kids.length; i += 1) {
416
+ const kid = kids[i];
417
+ if (kid && kid.tagName === "BUTTON") return kid;
418
+ if (kid && kid.children) {
419
+ for (let j = 0; j < kid.children.length; j += 1) {
420
+ if (kid.children[j] && kid.children[j].tagName === "BUTTON") return kid.children[j];
421
+ }
422
+ }
423
+ }
424
+ return null;
425
+ }
426
+
427
+ /**
428
+ * 把 nav 的直接子节点归一成「入口行」。
429
+ * - rc.1 及更早:子节点本身就是 button.panelRow
430
+ * - rc.2 起:子节点是 div.panelEntry,按钮在它里面(行内可能还有 panelUnpin 等按钮)
431
+ * @param child - nav 的直接子节点。
432
+ * @returns { wrapper, button };不是入口行时返回 null。
433
+ */
434
+ function rowOf(child) {
435
+ if (!child || child === runtime.bar || isOwnBar(child)) return null;
436
+ if (child.tagName === "BUTTON") return { wrapper: child, button: child };
437
+ if (child.tagName !== "DIV") return null;
438
+ const btn = findRowButton(child);
439
+ return btn ? { wrapper: child, button: btn } : null;
440
+ }
441
+
442
+ /** 「更多」锚点里的按钮(rc.1 span.moreAnchor 与 rc.3 换了类名的 span 都按 tagName 认)。 */
443
+ function moreButtonOf(child) {
444
+ if (!child || child.tagName !== "SPAN") return null;
445
+ return findRowButton(child);
446
+ }
447
+
448
+ /**
449
+ * 判断一个元素是否是「功能入口」导航。
450
+ * 判据只看结构不认类名(宿主类名每版都变):
451
+ * - 子节点是入口行(button,或 rc.2+ 的 div 包裹 + 按钮)与「更多」span;
452
+ * - 至少 2 行,或 1 行且带 aria-label(窄屏时外壳不渲染标题 span,不能靠“两段结构”判定);
453
+ * - 不含输入控件 / 链接。
454
+ * @param node - 待判定元素。
455
+ * @returns 命中与否。
456
+ */
457
+ function looksLikePanelNav(node) {
458
+ if (!node || node.tagName !== "NAV") return false;
459
+ const kids = node.children;
460
+ if (!kids || kids.length === 0) return false;
461
+ let rows = 0;
462
+ let labelled = 0;
463
+ for (let i = 0; i < kids.length; i += 1) {
464
+ const kid = kids[i];
465
+ if (kid === runtime.bar || isOwnBar(kid)) continue;
466
+ const row = rowOf(kid);
467
+ if (row) {
468
+ rows += 1;
469
+ if (typeof row.button.getAttribute === "function" && row.button.getAttribute("aria-label")) labelled += 1;
470
+ continue;
471
+ }
472
+ if (kid.tagName === "SPAN") continue;
473
+ return false;
474
+ }
475
+ if (rows === 0) return false;
476
+ if (rows < 2 && labelled === 0) return false;
477
+ if (typeof node.querySelector === "function" && node.querySelector("input, textarea, select, a, form")) return false;
478
+ return true;
479
+ }
480
+
481
+ /**
482
+ * 在文档里找「功能入口」导航。
483
+ * @param doc - document 或等价对象。
484
+ * @returns 命中的 nav,或 null。
485
+ */
486
+ function findNav(doc) {
487
+ if (!doc || typeof doc.querySelectorAll !== "function") return null;
488
+ const navs = doc.querySelectorAll("nav");
489
+ if (!navs || navs.length === 0) return null;
490
+ let best = null;
491
+ let bestRows = 0;
492
+ for (let i = 0; i < navs.length; i += 1) {
493
+ if (!looksLikePanelNav(navs[i])) continue;
494
+ let count = 0;
495
+ const kids = navs[i].children || [];
496
+ for (let j = 0; j < kids.length; j += 1) if (rowOf(kids[j])) count += 1;
497
+ if (count > bestRows) {
498
+ best = navs[i];
499
+ bestRows = count;
500
+ }
501
+ }
502
+ return best;
503
+ }
504
+
505
+ /** 找不到导航时打一条可复现的结构诊断(宿主改版时靠它定位)。 */
506
+ function describeNavs(doc) {
507
+ if (!doc || typeof doc.querySelectorAll !== "function") return "";
508
+ const navs = doc.querySelectorAll("nav");
509
+ const parts = [];
510
+ for (let i = 0; i < navs.length && i < 3; i += 1) {
511
+ const kids = navs[i].children || [];
512
+ const shape = [];
513
+ for (let j = 0; j < kids.length && j < 6; j += 1) {
514
+ const kid = kids[j];
515
+ const inner = kid && kid.children ? kid.children.length : 0;
516
+ shape.push(kid.tagName + (inner ? "(" + inner + ")" : ""));
517
+ }
518
+ parts.push("nav[" + i + "] " + kids.length + " kids: " + shape.join(","));
519
+ }
520
+ return parts.join(" | ");
521
+ }
522
+
523
+ /**
524
+ * 判断文档是否满足互动所需的最小能力。
525
+ * @param doc - document。
526
+ * @returns 是否可用。
527
+ */
528
+ function hasDom(doc) {
529
+ return !!doc && typeof doc.createElement === "function" && typeof doc.querySelector === "function";
530
+ }
531
+
532
+ /* ───────────────────────── DOM 层 ───────────────────────── */
533
+
534
+ /**
535
+ * 幂等注入样式表。
536
+ * @param doc - document。
537
+ * @returns 注入的 style 元素;已存在时返回 null。
538
+ */
539
+ function ensureStyle(doc) {
540
+ if (!hasDom(doc)) return null;
541
+ if (doc.querySelector('style[data-plugin-css="' + STYLE_ID + '"]')) return null;
542
+ const style = doc.createElement("style");
543
+ style.setAttribute("data-plugin-css", STYLE_ID);
544
+ style.textContent = CSS_TEXT;
545
+ (doc.head || doc.documentElement).appendChild(style);
546
+ return style;
547
+ }
548
+
549
+ /**
550
+ * 画一个小图标(16 网格)。
551
+ * @param doc - document。
552
+ * @param paths - path 的 d 值列表。
553
+ * @param size - 边长。
554
+ * @returns svg 元素。
555
+ */
556
+ function makeIcon(doc, paths, size) {
557
+ const svg = doc.createElementNS ? doc.createElementNS("http://www.w3.org/2000/svg", "svg") : doc.createElement("svg");
558
+ svg.setAttribute("viewBox", "0 0 16 16");
559
+ svg.setAttribute("width", String(size || 12));
560
+ svg.setAttribute("height", String(size || 12));
561
+ svg.setAttribute("fill", "none");
562
+ svg.setAttribute("stroke", "currentColor");
563
+ svg.setAttribute("stroke-width", "1.4");
564
+ svg.setAttribute("stroke-linecap", "round");
565
+ svg.setAttribute("stroke-linejoin", "round");
566
+ svg.setAttribute("aria-hidden", "true");
567
+ for (let i = 0; i < paths.length; i += 1) {
568
+ const path = doc.createElementNS ? doc.createElementNS("http://www.w3.org/2000/svg", "path") : doc.createElement("path");
569
+ path.setAttribute("d", paths[i]);
570
+ svg.appendChild(path);
571
+ }
572
+ return svg;
573
+ }
574
+
575
+ /**
576
+ * 造一个控制条按钮:图标 + 文字,点击执行一个动作。
577
+ * @param doc - document。
578
+ * @param action - expanded | compact | hidden | cycle。
579
+ * @param label - 文字标签(图标轨里被 CSS 隐藏)。
580
+ * @param title - tooltip 与无障碍名。
581
+ * @param iconPaths - 图标路径。
582
+ * @param pressed - 传入时写 aria-pressed(三档选择器用)。
583
+ * @returns button 元素。
584
+ */
585
+ function makeAction(doc, action, label, title, iconPaths, pressed) {
586
+ const button = doc.createElement("button");
587
+ button.setAttribute("type", "button");
588
+ button.setAttribute("data-navfold-action", action);
589
+ button.setAttribute("title", title);
590
+ button.setAttribute("aria-label", title);
591
+ if (typeof pressed === "boolean") button.setAttribute("aria-pressed", pressed ? "true" : "false");
592
+ button.appendChild(makeIcon(doc, iconPaths));
593
+ const text = doc.createElement("span");
594
+ text.setAttribute("data-navfold-label", "");
595
+ text.textContent = label;
596
+ button.appendChild(text);
597
+ button.addEventListener("click", (event) => {
598
+ if (event && typeof event.preventDefault === "function") {
599
+ event.preventDefault();
600
+ event.stopPropagation();
601
+ }
602
+ if (action === "all") toggleAll();
603
+ else if (action === "cycle") setMode(nextMode(runtime.mode));
604
+ else setMode(action);
605
+ });
606
+ return button;
607
+ }
608
+
609
+ /**
610
+ * 造单按钮循环控件:**一次只显示当前档那一个图标**(与三档选择器用同一套图标),
611
+ * 点一下换成下一档的图标。tooltip 说明点下去会变成什么。
612
+ * @param doc - document。
613
+ * @returns button 元素。
614
+ */
615
+ function makeCycle(doc) {
616
+ const next = nextMode(runtime.mode);
617
+ const button = doc.createElement("button");
618
+ button.setAttribute("type", "button");
619
+ button.setAttribute("data-navfold-action", "cycle");
620
+ button.setAttribute("data-navfold-glyph", runtime.mode);
621
+ button.setAttribute("title", t("cycle." + next));
622
+ button.setAttribute("aria-label", t("cycle." + next));
623
+ button.setAttribute("data-navfold-size", "large");
624
+ button.appendChild(makeIcon(doc, densityIcon(runtime.mode), 14));
625
+ button.addEventListener("click", (event) => {
626
+ if (event && typeof event.preventDefault === "function") {
627
+ event.preventDefault();
628
+ event.stopPropagation();
629
+ }
630
+ setMode(nextMode(runtime.mode));
631
+ });
632
+ return button;
633
+ }
634
+
635
+ /** 浮层的 Esc / 点外部 / 滚动 关闭处理器(挂载时注册,关闭时解绑) */
636
+ function onPopoverKey(event) {
637
+ if (!event || event.key !== "Escape") return;
638
+ if (typeof event.preventDefault === "function") event.preventDefault();
639
+ closeAll();
640
+ }
641
+
642
+ function onPopoverOutside(event) {
643
+ if (!runtime.popover) return;
644
+ const target = event && event.target;
645
+ if (!target) return;
646
+ // 点触发按钮交给它自己 toggle,避免"关了又立刻打开"
647
+ if (typeof target.closest === "function" && target.closest('[data-navfold-action="all"]')) return;
648
+ if (typeof runtime.popover.contains === "function" && runtime.popover.contains(target)) return;
649
+ closeAll();
650
+ }
651
+
652
+ /** 关闭"全部入口"浮层。 */
653
+ function closeAll() {
654
+ const pop = runtime.popover;
655
+ runtime.popover = null;
656
+ if (typeof window.removeEventListener === "function") {
657
+ window.removeEventListener("keydown", onPopoverKey, true);
658
+ window.removeEventListener("pointerdown", onPopoverOutside, true);
659
+ window.removeEventListener("scroll", closeAll, true);
660
+ }
661
+ if (pop && pop.parentNode) pop.parentNode.removeChild(pop);
662
+ }
663
+
664
+ /** 打开/关闭"全部入口"浮层:收起态下一键直达任一入口。 */
665
+ function toggleAll() {
666
+ if (runtime.popover) {
667
+ closeAll();
668
+ return;
669
+ }
670
+ const doc = document;
671
+ const rows = collectRows(runtime.nav || null);
672
+ if (!rows.length || !doc || !doc.body) return;
673
+ const pop = doc.createElement("div");
674
+ pop.setAttribute("data-navfold-popover", "");
675
+ pop.setAttribute("role", "menu");
676
+ pop.setAttribute("aria-label", t("popover.label"));
677
+ for (let i = 0; i < rows.length; i += 1) {
678
+ const row = rows[i];
679
+ const item = doc.createElement("button");
680
+ item.setAttribute("type", "button");
681
+ item.setAttribute("role", "menuitem");
682
+ item.textContent = row.label;
683
+ item.addEventListener("click", (event) => {
684
+ if (event && typeof event.preventDefault === "function") {
685
+ event.preventDefault();
686
+ event.stopPropagation();
687
+ }
688
+ closeAll();
689
+ try {
690
+ if (row.el && typeof row.el.click === "function") row.el.click();
691
+ } catch (err) {
692
+ warn("打开入口失败", err);
693
+ }
694
+ });
695
+ pop.appendChild(item);
696
+ }
697
+ doc.body.appendChild(pop);
698
+ const bar = runtime.bar;
699
+ if (bar && typeof bar.getBoundingClientRect === "function" && typeof window.innerWidth === "number") {
700
+ const rect = bar.getBoundingClientRect();
701
+ const popRect = typeof pop.getBoundingClientRect === "function" ? pop.getBoundingClientRect() : null;
702
+ const width = (popRect && popRect.width) || 200;
703
+ const height = (popRect && popRect.height) || 0;
704
+ const left = (rect.left || 0) + (rect.width || 0) - width;
705
+ // 上方放不下就翻到控制条下方,避免贴到视口顶部盖住入口
706
+ const above = (rect.top || 0) - height - 6;
707
+ const below = (rect.top || 0) + (rect.height || 0) + 6;
708
+ const top = above >= 8 ? above : Math.min(below, (window.innerHeight || 0) - height - 8);
709
+ pop.style.top = Math.max(8, top) + "px";
710
+ pop.style.left = Math.max(8, Math.min(left, window.innerWidth - width - 8)) + "px";
711
+ }
712
+ runtime.popover = pop;
713
+ if (typeof window.addEventListener === "function") {
714
+ window.addEventListener("keydown", onPopoverKey, true);
715
+ window.addEventListener("pointerdown", onPopoverOutside, true);
716
+ window.addEventListener("scroll", closeAll, true);
717
+ }
718
+ const first = pop.children && pop.children[0];
719
+ if (first && typeof first.focus === "function") first.focus();
720
+ }
721
+
722
+ /**
723
+ * 按当前档位与控件模型重绘控制条。
724
+ */
725
+ function renderBar() {
726
+ const bar = runtime.bar;
727
+ if (!bar) return;
728
+ const signature =
729
+ runtime.model +
730
+ "|" +
731
+ runtime.mode +
732
+ "|" +
733
+ (runtime.iconOnly ? "rail" : "wide") +
734
+ "|" +
735
+ runtime.totals.kept +
736
+ "/" +
737
+ runtime.totals.total;
738
+ if (signature === runtime.signature) return;
739
+ runtime.signature = signature;
740
+ const doc = bar.ownerDocument || document;
741
+ bar.textContent = "";
742
+ // 收起态先给一个"藏了多少"的徽标
743
+ const hiddenCount = Math.max(0, runtime.totals.total - runtime.totals.kept);
744
+ if (runtime.model !== "header" && runtime.mode === "hidden" && runtime.totals.total > 0 && hiddenCount > 0) {
745
+ const badge = doc.createElement("span");
746
+ badge.setAttribute("data-navfold-count", "");
747
+ badge.setAttribute("title", t("badge.title", { hidden: hiddenCount, kept: runtime.totals.kept }));
748
+ badge.textContent = t("badge.text", { hidden: hiddenCount });
749
+ bar.appendChild(badge);
750
+ }
751
+ // 图标轨里放不下排布,两种模型都退化成单按钮循环
752
+ const allButton = () => makeAction(doc, "all", t("bar.all"), t("bar.all.title"), LIST_ICON);
753
+ if (runtime.iconOnly) {
754
+ bar.appendChild(makeCycle(doc));
755
+ if (runtime.mode === "hidden") bar.appendChild(allButton());
756
+ return;
757
+ }
758
+ if (runtime.model === "header") {
759
+ bar.appendChild(makeHeaderButton(doc));
760
+ return;
761
+ }
762
+ if (runtime.model === "cycle") {
763
+ bar.appendChild(makeCycle(doc));
764
+ if (runtime.mode === "hidden") bar.appendChild(allButton());
765
+ return;
766
+ }
767
+ for (let i = 0; i < MODES.length; i += 1) {
768
+ const mode = MODES[i];
769
+ bar.appendChild(makeAction(doc, mode, densityLabel(mode), densityTitle(mode), densityIcon(mode), mode === runtime.mode));
770
+ }
771
+ if (runtime.mode === "hidden") bar.appendChild(allButton());
772
+ }
773
+
774
+ /**
775
+ * 侧栏是否被外壳收成了 56px 图标轨。
776
+ * 先读外壳自己的状态属性(收起时内容只是被平移到轨道里、布局宽度不变,量不出来),
777
+ * 读不到再退回宽度判断。
778
+ * @param nav - 命中的 nav。
779
+ * @returns 是否图标轨。
780
+ */
781
+ function isRailMode(nav) {
782
+ if (typeof document !== "undefined" && document && typeof document.querySelector === "function") {
783
+ const collapsed = document.querySelector('[data-sidebar-collapsed="true"]');
784
+ if (collapsed) return typeof collapsed.contains === "function" ? collapsed.contains(nav) : true;
785
+ const expanded = document.querySelector('[data-sidebar-collapsed="false"]');
786
+ if (expanded) return false;
787
+ }
788
+ const width = typeof nav.clientWidth === "number" ? nav.clientWidth : 0;
789
+ return width > 0 && width < ICON_ONLY_WIDTH;
790
+ }
791
+
792
+ /**
793
+ * 造"标题行"控件:整组只留这一行,点一下展开/收起。
794
+ * @param doc - document。
795
+ * @returns button 元素。
796
+ */
797
+ function makeHeaderButton(doc) {
798
+ const collapsed = runtime.mode === "hidden";
799
+ const hiddenCount = Math.max(0, runtime.totals.total - runtime.totals.kept);
800
+ const button = doc.createElement("button");
801
+ button.setAttribute("type", "button");
802
+ button.setAttribute("data-navfold-action", "header-toggle");
803
+ button.setAttribute("title", collapsed ? t("header.expand") : t("header.collapse"));
804
+ button.setAttribute("aria-label", collapsed ? t("header.expand") : t("header.collapse"));
805
+ button.setAttribute("aria-expanded", collapsed ? "false" : "true");
806
+ button.appendChild(makeIcon(doc, collapsed ? CHEVRON_DOWN : CHEVRON_UP, 14));
807
+ const label = doc.createElement("span");
808
+ label.textContent = t("header.label");
809
+ button.appendChild(label);
810
+ const count = doc.createElement("span");
811
+ count.setAttribute("data-navfold-header-count", "");
812
+ count.textContent = collapsed ? t("badge.text", { hidden: hiddenCount }) : String(runtime.totals.total);
813
+ button.appendChild(count);
814
+ button.addEventListener("click", (event) => {
815
+ if (event && typeof event.preventDefault === "function") {
816
+ event.preventDefault();
817
+ event.stopPropagation();
818
+ }
819
+ setMode(runtime.mode === "hidden" ? "expanded" : "hidden");
820
+ });
821
+ return button;
822
+ }
823
+
824
+ /**
825
+ * 让控制条跟上宽度档。
826
+ * @param nav - 命中的 nav。
827
+ */
828
+ function syncWidth(nav) {
829
+ const bar = runtime.bar;
830
+ if (!bar || !nav || typeof bar.removeAttribute !== "function") return;
831
+ const iconOnly = isRailMode(nav);
832
+ if (iconOnly) bar.setAttribute("data-navfold-icononly", "");
833
+ else bar.removeAttribute("data-navfold-icononly");
834
+ if (iconOnly !== runtime.iconOnly) {
835
+ runtime.iconOnly = iconOnly;
836
+ renderBar();
837
+ }
838
+ }
839
+
840
+ /**
841
+ * 把控制条挂到 nav 的末尾,并刷新内容。
842
+ * @param nav - 命中的 nav。
843
+ */
844
+ function mountBar(nav) {
845
+ if (!nav) return;
846
+ const doc = nav.ownerDocument || document;
847
+ if (!runtime.bar) {
848
+ const bar = doc.createElement("div");
849
+ bar.setAttribute(BAR_ATTR, "");
850
+ bar.setAttribute("role", "group");
851
+ bar.setAttribute("aria-label", t("bar.aria"));
852
+ bar.setAttribute("title", t("bar.title"));
853
+ runtime.bar = bar;
854
+ }
855
+ const wantFirst = runtime.model === "header";
856
+ if (typeof runtime.bar.setAttribute === "function") {
857
+ if (wantFirst) runtime.bar.setAttribute("data-navfold-header", "");
858
+ else if (typeof runtime.bar.removeAttribute === "function") runtime.bar.removeAttribute("data-navfold-header");
859
+ }
860
+ const kids = nav.children || [];
861
+ const atFirst = kids[0] === runtime.bar;
862
+ const atLast = kids[kids.length - 1] === runtime.bar;
863
+ if (runtime.bar.parentNode !== nav || (wantFirst ? !atFirst : !atLast)) {
864
+ if (wantFirst && typeof nav.insertBefore === "function") nav.insertBefore(runtime.bar, kids[0] || null);
865
+ else nav.appendChild(runtime.bar);
866
+ }
867
+ syncKeeps(nav);
868
+ syncWidth(nav);
869
+ syncTitles(nav);
870
+ renderBar();
871
+ }
872
+
873
+ /** 把当前档位写到命中的 nav 上(CSS 只认这一个属性)。 */
874
+ function paintNav() {
875
+ const nav = runtime.nav;
876
+ if (!nav || typeof nav.setAttribute !== "function") return;
877
+ try {
878
+ nav.setAttribute(NAV_ATTR, runtime.mode);
879
+ } catch (err) {
880
+ warn("写入档位失败", err);
881
+ }
882
+ }
883
+
884
+ /** 通知所有订阅者(控制条与设置分区共用)。 */
885
+ function notify() {
886
+ runtime.listeners.forEach((listener) => {
887
+ try {
888
+ listener();
889
+ } catch (err) {
890
+ /* 单个订阅失败不影响其余 */
891
+ }
892
+ });
893
+ }
894
+
895
+ /**
896
+ * 切换档位并落盘。
897
+ * @param mode - 目标档位。
898
+ */
899
+ function setMode(mode) {
900
+ runtime.mode = mode;
901
+ paintNav();
902
+ if (runtime.nav) syncTitles(runtime.nav);
903
+ renderBar();
904
+ try {
905
+ window.localStorage.setItem(modeKey(runtime.narrow), mode);
906
+ } catch (err) {
907
+ /* 隐私模式 / 配额不足:本次会话内有效 */
908
+ }
909
+ notify();
910
+ }
911
+
912
+ /** 读取当前档位。 */
913
+ function getMode() {
914
+ return runtime.mode;
915
+ }
916
+
917
+ /** 读取收起态要保留的行清单。 */
918
+ function getKeep() {
919
+ return runtime.keep.slice();
920
+ }
921
+
922
+ /** 读取自动档开关。 */
923
+ function getAuto() {
924
+ return runtime.auto;
925
+ }
926
+
927
+ /**
928
+ * 切换自动档并落盘。
929
+ * @param next - 是否开启。
930
+ */
931
+ function setAuto(next) {
932
+ runtime.auto = !!next;
933
+ try {
934
+ window.localStorage.setItem(STORAGE_AUTO, runtime.auto ? "on" : "off");
935
+ } catch (err) {
936
+ /* 同上 */
937
+ }
938
+ notify();
939
+ }
940
+
941
+ /**
942
+ * 标题行模型只支持「文字行 / 收起」:进标题行时把图标档暂存,离开时还原。
943
+ * @param nextModel - 即将生效的模型。
944
+ */
945
+ function reconcileHeaderMode(nextModel) {
946
+ if (nextModel === "header") {
947
+ if (runtime.mode === "compact") {
948
+ runtime.modeStash = "compact";
949
+ runtime.mode = "expanded";
950
+ persistStash();
951
+ }
952
+ return;
953
+ }
954
+ if (runtime.modeStash) {
955
+ // 离开标题行:还回你进标题行之前真正想用的档位
956
+ runtime.mode = runtime.modeStash;
957
+ runtime.modeStash = null;
958
+ persistStash();
959
+ }
960
+ }
961
+
962
+ /** 把暂存档位写盘(null 时删键)。 */
963
+ function persistStash() {
964
+ try {
965
+ if (runtime.modeStash) window.localStorage.setItem(STORAGE_STASH, runtime.modeStash);
966
+ else window.localStorage.removeItem(STORAGE_STASH);
967
+ } catch (err) {
968
+ /* 隐私模式:本次会话内有效即可 */
969
+ }
970
+ }
971
+
972
+ /**
973
+ * 切换控件模型并落盘。
974
+ * @param model - segmented | cycle。
975
+ */
976
+ function setModel(model) {
977
+ const previousModel = runtime.model;
978
+ runtime.model = resolveModel(model);
979
+ if (runtime.model !== previousModel) reconcileHeaderMode(runtime.model);
980
+ runtime.signature = "";
981
+ paintNav();
982
+ if (runtime.nav) mountBar(runtime.nav);
983
+ else renderBar();
984
+ try {
985
+ window.localStorage.setItem(STORAGE_MODEL, runtime.model);
986
+ } catch (err) {
987
+ /* 同上 */
988
+ }
989
+ notify();
990
+ }
991
+
992
+ /** 读取当前控件模型。 */
993
+ function getModel() {
994
+ return runtime.model;
995
+ }
996
+
997
+ /**
998
+ * 订阅状态变化。
999
+ * @param listener - 变化回调。
1000
+ * @returns 取消订阅。
1001
+ */
1002
+ function subscribe(listener) {
1003
+ runtime.listeners.add(listener);
1004
+ return () => {
1005
+ runtime.listeners.delete(listener);
1006
+ };
1007
+ }
1008
+
1009
+ /**
1010
+ * 统一告警出口。
1011
+ * @param message - 说明。
1012
+ * @param err - 可选异常。
1013
+ */
1014
+ function warn(message, err) {
1015
+ const detail = err === undefined ? "" : " · " + (err && err.message ? err.message : String(err));
1016
+ console.warn("[dsh-nav-fold] " + message + detail);
1017
+ }
1018
+
1019
+ /**
1020
+ * 找到导航就打标 + 挂控制条;找不到只告警一次(宽限期后)。
1021
+ */
1022
+ function scan() {
1023
+ const nav = runtime.nav;
1024
+ if (nav && nav.isConnected !== false && looksLikePanelNav(nav)) {
1025
+ // 标题行必须始终是 nav 的第一个子节点;被外壳挪走就重挂,连续失败则退回按钮条
1026
+ if (runtime.model === "header" && nav.children && nav.children[0] !== runtime.bar) {
1027
+ runtime.headerDrift += 1;
1028
+ mountBar(nav);
1029
+ if (runtime.headerDrift > 3) {
1030
+ runtime.headerDrift = 0;
1031
+ warn("标题行被外壳反复挪动,已退回按钮条");
1032
+ runtime.model = "segmented";
1033
+ runtime.signature = "";
1034
+ paintNav();
1035
+ mountBar(nav);
1036
+ notify();
1037
+ return;
1038
+ }
1039
+ return;
1040
+ }
1041
+ runtime.headerDrift = 0;
1042
+ paintNav();
1043
+ mountBar(nav);
1044
+ return;
1045
+ }
1046
+ const found = findNav(document);
1047
+ if (!found) {
1048
+ if (!runtime.warned && Date.now() - runtime.mountedAt > WARN_AFTER_MS) {
1049
+ runtime.warned = true;
1050
+ warn("未找到「功能入口」导航(DSH 版本可能已变更),保持原生 UI " + describeNavs(document));
1051
+ }
1052
+ return;
1053
+ }
1054
+ runtime.nav = found;
1055
+ runtime.warned = false;
1056
+ paintNav();
1057
+ mountBar(found);
1058
+ }
1059
+
1060
+ /**
1061
+ * 列出 nav 里的"入口行"按钮:直接子 button + 「更多」锚点(span > button),
1062
+ * 排除我们自己的控制条。
1063
+ * @param nav - 命中的 nav。
1064
+ * @returns 按钮数组。
1065
+ */
1066
+ function rowButtons(nav) {
1067
+ const out = [];
1068
+ if (!nav || !nav.children) return out;
1069
+ for (let i = 0; i < nav.children.length; i += 1) {
1070
+ const child = nav.children[i];
1071
+ if (!child) continue;
1072
+ const row = rowOf(child);
1073
+ if (row) {
1074
+ out.push(row.button);
1075
+ continue;
1076
+ }
1077
+ const more = moreButtonOf(child);
1078
+ if (more) out.push(more);
1079
+ }
1080
+ return out;
1081
+ }
1082
+
1083
+ /**
1084
+ * 图标档 / 图标轨下给每行补原生 title(悬停可见名称);回到文字行则摘掉。
1085
+ * 只写我们加的那一份(打 data-navfold-title 标记),外壳自己的 title 一律不碰。
1086
+ * @param nav - 命中的 nav。
1087
+ */
1088
+ function syncTitles(nav) {
1089
+ const buttons = rowButtons(nav);
1090
+ // rc.2 起外壳给每行配了 Tooltip:再叠原生 title 会双提示,交给外壳
1091
+ const rows = collectRows(nav);
1092
+ const shellHasTooltip = rows.some((row) => row.wrapper !== row.el);
1093
+ const wantTitles = (runtime.iconOnly || runtime.mode === "compact") && !shellHasTooltip;
1094
+ for (let i = 0; i < buttons.length; i += 1) {
1095
+ const el = buttons[i];
1096
+ if (!el || typeof el.setAttribute !== "function") continue;
1097
+ const marked = typeof el.getAttribute === "function" && el.getAttribute("data-navfold-title") !== null;
1098
+ if (!wantTitles) {
1099
+ if (marked) {
1100
+ if (typeof el.removeAttribute === "function") {
1101
+ el.removeAttribute("title");
1102
+ el.removeAttribute("data-navfold-title");
1103
+ }
1104
+ }
1105
+ continue;
1106
+ }
1107
+ if (hasOwnTitle(el)) continue;
1108
+ const label = rowLabel(el);
1109
+ if (!label) continue;
1110
+ el.setAttribute("title", label);
1111
+ el.setAttribute("data-navfold-title", "");
1112
+ }
1113
+ }
1114
+
1115
+ /**
1116
+ * 元素上是否已经有 title(含我们上一轮加的)——有就不重复写。
1117
+ * @param el - 行按钮。
1118
+ * @returns 是否已有。
1119
+ */
1120
+ function hasOwnTitle(el) {
1121
+ return typeof el.getAttribute === "function" && el.getAttribute("title") !== null;
1122
+ }
1123
+
1124
+ /**
1125
+ * 读一行入口的显示名(用于稳定记住"保留哪几行")。
1126
+ * @param row - 行元素。
1127
+ * @returns 标签文本。
1128
+ */
1129
+ function rowLabel(row) {
1130
+ if (!row || !row.children) return "";
1131
+ for (let i = 0; i < row.children.length; i += 1) {
1132
+ const child = row.children[i];
1133
+ if (child && child.tagName === "SPAN" && typeof child.textContent === "string" && child.textContent.trim()) {
1134
+ return child.textContent.trim();
1135
+ }
1136
+ }
1137
+ return typeof row.textContent === "string" ? row.textContent.trim() : "";
1138
+ }
1139
+
1140
+ /**
1141
+ * 收集当前导航里的所有入口行。
1142
+ * @param nav - 命中的 nav。
1143
+ * @returns [{ label, el }]。
1144
+ */
1145
+ function collectRows(nav) {
1146
+ const rows = [];
1147
+ if (!nav || !nav.children) return rows;
1148
+ for (let i = 0; i < nav.children.length; i += 1) {
1149
+ const row = rowOf(nav.children[i]);
1150
+ if (!row) continue;
1151
+ rows.push({ label: rowLabel(row.button), el: row.button, wrapper: row.wrapper });
1152
+ }
1153
+ return rows;
1154
+ }
1155
+
1156
+ /**
1157
+ * 把保留清单打标到行上,并更新计数(收起态徽标用)。
1158
+ * 清单为空时退回"保留第一行",避免把面板入口做成死路。
1159
+ * @param nav - 命中的 nav。
1160
+ */
1161
+ function syncKeeps(nav) {
1162
+ const rows = collectRows(nav);
1163
+ const resolved = resolveKeepIndices(rows);
1164
+ const effective = resolved.length > 0 ? resolved.map((item) => item.index) : rows.length > 0 ? [0] : [];
1165
+ // 自愈:行名变了(切语言 / 插件改名)就把解析到的当前名字写回存档
1166
+ if (runtime.keep.length > 0) {
1167
+ const healed = resolved.map((item) => ({ i: item.index, label: item.label }));
1168
+ if (JSON.stringify(healed) !== JSON.stringify(runtime.keep)) {
1169
+ runtime.keep = healed;
1170
+ persistKeep();
1171
+ }
1172
+ }
1173
+ let kept = 0;
1174
+ for (let i = 0; i < rows.length; i += 1) {
1175
+ const row = rows[i];
1176
+ const keep = effective.indexOf(i) !== -1;
1177
+ if (keep) kept += 1;
1178
+ const targets = row.wrapper && row.wrapper !== row.el ? [row.wrapper, row.el] : [row.el];
1179
+ for (let t = 0; t < targets.length; t += 1) {
1180
+ const target = targets[t];
1181
+ if (!target) continue;
1182
+ if (typeof target.setAttribute === "function" && keep) target.setAttribute("data-navfold-keep", "");
1183
+ else if (typeof target.removeAttribute === "function") target.removeAttribute("data-navfold-keep");
1184
+ }
1185
+ }
1186
+ const changed = runtime.totals.kept !== kept || runtime.totals.total !== rows.length;
1187
+ runtime.totals = { kept, total: rows.length };
1188
+ if (changed && runtime.listeners.size > 0) notify();
1189
+ }
1190
+
1191
+ /**
1192
+ * 切换某一行的"收起态保留"。
1193
+ * @param label - 行标签。
1194
+ */
1195
+ function toggleKeep(label) {
1196
+ const rows = collectRows(runtime.nav || null);
1197
+ let at = -1;
1198
+ for (let i = 0; i < rows.length; i += 1) {
1199
+ if (rows[i].label === label) {
1200
+ at = i;
1201
+ break;
1202
+ }
1203
+ }
1204
+ if (at === -1) return;
1205
+ const exists = runtime.keep.some((entry) => entry.i === at || entry.label === label);
1206
+ runtime.keep = exists
1207
+ ? runtime.keep.filter((entry) => !(entry.i === at || entry.label === label))
1208
+ : runtime.keep.concat([{ i: at, label: rows[at].label }]);
1209
+ persistKeep();
1210
+ if (runtime.nav) syncKeeps(runtime.nav);
1211
+ runtime.signature = "";
1212
+ renderBar();
1213
+ notify();
1214
+ }
1215
+
1216
+ /** 把保留清单写盘。 */
1217
+ function persistKeep() {
1218
+ try {
1219
+ window.localStorage.setItem(STORAGE_KEEP, JSON.stringify(runtime.keep));
1220
+ } catch (err) {
1221
+ /* 同上 */
1222
+ }
1223
+ }
1224
+
1225
+ /** 收起时全保留。 */
1226
+ function keepAll() {
1227
+ runtime.keep = collectRows(runtime.nav || null).map((row, index) => ({ i: index, label: row.label }));
1228
+ persistKeep();
1229
+ if (runtime.nav) syncKeeps(runtime.nav);
1230
+ runtime.signature = "";
1231
+ renderBar();
1232
+ notify();
1233
+ }
1234
+
1235
+ /** 清空保留清单(回到"默认保留第一行")。 */
1236
+ function clearKeep() {
1237
+ runtime.keep = [];
1238
+ persistKeep();
1239
+ if (runtime.nav) syncKeeps(runtime.nav);
1240
+ runtime.signature = "";
1241
+ renderBar();
1242
+ notify();
1243
+ }
1244
+
1245
+ /**
1246
+ * 点「恢复默认」:第一次只进入确认态(3 秒后自动取消),第二次才真正执行。
1247
+ */
1248
+ function requestReset() {
1249
+ if (runtime.confirmReset) {
1250
+ runtime.confirmReset = false;
1251
+ if (runtime.resetTimer) {
1252
+ window.clearTimeout(runtime.resetTimer);
1253
+ runtime.resetTimer = 0;
1254
+ }
1255
+ resetAll();
1256
+ return;
1257
+ }
1258
+ runtime.confirmReset = true;
1259
+ if (typeof window.setTimeout === "function") {
1260
+ runtime.resetTimer = window.setTimeout(() => {
1261
+ runtime.resetTimer = 0;
1262
+ runtime.confirmReset = false;
1263
+ notify();
1264
+ }, 3000);
1265
+ }
1266
+ notify();
1267
+ }
1268
+
1269
+ /** 恢复默认:档位 / 控件样式 / 自动档 / 保留行 全部回到出厂值。 */
1270
+ function resetAll() {
1271
+ runtime.confirmReset = false;
1272
+ runtime.modeStash = null;
1273
+ try {
1274
+ window.localStorage.removeItem(STORAGE_STASH);
1275
+ } catch (err) {
1276
+ /* 忽略 */
1277
+ }
1278
+ try {
1279
+ [STORAGE_MODE, STORAGE_MODE_NARROW, STORAGE_MODEL, STORAGE_AUTO, STORAGE_KEEP].forEach((key) => {
1280
+ window.localStorage.removeItem(key);
1281
+ });
1282
+ } catch (err) {
1283
+ /* 同上 */
1284
+ }
1285
+ runtime.keep = [];
1286
+ runtime.model = "segmented";
1287
+ runtime.auto = true;
1288
+ runtime.mode = pickInitialMode(null, runtime.narrow, window.innerHeight, true);
1289
+ if (runtime.nav) syncKeeps(runtime.nav);
1290
+ paintNav();
1291
+ runtime.signature = "";
1292
+ renderBar();
1293
+ notify();
1294
+ }
1295
+
1296
+ /**
1297
+ * 读保留清单存档:每项是 { i, label };兼容早期版本存的纯标签数组。
1298
+ * 存索引是为了"切语言后名字变了也能对上",存名字是为了"插件增删导致位置变了也能对上"。
1299
+ * @param raw - localStorage 原始值。
1300
+ * @returns { i, label } 数组。
1301
+ */
1302
+ function resolveKeep(raw) {
1303
+ if (typeof raw !== "string" || !raw) return [];
1304
+ try {
1305
+ const parsed = JSON.parse(raw);
1306
+ if (!Array.isArray(parsed)) return [];
1307
+ const out = [];
1308
+ for (let k = 0; k < parsed.length; k += 1) {
1309
+ const item = parsed[k];
1310
+ if (typeof item === "string") out.push({ i: -1, label: item });
1311
+ else if (item && typeof item.label === "string") out.push({ i: typeof item.i === "number" ? item.i : -1, label: item.label });
1312
+ }
1313
+ return out;
1314
+ } catch (err) {
1315
+ return [];
1316
+ }
1317
+ }
1318
+
1319
+ /**
1320
+ * 把保存的保留项对到当前行上:先按名字精确匹配,再按索引兜底。
1321
+ * @param rows - collectRows 的结果。
1322
+ * @returns [{ index, label }]。
1323
+ */
1324
+ function resolveKeepIndices(rows) {
1325
+ const out = [];
1326
+ const seen = new Set();
1327
+ for (let k = 0; k < runtime.keep.length; k += 1) {
1328
+ const entry = runtime.keep[k];
1329
+ if (!entry) continue;
1330
+ let at = -1;
1331
+ for (let i = 0; i < rows.length; i += 1) {
1332
+ if (rows[i].label === entry.label) {
1333
+ at = i;
1334
+ break;
1335
+ }
1336
+ }
1337
+ if (at === -1 && typeof entry.i === "number" && entry.i >= 0 && entry.i < rows.length) at = entry.i;
1338
+ if (at === -1 || seen.has(at)) continue;
1339
+ seen.add(at);
1340
+ out.push({ index: at, label: rows[at].label });
1341
+ }
1342
+ return out;
1343
+ }
1344
+
1345
+ /**
1346
+ * 跟随视口:窗口尺寸或断点变化时,没存档的桶按自动档重算档位。
1347
+ * @param media - 窄屏媒体查询对象。
1348
+ */
1349
+ function followViewport(media) {
1350
+ if (runtime.viewportHandler) return;
1351
+ runtime.viewportHandler = () => {
1352
+ const narrow = media ? !!media.matches : false;
1353
+ runtime.narrow = narrow;
1354
+ let stored = null;
1355
+ try {
1356
+ stored = window.localStorage.getItem(modeKey(narrow));
1357
+ } catch (err) {
1358
+ stored = null;
1359
+ }
1360
+ const hasStored = typeof stored === "string" && MODES.indexOf(stored) !== -1;
1361
+ let next = pickInitialMode(hasStored ? stored : null, narrow, window.innerHeight, runtime.auto);
1362
+ if (runtime.model === "header" && next === "compact") next = "expanded";
1363
+ if (next !== runtime.mode) {
1364
+ runtime.mode = next;
1365
+ paintNav();
1366
+ renderBar();
1367
+ }
1368
+ };
1369
+ if (typeof window.addEventListener === "function") window.addEventListener("resize", runtime.viewportHandler);
1370
+ if (media && typeof media.addEventListener === "function") media.addEventListener("change", runtime.viewportHandler);
1371
+ }
1372
+
1373
+ /**
1374
+ * 绑定 DOM:首扫 + 外壳重挂/重渲染时重挂控制条(节流),卸载时清理干净。
1375
+ * @returns 清理函数。
1376
+ */
1377
+ function attachDom() {
1378
+ const schedule = () => {
1379
+ if (runtime.timer) return;
1380
+ runtime.timer = window.setTimeout(() => {
1381
+ runtime.timer = 0;
1382
+ scan();
1383
+ }, RESCAN_MS);
1384
+ };
1385
+ runtime.mountedAt = Date.now();
1386
+ scan();
1387
+ const Observer = window.MutationObserver;
1388
+ if (typeof Observer === "function") {
1389
+ runtime.observer = new Observer((records) => {
1390
+ // 自己重绘控制条也会触发 childList——不忽略就会 150ms 一次无限重绘(表现为悬停闪烁)
1391
+ const bar = runtime.bar;
1392
+ const own = bar && records.every((record) => {
1393
+ const inBar = (node) => !!node && (node === bar || (typeof bar.contains === "function" && bar.contains(node)));
1394
+ if (inBar(record.target)) return true;
1395
+ const touched = [];
1396
+ if (record.addedNodes) for (let i = 0; i < record.addedNodes.length; i += 1) touched.push(record.addedNodes[i]);
1397
+ if (record.removedNodes) for (let i = 0; i < record.removedNodes.length; i += 1) touched.push(record.removedNodes[i]);
1398
+ return touched.length > 0 && touched.every(inBar);
1399
+ });
1400
+ if (own) return;
1401
+ schedule();
1402
+ });
1403
+ const target = document.documentElement || document.body;
1404
+ if (target) {
1405
+ runtime.observer.observe(target, {
1406
+ childList: true,
1407
+ subtree: true,
1408
+ attributes: true,
1409
+ attributeFilter: ["data-sidebar-collapsed"]
1410
+ });
1411
+ }
1412
+ }
1413
+ const Resize = window.ResizeObserver;
1414
+ if (typeof Resize === "function" && runtime.nav) {
1415
+ runtime.resize = new Resize(() => schedule());
1416
+ runtime.resize.observe(runtime.nav);
1417
+ }
1418
+ return () => {
1419
+ if (runtime.observer) {
1420
+ try {
1421
+ runtime.observer.disconnect();
1422
+ } catch (err) {
1423
+ /* 已断开 */
1424
+ }
1425
+ runtime.observer = null;
1426
+ }
1427
+ if (runtime.resize) {
1428
+ try {
1429
+ runtime.resize.disconnect();
1430
+ } catch (err) {
1431
+ /* 已断开 */
1432
+ }
1433
+ runtime.resize = null;
1434
+ }
1435
+ if (runtime.timer) {
1436
+ window.clearTimeout(runtime.timer);
1437
+ runtime.timer = 0;
1438
+ }
1439
+ if (runtime.bar && runtime.bar.parentNode) {
1440
+ try {
1441
+ runtime.bar.parentNode.removeChild(runtime.bar);
1442
+ } catch (err) {
1443
+ /* 节点已卸载 */
1444
+ }
1445
+ }
1446
+ runtime.bar = null;
1447
+ if (runtime.nav) {
1448
+ const rows = rowButtons(runtime.nav);
1449
+ for (let i = 0; i < rows.length; i += 1) {
1450
+ const el = rows[i];
1451
+ if (el && typeof el.getAttribute === "function" && el.getAttribute("data-navfold-title") !== null && typeof el.removeAttribute === "function") {
1452
+ el.removeAttribute("title");
1453
+ el.removeAttribute("data-navfold-title");
1454
+ }
1455
+ }
1456
+ }
1457
+ if (runtime.nav && typeof runtime.nav.removeAttribute === "function") {
1458
+ try {
1459
+ runtime.nav.removeAttribute(NAV_ATTR);
1460
+ } catch (err) {
1461
+ /* 节点已卸载 */
1462
+ }
1463
+ }
1464
+ runtime.nav = null;
1465
+ };
1466
+ }
1467
+
1468
+ /* ───────────────────────── 视图层 ───────────────────────── */
1469
+
1470
+ const PANEL_CSS = {
1471
+ wrap: { display: "grid", gap: 0, minWidth: 0 },
1472
+ summary: {
1473
+ display: "flex",
1474
+ flexWrap: "wrap",
1475
+ gap: 6,
1476
+ alignItems: "center",
1477
+ margin: 0,
1478
+ padding: "0 0 10px",
1479
+ fontSize: 12,
1480
+ color: "var(--dsw-alias-label-secondary,#666)"
1481
+ },
1482
+ group: {
1483
+ display: "grid",
1484
+ gap: 6,
1485
+ padding: "10px 0",
1486
+ borderTop: "1px solid var(--dsw-alias-border-l1,rgba(0,0,0,.08))",
1487
+ minWidth: 0
1488
+ },
1489
+ row: { display: "flex", flexWrap: "wrap", gap: 8, alignItems: "center", justifyContent: "space-between" },
1490
+ title: { fontSize: 13, fontWeight: 600, color: "var(--dsw-alias-label-primary,#111)" },
1491
+ desc: { margin: 0, fontSize: 12, lineHeight: 1.5, color: "var(--dsw-alias-label-secondary,#777)" },
1492
+ seg: {
1493
+ display: "inline-flex",
1494
+ gap: 2,
1495
+ padding: 2,
1496
+ borderRadius: 8,
1497
+ background: "var(--dsw-alias-bg-layer-2,rgba(0,0,0,.05))"
1498
+ },
1499
+ segBtn: {
1500
+ padding: "3px 10px",
1501
+ fontSize: 12,
1502
+ lineHeight: 1.5
1503
+ },
1504
+ microGroup: { display: "inline-flex", alignItems: "center", gap: 4 },
1505
+ count: { fontSize: 12, color: "var(--dsw-alias-label-secondary,#777)", fontVariantNumeric: "tabular-nums" },
1506
+ chipRow: { display: "flex", flexWrap: "wrap", gap: 6 },
1507
+ foot: {
1508
+ display: "flex",
1509
+ justifyContent: "flex-end",
1510
+ paddingTop: 10,
1511
+ borderTop: "1px solid var(--dsw-alias-border-l1,rgba(0,0,0,.08))"
1512
+ }
1513
+ };
1514
+
1515
+ /**
1516
+ * 造一个 React 图标元素。
1517
+ * 注意:设置面板是 React 树,必须用 createElement 产出 React 元素;
1518
+ * 直接塞 makeIcon 的 DOM 节点会触发 React #31(objects are not valid as a React child)。
1519
+ * @param paths - path 的 d 值列表。
1520
+ * @param size - 边长。
1521
+ * @returns React 元素。
1522
+ */
1523
+ function iconElement(paths, size) {
1524
+ const edge = size || 12;
1525
+ return react.createElement(
1526
+ "svg",
1527
+ {
1528
+ viewBox: "0 0 16 16",
1529
+ width: edge,
1530
+ height: edge,
1531
+ fill: "none",
1532
+ stroke: "currentColor",
1533
+ strokeWidth: 1.4,
1534
+ strokeLinecap: "round",
1535
+ strokeLinejoin: "round",
1536
+ "aria-hidden": "true"
1537
+ },
1538
+ paths.map((d, index) => react.createElement("path", { key: index, d }))
1539
+ );
1540
+ }
1541
+
1542
+ /** 设置页「nav-fold 导航折叠」分区:行式布局(标题左 / 控件右) */
1543
+ function NavFoldSettings() {
1544
+ const uid = typeof react.useId === "function" ? react.useId() : "nav-fold";
1545
+ const model = react.useSyncExternalStore(subscribe, getModel, getModel);
1546
+ const mode = react.useSyncExternalStore(subscribe, getMode, getMode);
1547
+ const auto = react.useSyncExternalStore(subscribe, getAuto, getAuto);
1548
+ // 快照必须含保留清单本身,否则加减保留行时 React 会跳过重渲染(chip 颜色不切换)
1549
+ const keepSnapshot = () =>
1550
+ runtime.keep.map((entry) => entry.i + ":" + entry.label).join("|") + "#" + runtime.totals.total + "#" + (runtime.confirmReset ? "c" : "");
1551
+ react.useSyncExternalStore(subscribe, keepSnapshot, keepSnapshot);
1552
+
1553
+ const rows = collectRows(runtime.nav || null);
1554
+ const keepIndices = new Set(resolveKeepIndices(rows).map((item) => item.index));
1555
+ const total = runtime.totals.total || rows.length;
1556
+ const kept = runtime.totals.kept;
1557
+ const el = react.createElement;
1558
+ const modelTitleId = uid + "-model";
1559
+ const autoTitleId = uid + "-auto";
1560
+ const keepTitleId = uid + "-keep";
1561
+ const modelOptions = [
1562
+ { value: "segmented", title: t("settings.model.segmented.title") },
1563
+ { value: "cycle", title: t("settings.model.cycle.title") },
1564
+ { value: "header", title: t("settings.model.header.title") }
1565
+ ];
1566
+
1567
+ return el(
1568
+ "div",
1569
+ { style: PANEL_CSS.wrap },
1570
+ // 摘要:一眼看到当前配置
1571
+ el(
1572
+ "p",
1573
+ { style: PANEL_CSS.summary },
1574
+ iconElement(densityIcon(mode), 14),
1575
+ el("span", null, t("mode." + mode) + " · " + t("settings.summary.entries", { n: total }))
1576
+ ),
1577
+ // 控制条样式
1578
+ el(
1579
+ "section",
1580
+ { style: PANEL_CSS.group, role: "group", "aria-labelledby": modelTitleId },
1581
+ el(
1582
+ "div",
1583
+ { style: PANEL_CSS.row },
1584
+ el("span", { id: modelTitleId, style: PANEL_CSS.title, key: "t" }, t("settings.model.title")),
1585
+ el(
1586
+ "div",
1587
+ { style: PANEL_CSS.seg, role: "radiogroup", "aria-labelledby": modelTitleId, key: "g" },
1588
+ modelOptions.map((option) =>
1589
+ el(
1590
+ "button",
1591
+ {
1592
+ key: option.value,
1593
+ type: "button",
1594
+ role: "radio",
1595
+ "aria-checked": model === option.value ? "true" : "false",
1596
+ "data-navfold-model": option.value,
1597
+ onClick: () => setModel(option.value),
1598
+ style: PANEL_CSS.segBtn
1599
+ },
1600
+ option.title
1601
+ )
1602
+ )
1603
+ )
1604
+ ),
1605
+ el("p", { style: PANEL_CSS.desc }, t("settings.model.desc"))
1606
+ ),
1607
+ // 自动档
1608
+ el(
1609
+ "section",
1610
+ { style: PANEL_CSS.group, role: "group", "aria-labelledby": autoTitleId },
1611
+ el(
1612
+ "div",
1613
+ { style: PANEL_CSS.row },
1614
+ el("span", { id: autoTitleId, style: PANEL_CSS.title, key: "t" }, t("settings.auto.title")),
1615
+ el(
1616
+ "button",
1617
+ {
1618
+ key: "s",
1619
+ type: "button",
1620
+ role: "switch",
1621
+ "aria-checked": auto ? "true" : "false",
1622
+ "aria-labelledby": autoTitleId,
1623
+ "data-navfold-auto": auto ? "on" : "off",
1624
+ onClick: () => setAuto(!auto)
1625
+ },
1626
+ el("span", { "aria-hidden": "true" })
1627
+ )
1628
+ ),
1629
+ el("p", { style: PANEL_CSS.desc }, t("settings.auto.desc"))
1630
+ ),
1631
+ // 收起时保留
1632
+ el(
1633
+ "section",
1634
+ { style: PANEL_CSS.group, role: "group", "aria-labelledby": keepTitleId },
1635
+ el(
1636
+ "div",
1637
+ { style: PANEL_CSS.row },
1638
+ el("span", { id: keepTitleId, style: PANEL_CSS.title, key: "t" }, t("settings.keep.title")),
1639
+ el(
1640
+ "div",
1641
+ { style: PANEL_CSS.microGroup, key: "m" },
1642
+ el("span", { style: PANEL_CSS.count, "aria-live": "polite" }, t("settings.keptCount", { kept: kept, total: total })),
1643
+ el(
1644
+ "button",
1645
+ { type: "button", "data-navfold-micro": "all", title: t("settings.keep.all"), "aria-label": t("settings.keep.all"), onClick: keepAll },
1646
+ iconElement(ALL_ICON, 12)
1647
+ ),
1648
+ el(
1649
+ "button",
1650
+ { type: "button", "data-navfold-micro": "none", title: t("settings.keep.none"), "aria-label": t("settings.keep.none"), onClick: clearKeep },
1651
+ iconElement(NONE_ICON, 12)
1652
+ )
1653
+ )
1654
+ ),
1655
+ rows.length === 0
1656
+ ? el("p", { style: PANEL_CSS.desc }, t("settings.keep.empty"))
1657
+ : el(
1658
+ "div",
1659
+ { style: PANEL_CSS.chipRow },
1660
+ rows.map((row, index) => {
1661
+ const on = keepIndices.has(index);
1662
+ return el(
1663
+ "button",
1664
+ {
1665
+ key: row.label,
1666
+ type: "button",
1667
+ "data-navfold-keep-row": row.label,
1668
+ "aria-pressed": on ? "true" : "false",
1669
+ onClick: () => toggleKeep(row.label)
1670
+ },
1671
+ on ? el("span", { "aria-hidden": "true" }, "✓") : null,
1672
+ el("span", null, row.label)
1673
+ );
1674
+ })
1675
+ ),
1676
+ el("p", { style: PANEL_CSS.desc }, t("settings.keep.hint"))
1677
+ ),
1678
+ el("p", { style: PANEL_CSS.desc }, t("settings.rail.hint")),
1679
+ el(
1680
+ "div",
1681
+ { style: PANEL_CSS.foot },
1682
+ el(
1683
+ "button",
1684
+ {
1685
+ type: "button",
1686
+ "data-navfold-restore": runtime.confirmReset ? "confirm" : "",
1687
+ "aria-live": "polite",
1688
+ onClick: requestReset
1689
+ },
1690
+ runtime.confirmReset ? t("settings.restore.confirm") : t("settings.restore")
1691
+ )
1692
+ )
1693
+ );
1694
+ }
1695
+
1696
+ /* ───────────────────────── 插件入口 ───────────────────────── */
1697
+
1698
+ /** 本插件用到的客户端服务(设置分区要 slots,文案要 locale) */
1699
+ const inject = ["slots", "locale"];
1700
+
1701
+ /**
1702
+ * 接上 shell 的 locale:注册字典并换成 bound 的 t();失败就保持 zh 回退,不影响功能。
1703
+ * @param ctx - 客户端上下文。
1704
+ */
1705
+ function wireLocale(ctx) {
1706
+ const locale = ctx && ctx.locale;
1707
+ if (!locale || typeof locale.register !== "function") return;
1708
+ try {
1709
+ locale.register(NS, DICT);
1710
+ } catch (err) {
1711
+ warn("locale 字典注册失败,回退中文", err);
1712
+ }
1713
+ if (typeof locale.bind !== "function") return;
1714
+ try {
1715
+ const bound = locale.bind(NS);
1716
+ t = (key, params) => {
1717
+ try {
1718
+ const value = bound(key, params);
1719
+ // bound 在缺词条时会原样回吐 key,这时用内置中文兜底(防止字典与组件版本错位露 key)
1720
+ return typeof value === "string" && value.length > 0 && value !== key ? value : formatText(dictText(DICT.zh, key), params);
1721
+ } catch (err) {
1722
+ return formatText(dictText(DICT.zh, key), params);
1723
+ }
1724
+ };
1725
+ } catch (err) {
1726
+ warn("locale 绑定失败,回退中文", err);
1727
+ }
1728
+ }
1729
+
1730
+ /**
1731
+ * 注册设置分区(幂等,失败只告警)。
1732
+ * @param ctx - 客户端上下文。
1733
+ */
1734
+ function registerSettings(ctx) {
1735
+ const slots = ctx && ctx.slots;
1736
+ if (!slots || typeof slots.inject !== "function" || typeof slots.register !== "function") {
1737
+ warn("slots 服务不可用,设置分区未挂载(控制条本身不受影响)");
1738
+ return;
1739
+ }
1740
+ try {
1741
+ slots.inject("settings.section", () => {
1742
+ try {
1743
+ return slots.register(
1744
+ {
1745
+ name: "settings.section",
1746
+ id: ENTRY_ID,
1747
+ order: 70,
1748
+ label: () => t("label"),
1749
+ inject: () => ({})
1750
+ },
1751
+ NavFoldSettings
1752
+ );
1753
+ } catch (err) {
1754
+ warn("注册设置分区失败", err);
1755
+ return () => {};
1756
+ }
1757
+ });
1758
+ } catch (err) {
1759
+ warn("settings.section 注入失败", err);
1760
+ }
1761
+ }
1762
+
1763
+ /**
1764
+ * 插件装配:读偏好 → 注入样式 → 挂设置分区 → 定位导航并挂控制条。
1765
+ * @param ctx - 客户端上下文。
1766
+ */
1767
+ function apply(ctx) {
1768
+ if (!ctx || typeof ctx.effect !== "function") {
1769
+ warn("ctx.effect 不可用,插件未启动");
1770
+ return;
1771
+ }
1772
+ ctx.effect(() => {
1773
+ let injected = null;
1774
+ let detach = null;
1775
+ let mediaRef = null;
1776
+ try {
1777
+ if (!hasDom(document)) {
1778
+ warn("当前环境没有 DOM,跳过");
1779
+ return () => {};
1780
+ }
1781
+ const media = typeof window.matchMedia === "function" ? window.matchMedia(NARROW_QUERY) : null;
1782
+ mediaRef = media;
1783
+ runtime.narrow = !!(media && media.matches);
1784
+ let storedMode = null;
1785
+ let storedModel = null;
1786
+ let storedAuto = null;
1787
+ let storedKeep = null;
1788
+ try {
1789
+ storedMode = window.localStorage.getItem(modeKey(runtime.narrow));
1790
+ storedModel = window.localStorage.getItem(STORAGE_MODEL);
1791
+ storedAuto = window.localStorage.getItem(STORAGE_AUTO);
1792
+ storedKeep = window.localStorage.getItem(STORAGE_KEEP);
1793
+ } catch (err) {
1794
+ storedMode = null;
1795
+ storedModel = null;
1796
+ storedAuto = null;
1797
+ storedKeep = null;
1798
+ }
1799
+ runtime.keep = resolveKeep(storedKeep);
1800
+ runtime.auto = resolveAuto(storedAuto);
1801
+ wireLocale(ctx);
1802
+ runtime.model = resolveModel(storedModel);
1803
+ runtime.mode = pickInitialMode(storedMode, runtime.narrow, window.innerHeight, runtime.auto);
1804
+ // 标题行只有「文字行 / 收起」两态:图标网格档在它下面不存在;载入时归一,并把原档位记进暂存
1805
+ let storedStash = null;
1806
+ try {
1807
+ storedStash = window.localStorage.getItem(STORAGE_STASH);
1808
+ } catch (err) {
1809
+ storedStash = null;
1810
+ }
1811
+ if (storedStash === "compact" || storedStash === "hidden") runtime.modeStash = storedStash;
1812
+ if (runtime.model === "header" && runtime.mode === "compact") {
1813
+ runtime.modeStash = "compact";
1814
+ runtime.mode = "expanded";
1815
+ persistStash();
1816
+ }
1817
+ followViewport(media);
1818
+ injected = ensureStyle(document);
1819
+ registerSettings(ctx);
1820
+ detach = attachDom();
1821
+ } catch (err) {
1822
+ warn("初始化失败,保持原生 UI", err);
1823
+ }
1824
+ return () => {
1825
+ if (runtime.viewportHandler) {
1826
+ if (typeof window.removeEventListener === "function") window.removeEventListener("resize", runtime.viewportHandler);
1827
+ if (mediaRef && typeof mediaRef.removeEventListener === "function") mediaRef.removeEventListener("change", runtime.viewportHandler);
1828
+ runtime.viewportHandler = null;
1829
+ }
1830
+ if (typeof detach === "function") detach();
1831
+ if (injected && injected.parentNode) {
1832
+ try {
1833
+ injected.parentNode.removeChild(injected);
1834
+ } catch (err) {
1835
+ /* 已被外壳移除 */
1836
+ }
1837
+ }
1838
+ };
1839
+ }, "nav-fold: 功能入口三态");
1840
+ }
1841
+
1842
+ exports.name = name;
1843
+ exports.inject = inject;
1844
+ exports.apply = apply;
1845
+ exports.__internals = {
1846
+ SETTINGS_LABEL: SETTINGS_LABEL,
1847
+ MODES: MODES,
1848
+ MODELS: MODELS,
1849
+ STORAGE_MODE: STORAGE_MODE,
1850
+ STORAGE_MODEL: STORAGE_MODEL,
1851
+ NAV_ATTR: NAV_ATTR,
1852
+ BAR_ATTR: BAR_ATTR,
1853
+ CSS_TEXT: CSS_TEXT,
1854
+ nextMode: nextMode,
1855
+ modeKey: modeKey,
1856
+ pickInitialMode: pickInitialMode,
1857
+ autoWantsCompact: autoWantsCompact,
1858
+ resolveAuto: resolveAuto,
1859
+ setAuto: setAuto,
1860
+ getAuto: getAuto,
1861
+ toggleKeep: toggleKeep,
1862
+ keepAll: keepAll,
1863
+ clearKeep: clearKeep,
1864
+ resetAll: resetAll,
1865
+ collectRows: collectRows,
1866
+ resolveKeep: resolveKeep,
1867
+ syncKeeps: syncKeeps,
1868
+ getKeep: getKeep,
1869
+ resolveModel: resolveModel,
1870
+ looksLikePanelNav: looksLikePanelNav,
1871
+ findNav: findNav,
1872
+ renderBar: renderBar,
1873
+ setMode: setMode,
1874
+ setModel: setModel,
1875
+ getMode: getMode,
1876
+ getModel: getModel,
1877
+ NavFoldSettings: NavFoldSettings,
1878
+ runtime: runtime,
1879
+ scan: scan
1880
+ };
1881
+ return module.exports;
1882
+ }
1883
+ });