dsh-nav-fold 0.1.0 → 0.3.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,37 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.1 — 2026-11-16
4
+
5
+ 修正 0.3.0 的固定方式(0.3.0 未公开发布,仅内部迭代)。
6
+
7
+ - 改为「顶部固定区」:图标排(或收起行)与工作区标题(含搜索/视图/新建)一起固定在顶部,**只有工作区文件夹与会话列表滚动**
8
+ - 固定区底色运行时取自外壳背景,不再写死白底,浅色/深色下都不会出现色块
9
+ - 侧栏不可见时(如手机抽屉收起)挂起不误报,展开后自动落位
10
+ - 结构不匹配时自动回退为粘性导航,并在诊断区记录一条异常
11
+ - 诊断区新增「状态 / 最近告警 / 固定状态(含底色)」三行
12
+ - 其余沿用 0.3.0:列数(自适应/8/7/6/5/4,手机自适应最多 6 列)、与外壳「更多」共存、语言回退英文、观察器收窄
13
+
14
+ ## 0.3.0 — 2026-11-16
15
+
16
+ - 图标档支持吸附:滚动会话列表时这排图标固定在侧栏顶部(默认开);收起档可吸附(默认关);文字档不提供(置灰并说明原因),避免把会话区挤没
17
+ - 图标档每行数量可选:自适应(默认,手机上最多 6 列)/ 8 / 7 / 6 / 5 / 4;选 7、8 列时会按侧栏实宽计算每列像素,低于 32px 给出提示并可一键切回自适应
18
+ - 与新版外壳共存:检测到侧栏自带「取消固定 / 更多」入口管理(rc.2+ 的 `button.panelUnpin`)时,收起态不再显示本插件的「全部」入口(可在设置里关闭该行为)
19
+ - 新增诊断区(默认折叠):结构版本、入口行数、档位、吸附与列数状态、最近一次告警时间,一键复制
20
+ - 语言回退修正:非中文环境缺词条时回退英文(此前回退中文,会中英混排)
21
+ - 性能:DOM 观察范围从整个 document 收窄到侧栏容器;另加 2 秒 `isConnected` 兜底,容器被整体替换时仍能自愈
22
+ - 设置面板新增「只重置控件样式」,可只把控件样式恢复成三档选择器
23
+
24
+ ## 0.2.0 — 2026-11-15
25
+
26
+ 适配 DSH 0.2.2-rc.2 / rc.3 的侧栏结构变化(入口行外面多了一层 `div.panelEntry`,行内新增「取消固定」按钮)。
27
+
28
+ - 定位器改为结构判定:`button`(rc.1 及更早)与 `div > button.panelRow`(rc.2+)都认,不再依赖"子节点只能是 button/span"
29
+ - 窄屏/图标轨下外壳不渲染标题 span 时也能识别(用 aria-label 兜底)
30
+ - 保留行、计数徽标、紧凑网格、收起态全部按包裹层生效(标记同时打在包裹层与按钮上)
31
+ - rc.2+ 外壳已给每行配 Tooltip,不再叠加原生 `title`(避免双提示)
32
+ - 找不到导航时打印结构诊断(各 nav 的子节点标签与层数),便于宿主改版后定位
33
+ - 发布范围收紧为 `>=0.2.2-rc.1 <0.3.0`
34
+
3
35
  ## 0.1.0 — 2026-11-12
4
36
 
5
37
  首个公开版本。
@@ -12,4 +44,4 @@
12
44
  - 图标档 / 56px 图标轨下每行带原生 `title`,悬停显示插件名
13
45
  - 设置面板:行式布局,含自动档开关、保留行多选、恢复默认(二次确认)
14
46
  - 文案跟随 shell 语言(zh / en)
15
- - 不读写官方 `panelPins`,不修改官方行结构,卸载即完全复原
47
+ - 不读写官方 `panelPins`,不修改官方行结构,卸载即完全复原
package/README.md CHANGED
@@ -45,6 +45,14 @@
45
45
  | `cycle` | 一个按钮,**一次只显示当前档那一个图标**,点了换成下一档 |
46
46
  | `header` | **标题行**:整组收成一行 `⌃ 功能入口 8`(位于入口列表最上方),点标题展开/收起;只有"文字行 / 收起"两态,图标网格档不可用。被外壳挪位会自动拉回,连续 3 次失败退回 `segmented` |
47
47
 
48
+ ## 固定顶部区域与列数(0.3.1)
49
+
50
+ - **固定顶部区域**:图标档默认开启——图标排 + 工作区标题(含搜索/视图/新建)一起固定在顶部,**只有文件夹与会话列表滚动**;收起档可选(默认关);文字档不提供(行数多,固定会把会话区挤没)
51
+ - **底色**:固定区背景在运行时取自外壳侧栏颜色,不写死白底,浅色/深色都不会出现色块
52
+ - **每行几个**:自适应(默认,手机上最多 6 列)/ 8 / 7 / 6 / 5 / 4;写死 7、8 列时按侧栏实际宽度提示是否过挤,可一键切回自适应
53
+ - **与外壳共存**:侧栏自带「取消固定 / 更多」(DSH 0.2.2-rc.2 起)时,收起态只保留外壳的菜单,避免两个入口菜单并存
54
+ - **诊断**:设置面板底部可展开,显示结构版本、行数、档位、吸附与列数、最近一次告警时间,可一键复制
55
+
48
56
  ## 设置面板(设置 → nav-fold 导航折叠)
49
57
 
50
58
  行式布局,与 shell 自己的设置项一致:
@@ -116,6 +124,10 @@ node --test test/*.test.mjs # 14 项,直接测上线产物 lib/client.js(v
116
124
 
117
125
  ## 版本契约(升级 DSH 后看这里)
118
126
 
119
- 定位器只依赖结构,不依赖 CSS Modules 的 hash 类名:`nav` 的子元素必须是 `button`/`span`(外加我们自己的控制条 `div`),至少一行是"图标 span + 文字 span"两段结构,且不含 `input/textarea/select/a/form`。图标轨判定优先读外壳的 `[data-sidebar-collapsed="true"]`(收起时内容是被平移进轨道的,布局宽度量不出来),读不到再退回宽度判断。
120
-
121
- 若控制台出现 `未找到「功能入口」导航`,说明外壳结构变了 —— 改 `looksLikePanelNav` 即可。
127
+ - 支持 **DSH >= 0.2.2-rc.1 < 0.3.0**(实测 rc.1 / rc.3)
128
+ - 侧栏入口行两种结构都适配:
129
+ - rc.1 及更早:`nav > button.panelRow`
130
+ - rc.2 起:`nav > div.panelEntry > button.panelRow`(行内可能还有「取消固定」按钮)
131
+ - 判据只看结构(标签层级 + aria-label),不认宿主 CSS Modules 的哈希类名
132
+ - 找不到入口导航时保持原生 UI,并在控制台打印一条结构诊断
133
+ - 升级 DSH 后若失效:先看那行诊断,再到仓库提 issue
package/lib/client.js CHANGED
@@ -29,7 +29,7 @@ const react = require("react");
29
29
  /** 插件名(cordis 插件标识) */
30
30
  const name = "nav-fold";
31
31
  /** 版本号:必须与 package.json.version 一致(有单测守着) */
32
- const PLUGIN_VERSION = "0.1.0";
32
+ const PLUGIN_VERSION = "0.3.1";
33
33
  /** 设置分区 / 控制条占用者 id */
34
34
  const ENTRY_ID = "nav-fold";
35
35
  /** 注入样式表的幂等标记 */
@@ -46,6 +46,24 @@ const STORAGE_KEEP = "dsh-nav-fold/v1/keep";
46
46
  const STORAGE_STASH = "dsh-nav-fold/v1/mode-stash";
47
47
  /** localStorage:控件模型 */
48
48
  const STORAGE_MODEL = "dsh-nav-fold/v1/model";
49
+ /** 图标档每行列数:auto / 8 / 7 / 6 / 5 / 4 */
50
+ const STORAGE_COLS = "dsh-nav-fold/v1/cols";
51
+ /** 图标档是否吸附在顶部 */
52
+ const STORAGE_STICK_COMPACT = "dsh-nav-fold/v1/stick-compact";
53
+ /** 收起档是否吸附在顶部 */
54
+ const STORAGE_STICK_HIDDEN = "dsh-nav-fold/v1/stick-hidden";
55
+ /** 外壳已有「更多」时,是否隐藏我们自己的「全部」入口 */
56
+ const STORAGE_SHELL_MORE = "dsh-nav-fold/v1/shell-more";
57
+ /** 列数可选值(字符串形式存盘) */
58
+ const COLS_OPTIONS = ["auto", "8", "7", "6", "5", "4"];
59
+ /** 每列可用的最小像素(图标 18px + 内边距),低于它判定为“挤” */
60
+ const COL_MIN_PX = 32;
61
+ /** 顶部固定区的五个标记属性(全部用属性选择器,不依赖外壳类名) */
62
+ const PIN_ATTR_AREA = "data-navfold-area";
63
+ const PIN_ATTR_REGION = "data-navfold-region";
64
+ const PIN_ATTR_STACK = "data-navfold-stack";
65
+ const PIN_ATTR_HEAD = "data-navfold-head";
66
+ const PIN_ATTR_LIST = "data-navfold-list";
49
67
  /** 命中导航元素的标记属性,三态值写在这个属性上 */
50
68
  const NAV_ATTR = "data-navfold";
51
69
  /** 自有控制条的标记属性 */
@@ -114,6 +132,21 @@ const DICT = {
114
132
  "settings.keep.none": "清空",
115
133
  "settings.restore": "恢复默认",
116
134
  "settings.restore.confirm": "再点一次确认",
135
+ "settings.resetModel": "只重置控件样式",
136
+ "settings.cells.title": "每行几个",
137
+ "settings.cells.auto": "自适应",
138
+ "settings.cells.desc": "只影响图标档。自适应按侧栏宽度排版(手机上最多 6 列);写死列数在窄侧栏或手机上可能挤压。",
139
+ "settings.cells.warn": "当前侧栏约 {width}px,{cols} 列每列仅 {px}px,可能挤压;显示异常请切回「自适应」。",
140
+ "settings.cells.warnMobile": "手机宽度下建议用「自适应」(最多 6 列),写死 {cols} 列容易挤压。",
141
+ "settings.cells.revert": "切回自适应",
142
+ "settings.stick.title": "固定顶部区域",
143
+ "settings.stick.compact.desc": "图标排与工作区标题一起固定在顶部,只有文件夹和会话列表滚动;底色跟随外壳,不会出现色块。",
144
+ "settings.stick.hidden.desc": "收起时只留一行(含「全部」入口);开启后这一行与工作区标题固定,仅列表滚动。",
145
+ "settings.shell.title": "与外壳共存",
146
+ "settings.shell.desc": "新版左侧栏自带「更多」(列出未固定的入口)。开启后收起时只保留外壳那一个,避免两个入口菜单并存。",
147
+ "settings.diag.title": "诊断",
148
+ "settings.diag.copy": "复制",
149
+ "settings.diag.copyFailed": "复制失败,请手动选择文本",
117
150
  "settings.rail.hint": "56px 图标轨里两种样式都会收成一个图标,点一下换档。"
118
151
  },
119
152
  en: {
@@ -169,6 +202,21 @@ const DICT = {
169
202
  "settings.keep.none": "None",
170
203
  "settings.restore": "Restore defaults",
171
204
  "settings.restore.confirm": "Click again to confirm",
205
+ "settings.resetModel": "Reset control style only",
206
+ "settings.cells.title": "Icons per row",
207
+ "settings.cells.auto": "Auto",
208
+ "settings.cells.desc": "Only affects the icon grid. Auto follows the sidebar width (6 columns max on phones); a fixed count may feel cramped on narrow sidebars.",
209
+ "settings.cells.warn": "Sidebar is about {width}px — {cols} columns give only {px}px each. Switch back to Auto if it looks cramped.",
210
+ "settings.cells.warnMobile": "On a phone width, Auto (6 columns max) is recommended; a fixed {cols} columns will feel cramped.",
211
+ "settings.cells.revert": "Use Auto",
212
+ "settings.stick.title": "Pin top area",
213
+ "settings.stick.compact.desc": "Keeps the icon row and the workspace title pinned; only folders and the session list scroll. Background follows the shell, so no colour block appears.",
214
+ "settings.stick.hidden.desc": "Collapsed mode keeps a single row (with the All entry); pin it so the row and the workspace title stay put while only the list scrolls.",
215
+ "settings.shell.title": "Coexist with shell",
216
+ "settings.shell.desc": "Newer sidebars ship their own More menu (unpinned entries). When on, collapsed mode keeps only the shell menu to avoid two entry menus.",
217
+ "settings.diag.title": "Diagnostics",
218
+ "settings.diag.copy": "Copy",
219
+ "settings.diag.copyFailed": "Copy failed, select the text manually",
172
220
  "settings.rail.hint": "In the 56px rail both styles reduce to a single icon you click to advance."
173
221
  }
174
222
  };
@@ -264,6 +312,37 @@ const CSS_TEXT = [
264
312
  '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
313
  '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
314
  'nav[data-navfold="hidden"]>button:not([data-navfold-keep]){display:none!important}',
315
+ // rc.2 起每个入口多一层 div.panelEntry:同一套表现要按包裹层再写一遍
316
+ 'nav[data-navfold="compact"]>div:not([' + BAR_ATTR + ']){display:flex!important;min-width:0}',
317
+ '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}',
318
+ '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}',
319
+ 'nav[data-navfold="compact"]>div:not([' + BAR_ATTR + '])>button:not([class*="panelRow"]){display:none!important}',
320
+ 'nav[data-navfold="hidden"]>div:not([data-navfold-keep]):not([' + BAR_ATTR + ']){display:none!important}',
321
+ // 图标档列数:8/7/6/5/4 写死;自适应在手机上最多 6 列
322
+ 'nav[data-navfold="compact"][data-navfold-cols="8"]{grid-template-columns:repeat(8,minmax(0,1fr))!important}',
323
+ 'nav[data-navfold="compact"][data-navfold-cols="7"]{grid-template-columns:repeat(7,minmax(0,1fr))!important}',
324
+ 'nav[data-navfold="compact"][data-navfold-cols="6"]{grid-template-columns:repeat(6,minmax(0,1fr))!important}',
325
+ 'nav[data-navfold="compact"][data-navfold-cols="5"]{grid-template-columns:repeat(5,minmax(0,1fr))!important}',
326
+ 'nav[data-navfold="compact"][data-navfold-cols="4"]{grid-template-columns:repeat(4,minmax(0,1fr))!important}',
327
+ '@media (max-width:767px){nav[data-navfold="compact"][data-navfold-cols="auto"]{grid-template-columns:repeat(6,minmax(0,1fr))!important}}',
328
+ 'nav[data-navfold="compact"][data-navfold-cols="8"]>button,nav[data-navfold="compact"][data-navfold-cols="8"]>div>button{height:30px!important;min-height:30px!important}',
329
+ 'nav[data-navfold="compact"][data-navfold-cols="5"]>button,nav[data-navfold="compact"][data-navfold-cols="5"]>div>button,nav[data-navfold="compact"][data-navfold-cols="4"]>button,nav[data-navfold="compact"][data-navfold-cols="4"]>div>button{height:36px!important;min-height:36px!important}',
330
+ // 顶部固定区(首选):整体重排成「固定头 + 独立滚动列表」,底色统一取外壳背景
331
+ '[data-navfold-area]{display:flex!important;flex-direction:column!important;overflow:hidden!important;height:100%!important}',
332
+ '[data-navfold-region]{flex:1 1 auto!important;min-height:0!important;display:flex!important;flex-direction:column!important}',
333
+ '[data-navfold-stack]{flex:1 1 auto!important;min-height:0!important;display:flex!important;flex-direction:column!important}',
334
+ '[data-navfold-head]{flex:0 0 auto!important;background:var(--navfold-pin-bg,transparent)!important}',
335
+ '[data-navfold-list]{flex:1 1 auto!important;min-height:0!important;overflow-y:auto!important;overscroll-behavior:contain!important;padding-bottom:8px}',
336
+ 'nav[data-navfold-pinned="on"]{position:static!important;background:var(--navfold-pin-bg,transparent)!important}',
337
+ 'nav[data-navfold-pinned="on"]::after{content:"";display:block;height:1px;margin-top:6px;background:linear-gradient(to right,transparent 0%,var(--dsw-alias-border-l1,rgba(0,0,0,.14)) 22%,var(--dsw-alias-border-l1,rgba(0,0,0,.14)) 78%,transparent 100%)}',
338
+ // 回退路径:结构不符时才退回粘性导航(底色同样对齐外壳,不制造色块)
339
+ 'nav[data-navfold-pinned="fallback"]{position:sticky!important;top:0!important;z-index:4!important;background:var(--navfold-pin-bg,transparent)!important}',
340
+ 'nav[data-navfold-pinned="fallback"]::after{content:"";position:absolute;left:0;right:0;bottom:-1px;height:1px;pointer-events:none;background:linear-gradient(to right,transparent 0%,var(--dsw-alias-border-l1,rgba(0,0,0,.14)) 22%,var(--dsw-alias-border-l1,rgba(0,0,0,.14)) 78%,transparent 100%)}',
341
+ // 设置面板:列数/吸附选中态沿用控件样式那套,提示用状态色
342
+ '[data-navfold-cols-btn][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)}',
343
+ '[data-navfold-warn]{margin:0;font-size:12px;line-height:1.5;color:var(--dsw-alias-state-warning-primary,#b26a00)}',
344
+ '[data-navfold-warn] button{margin-left:6px;padding:1px 8px;font-size:12px;border:1px solid currentColor;border-radius:6px;background:transparent;color:inherit;cursor:pointer}',
345
+ '[data-navfold-diag]{margin:0;padding:8px 10px;border-radius:8px;background:var(--dsw-alias-bg-layer-2,rgba(0,0,0,.04));font-size:11px;line-height:1.6;white-space:pre-wrap;word-break:break-all;color:var(--dsw-alias-label-secondary,#555);font-family:ui-monospace,SFMono-Regular,Menlo,monospace}',
267
346
  "nav[data-navfold]>[" + BAR_ATTR + "] [data-navfold-count]{margin-right:2px;font-variant-numeric:tabular-nums;opacity:.8}",
268
347
  "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)}",
269
348
  'nav[data-navfold="compact"]>[' + BAR_ATTR + "]{grid-column:1/-1}",
@@ -278,10 +357,11 @@ const CSS_TEXT = [
278
357
  "[data-navfold-model]{border:1px solid transparent;background:transparent;color:var(--dsw-alias-label-secondary,#666);border-radius:6px;cursor:pointer}",
279
358
  "[data-navfold-model]:hover{background:var(--dsw-alias-bg-layer-2,rgba(128,128,128,.12))}",
280
359
  '[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)}',
281
- "[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}",
282
- '[data-navfold-auto][aria-checked="true"]{background:var(--dsw-alias-accent,#4d6bfe)}',
283
- "[data-navfold-auto]>span{position:absolute;top:3px;left:3px;width:16px;height:16px;border-radius:999px;background:#fff;transition:left .12s ease}",
284
- '[data-navfold-auto][aria-checked="true"]>span{left:19px}',
360
+ "[data-navfold-switch]{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}",
361
+ '[data-navfold-switch][aria-checked="true"]{background:var(--dsw-alias-accent,#4d6bfe)}',
362
+ "[data-navfold-switch]>span{position:absolute;top:3px;left:3px;width:16px;height:16px;border-radius:999px;background:#fff;transition:left .12s ease}",
363
+ '[data-navfold-switch][aria-checked="true"]>span{left:19px}',
364
+ "[data-navfold-switch][disabled]{cursor:not-allowed;opacity:.45}",
285
365
  "[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}",
286
366
  "[data-navfold-keep-row]:hover{border-color:var(--dsw-alias-label-tertiary,rgba(0,0,0,.3))}",
287
367
  '[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))}',
@@ -324,7 +404,23 @@ const runtime = {
324
404
  headerDrift: 0,
325
405
  modeStash: null,
326
406
  confirmReset: false,
327
- resetTimer: 0
407
+ resetTimer: 0,
408
+ diagOpen: false,
409
+ cols: "auto",
410
+ stickCompact: true,
411
+ stickHidden: false,
412
+ hideAllWhenShellMore: true,
413
+ shellHasMore: false,
414
+ stuck: false,
415
+ structure: "unknown",
416
+ lastWarnAt: 0,
417
+ observedTarget: null,
418
+ poll: 0,
419
+ pinState: "off",
420
+ pinRetry: 0,
421
+ pinNodes: null,
422
+ pinBg: "",
423
+ anomalies: []
328
424
  };
329
425
 
330
426
  /* ───────────────────────── 纯函数(可单测) ───────────────────────── */
@@ -363,6 +459,208 @@ function resolveAuto(stored) {
363
459
  return stored !== "off";
364
460
  }
365
461
 
462
+ /**
463
+ * 解析开关型存档(on / off),缺省用默认值。
464
+ * @param stored - localStorage 原始值。
465
+ * @param fallback - 没有存档时的默认。
466
+ * @returns 布尔。
467
+ */
468
+ function resolveFlag(stored, fallback) {
469
+ if (stored === "on") return true;
470
+ if (stored === "off") return false;
471
+ return fallback;
472
+ }
473
+
474
+ /**
475
+ * 解析图标档列数。
476
+ * @param stored - localStorage 原始值。
477
+ * @returns auto / 8 / 7 / 6 / 5 / 4。
478
+ */
479
+ function resolveCols(stored) {
480
+ return typeof stored === "string" && COLS_OPTIONS.indexOf(stored) !== -1 ? stored : "auto";
481
+ }
482
+
483
+ /**
484
+ * 外壳是否自带「更多」/取消固定一类的入口管理(rc.2 起每行有 button.panelUnpin)。
485
+ * 命中时我们收起态的「全部」菜单就不再显示,避免两个入口菜单并存。
486
+ * @param nav - 命中的 nav。
487
+ * @returns 是否自带。
488
+ */
489
+ function classOf(el) {
490
+ if (!el) return "";
491
+ const viaAttr = typeof el.getAttribute === "function" ? el.getAttribute("class") || "" : "";
492
+ const viaProp = typeof el.className === "string" ? el.className : "";
493
+ return (viaProp + " " + viaAttr).trim();
494
+ }
495
+
496
+ function detectShellMore(nav) {
497
+ const kids = nav && nav.children ? nav.children : [];
498
+ for (let i = 0; i < kids.length; i += 1) {
499
+ const kid = kids[i];
500
+ if (!kid) continue;
501
+ if (kid.tagName === "BUTTON" && classOf(kid).indexOf("panelUnpin") !== -1) return true;
502
+ const inner = kid.children || [];
503
+ for (let j = 0; j < inner.length; j += 1) {
504
+ if (inner[j] && inner[j].tagName === "BUTTON" && classOf(inner[j]).indexOf("panelUnpin") !== -1) return true;
505
+ }
506
+ }
507
+ return false;
508
+ }
509
+
510
+ /** 当前模式是否应启用「顶部固定区」。 */
511
+ function wantsPin() {
512
+ return (runtime.mode === "compact" && runtime.stickCompact) || (runtime.mode === "hidden" && runtime.stickHidden);
513
+ }
514
+
515
+ /** 元素高度(取不到返回 0)。 */
516
+ function rectHeight(el) {
517
+ if (!el || typeof el.getBoundingClientRect !== "function") return 0;
518
+ try {
519
+ return el.getBoundingClientRect().height || 0;
520
+ } catch (err) {
521
+ return 0;
522
+ }
523
+ }
524
+
525
+ /**
526
+ * 在子树里找「短标题(<64)+ 高列表(>120)」的容器——不认类名,只看尺寸与层级。
527
+ * @param node - 起点。
528
+ * @param depth - 递归深度(上限 6)。
529
+ * @returns 容器元素或 null。
530
+ */
531
+ function findStack(node, depth) {
532
+ if (!node || depth > 6) return null;
533
+ const kids = node.children || [];
534
+ if (kids.length >= 2) {
535
+ const head = rectHeight(kids[0]);
536
+ const body = rectHeight(kids[1]);
537
+ if (head > 0 && head < 64 && body > 120) return node;
538
+ }
539
+ for (let i = 0; i < kids.length; i += 1) {
540
+ const hit = findStack(kids[i], depth + 1);
541
+ if (hit) return hit;
542
+ }
543
+ return null;
544
+ }
545
+
546
+ /**
547
+ * 探测顶部固定区需要的节点:滚动区 / 区域 / 容器 / 标题行 / 列表。
548
+ * @param nav - 命中的 nav。
549
+ * @returns { area, region, stack, head, list } 或 null。
550
+ */
551
+ function findPinTargets(nav) {
552
+ const area = nav && (nav.parentElement || nav.parentNode);
553
+ if (!area || !area.children) return null;
554
+ let region = null;
555
+ for (let i = 0; i < area.children.length; i += 1) {
556
+ const kid = area.children[i];
557
+ if (kid === nav || kid === runtime.bar || isOwnBar(kid)) continue;
558
+ region = kid;
559
+ break;
560
+ }
561
+ if (!region) return null;
562
+ const stack = findStack(region, 0);
563
+ if (!stack || !stack.children || stack.children.length < 2) return null;
564
+ return { area: area, region: region, stack: stack, head: stack.children[0], list: stack.children[1] };
565
+ }
566
+
567
+ /**
568
+ * 读面板底色:自身透明就向上找;取不到返回 transparent(宁可不涂色,也不制造色块)。
569
+ * @param el - 起点。
570
+ * @returns CSS 颜色字符串。
571
+ */
572
+ function readPanelBg(el) {
573
+ let cur = el;
574
+ for (let i = 0; i < 6 && cur; i += 1) {
575
+ try {
576
+ const bg = window.getComputedStyle(cur).backgroundColor;
577
+ if (bg && bg !== "transparent" && bg !== "rgba(0, 0, 0, 0)") return bg;
578
+ } catch (err) {
579
+ /* 继续向上找 */
580
+ }
581
+ cur = cur.parentElement || cur.parentNode;
582
+ }
583
+ return "transparent";
584
+ }
585
+
586
+ /** 记一条异常(最多留 3 条,供诊断区显示)。 */
587
+ function noteAnomaly(kind) {
588
+ runtime.anomalies.unshift({ kind: kind, at: Date.now() });
589
+ runtime.anomalies = runtime.anomalies.slice(0, 3);
590
+ runtime.lastWarnAt = runtime.anomalies[0].at;
591
+ }
592
+
593
+ /** 清掉固定区标记。 */
594
+ function clearPin() {
595
+ const nodes = runtime.pinNodes;
596
+ if (nodes) {
597
+ const map = { area: PIN_ATTR_AREA, region: PIN_ATTR_REGION, stack: PIN_ATTR_STACK, head: PIN_ATTR_HEAD, list: PIN_ATTR_LIST };
598
+ const keys = Object.keys(map);
599
+ for (let i = 0; i < keys.length; i += 1) {
600
+ const el = nodes[keys[i]];
601
+ if (el && typeof el.removeAttribute === "function") el.removeAttribute(map[keys[i]]);
602
+ }
603
+ }
604
+ runtime.pinNodes = null;
605
+ runtime.pinBg = "";
606
+ }
607
+
608
+ /**
609
+ * 应用 / 撤销顶部固定区。
610
+ * @param nav - 命中的 nav。
611
+ * @returns applied / fallback / off。
612
+ */
613
+ function applyPin(nav) {
614
+ if (!wantsPin()) {
615
+ clearPin();
616
+ runtime.pinState = "off";
617
+ return "off";
618
+ }
619
+ const areaNode = nav.parentElement || nav.parentNode;
620
+ if (!rectHeight(areaNode)) {
621
+ // 侧栏在手机抽屉里、或整块不可见时高度为 0:先挂起,等它出现再固定,不记异常
622
+ clearPin();
623
+ runtime.pinState = "pending";
624
+ return "pending";
625
+ }
626
+ const targets = findPinTargets(nav);
627
+ if (!targets) {
628
+ clearPin();
629
+ runtime.pinState = "fallback";
630
+ return "fallback";
631
+ }
632
+ const map = { area: PIN_ATTR_AREA, region: PIN_ATTR_REGION, stack: PIN_ATTR_STACK, head: PIN_ATTR_HEAD, list: PIN_ATTR_LIST };
633
+ const keys = Object.keys(map);
634
+ for (let i = 0; i < keys.length; i += 1) {
635
+ const el = targets[keys[i]];
636
+ if (el && typeof el.setAttribute === "function") el.setAttribute(map[keys[i]], "");
637
+ }
638
+ runtime.pinNodes = targets;
639
+ runtime.pinState = "applied";
640
+ runtime.pinBg = readPanelBg(targets.area);
641
+ try {
642
+ if (targets.area.style && typeof targets.area.style.setProperty === "function") {
643
+ targets.area.style.setProperty("--navfold-pin-bg", runtime.pinBg);
644
+ }
645
+ } catch (err) {
646
+ /* 设不上就退回 transparent */
647
+ }
648
+ return "applied";
649
+ }
650
+
651
+ /**
652
+ * 记录当前侧栏结构版本:flat(rc.1 及更早)/ wrapped(rc.2 起,行外多一层 div)。
653
+ * @param nav - 命中的 nav。
654
+ * @returns 结构标记。
655
+ */
656
+ function detectStructure(nav) {
657
+ const kids = nav && nav.children ? nav.children : [];
658
+ for (let i = 0; i < kids.length; i += 1) {
659
+ if (kids[i] && kids[i].tagName === "DIV" && findRowButton(kids[i])) return "wrapped";
660
+ }
661
+ return "flat";
662
+ }
663
+
366
664
  /**
367
665
  * 决定控件模型:已存值优先,否则三档选择器。
368
666
  * @param stored - localStorage 里的原始值。
@@ -392,9 +690,59 @@ function autoWantsCompact(narrow, height) {
392
690
  return typeof height === "number" && height > 0 && height < AUTO_HEIGHT_PX;
393
691
  }
394
692
 
693
+ /** 是不是我们自己的控制条。 */
694
+ function isOwnBar(el) {
695
+ return !!el && el !== runtime.bar && typeof el.getAttribute === "function" && el.getAttribute(BAR_ATTR) !== null;
696
+ }
697
+
698
+ /**
699
+ * 在包裹层里找行按钮(不依赖 querySelector,假 DOM 与真 DOM 都能跑)。
700
+ * rc.2 起结构是 div.panelEntry > button.panelRow,Tooltip 不额外包一层。
701
+ * @param host - 包裹层元素。
702
+ * @returns 行按钮或 null。
703
+ */
704
+ function findRowButton(host) {
705
+ if (!host || !host.children) return null;
706
+ const kids = host.children;
707
+ for (let i = 0; i < kids.length; i += 1) {
708
+ const kid = kids[i];
709
+ if (kid && kid.tagName === "BUTTON") return kid;
710
+ if (kid && kid.children) {
711
+ for (let j = 0; j < kid.children.length; j += 1) {
712
+ if (kid.children[j] && kid.children[j].tagName === "BUTTON") return kid.children[j];
713
+ }
714
+ }
715
+ }
716
+ return null;
717
+ }
718
+
719
+ /**
720
+ * 把 nav 的直接子节点归一成「入口行」。
721
+ * - rc.1 及更早:子节点本身就是 button.panelRow
722
+ * - rc.2 起:子节点是 div.panelEntry,按钮在它里面(行内可能还有 panelUnpin 等按钮)
723
+ * @param child - nav 的直接子节点。
724
+ * @returns { wrapper, button };不是入口行时返回 null。
725
+ */
726
+ function rowOf(child) {
727
+ if (!child || child === runtime.bar || isOwnBar(child)) return null;
728
+ if (child.tagName === "BUTTON") return { wrapper: child, button: child };
729
+ if (child.tagName !== "DIV") return null;
730
+ const btn = findRowButton(child);
731
+ return btn ? { wrapper: child, button: btn } : null;
732
+ }
733
+
734
+ /** 「更多」锚点里的按钮(rc.1 span.moreAnchor 与 rc.3 换了类名的 span 都按 tagName 认)。 */
735
+ function moreButtonOf(child) {
736
+ if (!child || child.tagName !== "SPAN") return null;
737
+ return findRowButton(child);
738
+ }
739
+
395
740
  /**
396
- * 判断一个元素是否是「功能入口」导航:子元素只能是 button / span(以及我们自己的
397
- * 控制条),至少一行是“图标 + 文字”两段结构,且不含输入控件或链接。
741
+ * 判断一个元素是否是「功能入口」导航。
742
+ * 判据只看结构不认类名(宿主类名每版都变):
743
+ * - 子节点是入口行(button,或 rc.2+ 的 div 包裹 + 按钮)与「更多」span;
744
+ * - 至少 2 行,或 1 行且带 aria-label(窄屏时外壳不渲染标题 span,不能靠“两段结构”判定);
745
+ * - 不含输入控件 / 链接。
398
746
  * @param node - 待判定元素。
399
747
  * @returns 命中与否。
400
748
  */
@@ -402,23 +750,22 @@ function looksLikePanelNav(node) {
402
750
  if (!node || node.tagName !== "NAV") return false;
403
751
  const kids = node.children;
404
752
  if (!kids || kids.length === 0) return false;
405
- let buttons = 0;
406
- let twoPart = 0;
753
+ let rows = 0;
754
+ let labelled = 0;
407
755
  for (let i = 0; i < kids.length; i += 1) {
408
756
  const kid = kids[i];
409
- if (kid === runtime.bar) continue;
410
- const tag = kid.tagName;
411
- if (tag === "BUTTON") {
412
- buttons += 1;
413
- const inner = kid.children;
414
- if (inner && inner.length === 2) twoPart += 1;
757
+ if (kid === runtime.bar || isOwnBar(kid)) continue;
758
+ const row = rowOf(kid);
759
+ if (row) {
760
+ rows += 1;
761
+ if (typeof row.button.getAttribute === "function" && row.button.getAttribute("aria-label")) labelled += 1;
415
762
  continue;
416
763
  }
417
- if (tag === "SPAN") continue;
418
- if (tag === "DIV" && typeof kid.getAttribute === "function" && kid.getAttribute(BAR_ATTR) !== null) continue;
764
+ if (kid.tagName === "SPAN") continue;
419
765
  return false;
420
766
  }
421
- if (buttons === 0 || twoPart === 0) return false;
767
+ if (rows === 0) return false;
768
+ if (rows < 2 && labelled === 0) return false;
422
769
  if (typeof node.querySelector === "function" && node.querySelector("input, textarea, select, a, form")) return false;
423
770
  return true;
424
771
  }
@@ -431,11 +778,38 @@ function looksLikePanelNav(node) {
431
778
  function findNav(doc) {
432
779
  if (!doc || typeof doc.querySelectorAll !== "function") return null;
433
780
  const navs = doc.querySelectorAll("nav");
434
- if (!navs) return null;
781
+ if (!navs || navs.length === 0) return null;
782
+ let best = null;
783
+ let bestRows = 0;
435
784
  for (let i = 0; i < navs.length; i += 1) {
436
- if (looksLikePanelNav(navs[i])) return navs[i];
785
+ if (!looksLikePanelNav(navs[i])) continue;
786
+ let count = 0;
787
+ const kids = navs[i].children || [];
788
+ for (let j = 0; j < kids.length; j += 1) if (rowOf(kids[j])) count += 1;
789
+ if (count > bestRows) {
790
+ best = navs[i];
791
+ bestRows = count;
792
+ }
437
793
  }
438
- return null;
794
+ return best;
795
+ }
796
+
797
+ /** 找不到导航时打一条可复现的结构诊断(宿主改版时靠它定位)。 */
798
+ function describeNavs(doc) {
799
+ if (!doc || typeof doc.querySelectorAll !== "function") return "";
800
+ const navs = doc.querySelectorAll("nav");
801
+ const parts = [];
802
+ for (let i = 0; i < navs.length && i < 3; i += 1) {
803
+ const kids = navs[i].children || [];
804
+ const shape = [];
805
+ for (let j = 0; j < kids.length && j < 6; j += 1) {
806
+ const kid = kids[j];
807
+ const inner = kid && kid.children ? kid.children.length : 0;
808
+ shape.push(kid.tagName + (inner ? "(" + inner + ")" : ""));
809
+ }
810
+ parts.push("nav[" + i + "] " + kids.length + " kids: " + shape.join(","));
811
+ }
812
+ return parts.join(" | ");
439
813
  }
440
814
 
441
815
  /**
@@ -667,10 +1041,14 @@ function renderBar() {
667
1041
  bar.appendChild(badge);
668
1042
  }
669
1043
  // 图标轨里放不下排布,两种模型都退化成单按钮循环
670
- const allButton = () => makeAction(doc, "all", t("bar.all"), t("bar.all.title"), LIST_ICON);
1044
+ const skipAll = runtime.shellHasMore && runtime.hideAllWhenShellMore;
1045
+ const allButton = () => (skipAll ? null : makeAction(doc, "all", t("bar.all"), t("bar.all.title"), LIST_ICON));
671
1046
  if (runtime.iconOnly) {
672
1047
  bar.appendChild(makeCycle(doc));
673
- if (runtime.mode === "hidden") bar.appendChild(allButton());
1048
+ if (runtime.mode === "hidden") {
1049
+ const all = allButton();
1050
+ if (all) bar.appendChild(all);
1051
+ }
674
1052
  return;
675
1053
  }
676
1054
  if (runtime.model === "header") {
@@ -679,14 +1057,20 @@ function renderBar() {
679
1057
  }
680
1058
  if (runtime.model === "cycle") {
681
1059
  bar.appendChild(makeCycle(doc));
682
- if (runtime.mode === "hidden") bar.appendChild(allButton());
1060
+ if (runtime.mode === "hidden") {
1061
+ const all = allButton();
1062
+ if (all) bar.appendChild(all);
1063
+ }
683
1064
  return;
684
1065
  }
685
1066
  for (let i = 0; i < MODES.length; i += 1) {
686
1067
  const mode = MODES[i];
687
1068
  bar.appendChild(makeAction(doc, mode, densityLabel(mode), densityTitle(mode), densityIcon(mode), mode === runtime.mode));
688
1069
  }
689
- if (runtime.mode === "hidden") bar.appendChild(allButton());
1070
+ if (runtime.mode === "hidden") {
1071
+ const all = allButton();
1072
+ if (all) bar.appendChild(all);
1073
+ }
690
1074
  }
691
1075
 
692
1076
  /**
@@ -794,6 +1178,19 @@ function paintNav() {
794
1178
  if (!nav || typeof nav.setAttribute !== "function") return;
795
1179
  try {
796
1180
  nav.setAttribute(NAV_ATTR, runtime.mode);
1181
+ nav.setAttribute("data-navfold-cols", runtime.cols);
1182
+ const before = runtime.pinState;
1183
+ const state = applyPin(nav);
1184
+ nav.setAttribute("data-navfold-pinned", state === "applied" ? "on" : state === "fallback" ? "fallback" : "off");
1185
+ // 挂起态在下一帧再试一次(抽屉展开动画结束时高度才会非 0)
1186
+ if (state === "pending" && typeof window.setTimeout === "function" && !runtime.pinRetry) {
1187
+ runtime.pinRetry = window.setTimeout(() => {
1188
+ runtime.pinRetry = 0;
1189
+ paintNav();
1190
+ }, 350);
1191
+ }
1192
+ // 回退只在“本来想固定但结构不符”时记一次,避免每次重扫刷屏
1193
+ if (state === "fallback" && before !== "fallback") noteAnomaly("顶部固定未生效(结构不匹配),已回退为粘性导航");
797
1194
  } catch (err) {
798
1195
  warn("写入档位失败", err);
799
1196
  }
@@ -912,6 +1309,164 @@ function getModel() {
912
1309
  return runtime.model;
913
1310
  }
914
1311
 
1312
+ /** 落盘一个键(失败不影响功能)。 */
1313
+ function persist(key, value) {
1314
+ try {
1315
+ window.localStorage.setItem(key, value);
1316
+ } catch (err) {
1317
+ /* 隐私模式:本次会话内有效即可 */
1318
+ }
1319
+ }
1320
+
1321
+ /** 只重置控件样式(不动档位、自动档与保留行)。 */
1322
+ function resetModelOnly() {
1323
+ const previous = runtime.model;
1324
+ runtime.model = "segmented";
1325
+ if (previous !== "segmented") reconcileHeaderMode("segmented");
1326
+ persist(STORAGE_MODEL, runtime.model);
1327
+ runtime.signature = "";
1328
+ paintNav();
1329
+ if (runtime.nav) mountBar(runtime.nav);
1330
+ notify();
1331
+ }
1332
+
1333
+ /** 读取图标档列数。 */
1334
+ function getCols() {
1335
+ return runtime.cols;
1336
+ }
1337
+
1338
+ /**
1339
+ * 设置图标档列数。
1340
+ * @param value - auto / 8 / 7 / 6 / 5 / 4。
1341
+ */
1342
+ function setCols(value) {
1343
+ runtime.cols = resolveCols(typeof value === "number" ? String(value) : value);
1344
+ persist(STORAGE_COLS, runtime.cols);
1345
+ paintNav();
1346
+ notify();
1347
+ }
1348
+
1349
+ /** 读取图标档吸附开关。 */
1350
+ function getStickCompact() {
1351
+ return runtime.stickCompact;
1352
+ }
1353
+
1354
+ /**
1355
+ * 图标档吸附开关。
1356
+ * @param value - 是否吸附。
1357
+ */
1358
+ function setStickCompact(value) {
1359
+ runtime.stickCompact = !!value;
1360
+ persist(STORAGE_STICK_COMPACT, runtime.stickCompact ? "on" : "off");
1361
+ paintNav();
1362
+ notify();
1363
+ }
1364
+
1365
+ /** 读取收起档吸附开关。 */
1366
+ function getStickHidden() {
1367
+ return runtime.stickHidden;
1368
+ }
1369
+
1370
+ /**
1371
+ * 收起档吸附开关。
1372
+ * @param value - 是否吸附。
1373
+ */
1374
+ function setStickHidden(value) {
1375
+ runtime.stickHidden = !!value;
1376
+ persist(STORAGE_STICK_HIDDEN, runtime.stickHidden ? "on" : "off");
1377
+ paintNav();
1378
+ notify();
1379
+ }
1380
+
1381
+ /** 读取「外壳已有更多时隐藏我的全部入口」。 */
1382
+ function getHideAllWhenShellMore() {
1383
+ return runtime.hideAllWhenShellMore;
1384
+ }
1385
+
1386
+ /**
1387
+ * 「外壳已有更多时隐藏我的全部入口」开关。
1388
+ * @param value - 是否隐藏。
1389
+ */
1390
+ function setHideAllWhenShellMore(value) {
1391
+ runtime.hideAllWhenShellMore = !!value;
1392
+ persist(STORAGE_SHELL_MORE, runtime.hideAllWhenShellMore ? "on" : "off");
1393
+ runtime.signature = "";
1394
+ renderBar();
1395
+ notify();
1396
+ }
1397
+
1398
+ /** 图标档按当前侧栏宽度算出的每列像素(拿不到宽度返回 0)。 */
1399
+ function columnWidth() {
1400
+ const nav = runtime.nav;
1401
+ if (!nav) return 0;
1402
+ const width = typeof nav.clientWidth === "number" ? nav.clientWidth : 0;
1403
+ const cols = runtime.cols === "auto" ? 0 : Number(runtime.cols);
1404
+ if (!cols || !width) return 0;
1405
+ return (width - (cols - 1) * 2) / cols;
1406
+ }
1407
+
1408
+ /** 诊断信息(设置面板展示 + 可复制)。 */
1409
+ function diagnosticsText() {
1410
+ const ua = typeof navigator !== "undefined" && navigator && navigator.userAgent ? navigator.userAgent : "n/a";
1411
+ const latest = runtime.anomalies && runtime.anomalies[0];
1412
+ const warnAt = latest ? new Date(latest.at).toLocaleString() + " · " + latest.kind : "—";
1413
+ const pinText =
1414
+ runtime.pinState === "applied"
1415
+ ? "已应用(" + runtime.mode + "档)· 底色 " + (runtime.pinBg || "transparent")
1416
+ : runtime.pinState === "fallback"
1417
+ ? "回退为粘性导航 · 底色 " + (runtime.pinBg || "transparent")
1418
+ : runtime.pinState === "pending"
1419
+ ? "待定(侧栏当前不可见,展开后自动固定)"
1420
+ : "未启用";
1421
+ return [
1422
+ "dsh-nav-fold " + PLUGIN_VERSION,
1423
+ "状态 " + (latest ? "异常" : "无异常"),
1424
+ "最近告警 " + warnAt,
1425
+ "固定状态 " + pinText,
1426
+ "结构版本 " + (runtime.structure === "wrapped" ? "rc.2+(包裹行 div.panelEntry)" : runtime.structure === "flat" ? "rc.1 及更早(扁平行)" : "未知"),
1427
+ "入口行数 " + runtime.totals.total,
1428
+ "当前档位 " + runtime.mode + " / 控件样式 " + runtime.model,
1429
+ "固定开关 图标档 " + (runtime.stickCompact ? "开" : "关") + ",收起档 " + (runtime.stickHidden ? "开" : "关"),
1430
+ "列数 " + runtime.cols + (runtime.cols === "auto" ? "(自适应)" : ""),
1431
+ "外壳自带入口管理 " + (runtime.shellHasMore ? "是" : "否"),
1432
+ "UA " + ua
1433
+ ].join("\n");
1434
+ }
1435
+
1436
+ /** 诊断区是否展开。 */
1437
+ function getDiagOpen() {
1438
+ return runtime.diagOpen;
1439
+ }
1440
+
1441
+ /** 展开 / 收起诊断区。 */
1442
+ function toggleDiag() {
1443
+ runtime.diagOpen = !runtime.diagOpen;
1444
+ notify();
1445
+ }
1446
+
1447
+ /** 复制诊断信息到剪贴板(失败时退回提示)。 */
1448
+ function copyDiagnostics() {
1449
+ const text = diagnosticsText();
1450
+ try {
1451
+ if (typeof navigator !== "undefined" && navigator.clipboard && typeof navigator.clipboard.writeText === "function") {
1452
+ navigator.clipboard.writeText(text);
1453
+ return;
1454
+ }
1455
+ } catch (err) {
1456
+ /* 落到下面 */
1457
+ }
1458
+ try {
1459
+ const area = document.createElement("textarea");
1460
+ area.value = text;
1461
+ document.body.appendChild(area);
1462
+ area.select();
1463
+ document.execCommand("copy");
1464
+ document.body.removeChild(area);
1465
+ } catch (err) {
1466
+ warn("复制诊断信息失败", err);
1467
+ }
1468
+ }
1469
+
915
1470
  /**
916
1471
  * 订阅状态变化。
917
1472
  * @param listener - 变化回调。
@@ -957,20 +1512,28 @@ function scan() {
957
1512
  return;
958
1513
  }
959
1514
  runtime.headerDrift = 0;
1515
+ runtime.structure = detectStructure(nav);
1516
+ runtime.shellHasMore = detectShellMore(nav);
1517
+ retargetObserver(nav.parentElement || nav);
960
1518
  paintNav();
961
1519
  mountBar(nav);
962
1520
  return;
963
1521
  }
964
1522
  const found = findNav(document);
965
1523
  if (!found) {
1524
+ retargetObserver(document.documentElement || document.body);
966
1525
  if (!runtime.warned && Date.now() - runtime.mountedAt > WARN_AFTER_MS) {
967
1526
  runtime.warned = true;
968
- warn("未找到「功能入口」导航(DSH 版本可能已变更),保持原生 UI");
1527
+ noteAnomaly("未找到「功能入口」导航(DSH 版本可能已变更)");
1528
+ warn("未找到「功能入口」导航(DSH 版本可能已变更),保持原生 UI " + describeNavs(document));
969
1529
  }
970
1530
  return;
971
1531
  }
972
1532
  runtime.nav = found;
973
1533
  runtime.warned = false;
1534
+ runtime.structure = detectStructure(found);
1535
+ runtime.shellHasMore = detectShellMore(found);
1536
+ retargetObserver(found.parentElement || found);
974
1537
  paintNav();
975
1538
  mountBar(found);
976
1539
  }
@@ -987,15 +1550,13 @@ function rowButtons(nav) {
987
1550
  for (let i = 0; i < nav.children.length; i += 1) {
988
1551
  const child = nav.children[i];
989
1552
  if (!child) continue;
990
- if (child.tagName === "BUTTON") {
991
- out.push(child);
1553
+ const row = rowOf(child);
1554
+ if (row) {
1555
+ out.push(row.button);
992
1556
  continue;
993
1557
  }
994
- if (child.tagName === "SPAN" && child.children) {
995
- for (let j = 0; j < child.children.length; j += 1) {
996
- if (child.children[j] && child.children[j].tagName === "BUTTON") out.push(child.children[j]);
997
- }
998
- }
1558
+ const more = moreButtonOf(child);
1559
+ if (more) out.push(more);
999
1560
  }
1000
1561
  return out;
1001
1562
  }
@@ -1007,7 +1568,10 @@ function rowButtons(nav) {
1007
1568
  */
1008
1569
  function syncTitles(nav) {
1009
1570
  const buttons = rowButtons(nav);
1010
- const wantTitles = runtime.iconOnly || runtime.mode === "compact";
1571
+ // rc.2 起外壳给每行配了 Tooltip:再叠原生 title 会双提示,交给外壳
1572
+ const rows = collectRows(nav);
1573
+ const shellHasTooltip = rows.some((row) => row.wrapper !== row.el);
1574
+ const wantTitles = (runtime.iconOnly || runtime.mode === "compact") && !shellHasTooltip;
1011
1575
  for (let i = 0; i < buttons.length; i += 1) {
1012
1576
  const el = buttons[i];
1013
1577
  if (!el || typeof el.setAttribute !== "function") continue;
@@ -1063,9 +1627,9 @@ function collectRows(nav) {
1063
1627
  const rows = [];
1064
1628
  if (!nav || !nav.children) return rows;
1065
1629
  for (let i = 0; i < nav.children.length; i += 1) {
1066
- const child = nav.children[i];
1067
- if (!child || child.tagName !== "BUTTON") continue;
1068
- rows.push({ label: rowLabel(child), el: child });
1630
+ const row = rowOf(nav.children[i]);
1631
+ if (!row) continue;
1632
+ rows.push({ label: rowLabel(row.button), el: row.button, wrapper: row.wrapper });
1069
1633
  }
1070
1634
  return rows;
1071
1635
  }
@@ -1092,9 +1656,12 @@ function syncKeeps(nav) {
1092
1656
  const row = rows[i];
1093
1657
  const keep = effective.indexOf(i) !== -1;
1094
1658
  if (keep) kept += 1;
1095
- if (typeof row.el.setAttribute === "function") {
1096
- if (keep) row.el.setAttribute("data-navfold-keep", "");
1097
- else if (typeof row.el.removeAttribute === "function") row.el.removeAttribute("data-navfold-keep");
1659
+ const targets = row.wrapper && row.wrapper !== row.el ? [row.wrapper, row.el] : [row.el];
1660
+ for (let t = 0; t < targets.length; t += 1) {
1661
+ const target = targets[t];
1662
+ if (!target) continue;
1663
+ if (typeof target.setAttribute === "function" && keep) target.setAttribute("data-navfold-keep", "");
1664
+ else if (typeof target.removeAttribute === "function") target.removeAttribute("data-navfold-keep");
1098
1665
  }
1099
1666
  }
1100
1667
  const changed = runtime.totals.kept !== kept || runtime.totals.total !== rows.length;
@@ -1190,7 +1757,17 @@ function resetAll() {
1190
1757
  /* 忽略 */
1191
1758
  }
1192
1759
  try {
1193
- [STORAGE_MODE, STORAGE_MODE_NARROW, STORAGE_MODEL, STORAGE_AUTO, STORAGE_KEEP].forEach((key) => {
1760
+ [
1761
+ STORAGE_MODE,
1762
+ STORAGE_MODE_NARROW,
1763
+ STORAGE_MODEL,
1764
+ STORAGE_AUTO,
1765
+ STORAGE_KEEP,
1766
+ STORAGE_COLS,
1767
+ STORAGE_STICK_COMPACT,
1768
+ STORAGE_STICK_HIDDEN,
1769
+ STORAGE_SHELL_MORE
1770
+ ].forEach((key) => {
1194
1771
  window.localStorage.removeItem(key);
1195
1772
  });
1196
1773
  } catch (err) {
@@ -1199,6 +1776,10 @@ function resetAll() {
1199
1776
  runtime.keep = [];
1200
1777
  runtime.model = "segmented";
1201
1778
  runtime.auto = true;
1779
+ runtime.cols = "auto";
1780
+ runtime.stickCompact = true;
1781
+ runtime.stickHidden = false;
1782
+ runtime.hideAllWhenShellMore = true;
1202
1783
  runtime.mode = pickInitialMode(null, runtime.narrow, window.innerHeight, true);
1203
1784
  if (runtime.nav) syncKeeps(runtime.nav);
1204
1785
  paintNav();
@@ -1288,6 +1869,27 @@ function followViewport(media) {
1288
1869
  * 绑定 DOM:首扫 + 外壳重挂/重渲染时重挂控制条(节流),卸载时清理干净。
1289
1870
  * @returns 清理函数。
1290
1871
  */
1872
+ /**
1873
+ * 把观察器挪到指定节点:找得到 nav 时只盯侧栏容器,找不到时退回全文档。
1874
+ * @param target - 观察目标。
1875
+ */
1876
+ function retargetObserver(target) {
1877
+ if (!runtime.observer || !target) return;
1878
+ if (runtime.observedTarget === target) return;
1879
+ try {
1880
+ runtime.observer.disconnect();
1881
+ runtime.observer.observe(target, {
1882
+ childList: true,
1883
+ subtree: true,
1884
+ attributes: true,
1885
+ attributeFilter: ["data-sidebar-collapsed"]
1886
+ });
1887
+ runtime.observedTarget = target;
1888
+ } catch (err) {
1889
+ /* 观察失败不影响主流程,下一次 scan 会重试 */
1890
+ }
1891
+ }
1892
+
1291
1893
  function attachDom() {
1292
1894
  const schedule = () => {
1293
1895
  if (runtime.timer) return;
@@ -1314,14 +1916,17 @@ function attachDom() {
1314
1916
  if (own) return;
1315
1917
  schedule();
1316
1918
  });
1317
- const target = document.documentElement || document.body;
1318
- if (target) {
1319
- runtime.observer.observe(target, {
1320
- childList: true,
1321
- subtree: true,
1322
- attributes: true,
1323
- attributeFilter: ["data-sidebar-collapsed"]
1324
- });
1919
+ retargetObserver(document.documentElement || document.body);
1920
+ // 兜底:容器整体被替换时观察器盯的是已脱离文档的节点,只能靠低频查 isConnected
1921
+ if (typeof window.setInterval === "function") {
1922
+ runtime.poll = window.setInterval(() => {
1923
+ if (!runtime.nav || runtime.nav.isConnected !== false) return;
1924
+ runtime.nav = null;
1925
+ runtime.warned = false;
1926
+ noteAnomaly("侧栏容器被整体替换,已自动重挂");
1927
+ retargetObserver(document.documentElement || document.body);
1928
+ scan();
1929
+ }, 2000);
1325
1930
  }
1326
1931
  }
1327
1932
  const Resize = window.ResizeObserver;
@@ -1338,6 +1943,14 @@ function attachDom() {
1338
1943
  }
1339
1944
  runtime.observer = null;
1340
1945
  }
1946
+ if (runtime.poll) {
1947
+ window.clearInterval(runtime.poll);
1948
+ runtime.poll = 0;
1949
+ }
1950
+ if (runtime.observer) {
1951
+ runtime.observer.disconnect();
1952
+ runtime.observedTarget = null;
1953
+ }
1341
1954
  if (runtime.resize) {
1342
1955
  try {
1343
1956
  runtime.resize.disconnect();
@@ -1421,9 +2034,19 @@ const PANEL_CSS = {
1421
2034
  foot: {
1422
2035
  display: "flex",
1423
2036
  justifyContent: "flex-end",
2037
+ gap: 8,
1424
2038
  paddingTop: 10,
1425
2039
  borderTop: "1px solid var(--dsw-alias-border-l1,rgba(0,0,0,.08))"
1426
- }
2040
+ },
2041
+ diagToggle: {
2042
+ padding: "2px 6px",
2043
+ border: "none",
2044
+ background: "transparent",
2045
+ color: "var(--dsw-alias-label-secondary,#666)",
2046
+ fontSize: 12,
2047
+ cursor: "pointer"
2048
+ },
2049
+ diag: { margin: 0 }
1427
2050
  };
1428
2051
 
1429
2052
  /**
@@ -1463,6 +2086,51 @@ function NavFoldSettings() {
1463
2086
  const keepSnapshot = () =>
1464
2087
  runtime.keep.map((entry) => entry.i + ":" + entry.label).join("|") + "#" + runtime.totals.total + "#" + (runtime.confirmReset ? "c" : "");
1465
2088
  react.useSyncExternalStore(subscribe, keepSnapshot, keepSnapshot);
2089
+ const cols = react.useSyncExternalStore(subscribe, getCols, getCols);
2090
+ const stickCompact = react.useSyncExternalStore(subscribe, getStickCompact, getStickCompact);
2091
+ const stickHidden = react.useSyncExternalStore(subscribe, getStickHidden, getStickHidden);
2092
+ const shellMore = react.useSyncExternalStore(subscribe, getHideAllWhenShellMore, getHideAllWhenShellMore);
2093
+ const diagOpen = react.useSyncExternalStore(subscribe, getDiagOpen, getDiagOpen);
2094
+ const cellsTitleId = uid + "-cells";
2095
+ const iconStickId = uid + "-stick-icon";
2096
+ const hiddenStickId = uid + "-stick-hidden";
2097
+ const shellId = uid + "-shell";
2098
+ const diagId = uid + "-diag";
2099
+ // 列数挤压提示:按当前侧栏实宽算每列像素,低于阈值就提示(不阻断)
2100
+ const navWidth = runtime.nav && typeof runtime.nav.clientWidth === "number" ? runtime.nav.clientWidth : 0;
2101
+ const colsNum = cols === "auto" ? 0 : Number(cols);
2102
+ const perCol = colsNum && navWidth ? (navWidth - (colsNum - 1) * 2) / colsNum : 0;
2103
+ const mobileWidth =
2104
+ typeof window !== "undefined" && typeof window.matchMedia === "function" ? window.matchMedia(NARROW_QUERY).matches : false;
2105
+ const cramped = colsNum > 0 && perCol > 0 && perCol < COL_MIN_PX;
2106
+ const mobileTight = mobileWidth && colsNum >= 7;
2107
+ const makeWarn = () =>
2108
+ cramped || mobileTight
2109
+ ? el(
2110
+ "p",
2111
+ { "data-navfold-warn": "" },
2112
+ mobileTight
2113
+ ? t("settings.cells.warnMobile")
2114
+ : t("settings.cells.warn", { width: Math.round(navWidth), cols: colsNum, px: Math.round(perCol) }),
2115
+ el("button", { type: "button", onClick: () => setCols("auto") }, t("settings.cells.revert"))
2116
+ )
2117
+ : null;
2118
+ const switchOf = (checked, ids, onToggle, attrs) =>
2119
+ el(
2120
+ "button",
2121
+ Object.assign(
2122
+ {
2123
+ type: "button",
2124
+ role: "switch",
2125
+ "aria-checked": checked ? "true" : "false",
2126
+ "aria-labelledby": ids,
2127
+ "data-navfold-switch": "",
2128
+ onClick: onToggle
2129
+ },
2130
+ attrs || {}
2131
+ ),
2132
+ el("span", { "aria-hidden": "true" })
2133
+ );
1466
2134
 
1467
2135
  const rows = collectRows(runtime.nav || null);
1468
2136
  const keepIndices = new Set(resolveKeepIndices(rows).map((item) => item.index));
@@ -1535,6 +2203,7 @@ function NavFoldSettings() {
1535
2203
  "aria-checked": auto ? "true" : "false",
1536
2204
  "aria-labelledby": autoTitleId,
1537
2205
  "data-navfold-auto": auto ? "on" : "off",
2206
+ "data-navfold-switch": "",
1538
2207
  onClick: () => setAuto(!auto)
1539
2208
  },
1540
2209
  el("span", { "aria-hidden": "true" })
@@ -1589,10 +2258,98 @@ function NavFoldSettings() {
1589
2258
  ),
1590
2259
  el("p", { style: PANEL_CSS.desc }, t("settings.keep.hint"))
1591
2260
  ),
2261
+ // 图标档:每行几个 + 吸附
2262
+ el(
2263
+ "section",
2264
+ { style: PANEL_CSS.group, role: "group", "aria-labelledby": cellsTitleId },
2265
+ el(
2266
+ "div",
2267
+ { style: PANEL_CSS.row },
2268
+ el("span", { id: cellsTitleId, style: PANEL_CSS.title, key: "t" }, t("settings.cells.title")),
2269
+ el(
2270
+ "div",
2271
+ { style: PANEL_CSS.seg, role: "radiogroup", "aria-labelledby": cellsTitleId, key: "g" },
2272
+ COLS_OPTIONS.map((value) =>
2273
+ el(
2274
+ "button",
2275
+ {
2276
+ key: value,
2277
+ type: "button",
2278
+ role: "radio",
2279
+ "aria-checked": cols === value ? "true" : "false",
2280
+ "data-navfold-cols-btn": value,
2281
+ onClick: () => setCols(value),
2282
+ style: PANEL_CSS.segBtn
2283
+ },
2284
+ value === "auto" ? t("settings.cells.auto") : value
2285
+ )
2286
+ )
2287
+ )
2288
+ ),
2289
+ makeWarn(),
2290
+ el("p", { style: PANEL_CSS.desc }, t("settings.cells.desc")),
2291
+ el(
2292
+ "div",
2293
+ { style: PANEL_CSS.row },
2294
+ el("span", { id: iconStickId, style: PANEL_CSS.title, key: "t2" }, t("settings.stick.title")),
2295
+ switchOf(stickCompact, iconStickId, () => setStickCompact(!stickCompact), { "data-navfold-stick": "compact" })
2296
+ ),
2297
+ el("p", { style: PANEL_CSS.desc }, t("settings.stick.compact.desc"))
2298
+ ),
2299
+ // 收起档:吸附(默认关)
2300
+ el(
2301
+ "section",
2302
+ { style: PANEL_CSS.group, role: "group", "aria-labelledby": hiddenStickId },
2303
+ el(
2304
+ "div",
2305
+ { style: PANEL_CSS.row },
2306
+ el("span", { id: hiddenStickId, style: PANEL_CSS.title, key: "t" }, t("settings.stick.title")),
2307
+ switchOf(stickHidden, hiddenStickId, () => setStickHidden(!stickHidden), { "data-navfold-stick": "hidden" })
2308
+ ),
2309
+ el("p", { style: PANEL_CSS.desc }, t("settings.stick.hidden.desc"))
2310
+ ),
2311
+ // 与外壳共存
2312
+ el(
2313
+ "section",
2314
+ { style: PANEL_CSS.group, role: "group", "aria-labelledby": shellId },
2315
+ el(
2316
+ "div",
2317
+ { style: PANEL_CSS.row },
2318
+ el("span", { id: shellId, style: PANEL_CSS.title, key: "t" }, t("settings.shell.title")),
2319
+ switchOf(shellMore, shellId, () => setHideAllWhenShellMore(!shellMore), { "data-navfold-shell-more": shellMore ? "on" : "off" })
2320
+ ),
2321
+ el("p", { style: PANEL_CSS.desc }, t("settings.shell.desc"))
2322
+ ),
1592
2323
  el("p", { style: PANEL_CSS.desc }, t("settings.rail.hint")),
2324
+ // 诊断(默认折叠)
2325
+ el(
2326
+ "section",
2327
+ { style: PANEL_CSS.group, role: "group", "aria-labelledby": diagId },
2328
+ el(
2329
+ "div",
2330
+ { style: PANEL_CSS.row },
2331
+ el(
2332
+ "button",
2333
+ {
2334
+ id: diagId,
2335
+ type: "button",
2336
+ "aria-expanded": diagOpen ? "true" : "false",
2337
+ "data-navfold-diag-toggle": "",
2338
+ onClick: toggleDiag,
2339
+ style: PANEL_CSS.diagToggle
2340
+ },
2341
+ (diagOpen ? "▾ " : "▸ ") + t("settings.diag.title")
2342
+ ),
2343
+ diagOpen
2344
+ ? el("button", { type: "button", "data-navfold-micro": "copy", onClick: copyDiagnostics }, t("settings.diag.copy"))
2345
+ : null
2346
+ ),
2347
+ diagOpen ? el("pre", { "data-navfold-diag": "", style: PANEL_CSS.diag }, diagnosticsText()) : null
2348
+ ),
1593
2349
  el(
1594
2350
  "div",
1595
2351
  { style: PANEL_CSS.foot },
2352
+ el("button", { type: "button", "data-navfold-reset-model": "on", onClick: resetModelOnly }, t("settings.resetModel")),
1596
2353
  el(
1597
2354
  "button",
1598
2355
  {
@@ -1627,13 +2384,15 @@ function wireLocale(ctx) {
1627
2384
  if (typeof locale.bind !== "function") return;
1628
2385
  try {
1629
2386
  const bound = locale.bind(NS);
2387
+ // 缺词条时的兜底语言:中文环境用中文,其它语言用英文(DSH 还支持 ja/de/fr/es/pt/ru,回退中文会中英混排)
2388
+ const lang = (document.documentElement && document.documentElement.lang) || "";
2389
+ const fallback = /^zh/i.test(lang) ? DICT.zh : DICT.en;
1630
2390
  t = (key, params) => {
1631
2391
  try {
1632
2392
  const value = bound(key, params);
1633
- // bound 在缺词条时会原样回吐 key,这时用内置中文兜底(防止字典与组件版本错位露 key)
1634
- return typeof value === "string" && value.length > 0 && value !== key ? value : formatText(dictText(DICT.zh, key), params);
2393
+ return typeof value === "string" && value.length > 0 && value !== key ? value : formatText(dictText(fallback, key), params);
1635
2394
  } catch (err) {
1636
- return formatText(dictText(DICT.zh, key), params);
2395
+ return formatText(dictText(fallback, key), params);
1637
2396
  }
1638
2397
  };
1639
2398
  } catch (err) {
@@ -1699,19 +2458,35 @@ function apply(ctx) {
1699
2458
  let storedModel = null;
1700
2459
  let storedAuto = null;
1701
2460
  let storedKeep = null;
2461
+ let storedCols = null;
2462
+ let storedStickCompact = null;
2463
+ let storedStickHidden = null;
2464
+ let storedShellMore = null;
1702
2465
  try {
1703
2466
  storedMode = window.localStorage.getItem(modeKey(runtime.narrow));
1704
2467
  storedModel = window.localStorage.getItem(STORAGE_MODEL);
1705
2468
  storedAuto = window.localStorage.getItem(STORAGE_AUTO);
1706
2469
  storedKeep = window.localStorage.getItem(STORAGE_KEEP);
2470
+ storedCols = window.localStorage.getItem(STORAGE_COLS);
2471
+ storedStickCompact = window.localStorage.getItem(STORAGE_STICK_COMPACT);
2472
+ storedStickHidden = window.localStorage.getItem(STORAGE_STICK_HIDDEN);
2473
+ storedShellMore = window.localStorage.getItem(STORAGE_SHELL_MORE);
1707
2474
  } catch (err) {
1708
2475
  storedMode = null;
1709
2476
  storedModel = null;
1710
2477
  storedAuto = null;
1711
2478
  storedKeep = null;
2479
+ storedCols = null;
2480
+ storedStickCompact = null;
2481
+ storedStickHidden = null;
2482
+ storedShellMore = null;
1712
2483
  }
1713
2484
  runtime.keep = resolveKeep(storedKeep);
1714
2485
  runtime.auto = resolveAuto(storedAuto);
2486
+ runtime.cols = resolveCols(storedCols);
2487
+ runtime.stickCompact = resolveFlag(storedStickCompact, true);
2488
+ runtime.stickHidden = resolveFlag(storedStickHidden, false);
2489
+ runtime.hideAllWhenShellMore = resolveFlag(storedShellMore, true);
1715
2490
  wireLocale(ctx);
1716
2491
  runtime.model = resolveModel(storedModel);
1717
2492
  runtime.mode = pickInitialMode(storedMode, runtime.narrow, window.innerHeight, runtime.auto);
@@ -1790,7 +2565,20 @@ exports.__internals = {
1790
2565
  getModel: getModel,
1791
2566
  NavFoldSettings: NavFoldSettings,
1792
2567
  runtime: runtime,
1793
- scan: scan
2568
+ scan: scan,
2569
+ getCols: getCols,
2570
+ setCols,
2571
+ getStickCompact,
2572
+ setStickCompact,
2573
+ getStickHidden,
2574
+ setStickHidden,
2575
+ getHideAllWhenShellMore,
2576
+ setHideAllWhenShellMore,
2577
+ getDiagOpen,
2578
+ toggleDiag,
2579
+ resetModelOnly,
2580
+ diagnosticsText,
2581
+ COLS_OPTIONS
1794
2582
  };
1795
2583
  return module.exports;
1796
2584
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-nav-fold",
3
- "version": "0.1.0",
4
- "description": "nav-fold 导航折叠 · 把 DSH 左侧栏顶部的功能入口折叠成图标网格或收起(三态 + 三种控件模型,设置内可切换)",
3
+ "version": "0.3.1",
4
+ "description": "nav-fold 导航折叠 · 把 DSH 左侧栏顶部的功能入口折叠成图标网格或收起(三态 + 三种控件模型,兼容 rc.1 扁平行与 rc.2+ 包裹行)",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "exports": {
@@ -24,7 +24,7 @@
24
24
  ],
25
25
  "dsh": {
26
26
  "engines": {
27
- "dsh": ">=0.2.2-rc.1"
27
+ "dsh": ">=0.2.2-rc.1 <0.3.0"
28
28
  },
29
29
  "bundle": {
30
30
  "patch": "./cordis.patch.yml"
@@ -38,7 +38,7 @@
38
38
  }
39
39
  },
40
40
  "peerDependencies": {
41
- "@deepseek-ai/dsh": ">=0.2.2-rc.1",
41
+ "@deepseek-ai/dsh": ">=0.2.2-rc.1 <0.3.0",
42
42
  "react": "^18.2.0"
43
43
  },
44
44
  "scripts": {