nx-sk 0.16.0 → 0.18.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.
Files changed (37) hide show
  1. package/CHANGELOG.md +77 -1
  2. package/README.md +14 -1
  3. package/assets/nx-sk/SKILL.md +11 -1
  4. package/assets/nx-sk/references/40-files.md +36 -5
  5. package/assets/sk-needdo/SKILL.md +28 -3
  6. package/assets/sk-needdo/references/20-schema.md +5 -1
  7. package/assets/sk-needdo/references/30-fill.md +2 -2
  8. package/assets/sk-needdo/references/50-example.md +15 -9
  9. package/assets/sk-source/SKILL.md +1 -1
  10. package/package.json +1 -1
  11. package/src/core/fields.js +22 -7
  12. package/src/core/store.js +6 -1
  13. package/src/modules/entries/view.jsx +22 -1
  14. package/src/modules/files/index.js +9 -0
  15. package/src/modules/files/service.js +47 -0
  16. package/src/modules/files/view.jsx +32 -0
  17. package/src/modules/sections/service.js +9 -3
  18. package/src/modules/settings/navManager.jsx +102 -67
  19. package/src/modules/settings/view.jsx +3 -1
  20. package/src/web/frontend/App.jsx +69 -22
  21. package/src/web/frontend/components/fieldEditor.jsx +73 -6
  22. package/src/web/frontend/components/navModel.js +64 -7
  23. package/src/web/frontend/styles.css +60 -3
  24. package/src/web/public/assets/{files-Cc9BanTT.js → files--aIy09Sp.js} +1 -1
  25. package/src/web/public/assets/index-BWIrglCf.js +41 -0
  26. package/src/web/public/assets/index-CEIiV0jA.css +1 -0
  27. package/src/web/public/assets/{view-DtLbyce-.js → view-0jlrnuBr.js} +1 -1
  28. package/src/web/public/assets/{view-C_8pbtZX.js → view-1SYBZ3dg.js} +1 -1
  29. package/src/web/public/assets/view-Bt7O8gS_.js +2 -0
  30. package/src/web/public/assets/view-Bt8MZAtu.js +1 -0
  31. package/src/web/public/assets/view-CjX_ywS7.js +36 -0
  32. package/src/web/public/index.html +2 -2
  33. package/src/web/public/assets/index-B1tuW-Bw.js +0 -41
  34. package/src/web/public/assets/index-BotRwCy_.css +0 -1
  35. package/src/web/public/assets/view-C1Ux-1yp.js +0 -1
  36. package/src/web/public/assets/view-CLufVxNB.js +0 -35
  37. package/src/web/public/assets/view-U7H8BYBr.js +0 -1
@@ -174,6 +174,30 @@ export default function FilesView() {
174
174
  await reload();
175
175
  });
176
176
 
177
+ /**
178
+ * 一键清理**未引用**的附件(孤儿附件)。
179
+ *
180
+ * 判据与「未引用」筛选片同一套:没有任何条目的 file 字段引用它、正文里也没有引用它的图。
181
+ * 逐个删是折磨 —— 批量导入 SOP 截图、临时传一份再删,都会留下这种孤儿。
182
+ * 物理原件一起删、不可撤销,所以先弹确认并说清数量。
183
+ */
184
+ const cleanup = guard(async () => {
185
+ const n = data?.unlinked || 0;
186
+ if (!n) return;
187
+ const ok = await dialog({
188
+ message: `清理 ${n} 个未被任何条目引用的附件?`,
189
+ detail: '物理原件会一起删除,不可撤销。\n想留底就先在「导出导入」页导一份。',
190
+ danger: true,
191
+ confirmText: '清理',
192
+ });
193
+ if (!ok) return;
194
+ const r = await api('/api/files/cleanup', { method: 'POST', body: {} });
195
+ toast(r.count ? `已清理 ${r.count} 个未引用的附件` : '没有未引用的附件');
196
+ await refreshAttachments();
197
+ await load();
198
+ await reload();
199
+ });
200
+
177
201
  if (err) {
178
202
  return <div className="pad stack"><div className="bad"><strong>附件库读不到</strong></div><pre className="block">{err}</pre></div>;
179
203
  }
@@ -206,6 +230,14 @@ export default function FilesView() {
206
230
  onChange={(e) => setQ(e.target.value)}
207
231
  />
208
232
  <button className="btn small ghost" onClick={load}>刷新</button>
233
+ <button
234
+ className="btn small ghost danger-ghost"
235
+ disabled={!data.unlinked}
236
+ onClick={cleanup}
237
+ title="删除所有没有任何条目引用的附件(物理原件一并删除,不可撤销)"
238
+ >
239
+ 清理未引用{data.unlinked ? `(${data.unlinked})` : ''}
240
+ </button>
209
241
  <button className="btn small ghost" onClick={openPathImport}>本机路径导入</button>
210
242
  <button className="btn small" onClick={() => pickerRef.current?.click()}>上传文件</button>
211
243
  <input
@@ -3,7 +3,7 @@
3
3
  import { loadStore, mutateStore } from '../../core/store.js';
4
4
  import { assertFieldKey, assertSafeId } from '../../core/paths.js';
5
5
  import { badInput, blocked, conflict, notFound } from '../../core/errors.js';
6
- import { FILL_POLICIES, FIELD_TYPES, SOURCE_FIELD, SOURCE_GROUP, findSection, getTemplate, groupFields, instantiateTemplate, mergeTemplate, sectionNames, syncSectionGroups, templateSummaries } from '../../core/fields.js';
6
+ import { FILL_POLICIES, FIELD_TYPES, ensureSourceBuiltin, findSection, getTemplate, groupFields, instantiateTemplate, mergeTemplate, sectionNames, syncSectionGroups, templateSummaries } from '../../core/fields.js';
7
7
  import { dumpSection, formatValue } from '../../core/render.js';
8
8
  import { sensitiveViewer } from '../../core/vault.js';
9
9
  import { nowIso } from '../../core/ids.js';
@@ -130,8 +130,9 @@ export async function addSection({ id, title, template, description, order, fiel
130
130
  }
131
131
  draft = t;
132
132
  } else {
133
- // 自定义栏目也自带「原始资料」袋:每个栏目都该有乱入的地方(见 core/fields.js 的说明)
134
- draft = { id: sid, title: title || sid, description: description || '', order: Number.isFinite(order) ? order : 50, template: null, kv: false, titleField: null, titleLabel: '名称', groups: [{ ...SOURCE_GROUP }], fields: [{ ...SOURCE_FIELD }] };
133
+ // 自定义栏目。groups/fields 先空着——用户的 --fields/--groups 应用完,
134
+ // 再由 ensureSourceBuiltin 统一补上自带的「原始资料」袋(见下方)。
135
+ draft = { id: sid, title: title || sid, description: description || '', order: Number.isFinite(order) ? order : 50, template: null, kv: false, titleField: null, titleLabel: '名称', groups: [], fields: [] };
135
136
  }
136
137
  if (Array.isArray(groups)) draft.groups = groups.map(validateGroupDef);
137
138
  if (Array.isArray(fields)) {
@@ -141,6 +142,11 @@ export async function addSection({ id, title, template, description, order, fiel
141
142
  // 与 normalize 同一条规则:--fields 引用了 --groups 没声明的分组时自动补上,
142
143
  // 否则面板按声明数组渲染会整组消失(CLI 从字段推导所以看不出来)。
143
144
  draft.groups = syncSectionGroups(draft.groups, draft.fields);
145
+ // 「每个结构自带」:无论模板实例还是自定义栏目(也无论是否传了 --fields/--groups),
146
+ // 非 KV 栏目都自带「原始资料」袋——杂乱资料先原样入袋,再按字段字典整理。
147
+ const ensured = ensureSourceBuiltin(draft.groups, draft.fields, { kv: draft.kv });
148
+ draft.groups = ensured.groups;
149
+ draft.fields = ensured.fields;
144
150
  draft.createdAt = nowIso();
145
151
  draft.updatedAt = draft.createdAt;
146
152
 
@@ -7,15 +7,21 @@
7
7
  //
8
8
  // **受控组件**:数据(cfg)与保存都在设置页;这里只管画与调 onChange。
9
9
  // 所有数据操作走 navModel 的纯函数(可单测),组件里不做状态体操。
10
- import { useMemo, useState } from 'react';
10
+ //
11
+ // **拖动时列表本身不动**。早前这里是「实时预览」:拖动过程中就把被拖的行挪到落点上。
12
+ // 那条路必然抖,原因很硬——预览一挪行,指针底下的元素就换了、下面的容器也整体位移一行
13
+ // (28px),dragover 于是算出另一个落点,再挪,再算……自己推自己,屏幕上就是闪屏;
14
+ // 跨容器时位移最大,闪得最厉害。
15
+ // 现在改为:行按**原样**待在原地(被拖的那行半透明),落点用一条**不占布局**的指示线
16
+ // (inset 阴影压在行边上)表示。列表在拖动期间是静止的 → 指针与行的对应关系恒定,
17
+ // 落点只随指针单调变化,怎么晃都不会跳。松手一次性提交,结果就是指示线指的位置。
18
+ import { useState } from 'react';
11
19
  import * as nav from '../../web/frontend/components/navModel.js';
12
20
 
13
21
  export default function NavManager({ sections, value, onChange }) {
14
22
  const [drag, setDrag] = useState(null); // { kind:'section', sid } | { kind:'group', gi }
15
- const [over, setOver] = useState(null); // { key, index }:当前拖到哪个容器的第几位
23
+ const [over, setOver] = useState(null); // { key, index }:落在哪个容器的第几行之前;组合 { key, group:true }
16
24
 
17
- // 注意顺序:preview 的依赖里用到 allIds / preview 的计算也用到预览配置,
18
- // const 声明晚于使用就是 TDZ 崩("Cannot access … before initialization")
19
25
  const allIds = sections.map((s) => s.id);
20
26
  const sectionOf = (id) => sections.find((s) => s.id === id) || null;
21
27
 
@@ -26,62 +32,91 @@ export default function NavManager({ sections, value, onChange }) {
26
32
  return Number.isFinite(gi) ? { kind: 'group', gi } : null;
27
33
  };
28
34
 
29
- /**
30
- * **实时预览**:拖动过程中就把落点算出来渲染,松手前就看到最终顺序(所见即所得)。
31
- * 插入位由 nav.insertionIndex 换算(同容器内往下拖要让位)——那条逻辑在模型里,有单测。
32
- */
33
- const preview = useMemo(() => {
34
- if (drag?.kind !== 'section' || !over) return value;
35
- const target = keyToTarget(over.key);
36
- if (!target) return value;
37
- const index = nav.insertionIndex(value, drag.sid, target, over.index, allIds);
38
- return nav.moveToContainer(value, drag.sid, target, index, allIds);
39
- }, [value, drag, over, allIds]);
40
-
41
35
  const draggingSid = drag?.kind === 'section' ? drag.sid : null;
42
36
  // 平铺容器的内容与顺序都来自模型:显式排过的(order)优先,其余按栏目自身顺序
43
- const pool = nav.ungroupedIds(preview, allIds);
37
+ const pool = nav.ungroupedIds(value, allIds);
44
38
 
45
39
  const endDrag = () => { setDrag(null); setOver(null); };
46
40
 
47
- /** 松手即提交预览里的顺序(预览就是结果,不再重新算一遍)。 */
48
- const commit = () => { if (preview !== value) onChange(preview); endDrag(); };
49
-
50
41
  // 只在落点**真的变了**才 setState:dragover 每次鼠标移动都触发,
51
- // 不做这层去重就是每次移动都重排一遍整页 → 抖
42
+ // 不做这层去重就是每次移动都重算一遍整页 → 抖
52
43
  const setOverIfChanged = (next) => setOver((o) => (o && o.key === next.key && o.index === next.index ? o : next));
53
44
 
54
- // 容器外壳:接住「拖到空白处 = 追加到末尾」,并显示落点高亮
45
+ /**
46
+ * 指针在容器里落在第几行之前(0..n)。
47
+ * 行位置每帧现取(行高/换行会随窗口变),判据交给 nav.slotAt:只比**中线**。
48
+ * 于是行的上下边缘、行间缝隙、容器内边距都归到最近的一侧,不再出现
49
+ * 「压在行上是一个落点、挪进缝隙变成追加到末尾」这种整列表跳位。
50
+ */
51
+ const slotOf = (el, y) => nav.slotAt(
52
+ [...el.querySelectorAll('[data-nav-row]')].map((row) => {
53
+ const r = row.getBoundingClientRect();
54
+ return r.top + r.height / 2;
55
+ }),
56
+ y,
57
+ );
58
+
59
+ /** 松手:按当前指示线落位。结构没变就不提交(否则拖一下就提示「有未保存的改动」)。 */
60
+ const commit = () => {
61
+ const target = over ? keyToTarget(over.key) : null;
62
+ if (drag?.kind === 'group') {
63
+ // 分组只能落到分组卡上(落到平铺 / 隐藏里没有意义,那两处不是「第几个分组」)
64
+ if (target?.kind === 'group') {
65
+ const next = nav.moveGroupTo(value, drag.gi, target.gi);
66
+ if (next !== value) onChange(next);
67
+ }
68
+ endDrag();
69
+ return;
70
+ }
71
+ if (draggingSid && target) {
72
+ const index = nav.insertionIndex(value, draggingSid, target, over.index, allIds);
73
+ const next = nav.moveToContainer(value, draggingSid, target, index, allIds);
74
+ if (!nav.sameStructure(next, value, allIds)) onChange(next);
75
+ }
76
+ endDrag();
77
+ };
78
+
79
+ // 容器:整块都是落点(含空白处 / 说明文字 / 分组头)。
80
+ // 拖栏目时落点位置由行中线算出;拖分组时整张分组卡都是落点——
81
+ // 只认那 28px 的分组头的话,手要瞄得很准,松手稍偏就白拖了。
55
82
  const zone = (key, base = '') => ({
56
83
  className: `${base} ${over?.key === key ? 'drop-target' : ''}`,
57
- onDragOver: (e) => { if (draggingSid) { e.preventDefault(); setOverIfChanged({ key, index: null }); } },
58
- onDragLeave: () => setOver((o) => (o?.key === key && o.index === null ? null : o)),
84
+ onDragOver: (e) => {
85
+ if (drag?.kind === 'group') {
86
+ if (keyToTarget(key)?.kind !== 'group') { setOver(null); return; }
87
+ e.preventDefault();
88
+ e.dataTransfer.dropEffect = 'move';
89
+ setOverIfChanged({ key, group: true });
90
+ return;
91
+ }
92
+ if (!draggingSid) return;
93
+ e.preventDefault(); // 不拦就没有 drop
94
+ e.dataTransfer.dropEffect = 'move';
95
+ setOverIfChanged({ key, index: slotOf(e.currentTarget, e.clientY) });
96
+ },
59
97
  onDrop: (e) => { e.preventDefault(); commit(); },
60
98
  });
61
99
 
62
100
  /**
63
- * 行的落点判定。两条防抖铁律:
64
- * ① 行内事件**就地拦下**(preventDefault + stopPropagation):一旦冒泡到容器,
65
- * 容器会把它当成「拖到空白处」翻成「追加到末尾」——指针正好压在被拖的行上时,
66
- * 两个判断来回切,页面就抖。
67
- * ② 插入位取自**原始配置**里的位置(不随预览漂移)+ 指针在上半/下半决定前后。
68
- * 若反过来用「预览后的行号」,预览一重排索引就变,等于自己推自己。
101
+ * 拖起一行。拖影取**整行**而不是那个 10px 的把手——把手小到看不出在拖什么,
102
+ * 松手前心里没底。setData 是给 Firefox 的:不设就不算启动拖拽。
69
103
  */
70
- const rowProps = (key, sid) => ({
71
- onDragOver: (e) => {
72
- if (!draggingSid) return;
73
- e.preventDefault();
74
- e.stopPropagation();
75
- if (draggingSid === sid) return; // 悬停在自己身上:保持当前落点,不重算
76
- const rect = e.currentTarget.getBoundingClientRect();
77
- const below = e.clientY > rect.top + rect.height / 2;
78
- const at = nav.containerOf(value, sid, allIds);
79
- const index = (typeof at.index === 'number' ? at.index : 0) + (below ? 1 : 0);
80
- setOverIfChanged({ key, index });
81
- },
82
- onDrop: (e) => { e.preventDefault(); e.stopPropagation(); commit(); },
83
- onDragStart: () => setDrag({ kind: 'section', sid }),
84
- });
104
+ const startSectionDrag = (e, sid) => {
105
+ e.dataTransfer.effectAllowed = 'move';
106
+ e.dataTransfer.setData('text/plain', sid);
107
+ const row = e.currentTarget.closest('.nav-row');
108
+ if (row) e.dataTransfer.setDragImage(row, 14, 14);
109
+ setDrag({ kind: 'section', sid });
110
+ setOver(null);
111
+ };
112
+
113
+ /** 行的落点指示:落在第 i 行之前画上边,落在末尾画最后一行的下边。 */
114
+ const markOf = (key, i, n) => {
115
+ if (over?.key !== key || typeof over.index !== 'number') return '';
116
+ if (over.index === i) return 'ins-before';
117
+ if (i === n - 1 && over.index >= n) return 'ins-after';
118
+ return '';
119
+ };
85
120
 
86
121
  return (
87
122
  <div className="stack">
@@ -90,10 +125,11 @@ export default function NavManager({ sections, value, onChange }) {
90
125
  <div className="hint">平铺:不进分组也不隐藏的栏目,直接显示在头部(拖到这里 = 移出分组 / 取消隐藏)</div>
91
126
  {pool.length ? (
92
127
  <div className="nav-list">
93
- {pool.map((sid) => (
128
+ {pool.map((sid, i) => (
94
129
  <SectionRow key={sid} section={sectionOf(sid)} sid={sid}
95
130
  dragging={draggingSid === sid}
96
- {...rowProps('pool', sid)}
131
+ mark={markOf('pool', i, pool.length)}
132
+ onDragStart={(e) => startSectionDrag(e, sid)}
97
133
  onDragEnd={endDrag}
98
134
  actions={null} />
99
135
  ))}
@@ -102,19 +138,17 @@ export default function NavManager({ sections, value, onChange }) {
102
138
  </section>
103
139
 
104
140
  {/* ② 分组:组名可改、组间可拖把手换位 */}
105
- {preview.groups.map((g, gi) => (
141
+ {value.groups.map((g, gi) => (
106
142
  <section key={gi} {...zone(`g${gi}`, 'card nav-group')}>
107
- <div
108
- className={`colhead ${over?.key === `g${gi}` && over.group ? 'drop-target' : ''}`}
109
- onDragOver={(e) => { if (drag?.kind === 'group') { e.preventDefault(); setOver({ key: `g${gi}`, group: true }); } }}
110
- onDrop={(e) => {
111
- e.preventDefault();
112
- if (drag?.kind === 'group' && drag.gi !== gi) onChange(nav.moveGroup(value, drag.gi, gi - drag.gi));
113
- endDrag();
114
- }}
115
- >
143
+ <div className={`colhead ${over?.key === `g${gi}` && over.group ? 'drop-target' : ''}`}>
116
144
  <span className="grip" title="拖动调整分组顺序" draggable
117
- onDragStart={() => setDrag({ kind: 'group', gi })} onDragEnd={endDrag} />
145
+ onDragStart={(e) => {
146
+ e.dataTransfer.effectAllowed = 'move';
147
+ e.dataTransfer.setData('text/plain', `g${gi}`);
148
+ setDrag({ kind: 'group', gi });
149
+ setOver(null);
150
+ }}
151
+ onDragEnd={endDrag} />
118
152
  <input className="nav-title" placeholder="组名,如「求职」" value={g.title}
119
153
  onChange={(e) => onChange(nav.renameGroup(value, gi, e.target.value))} />
120
154
  <span className="muted">{g.sections.length} 个栏目</span>
@@ -124,10 +158,11 @@ export default function NavManager({ sections, value, onChange }) {
124
158
  </div>
125
159
  {g.sections.length ? (
126
160
  <div className="nav-list">
127
- {g.sections.map((sid) => (
161
+ {g.sections.map((sid, i) => (
128
162
  <SectionRow key={sid} section={sectionOf(sid)} sid={sid}
129
163
  dragging={draggingSid === sid}
130
- {...rowProps(`g${gi}`, sid)}
164
+ mark={markOf(`g${gi}`, i, g.sections.length)}
165
+ onDragStart={(e) => startSectionDrag(e, sid)}
131
166
  onDragEnd={endDrag}
132
167
  actions={<button className="btn small ghost" onClick={() => onChange(nav.ungroupSection(value, sid))}>移出</button>} />
133
168
  ))}
@@ -140,15 +175,16 @@ export default function NavManager({ sections, value, onChange }) {
140
175
  <section {...zone('hidden', 'card nav-group nav-hidden')}>
141
176
  <div className="colhead">
142
177
  隐藏
143
- <span className="muted">{preview.hidden.length} 个栏目</span>
178
+ <span className="muted">{value.hidden.length} 个栏目</span>
144
179
  <span className="right muted">不进头部 · #/栏目id 直达仍可用</span>
145
180
  </div>
146
- {preview.hidden.length ? (
181
+ {value.hidden.length ? (
147
182
  <div className="nav-list">
148
- {preview.hidden.map((sid) => (
183
+ {value.hidden.map((sid, i) => (
149
184
  <SectionRow key={sid} section={sectionOf(sid)} sid={sid}
150
185
  dragging={draggingSid === sid}
151
- {...rowProps('hidden', sid)}
186
+ mark={markOf('hidden', i, value.hidden.length)}
187
+ onDragStart={(e) => startSectionDrag(e, sid)}
152
188
  onDragEnd={endDrag}
153
189
  actions={<button className="btn small ghost" onClick={() => onChange(nav.ungroupSection(value, sid))}>移出</button>} />
154
190
  ))}
@@ -165,9 +201,9 @@ export default function NavManager({ sections, value, onChange }) {
165
201
  }
166
202
 
167
203
  /** 一行栏目:把手(拖)+ 名称 + 计数 + 容器自己的动作(移出 / 无)。 */
168
- function SectionRow({ section, sid, dragging, actions, onDragStart, onDragEnd, onDragOver, onDrop }) {
204
+ function SectionRow({ section, sid, dragging, mark, actions, onDragStart, onDragEnd }) {
169
205
  return (
170
- <div className={`row nav-row ${dragging ? 'dragging' : ''}`} onDragOver={onDragOver} onDrop={onDrop}>
206
+ <div className={`row nav-row ${dragging ? 'dragging' : ''} ${mark}`} data-nav-row data-sid={sid}>
171
207
  <span className="grip" title="拖动:换位 / 换容器" draggable onDragStart={onDragStart} onDragEnd={onDragEnd} />
172
208
  <span className="name">{section ? section.title : `栏目已删除(${sid})`}</span>
173
209
  <span className="desc">{section ? `${section.entries} 条` : '保存前请移出'}</span>
@@ -175,4 +211,3 @@ function SectionRow({ section, sid, dragging, actions, onDragStart, onDragEnd, o
175
211
  </div>
176
212
  );
177
213
  }
178
-
@@ -36,7 +36,9 @@ export default function SettingsView() {
36
36
  useEffect(() => { load(); }, [load]);
37
37
 
38
38
  const problems = useMemo(() => (form ? nav.validate(navCfg, sectionIds) : []), [navCfg, sectionIds, form]);
39
- const dirty = !!baseline && (nav.isDirty(navCfg, baseline.navCfg) || nav.isDirty(form, baseline.form));
39
+ // 导航按「结构」判脏:拖出去又拖回原位不算改动(order 里会留下一串脚印,但不影响长相);
40
+ // 其余设置项逐键比
41
+ const dirty = !!baseline && (!nav.sameStructure(navCfg, baseline.navCfg, sectionIds) || nav.isDirty(form, baseline.form));
40
42
 
41
43
  // 一次保存全部设置:标量项 + 导航(分组 / 隐藏)。分成两块各存各的,
42
44
  // 用户就得记住「刚才那块存了没」——统一保存 + 统一的脏值提示才是清晰的。
@@ -1,4 +1,4 @@
1
- import { Suspense, useEffect, useMemo, useRef, useState } from 'react';
1
+ import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
2
  import { SECTION_VIEW, VIEWS } from './registry.js';
3
3
  import { Copyable, DialogHost, ErrorBoundary, Toasts } from './components/ui.jsx';
4
4
  import { useStore } from './store.jsx';
@@ -14,6 +14,9 @@ function viewFromHash() {
14
14
  export default function App() {
15
15
  const { boot, bootError, ui, patchUi, reload } = useStore();
16
16
  const view = normalizeViewId(ui.view);
17
+ // 展开着哪个分组入口(按下标记):**同一时刻只开一个**。
18
+ // 交给 App 托管而不是各组件各开各的——否则快速划过两个分组会叠出两个菜单。
19
+ const [openGroup, setOpenGroup] = useState(null);
17
20
 
18
21
  // 栏目 tab 是**数据驱动**的(bootstrap.sections);分组与隐藏来自 settings(设置页可配);
19
22
  // 静态 tab 来自前端注册表。渲染顺序:未分组栏目(按 order)→ 分组(按配置顺序)→ 工具(按 order)。
@@ -79,6 +82,11 @@ export default function App() {
79
82
  window.location.hash = `#/${id}`;
80
83
  };
81
84
 
85
+ // 分组入口的开关(稳定引用:子组件的监听/定时器不会因为父组件重渲染而反复重挂)
86
+ const openGroupAt = useCallback((gi) => setOpenGroup(gi), []);
87
+ // 只关**自己**:A 组的「离开延迟关闭」可能晚于 B 组的展开,不加这个判断会把刚开的 B 关掉
88
+ const closeGroupAt = useCallback((gi) => setOpenGroup((cur) => (cur === gi ? null : cur)), []);
89
+
82
90
  return (
83
91
  <div className="app">
84
92
  {/* 身份栏:左边只说「我是谁」,右边才是「存储在哪 / 能做什么」。
@@ -112,8 +120,9 @@ export default function App() {
112
120
  {typeof t.count === 'number' ? <span className="count">{t.count}</span> : null}
113
121
  </button>
114
122
  ))}
115
- {nav.groups.map((g) => (
116
- <GroupTab key={g.title} group={g} currentId={currentId} onGo={go} />
123
+ {nav.groups.map((g, gi) => (
124
+ <GroupTab key={gi} gi={gi} group={g} currentId={currentId}
125
+ open={openGroup === gi} onOpen={openGroupAt} onClose={closeGroupAt} onGo={go} />
117
126
  ))}
118
127
  {nav.tools.length ? <span className="tabs-sep" aria-hidden /> : null}
119
128
  {nav.tools.map((t) => (
@@ -156,51 +165,89 @@ function SectionPane({ sectionId }) {
156
165
  return <View sectionId={sectionId} />;
157
166
  }
158
167
 
168
+ // 悬浮展开的两个时间常数:
169
+ // OPEN —— 悬停**意图**:停住才展开。少了这道延迟,鼠标横穿导航栏去点右边的 tab 时,
170
+ // 路过的分组会被顺带弹开又收起,一眼看过去就是「乱闪」。
171
+ // CLOSE —— 从 pill 划到菜单行要时间(中间还隔着 4px 空隙),太快就是「刚展开就消失」。
172
+ const OPEN_INTENT_MS = 130;
173
+ const CLOSE_DELAY_MS = 180;
174
+
175
+ /**
176
+ * 只有**真能悬浮**的设备才走 hover 这条路。
177
+ * 触屏 tap 会先合成 mouseenter 再发 click:悬停逻辑先把它打开,click 的「切换」
178
+ * 随即又关上——菜单在手机上等于永远出不来。所以按 `(hover: hover)` 分流。
179
+ */
180
+ const canHover = () => (typeof window === 'undefined' ? false : window.matchMedia('(hover: hover)').matches);
181
+
159
182
  /**
160
183
  * 头部的一个**分组入口**:一个 pill 收拢多个栏目(同域栏目不再挤成一排)。
161
- * 悬浮展开、点击也能开(触屏没有 hover);点行切换栏目。
162
- * 外点关闭用 `pointerdown`——`click` 与触发按钮自己的 onClick 同阶段冒泡,
163
- * 会「点一下关了又弹开」;受控组件而非纯 CSS hover,是为了能用键盘 Esc 关。
184
+ * 悬浮展开(带意图延迟)、点击切换(触屏没有 hover,只走这条路);点行切换栏目。
185
+ *
186
+ * 展开态**由 App 托管**(`open` 受控、同一时刻只开一个):各开各的会在快速划过时
187
+ * 叠出两个菜单。外点关闭用 `pointerdown`——`click` 与触发按钮自己的 onClick
188
+ * 同阶段冒泡,会「点一下关了又弹开」;不用纯 CSS hover 而用受控状态,
189
+ * 是为了能用键盘 Esc 关、也为了「只开一个」这条约束。
164
190
  */
165
- function GroupTab({ group, currentId, onGo }) {
166
- const [open, setOpen] = useState(false);
191
+ function GroupTab({ group, gi, currentId, open, onOpen, onClose, onGo }) {
167
192
  const ref = useRef(null);
168
- // 离开时**延迟**再关:鼠标斜着从 pill 划到菜单行会短暂出界,立刻关就「刚展开就消失」
169
- const closeTimer = useRef(null);
193
+ const intentTimer = useRef(null); // 悬停意图:还没到点就离开 → 撤销
194
+ const closeTimer = useRef(null); // 离开后的宽限期:划进菜单就撤销
170
195
  const active = group.sections.some((s) => s.id === currentId);
171
196
  // 角标是**栏目数**,不是条目数之和 —— 组是容器,不是「一条栏目」;展开后每行有自己的条目数
172
197
  const sectionCount = groupSectionCount(group);
173
198
 
174
- const cancelClose = () => {
175
- if (closeTimer.current) { clearTimeout(closeTimer.current); closeTimer.current = null; }
199
+ const drop = (t) => { if (t.current) { clearTimeout(t.current); t.current = null; } };
200
+ const openNow = () => { drop(intentTimer); drop(closeTimer); onOpen(gi); };
201
+ const closeNow = () => { drop(intentTimer); drop(closeTimer); onClose(gi); };
202
+
203
+ const onEnter = () => {
204
+ if (!canHover()) return;
205
+ drop(closeTimer); // 从菜单划回 pill:本来要关,撤销
206
+ if (open) return;
207
+ drop(intentTimer);
208
+ intentTimer.current = setTimeout(() => { intentTimer.current = null; onOpen(gi); }, OPEN_INTENT_MS);
209
+ };
210
+ const onLeave = () => {
211
+ if (!canHover()) return;
212
+ drop(intentTimer); // 只是路过,别开
213
+ drop(closeTimer);
214
+ closeTimer.current = setTimeout(() => { closeTimer.current = null; onClose(gi); }, CLOSE_DELAY_MS);
176
215
  };
177
- const openNow = () => { cancelClose(); setOpen(true); };
178
- const closeSoon = () => { cancelClose(); closeTimer.current = setTimeout(() => setOpen(false), 140); };
179
- useEffect(() => cancelClose, []);
216
+
217
+ useEffect(() => () => {
218
+ if (intentTimer.current) clearTimeout(intentTimer.current);
219
+ if (closeTimer.current) clearTimeout(closeTimer.current);
220
+ }, []);
221
+
222
+ // 已经开着(点开 / 别的组让位 / 换了栏目)→ 清掉还没生效的意图
223
+ useEffect(() => {
224
+ if (open && intentTimer.current) { clearTimeout(intentTimer.current); intentTimer.current = null; }
225
+ }, [open]);
180
226
 
181
227
  useEffect(() => {
182
228
  if (!open) return undefined;
183
- const onDown = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
184
- const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
229
+ const onDown = (e) => { if (ref.current && !ref.current.contains(e.target)) onClose(gi); };
230
+ const onKey = (e) => { if (e.key === 'Escape') onClose(gi); };
185
231
  document.addEventListener('pointerdown', onDown);
186
232
  document.addEventListener('keydown', onKey);
187
233
  return () => {
188
234
  document.removeEventListener('pointerdown', onDown);
189
235
  document.removeEventListener('keydown', onKey);
190
236
  };
191
- }, [open]);
237
+ }, [open, gi, onClose]);
192
238
 
193
239
  return (
194
240
  <span
195
241
  className="tab-group"
196
242
  ref={ref}
197
- onMouseEnter={openNow}
198
- onMouseLeave={closeSoon}
243
+ onMouseEnter={onEnter}
244
+ onMouseLeave={onLeave}
199
245
  >
200
246
  <button
201
247
  className={`tab ${active ? 'active' : ''}`}
202
248
  aria-expanded={open}
203
- onClick={openNow}
249
+ aria-haspopup="menu"
250
+ onClick={() => (open ? closeNow() : openNow())}
204
251
  title={`${group.title}:${sectionCount} 个栏目`}
205
252
  >
206
253
  {group.title}
@@ -214,7 +261,7 @@ function GroupTab({ group, currentId, onGo }) {
214
261
  key={s.id}
215
262
  role="menuitem"
216
263
  className={`tab-menu-row ${s.id === currentId ? 'current' : ''}`}
217
- onClick={() => { cancelClose(); setOpen(false); onGo(s.id); }}
264
+ onClick={() => { closeNow(); onGo(s.id); }}
218
265
  >
219
266
  <span className="grow nowrap">{s.title}</span>
220
267
  {typeof s.count === 'number' ? <span className="count">{s.count}</span> : null}
@@ -84,9 +84,13 @@ export function FileFieldControl({ def, value, onChange }) {
84
84
  // 附件多的时候不把表单撑长:默认只露 5 行,窗口内上下滚动;需要看全时一键展开
85
85
  const [expanded, setExpanded] = useState(false);
86
86
  const uploadRef = useRef(null);
87
+ // 附件库选择器:默认收起,点开才搜索 / 挑选(表单是给人填的,不是给人翻附件库的)
88
+ const [pickerOpen, setPickerOpen] = useState(false);
89
+ const [pickQuery, setPickQuery] = useState('');
87
90
  // dragenter/dragleave 在子元素间穿梭时会成对触发,用深度计数避免「还没离开就熄掉高亮」
88
91
  const dragDepth = useRef(0);
89
92
  const ids = toIds(value);
93
+ const idsKey = ids.join(',');
90
94
  const max = Number(def.maxItems) || 0;
91
95
  const full = max > 0 && ids.length >= max;
92
96
 
@@ -97,9 +101,37 @@ export function FileFieldControl({ def, value, onChange }) {
97
101
  }, []);
98
102
  useEffect(() => { load(true); }, [load]);
99
103
 
100
- const all = data?.files || [];
104
+ const all = useMemo(() => data?.files || [], [data]);
101
105
  const byId = (id) => all.find((f) => f.id === id) || null;
102
- const available = all.filter((f) => !ids.includes(f.id));
106
+ // 本字段还没挂的附件
107
+ const available = useMemo(
108
+ () => all.filter((f) => !idsKey.split(',').includes(f.id)),
109
+ [all, idsKey],
110
+ );
111
+ // **未引用优先**:附件中心刚导入、还没挂到任何条目的原件排在前面。
112
+ // 理由:选附件时最常要的正是「刚传的那几个」;已被别处引用的往后排,
113
+ // 仍然可选(同一个原件可以被多条条目共享)。
114
+ const ordered = useMemo(() => {
115
+ const free = [];
116
+ const used = [];
117
+ for (const f of available) (f.usedBy?.length ? used : free).push(f);
118
+ return [...free, ...used];
119
+ }, [available]);
120
+ // 关键字搜索:名称 / 备注 / 标签
121
+ const matched = useMemo(() => {
122
+ const q = pickQuery.trim().toLowerCase();
123
+ if (!q) return ordered;
124
+ return ordered.filter((f) => [f.name, f.note, ...(f.tags || [])]
125
+ .join('\n').toLowerCase().includes(q));
126
+ }, [ordered, pickQuery]);
127
+
128
+ // Esc 关掉选择器
129
+ useEffect(() => {
130
+ if (!pickerOpen) return undefined;
131
+ const onKey = (e) => { if (e.key === 'Escape') setPickerOpen(false); };
132
+ window.addEventListener('keydown', onKey);
133
+ return () => window.removeEventListener('keydown', onKey);
134
+ }, [pickerOpen]);
103
135
 
104
136
  const upload = guard(async (fileList) => {
105
137
  const picked = [...(fileList || [])];
@@ -175,10 +207,15 @@ export function FileFieldControl({ def, value, onChange }) {
175
207
  </div>
176
208
  ) : null}
177
209
  <div className="file-pick-row">
178
- <select value="" disabled={full || !available.length} onChange={(e) => add(e.target.value)}>
179
- <option value="">{available.length ? '(从附件库选一个,选中即追加)' : '(库里没有可再选的附件)'}</option>
180
- {available.map((f) => <option key={f.id} value={f.id}>{f.name}</option>)}
181
- </select>
210
+ <button
211
+ type="button"
212
+ className="btn small"
213
+ disabled={full || !available.length}
214
+ onClick={() => setPickerOpen((v) => !v)}
215
+ title="从附件库挑附件(可搜索;未引用的排在前面)"
216
+ >
217
+ 从附件库选…
218
+ </button>
182
219
  <button type="button" className="btn small" disabled={full} onClick={() => uploadRef.current?.click()}>上传文件</button>
183
220
  <button type="button" className="btn small ghost" onClick={() => { patchUi({ view: 'files' }); window.location.hash = '#/files'; }}>附件中心</button>
184
221
  <input
@@ -189,6 +226,36 @@ export function FileFieldControl({ def, value, onChange }) {
189
226
  onChange={(e) => { upload(e.target.files); e.target.value = ''; }}
190
227
  />
191
228
  </div>
229
+ {pickerOpen ? (
230
+ <div className="file-pick-panel">
231
+ <div className="file-pick-search">
232
+ <input
233
+ autoFocus
234
+ value={pickQuery}
235
+ placeholder="按名称 / 备注 / 标签搜索附件"
236
+ onChange={(e) => setPickQuery(e.target.value)}
237
+ />
238
+ <span className="hint nowrap">{matched.length} / {available.length}</span>
239
+ <button type="button" className="btn small ghost" onClick={() => setPickerOpen(false)}>关闭</button>
240
+ </div>
241
+ {matched.length ? (
242
+ <div className="file-pick-list">
243
+ {matched.map((f) => (
244
+ <button type="button" key={f.id} className="file-pick-item" onClick={() => add(f.id)} title="点击追加到本字段">
245
+ {f.isImage
246
+ ? <img src={f.url} alt="" />
247
+ : <span className="ext-badge" style={{ fontSize: 12, width: 34, textAlign: 'center' }}>{f.ext ? f.ext.slice(1).toUpperCase() : 'FILE'}</span>}
248
+ <span className="file-pick-name grow nowrap">{f.name}</span>
249
+ <span className="hint nowrap">{f.usedBy?.length ? `已被 ${f.usedBy.length} 处引用` : '未引用'}</span>
250
+ </button>
251
+ ))}
252
+ </div>
253
+ ) : (
254
+ <div className="hint pad">没有匹配的附件。换个关键字,或先「上传文件」。</div>
255
+ )}
256
+ <div className="hint pad">未引用的排在前面;点一行即追加到本字段(可连续点多个)。</div>
257
+ </div>
258
+ ) : null}
192
259
  {full ? <span className="hint">已达上限({max} 个):先移除一个,或把字段的 maxItems 调大。</span> : null}
193
260
  {def.hint ? <span className="hint">{def.hint}</span> : null}
194
261
  </div>