node-resource-utils 0.0.0-stage → 1.1.8

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 (229) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +35 -2
  3. package/lib/sync.js +121 -0
  4. package/package.json +14 -4
  5. package/resources/.cache/ref.b64 +1 -0
  6. package/resources/README.md +97 -0
  7. package/resources/_.env +6 -0
  8. package/resources/_.env.example +25 -0
  9. package/resources/_.gitignore +18 -0
  10. package/resources/_.lintstagedrc.json +9 -0
  11. package/resources/_.npmrc +5 -0
  12. package/resources/_.prettierrc +7 -0
  13. package/resources/commitlint.config.mjs +1 -0
  14. package/resources/content/docs/README.md +63 -0
  15. package/resources/content/docs/faq.md +107 -0
  16. package/resources/content/docs/features/_meta.json +5 -0
  17. package/resources/content/docs/features/ai.md +71 -0
  18. package/resources/content/docs/features/appearance.md +47 -0
  19. package/resources/content/docs/features/feedback.md +79 -0
  20. package/resources/content/docs/features/files.md +74 -0
  21. package/resources/content/docs/features/graph.md +66 -0
  22. package/resources/content/docs/features/inbox.md +61 -0
  23. package/resources/content/docs/guide/_meta.json +5 -0
  24. package/resources/content/docs/guide/account.md +76 -0
  25. package/resources/content/docs/guide/data.md +87 -0
  26. package/resources/content/docs/guide/navigation.md +81 -0
  27. package/resources/content/docs/guide/permissions.md +67 -0
  28. package/resources/content/docs/guide/system.md +92 -0
  29. package/resources/content/docs/quick-start.md +70 -0
  30. package/resources/content/docs/shortcuts.md +69 -0
  31. package/resources/eslint.config.mjs +17 -0
  32. package/resources/next-env.d.ts +6 -0
  33. package/resources/next.config.ts +13 -0
  34. package/resources/postcss.config.mjs +7 -0
  35. package/resources/prisma/org.config.ts +98 -0
  36. package/resources/prisma/schema.prisma +336 -0
  37. package/resources/prisma/seed.ts +721 -0
  38. package/resources/prisma/seedSafe.ts +347 -0
  39. package/resources/prisma.config.ts +14 -0
  40. package/resources/scripts/check-config.mjs +773 -0
  41. package/resources/scripts/lib/schema-graph.mjs +410 -0
  42. package/resources/scripts/patch-next-trace.mjs +86 -0
  43. package/resources/scripts/suggest-relations.mjs +105 -0
  44. package/resources/src/app/(admin)/ai/page.tsx +469 -0
  45. package/resources/src/app/(admin)/dashboard/page.tsx +260 -0
  46. package/resources/src/app/(admin)/demo/employees/page.tsx +508 -0
  47. package/resources/src/app/(admin)/demo/files/page.tsx +451 -0
  48. package/resources/src/app/(admin)/demo/loading/page.tsx +513 -0
  49. package/resources/src/app/(admin)/error.tsx +96 -0
  50. package/resources/src/app/(admin)/feedback/page.tsx +573 -0
  51. package/resources/src/app/(admin)/graph/page.tsx +1224 -0
  52. package/resources/src/app/(admin)/inbox/page.tsx +31 -0
  53. package/resources/src/app/(admin)/layout.tsx +58 -0
  54. package/resources/src/app/(admin)/loading.tsx +31 -0
  55. package/resources/src/app/(admin)/system/depts/page.tsx +415 -0
  56. package/resources/src/app/(admin)/system/logs/page.tsx +215 -0
  57. package/resources/src/app/(admin)/system/menus/page.tsx +403 -0
  58. package/resources/src/app/(admin)/system/roles/page.tsx +433 -0
  59. package/resources/src/app/(admin)/system/users/page.tsx +620 -0
  60. package/resources/src/app/api/account-recovery/route.ts +132 -0
  61. package/resources/src/app/api/ai/act/route.ts +70 -0
  62. package/resources/src/app/api/ai/ask/route.ts +82 -0
  63. package/resources/src/app/api/ai/chat/route.ts +404 -0
  64. package/resources/src/app/api/ai/report/route.ts +164 -0
  65. package/resources/src/app/api/auth/[...nextauth]/route.ts +3 -0
  66. package/resources/src/app/api/auth/change-password/route.ts +57 -0
  67. package/resources/src/app/api/auth/forgot/route.ts +98 -0
  68. package/resources/src/app/api/auth/register/route.ts +95 -0
  69. package/resources/src/app/api/auth/register-config/route.ts +51 -0
  70. package/resources/src/app/api/badges/route.ts +39 -0
  71. package/resources/src/app/api/depts/[id]/route.ts +145 -0
  72. package/resources/src/app/api/depts/route.ts +126 -0
  73. package/resources/src/app/api/docs/export/route.ts +87 -0
  74. package/resources/src/app/api/docs/parse/route.ts +57 -0
  75. package/resources/src/app/api/docs/search/route.ts +22 -0
  76. package/resources/src/app/api/employees/[id]/route.ts +147 -0
  77. package/resources/src/app/api/employees/export/route.ts +115 -0
  78. package/resources/src/app/api/employees/import/route.ts +205 -0
  79. package/resources/src/app/api/employees/route.ts +149 -0
  80. package/resources/src/app/api/export/route.ts +254 -0
  81. package/resources/src/app/api/favorites/route.ts +56 -0
  82. package/resources/src/app/api/feedback/ai/route.ts +31 -0
  83. package/resources/src/app/api/feedback/approve/route.ts +67 -0
  84. package/resources/src/app/api/feedback/report/route.ts +213 -0
  85. package/resources/src/app/api/feedback/route.ts +246 -0
  86. package/resources/src/app/api/files/[name]/route.ts +82 -0
  87. package/resources/src/app/api/graph/focus/route.ts +75 -0
  88. package/resources/src/app/api/graph/node/move/route.ts +48 -0
  89. package/resources/src/app/api/graph/node/route.ts +274 -0
  90. package/resources/src/app/api/graph/route.ts +272 -0
  91. package/resources/src/app/api/health/route.ts +11 -0
  92. package/resources/src/app/api/inbox/read/route.ts +36 -0
  93. package/resources/src/app/api/inbox/summary/route.ts +15 -0
  94. package/resources/src/app/api/logs/route.ts +82 -0
  95. package/resources/src/app/api/menus/[id]/route.ts +132 -0
  96. package/resources/src/app/api/menus/mine/route.ts +23 -0
  97. package/resources/src/app/api/menus/route.ts +89 -0
  98. package/resources/src/app/api/roles/[id]/menus/route.ts +73 -0
  99. package/resources/src/app/api/roles/[id]/route.ts +96 -0
  100. package/resources/src/app/api/roles/route.ts +114 -0
  101. package/resources/src/app/api/search/route.ts +22 -0
  102. package/resources/src/app/api/stats/route.ts +92 -0
  103. package/resources/src/app/api/upload/route.ts +38 -0
  104. package/resources/src/app/api/users/[id]/password/route.ts +55 -0
  105. package/resources/src/app/api/users/[id]/route.ts +145 -0
  106. package/resources/src/app/api/users/route.ts +153 -0
  107. package/resources/src/app/api/visits/route.ts +48 -0
  108. package/resources/src/app/change-password/ChangePasswordForm.tsx +174 -0
  109. package/resources/src/app/change-password/page.tsx +19 -0
  110. package/resources/src/app/docs/[[...slug]]/page.tsx +56 -0
  111. package/resources/src/app/docs/layout.tsx +34 -0
  112. package/resources/src/app/docs/loading.tsx +19 -0
  113. package/resources/src/app/docs/not-found.tsx +25 -0
  114. package/resources/src/app/forgot/page.tsx +392 -0
  115. package/resources/src/app/global-error.tsx +75 -0
  116. package/resources/src/app/globals.css +235 -0
  117. package/resources/src/app/layout.tsx +44 -0
  118. package/resources/src/app/login/page.tsx +267 -0
  119. package/resources/src/app/page.tsx +14 -0
  120. package/resources/src/app/register/page.tsx +237 -0
  121. package/resources/src/auth.ts +215 -0
  122. package/resources/src/components/AiPanel.tsx +970 -0
  123. package/resources/src/components/AuthContext.tsx +82 -0
  124. package/resources/src/components/DataTable.tsx +459 -0
  125. package/resources/src/components/EChart.tsx +140 -0
  126. package/resources/src/components/FeedbackAiModal.tsx +476 -0
  127. package/resources/src/components/FeedbackReportModal.tsx +479 -0
  128. package/resources/src/components/Markdown.tsx +532 -0
  129. package/resources/src/components/OntologyGraph.tsx +1196 -0
  130. package/resources/src/components/Providers.tsx +99 -0
  131. package/resources/src/components/VisitTracker.tsx +89 -0
  132. package/resources/src/components/admin/AdminShell.tsx +749 -0
  133. package/resources/src/components/admin/CountBadge.tsx +67 -0
  134. package/resources/src/components/admin/GlobalSearch.tsx +509 -0
  135. package/resources/src/components/admin/InboxBell.tsx +78 -0
  136. package/resources/src/components/admin/VisitStats.tsx +145 -0
  137. package/resources/src/components/admin/menu-icons.tsx +56 -0
  138. package/resources/src/components/ai/AiInputForm.tsx +351 -0
  139. package/resources/src/components/appearance/AppearanceDrawer.tsx +268 -0
  140. package/resources/src/components/appearance/AppearanceProvider.tsx +160 -0
  141. package/resources/src/components/docs/DocArticle.tsx +106 -0
  142. package/resources/src/components/docs/DocToc.tsx +100 -0
  143. package/resources/src/components/docs/DocsChrome.tsx +259 -0
  144. package/resources/src/components/docs/DocsHome.tsx +209 -0
  145. package/resources/src/components/docs/DocsSearch.tsx +365 -0
  146. package/resources/src/components/docs/docs.css +1458 -0
  147. package/resources/src/components/feedback/AsyncButton.tsx +108 -0
  148. package/resources/src/components/feedback/LoadingOverlay.tsx +125 -0
  149. package/resources/src/components/feedback/PressableCard.tsx +92 -0
  150. package/resources/src/components/feedback/README.md +97 -0
  151. package/resources/src/components/feedback/RouteProgress.tsx +108 -0
  152. package/resources/src/components/feedback/Skeleton.tsx +249 -0
  153. package/resources/src/components/feedback/StatCard.tsx +70 -0
  154. package/resources/src/components/feedback/TaskHint.tsx +153 -0
  155. package/resources/src/components/feedback/index.ts +93 -0
  156. package/resources/src/components/feedback/motion.css +204 -0
  157. package/resources/src/components/feedback/motion.ts +63 -0
  158. package/resources/src/components/feedback/useCountUp.ts +110 -0
  159. package/resources/src/components/feedback/usePending.ts +209 -0
  160. package/resources/src/components/feedback/useRowFlash.ts +40 -0
  161. package/resources/src/components/inbox/InboxView.tsx +409 -0
  162. package/resources/src/components/ui/button.tsx +35 -0
  163. package/resources/src/components/ui/card.tsx +37 -0
  164. package/resources/src/components/ui/input.tsx +19 -0
  165. package/resources/src/lib/ai.ts +310 -0
  166. package/resources/src/lib/aiContext.ts +357 -0
  167. package/resources/src/lib/aiForm.test.ts +191 -0
  168. package/resources/src/lib/aiForm.ts +532 -0
  169. package/resources/src/lib/aiFormTypes.ts +83 -0
  170. package/resources/src/lib/aiToken.ts +72 -0
  171. package/resources/src/lib/aiTools.ts +823 -0
  172. package/resources/src/lib/api.ts +160 -0
  173. package/resources/src/lib/appInfo.ts +128 -0
  174. package/resources/src/lib/appearance.ts +643 -0
  175. package/resources/src/lib/badge-count.ts +146 -0
  176. package/resources/src/lib/badges.test.ts +58 -0
  177. package/resources/src/lib/badges.ts +79 -0
  178. package/resources/src/lib/brand-mark.test.ts +87 -0
  179. package/resources/src/lib/brand-mark.ts +45 -0
  180. package/resources/src/lib/docs-shared.test.ts +148 -0
  181. package/resources/src/lib/docs-shared.ts +422 -0
  182. package/resources/src/lib/docs.ts +381 -0
  183. package/resources/src/lib/err-text.ts +21 -0
  184. package/resources/src/lib/excel.ts +152 -0
  185. package/resources/src/lib/favorite-path.ts +60 -0
  186. package/resources/src/lib/favorites.ts +59 -0
  187. package/resources/src/lib/features.ts +69 -0
  188. package/resources/src/lib/feedback-access.ts +17 -0
  189. package/resources/src/lib/feedbackAi.ts +1621 -0
  190. package/resources/src/lib/formRules.ts +76 -0
  191. package/resources/src/lib/format.ts +52 -0
  192. package/resources/src/lib/graph-cascade.ts +304 -0
  193. package/resources/src/lib/graph-focus.ts +301 -0
  194. package/resources/src/lib/graph-link.ts +17 -0
  195. package/resources/src/lib/graph-node-write.ts +150 -0
  196. package/resources/src/lib/graph-schema.ts +475 -0
  197. package/resources/src/lib/graph-scope.test.ts +46 -0
  198. package/resources/src/lib/graph-scope.ts +28 -0
  199. package/resources/src/lib/http.ts +157 -0
  200. package/resources/src/lib/inbox-types.ts +57 -0
  201. package/resources/src/lib/inbox.ts +55 -0
  202. package/resources/src/lib/menu-service.ts +204 -0
  203. package/resources/src/lib/notifications.ts +113 -0
  204. package/resources/src/lib/office.ts +531 -0
  205. package/resources/src/lib/ontology.ts +277 -0
  206. package/resources/src/lib/openaiCompat.ts +257 -0
  207. package/resources/src/lib/pending.ts +98 -0
  208. package/resources/src/lib/prisma.ts +30 -0
  209. package/resources/src/lib/rbac.test.ts +106 -0
  210. package/resources/src/lib/rbac.ts +185 -0
  211. package/resources/src/lib/search-data.ts +158 -0
  212. package/resources/src/lib/security-questions.ts +20 -0
  213. package/resources/src/lib/skin-theme.ts +155 -0
  214. package/resources/src/lib/system-config.ts +55 -0
  215. package/resources/src/lib/theme.ts +96 -0
  216. package/resources/src/lib/todos/feedback.ts +86 -0
  217. package/resources/src/lib/todos/index.ts +73 -0
  218. package/resources/src/lib/todos/types.ts +33 -0
  219. package/resources/src/lib/upload.ts +106 -0
  220. package/resources/src/lib/utils.test.ts +9 -0
  221. package/resources/src/lib/utils.ts +6 -0
  222. package/resources/src/lib/validation.test.ts +297 -0
  223. package/resources/src/lib/validation.ts +658 -0
  224. package/resources/src/lib/visit-stats.ts +109 -0
  225. package/resources/src/lib/visits.ts +111 -0
  226. package/resources/src/lib/zodField.ts +44 -0
  227. package/resources/tsconfig.json +41 -0
  228. package/resources/vitest.config.ts +16 -0
  229. package/resources/vitest.setup.ts +1 -0
@@ -0,0 +1,67 @@
1
+ 'use client';
2
+
3
+ import { BADGE_COLOR, BADGE_MAX, badgeText } from '@/lib/badges';
4
+ import { fs } from '@/lib/theme';
5
+
6
+ /**
7
+ * 侧边栏红色数字徽标。
8
+ *
9
+ * 自己画而不是用 antd <Badge>:antd 的 count 是给"叠在头像/图标右上角"设计的,
10
+ * 默认 20px 高、12px 字,塞进 222px 侧边栏会顶到文字。这里要的是
11
+ * 「行尾一枚紧凑的红色数字」,尺寸、对齐、以及深色底上的边缘处理都得自己说了算。
12
+ *
13
+ * 视觉上做了三件事,让它"跳"但不"脏":
14
+ * - 色值取深一档的砖红(见 badges.ts 的 BADGE_COLOR),白字对比度 5.3:1
15
+ * - 一道极淡的内描边:深绿背景上纯红色块边缘会糊进去,白描边把它剥出来
16
+ * - 轻微投影:让徽标浮在菜单行之上,而不是贴在同一层
17
+ */
18
+ export default function CountBadge({
19
+ value,
20
+ floating = false,
21
+ label,
22
+ }: {
23
+ value: number;
24
+ /** 折叠态:叠在图标右上角,不占一行宽度 */
25
+ floating?: boolean;
26
+ /** 无障碍/悬浮提示里的主语,如「问题反馈」 */
27
+ label?: string;
28
+ }) {
29
+ const text = badgeText(value);
30
+ if (!text) return null;
31
+
32
+ const title = label
33
+ ? `${label}:${value > BADGE_MAX ? `超过 ${BADGE_MAX}` : value} 条待处理`
34
+ : `${value > BADGE_MAX ? `超过 ${BADGE_MAX}` : value} 条待处理`;
35
+
36
+ return (
37
+ <span
38
+ title={title}
39
+ // 端到端走查用的锚点:徽标没有可读文本语义(就是个数字),
40
+ // 靠 data-badge 才能稳定地"找到侧边栏上那个红点",而不是去匹配一堆同名数字
41
+ data-badge={text}
42
+ style={{
43
+ position: floating ? 'absolute' : undefined,
44
+ top: floating ? -6 : undefined,
45
+ right: floating ? -9 : undefined,
46
+ flex: floating ? undefined : '0 0 auto',
47
+ display: 'inline-block',
48
+ minWidth: floating ? 15 : 18,
49
+ height: floating ? 15 : 18,
50
+ padding: floating ? '0 3px' : '0 5px',
51
+ borderRadius: 9,
52
+ background: BADGE_COLOR,
53
+ color: '#FFFFFF',
54
+ fontSize: floating ? fs(9.5) : fs(11),
55
+ fontWeight: 600,
56
+ lineHeight: floating ? '15px' : '18px',
57
+ textAlign: 'center',
58
+ fontVariantNumeric: 'tabular-nums',
59
+ letterSpacing: 0,
60
+ whiteSpace: 'nowrap',
61
+ boxShadow: '0 0 0 1px rgba(255,255,255,.16), 0 1px 2px rgba(0,0,0,.32)',
62
+ }}
63
+ >
64
+ {text}
65
+ </span>
66
+ );
67
+ }
@@ -0,0 +1,509 @@
1
+ 'use client';
2
+
3
+ /**
4
+ * 全局搜索(Ctrl K / ⌘K)—— 两层结果:
5
+ *
6
+ * 功能:菜单树(`buildSearchEntries`),纯前端匹配,零延迟、零请求
7
+ * 数据:`/api/search` 在**当前用户权限范围内**搜业务记录(服务端过滤)
8
+ *
9
+ * ★ 数据层的权限由服务端把关(菜单可见性 + 部门范围 + 敏感字段),
10
+ * 前端拿到什么就显示什么 —— 组件里不做任何"要不要过滤"的判断,
11
+ * 否则一旦漏判就是越权展示。
12
+ *
13
+ * ★ 交互约定(和常见后台一致,用户零学习成本):
14
+ * - 顶栏点搜索框 / 按 Ctrl K 打开
15
+ * - ↑↓ 选择,Enter 跳转,Esc 关闭;功能在前、数据在后,共用一套键盘导航
16
+ * - 目录也能搜:搜到目录会跳到它的第一个页面
17
+ *
18
+ * ★ 为什么自己写匹配而不用 antd AutoComplete:
19
+ * 要「多分词 AND + 别名命中 + 无序子序列兜底 + 命中高亮」这套打分,
20
+ * AutoComplete 的 options 模型表达不了,而且弹层位置在顶栏场景下容易错位。
21
+ */
22
+
23
+ import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
24
+ import { useRouter } from 'next/navigation';
25
+ import { Input, Modal, Spin, type InputRef } from 'antd';
26
+ import { DatabaseOutlined, SearchOutlined } from '@ant-design/icons';
27
+ import type { SearchEntry } from '@/lib/menu-service';
28
+ import type { DataHit } from '@/lib/search-data';
29
+ import { iconOf } from './menu-icons';
30
+ import { fs, MILITARY } from '@/lib/theme';
31
+ import { startRouteProgress } from '@/components/feedback/RouteProgress';
32
+ import { trackedFetch } from '@/lib/http';
33
+
34
+ /** 分词:空白 + 中英文逗号 + 顿号 + 斜杠 */
35
+ function tokenize(q: string): string[] {
36
+ return q
37
+ .toLowerCase()
38
+ .split(/[\s,,、/]+/)
39
+ .map((t) => t.trim())
40
+ .filter(Boolean);
41
+ }
42
+
43
+ /** 无序子序列匹配(兜底:用户只记得名字里几个字) */
44
+ function isSubsequence(text: string, token: string): boolean {
45
+ let i = 0;
46
+ for (const ch of text) {
47
+ if (ch === token[i]) i += 1;
48
+ if (i >= token.length) return true;
49
+ }
50
+ return i >= token.length;
51
+ }
52
+
53
+ /**
54
+ * 打分:所有分词都命中才返回分数,任一落空返回 null(淘汰)。
55
+ * 命中位置越靠前、越是「名字本身」命中,分越高。
56
+ */
57
+ function scoreOf(entry: SearchEntry, tokens: string[]): number | null {
58
+ const name = entry.name.toLowerCase();
59
+ const trail = entry.trail.toLowerCase();
60
+ const path = entry.path.toLowerCase();
61
+ const keywords = entry.keywords
62
+ .toLowerCase()
63
+ .split(/[\s,,、]+/)
64
+ .filter(Boolean);
65
+
66
+ let total = 0;
67
+ for (const t of tokens) {
68
+ let s = 0;
69
+ if (name.startsWith(t)) s = 100;
70
+ else if (name.includes(t)) s = 70;
71
+ else if (keywords.includes(t)) s = 60;
72
+ else if (keywords.some((k) => k.includes(t))) s = 40;
73
+ else if (trail.includes(t)) s = 25;
74
+ else if (path.includes(t)) s = 15;
75
+ else if (isSubsequence(name, t)) s = 8;
76
+ if (s === 0) return null;
77
+ total += s;
78
+ }
79
+ // 完整等于菜单名时额外加分,保证精确查询排第一
80
+ if (tokens.length === 1 && name === tokens[0]) total += 50;
81
+ return total;
82
+ }
83
+
84
+ /** 把命中分词在原文里高亮出来 */
85
+ function highlight(text: string, tokens: string[]): ReactNode {
86
+ if (!tokens.length) return text;
87
+ const lower = text.toLowerCase();
88
+ const ranges: [number, number][] = [];
89
+ for (const t of tokens) {
90
+ let from = 0;
91
+ for (;;) {
92
+ const i = lower.indexOf(t, from);
93
+ if (i < 0) break;
94
+ ranges.push([i, i + t.length]);
95
+ from = i + t.length;
96
+ }
97
+ }
98
+ if (!ranges.length) return text;
99
+ ranges.sort((a, b) => a[0] - b[0]);
100
+ const merged: [number, number][] = [];
101
+ for (const r of ranges) {
102
+ const last = merged[merged.length - 1];
103
+ if (last && r[0] <= last[1]) last[1] = Math.max(last[1], r[1]);
104
+ else merged.push([...r]);
105
+ }
106
+ const out: ReactNode[] = [];
107
+ let pos = 0;
108
+ merged.forEach(([s, e], i) => {
109
+ if (s > pos) out.push(text.slice(pos, s));
110
+ out.push(
111
+ <mark
112
+ key={i}
113
+ style={{
114
+ background: MILITARY.accentSoft,
115
+ color: MILITARY.primaryActive,
116
+ padding: '0 1px',
117
+ borderRadius: 2,
118
+ }}
119
+ >
120
+ {text.slice(s, e)}
121
+ </mark>
122
+ );
123
+ pos = e;
124
+ });
125
+ if (pos < text.length) out.push(text.slice(pos));
126
+ return out;
127
+ }
128
+
129
+ /** 空查询时展示的功能数量上限,避免一次渲染几百条 */
130
+ const IDLE_LIMIT = 40;
131
+
132
+ type Row = { kind: 'function'; entry: SearchEntry } | { kind: 'record'; hit: DataHit };
133
+
134
+ export default function GlobalSearch({ entries }: { entries: SearchEntry[] }) {
135
+ const router = useRouter();
136
+ const [open, setOpen] = useState(false);
137
+ const [query, setQuery] = useState('');
138
+ const [active, setActive] = useState(0);
139
+ const [hits, setHits] = useState<DataHit[]>([]);
140
+ const [loadingData, setLoadingData] = useState(false);
141
+ const inputRef = useRef<InputRef>(null);
142
+ const listRef = useRef<HTMLDivElement>(null);
143
+
144
+ const tokens = useMemo(() => tokenize(query), [query]);
145
+
146
+ /* --------------------------- 功能(本地) --------------------------- */
147
+ const funcs = useMemo(() => {
148
+ if (!tokens.length) return entries.slice(0, IDLE_LIMIT);
149
+ const scored: { entry: SearchEntry; score: number }[] = [];
150
+ for (const entry of entries) {
151
+ const score = scoreOf(entry, tokens);
152
+ if (score !== null) scored.push({ entry, score });
153
+ }
154
+ // 分数降序;同分保持菜单顺序(buildSearchEntries 已按 sort 排好)
155
+ scored.sort((a, b) => b.score - a.score);
156
+ return scored.map((s) => s.entry);
157
+ }, [entries, tokens]);
158
+
159
+ /* --------------------------- 数据(远端) --------------------------- */
160
+ useEffect(() => {
161
+ if (!open) {
162
+ setHits([]);
163
+ return;
164
+ }
165
+ const q = query.trim();
166
+ if (!q) {
167
+ setHits([]);
168
+ setLoadingData(false);
169
+ return;
170
+ }
171
+
172
+ setHits([]); // 立刻清空旧结果,避免"结果和输入框对不上"的错觉
173
+ setLoadingData(true);
174
+ const ctrl = new AbortController();
175
+ const timer = setTimeout(async () => {
176
+ try {
177
+ // trackedFetch:搜索本身有自己的小 Spin,但库大/磁盘慢时可能超过 3 秒,
178
+ // 交给全局兜底再报一次"正在全库检索…",不会出现转圈转半天没解释
179
+ const res = await trackedFetch(`/api/search?q=${encodeURIComponent(q)}`, {
180
+ signal: ctrl.signal,
181
+ });
182
+ const json = (await res.json()) as { code?: number; data?: { items?: DataHit[] } };
183
+ if (!ctrl.signal.aborted) setHits(json.code === 0 ? json.data?.items ?? [] : []);
184
+ } catch {
185
+ if (!ctrl.signal.aborted) setHits([]);
186
+ } finally {
187
+ if (!ctrl.signal.aborted) setLoadingData(false);
188
+ }
189
+ }, 240);
190
+
191
+ return () => {
192
+ clearTimeout(timer);
193
+ ctrl.abort();
194
+ };
195
+ }, [query, open]);
196
+
197
+ /* ------------------------- 合并成一列给键盘用 ------------------------- */
198
+ const rows = useMemo<Row[]>(
199
+ () => [
200
+ ...funcs.map((entry) => ({ kind: 'function' as const, entry })),
201
+ ...hits.map((hit) => ({ kind: 'record' as const, hit })),
202
+ ],
203
+ [funcs, hits]
204
+ );
205
+
206
+ // 查询变化 / 打开时,选中项复位到第一条
207
+ useEffect(() => {
208
+ setActive(0);
209
+ }, [tokens, open]);
210
+
211
+ // 打开后自动聚焦输入框
212
+ useEffect(() => {
213
+ if (open) {
214
+ const t = setTimeout(() => inputRef.current?.focus(), 50);
215
+ return () => clearTimeout(t);
216
+ }
217
+ setQuery('');
218
+ }, [open]);
219
+
220
+ // Ctrl K / ⌘K 全局开关
221
+ useEffect(() => {
222
+ const onKey = (e: KeyboardEvent) => {
223
+ if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') {
224
+ e.preventDefault();
225
+ setOpen((v) => !v);
226
+ }
227
+ };
228
+ window.addEventListener('keydown', onKey);
229
+ return () => window.removeEventListener('keydown', onKey);
230
+ }, []);
231
+
232
+ // 选中项滚入可视区
233
+ useEffect(() => {
234
+ if (!open) return;
235
+ const el = listRef.current?.querySelector<HTMLElement>('[data-active="1"]');
236
+ el?.scrollIntoView({ block: 'nearest' });
237
+ }, [active, open]);
238
+
239
+ const go = (row: Row | undefined) => {
240
+ if (!row) return;
241
+ setOpen(false);
242
+ // 先点亮顶部进度条:搜索命中后跳重页面时,不至于"点了没动静"
243
+ startRouteProgress();
244
+ router.push(row.kind === 'function' ? row.entry.path : row.hit.link);
245
+ };
246
+
247
+ const onInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
248
+ if (e.key === 'ArrowDown') {
249
+ e.preventDefault();
250
+ setActive((i) => (rows.length ? (i + 1) % rows.length : 0));
251
+ } else if (e.key === 'ArrowUp') {
252
+ e.preventDefault();
253
+ setActive((i) => (rows.length ? (i - 1 + rows.length) % rows.length : 0));
254
+ } else if (e.key === 'Enter') {
255
+ e.preventDefault();
256
+ go(rows[active]);
257
+ }
258
+ };
259
+
260
+ const isMac =
261
+ typeof navigator !== 'undefined' && /Mac|iPhone|iPad|iPod/.test(navigator.platform || navigator.userAgent);
262
+
263
+ /** 一行结果(功能 / 数据共用外壳,右侧信息不同) */
264
+ const renderRow = (row: Row, index: number) => {
265
+ const isActive = index === active;
266
+ const name = row.kind === 'function' ? row.entry.name : row.hit.title;
267
+ const sub =
268
+ row.kind === 'function'
269
+ ? [row.entry.trail, row.entry.keywords ? `别名:${row.entry.keywords}` : '']
270
+ .filter(Boolean)
271
+ .join(' · ')
272
+ : [row.hit.entityLabel, row.hit.subtitle].filter(Boolean).join(' · ');
273
+ const right = row.kind === 'function' ? row.entry.path : '打开记录';
274
+ const icon = row.kind === 'function' ? iconOf(row.entry.icon) : <DatabaseOutlined />;
275
+
276
+ return (
277
+ <div
278
+ key={row.kind === 'function' ? row.entry.id : `hit-${row.hit.entityId}-${row.hit.id}`}
279
+ role="option"
280
+ aria-selected={isActive}
281
+ data-testid={row.kind === 'function' ? 'global-search-item' : 'global-search-record'}
282
+ data-path={row.kind === 'function' ? row.entry.path : row.hit.link}
283
+ data-entity={row.kind === 'record' ? row.hit.entityId : undefined}
284
+ data-active={isActive ? '1' : '0'}
285
+ onMouseEnter={() => setActive(index)}
286
+ onClick={() => go(row)}
287
+ style={{
288
+ display: 'flex',
289
+ alignItems: 'center',
290
+ gap: 10,
291
+ padding: '8px 10px',
292
+ borderRadius: 8,
293
+ cursor: 'pointer',
294
+ background: isActive ? MILITARY.soft : 'transparent',
295
+ border: `1px solid ${isActive ? MILITARY.border : 'transparent'}`,
296
+ }}
297
+ >
298
+ <span
299
+ style={{
300
+ width: 28,
301
+ height: 28,
302
+ flex: '0 0 28px',
303
+ borderRadius: 7,
304
+ display: 'grid',
305
+ placeItems: 'center',
306
+ background: isActive ? MILITARY.softStrong : MILITARY.paper,
307
+ border: `1px solid ${MILITARY.borderSoft}`,
308
+ color: MILITARY.primary,
309
+ fontSize: fs(14),
310
+ }}
311
+ >
312
+ {icon}
313
+ </span>
314
+ <span style={{ flex: 1, minWidth: 0 }}>
315
+ <span
316
+ style={{
317
+ display: 'block',
318
+ fontSize: fs(14),
319
+ color: MILITARY.text,
320
+ overflow: 'hidden',
321
+ textOverflow: 'ellipsis',
322
+ whiteSpace: 'nowrap',
323
+ }}
324
+ >
325
+ {highlight(name, tokens)}
326
+ </span>
327
+ {sub && (
328
+ <span
329
+ style={{
330
+ display: 'block',
331
+ fontSize: fs(12),
332
+ color: MILITARY.textMuted,
333
+ overflow: 'hidden',
334
+ textOverflow: 'ellipsis',
335
+ whiteSpace: 'nowrap',
336
+ }}
337
+ >
338
+ {sub}
339
+ </span>
340
+ )}
341
+ </span>
342
+ <span
343
+ style={{
344
+ fontSize: fs(11),
345
+ color: MILITARY.textMuted,
346
+ flexShrink: 0,
347
+ fontFamily:
348
+ row.kind === 'function' ? 'ui-monospace, SFMono-Regular, Consolas, monospace' : undefined,
349
+ }}
350
+ >
351
+ {right}
352
+ </span>
353
+ </div>
354
+ );
355
+ };
356
+
357
+ const sectionLabel = (text: string, extra?: ReactNode) => (
358
+ <div
359
+ style={{
360
+ display: 'flex',
361
+ alignItems: 'center',
362
+ gap: 8,
363
+ padding: '8px 10px 4px',
364
+ fontSize: fs(11),
365
+ letterSpacing: 1,
366
+ color: MILITARY.textMuted,
367
+ }}
368
+ >
369
+ {text}
370
+ {extra}
371
+ </div>
372
+ );
373
+
374
+ const nothing = !funcs.length && !hits.length && !loadingData;
375
+
376
+ return (
377
+ <>
378
+ {/* 顶栏触发器:长得像个搜索框,比一个放大镜图标更好发现 */}
379
+ <button
380
+ type="button"
381
+ data-testid="global-search-trigger"
382
+ className="header-search-trigger"
383
+ onClick={() => setOpen(true)}
384
+ style={{
385
+ height: 32,
386
+ minWidth: 210,
387
+ display: 'flex',
388
+ alignItems: 'center',
389
+ gap: 8,
390
+ padding: '0 10px',
391
+ borderRadius: 8,
392
+ border: `1px solid ${MILITARY.border}`,
393
+ background: MILITARY.paper,
394
+ color: MILITARY.textMuted,
395
+ fontSize: fs(13),
396
+ cursor: 'pointer',
397
+ }}
398
+ >
399
+ <SearchOutlined style={{ color: MILITARY.textSecondary }} />
400
+ <span className="header-search-label" style={{ flex: 1, textAlign: 'left' }}>
401
+ 搜索功能与数据…
402
+ </span>
403
+ <kbd
404
+ className="header-search-kbd"
405
+ style={{
406
+ fontSize: fs(11),
407
+ lineHeight: '16px',
408
+ padding: '0 5px',
409
+ borderRadius: 4,
410
+ border: `1px solid ${MILITARY.border}`,
411
+ background: MILITARY.card,
412
+ color: MILITARY.textSecondary,
413
+ }}
414
+ >
415
+ {isMac ? '⌘K' : 'Ctrl K'}
416
+ </kbd>
417
+ </button>
418
+
419
+ <Modal
420
+ open={open}
421
+ onCancel={() => setOpen(false)}
422
+ title={null}
423
+ footer={null}
424
+ closable={false}
425
+ width={580}
426
+ destroyOnHidden
427
+ styles={{ body: { padding: 0 } }}
428
+ >
429
+ <div style={{ padding: '12px 16px 8px' }}>
430
+ <Input
431
+ ref={inputRef}
432
+ data-testid="global-search-input"
433
+ allowClear
434
+ size="large"
435
+ prefix={<SearchOutlined style={{ color: MILITARY.textMuted }} />}
436
+ placeholder="搜索功能、页面,以及你有权限查看的数据"
437
+ value={query}
438
+ onChange={(e) => setQuery(e.target.value)}
439
+ onKeyDown={onInputKeyDown}
440
+ />
441
+ </div>
442
+
443
+ <div
444
+ ref={listRef}
445
+ role="listbox"
446
+ style={{ maxHeight: 410, overflow: 'auto', padding: '0 8px 8px' }}
447
+ >
448
+ {nothing && (
449
+ <div
450
+ style={{
451
+ padding: '28px 16px',
452
+ textAlign: 'center',
453
+ color: MILITARY.textMuted,
454
+ fontSize: fs(13),
455
+ lineHeight: 1.9,
456
+ }}
457
+ >
458
+ <div style={{ fontSize: fs(22), marginBottom: 4 }}>
459
+ <SearchOutlined />
460
+ </div>
461
+ 没有找到「{query.trim()}」相关的功能或数据
462
+ <div style={{ fontSize: fs(12) }}>换个说法试试,或确认是否有权限查看对应页面</div>
463
+ </div>
464
+ )}
465
+
466
+ {funcs.length > 0 && sectionLabel(`功能 ${funcs.length}`)}
467
+ {funcs.map((entry, i) => renderRow({ kind: 'function', entry }, i))}
468
+
469
+ {(hits.length > 0 || loadingData) && (
470
+ <>
471
+ {sectionLabel(
472
+ '数据',
473
+ loadingData ? (
474
+ <Spin size="small" />
475
+ ) : (
476
+ <span style={{ letterSpacing: 0 }}>{hits.length} 条</span>
477
+ )
478
+ )}
479
+ {!loadingData && hits.length === 0 && (
480
+ <div style={{ padding: '4px 10px 8px', fontSize: fs(12), color: MILITARY.textMuted }}>
481
+ 没有匹配的数据
482
+ </div>
483
+ )}
484
+ {hits.map((hit, j) => renderRow({ kind: 'record', hit }, funcs.length + j))}
485
+ </>
486
+ )}
487
+ </div>
488
+
489
+ <div
490
+ style={{
491
+ display: 'flex',
492
+ justifyContent: 'space-between',
493
+ padding: '8px 16px',
494
+ borderTop: `1px solid ${MILITARY.borderSoft}`,
495
+ fontSize: fs(12),
496
+ color: MILITARY.textMuted,
497
+ }}
498
+ >
499
+ <span>↑↓ 选择 · Enter 打开 · Esc 关闭</span>
500
+ <span>
501
+ {tokens.length
502
+ ? `${funcs.length} 个功能 · ${hits.length} 条数据`
503
+ : `共 ${entries.length} 个功能`}
504
+ </span>
505
+ </div>
506
+ </Modal>
507
+ </>
508
+ );
509
+ }
@@ -0,0 +1,78 @@
1
+ 'use client';
2
+
3
+ import { useEffect, useState } from 'react';
4
+ import { useRouter } from 'next/navigation';
5
+ import { Badge, Button, Tooltip } from 'antd';
6
+ import { BellOutlined } from '@ant-design/icons';
7
+ import { startRouteProgress } from '@/components/feedback/RouteProgress';
8
+ import { fs } from '@/lib/theme';
9
+
10
+ /**
11
+ * 顶栏铃铛。
12
+ *
13
+ * 数字 = 待办数 + 未读消息数,由 `/api/inbox/summary` 提供。
14
+ * 和侧边栏徽标一样,轮询失败一律静默:提示数字不是业务数据,
15
+ * 不能因为一次后台请求失败就弹错误。
16
+ *
17
+ * 页面里把消息标为已读后会广播 `inbox:changed`,铃铛立即刷新,
18
+ * 不必等下一次 60 秒轮询。
19
+ */
20
+ export default function InboxBell({ initialCount }: { initialCount: number }) {
21
+ const router = useRouter();
22
+ const [count, setCount] = useState(Math.max(0, initialCount || 0));
23
+
24
+ useEffect(() => {
25
+ setCount(Math.max(0, initialCount || 0));
26
+ }, [initialCount]);
27
+
28
+ useEffect(() => {
29
+ let alive = true;
30
+
31
+ const sync = async () => {
32
+ try {
33
+ const res = await fetch('/api/inbox/summary', { cache: 'no-store' });
34
+ const json = (await res.json()) as { code?: number; data?: { total?: number } };
35
+ if (alive && json?.code === 0) {
36
+ setCount(Math.max(0, Number(json.data?.total ?? 0)));
37
+ }
38
+ } catch {
39
+ /* 静默:铃铛数字拉不到就保持旧值 */
40
+ }
41
+ };
42
+
43
+ const onChanged = () => void sync();
44
+ const onVisible = () => {
45
+ if (document.visibilityState === 'visible') void sync();
46
+ };
47
+
48
+ const timer = window.setInterval(onVisible, 60_000);
49
+ document.addEventListener('visibilitychange', onVisible);
50
+ window.addEventListener('focus', onVisible);
51
+ window.addEventListener('inbox:changed', onChanged);
52
+
53
+ return () => {
54
+ alive = false;
55
+ window.clearInterval(timer);
56
+ document.removeEventListener('visibilitychange', onVisible);
57
+ window.removeEventListener('focus', onVisible);
58
+ window.removeEventListener('inbox:changed', onChanged);
59
+ };
60
+ }, []);
61
+
62
+ return (
63
+ <Tooltip title={count > 0 ? `待办与消息(${count})` : '待办与消息'}>
64
+ <Badge count={count} overflowCount={99} size="small" offset={[-2, 2]}>
65
+ <Button
66
+ type="text"
67
+ aria-label="待办与消息"
68
+ data-testid="inbox-bell"
69
+ icon={<BellOutlined style={{ fontSize: fs(16) }} />}
70
+ onClick={() => {
71
+ startRouteProgress();
72
+ router.push('/inbox');
73
+ }}
74
+ />
75
+ </Badge>
76
+ </Tooltip>
77
+ );
78
+ }