@ysgroup/core 0.1.26 → 0.1.28

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ysgroup/core",
3
- "version": "0.1.26",
3
+ "version": "0.1.28",
4
4
  "type": "module",
5
5
  "main": "src/index.ts",
6
6
  "types": "src/index.ts",
@@ -23,6 +23,6 @@
23
23
  "access": "public"
24
24
  },
25
25
  "devDependencies": {
26
- "@ysgroup/theme": "^0.2.6"
26
+ "@ysgroup/theme": "^0.3.1"
27
27
  }
28
28
  }
package/src/catalog.ts ADDED
@@ -0,0 +1,270 @@
1
+ /* @ysgroup/core —— 列表数据缓存骨架:把「查一次、缓存、收到推送再重拉」做成 Pinia store 工厂。
2
+ *
3
+ * 用法:
4
+ * export const useCatalogStore = createYsCatalog<{ schools: SchoolRow[]; roles: RoleRow[] }>({
5
+ * id: "template-catalog",
6
+ * tables: {
7
+ * schools: "query_schools",
8
+ * roles: { event: "query_user_roles", data: () => ({}) },
9
+ * },
10
+ * dirtyTables: (kind) => (kind === "users" ? ["roles"] : kind === "schools" ? ["schools"] : []),
11
+ * });
12
+ * const catalog = useCatalogStore();
13
+ * await catalog.ensure("schools", "roles"); // 页面进入时
14
+ * catalog.rows.schools; // 响应式行
15
+ * await catalog.refresh("schools"); // 保存后
16
+ * catalog.bind(); // 登录并连接后调用一次
17
+ * catalog.reset(); // 退出登录时
18
+ *
19
+ * 规则:
20
+ * - ensure 只在第一次(或上次失败、已知过期)时加载;同一张表的在途请求只发一次。
21
+ * - 收到 changeEvent 推送,只重拉已加载或在途的表;coalesceMs 内的多次推送合并成一轮。
22
+ * 推送到达时这张表正在请求,就等它回来再拉一次,不会堆出并发请求。
23
+ * - 重连(__connected)后把已加载、在途和上次加载失败的表补拉一次,同样合并。
24
+ * - 重拉期间旧行保留、loaded 不变,页面不闪;加载失败把文案写进 errors[表] 并向调用方抛出,行保持原样。
25
+ * - refresh 作废在途请求重新发;旧响应不会覆盖新状态,reset(退出登录)之后迟到的响应直接丢弃。
26
+ */
27
+ import { defineStore, type StoreDefinition } from "pinia";
28
+ import { reactive } from "vue";
29
+ import { formatError } from "./errors";
30
+ import { useYsStore } from "./store";
31
+
32
+ /** 一张表的查询:事件名,或事件名 + 每次查询时取的参数。 */
33
+ export type YsCatalogSource =
34
+ | string
35
+ | { event: string; data?: () => Record<string, unknown> };
36
+
37
+ type TableName<Tables> = Extract<keyof Tables, string>;
38
+
39
+ export interface YsCatalogOptions<Tables extends Record<string, unknown[]>> {
40
+ /** Pinia store id,全应用唯一。 */
41
+ id: string;
42
+ /** 每张表的查询事件;查询必须返回数组。 */
43
+ tables: { [K in keyof Tables]: YsCatalogSource };
44
+ /** 推送的 kind(和整条推送数据)→ 受影响的表。不传时重拉与 kind 同名的表。 */
45
+ dirtyTables?: (
46
+ kind: string,
47
+ payload: unknown,
48
+ ) => readonly TableName<Tables>[];
49
+ /** 数据变更推送的事件名,默认 business_changed;推送数据里的 kind 交给 dirtyTables。 */
50
+ changeEvent?: string;
51
+ /** 这段时间(毫秒)内的多次失效合并成一轮重拉,默认 150;0 表示立即重拉。 */
52
+ coalesceMs?: number;
53
+ }
54
+
55
+ export interface YsCatalogState<Tables> {
56
+ /** 每张表的行(响应式)。没加载或 reset 后是空数组,重拉期间保留旧行。 */
57
+ rows: Tables;
58
+ /** 这张表成功加载过(重拉期间保持 true,reset 后为 false)。 */
59
+ loaded: Record<TableName<Tables>, boolean>;
60
+ /** 这张表有请求在途。 */
61
+ loading: Record<TableName<Tables>, boolean>;
62
+ /** 最近一次加载失败的文案;成功后清空,空串表示没有错误。 */
63
+ errors: Record<TableName<Tables>, string>;
64
+ }
65
+
66
+ export interface YsCatalogActions<Tables> {
67
+ /** 需要这些表:没加载过(或上次失败、已知过期)才请求。失败时抛出,文案同时写进 errors。未登录时什么都不做。 */
68
+ ensure(...tables: TableName<Tables>[]): Promise<void>;
69
+ /** 立即重拉这些表(保存后调用):作废在途请求重新发。失败时抛出。不传表名什么都不做。 */
70
+ refresh(...tables: TableName<Tables>[]): Promise<void>;
71
+ /** 订阅数据变更推送和重连事件。登录并连接后调用;重复调用无影响。 */
72
+ bind(): void;
73
+ /** 退出登录时调用:清空数据和状态、取消订阅,在途请求的结果作废。 */
74
+ reset(): void;
75
+ }
76
+
77
+ export type YsCatalogStoreDefinition<Tables> = StoreDefinition<
78
+ string,
79
+ YsCatalogState<Tables>,
80
+ Record<never, never>,
81
+ YsCatalogActions<Tables>
82
+ >;
83
+
84
+ /** useCatalogStore() 的返回值类型。 */
85
+ export type YsCatalogStore<Tables> = ReturnType<
86
+ YsCatalogStoreDefinition<Tables>
87
+ >;
88
+
89
+ const DEFAULT_CHANGE_EVENT = "business_changed";
90
+ const DEFAULT_COALESCE_MS = 150;
91
+
92
+ export function createYsCatalog<Tables extends Record<string, unknown[]>>(
93
+ options: YsCatalogOptions<Tables>,
94
+ ): YsCatalogStoreDefinition<Tables> {
95
+ type Table = TableName<Tables>;
96
+ const names = Object.keys(options.tables) as Table[];
97
+ const changeEvent = options.changeEvent ?? DEFAULT_CHANGE_EVENT;
98
+ const coalesceMs = options.coalesceMs ?? DEFAULT_COALESCE_MS;
99
+
100
+ function perTable<T>(value: () => T): Record<Table, T> {
101
+ return Object.fromEntries(names.map((name) => [name, value()])) as Record<
102
+ Table,
103
+ T
104
+ >;
105
+ }
106
+
107
+ const useStore = defineStore(options.id, () => {
108
+ const ys = useYsStore();
109
+ const rows = reactive(perTable<unknown[]>(() => [])) as Tables;
110
+ const loaded = reactive(perTable(() => false)) as Record<Table, boolean>;
111
+ const loading = reactive(perTable(() => false)) as Record<Table, boolean>;
112
+ const errors = reactive(perTable(() => "")) as Record<Table, string>;
113
+
114
+ /** 每张表的请求代次:refresh、reset 时加一,回来的响应代次对不上就不写入。 */
115
+ const generation = perTable(() => 0);
116
+ const inflight = new Map<Table, Promise<void>>();
117
+ /** 已失效、等下一轮重拉的表。 */
118
+ const pending = new Set<Table>();
119
+ let timer: ReturnType<typeof setTimeout> | null = null;
120
+ let offChange: (() => void) | undefined;
121
+ let offConnected: (() => void) | undefined;
122
+
123
+ function known(table: string): table is Table {
124
+ return Object.prototype.hasOwnProperty.call(generation, table);
125
+ }
126
+
127
+ async function fetchRows(table: Table): Promise<unknown[]> {
128
+ if (!ys.connected) await ys.waitUntilConnected();
129
+ if (!ys.client() || !ys.accessToken) throw new Error("服务未连接");
130
+ const source = options.tables[table];
131
+ const event = typeof source === "string" ? source : source.event;
132
+ const data = typeof source === "string" ? {} : (source.data?.() ?? {});
133
+ const result = await ys.call<unknown>(event, data);
134
+ if (!Array.isArray(result)) throw new Error("返回的数据不是列表");
135
+ return result;
136
+ }
137
+
138
+ /** 这一代请求结束:清在途标记;期间又失效过就接着拉下一轮。 */
139
+ function settle(table: Table): void {
140
+ inflight.delete(table);
141
+ loading[table] = false;
142
+ if (pending.has(table) && !timer) flush();
143
+ }
144
+
145
+ async function run(table: Table, gen: number): Promise<void> {
146
+ let result: unknown[];
147
+ try {
148
+ result = await fetchRows(table);
149
+ } catch (error) {
150
+ // 已被 refresh 取代:跟着新请求走;已 reset:没有新请求,丢弃。
151
+ if (gen !== generation[table]) return inflight.get(table);
152
+ errors[table] = formatError(error, "加载失败");
153
+ settle(table);
154
+ throw error;
155
+ }
156
+ if (gen !== generation[table]) return inflight.get(table);
157
+ rows[table] = result as Tables[Table];
158
+ loaded[table] = true;
159
+ errors[table] = "";
160
+ settle(table);
161
+ }
162
+
163
+ function load(table: Table): Promise<void> {
164
+ const existing = inflight.get(table);
165
+ if (existing) return existing;
166
+ if (!ys.isLoggedIn) return Promise.resolve();
167
+ // 这次请求在失效之后才发出,拿到的就是新数据,不用再排下一轮。
168
+ pending.delete(table);
169
+ loading[table] = true;
170
+ const task = run(table, ++generation[table]);
171
+ inflight.set(table, task);
172
+ return task;
173
+ }
174
+
175
+ function unique(tables: readonly Table[]): Table[] {
176
+ const list = [...new Set(tables)];
177
+ for (const table of list)
178
+ if (!known(table)) throw new Error(`未登记的表:${String(table)}`);
179
+ return list;
180
+ }
181
+
182
+ async function ensure(...tables: Table[]): Promise<void> {
183
+ await Promise.all(
184
+ unique(tables).map((table) => {
185
+ const fresh =
186
+ loaded[table] &&
187
+ !errors[table] &&
188
+ !pending.has(table) &&
189
+ !inflight.has(table);
190
+ return fresh ? undefined : load(table);
191
+ }),
192
+ );
193
+ }
194
+
195
+ async function refresh(...tables: Table[]): Promise<void> {
196
+ const list = unique(tables);
197
+ for (const table of list) {
198
+ // 在途请求可能早于这次修改,作废它;它的调用方会跟着新请求走。
199
+ generation[table] += 1;
200
+ inflight.delete(table);
201
+ loading[table] = false;
202
+ }
203
+ await Promise.all(list.map((table) => load(table)));
204
+ }
205
+
206
+ function flush(): void {
207
+ if (timer) clearTimeout(timer);
208
+ timer = null;
209
+ for (const table of [...pending]) {
210
+ // 正在请求的等它回来(settle)再拉,同一张表不并发。
211
+ if (inflight.has(table)) continue;
212
+ pending.delete(table);
213
+ // 后台重拉:失败已写进 errors,这里没有调用方可抛。
214
+ void load(table).catch(() => undefined);
215
+ }
216
+ }
217
+
218
+ function invalidate(tables: readonly string[], retryFailed = false): void {
219
+ for (const table of tables) {
220
+ if (!known(table)) continue;
221
+ if (
222
+ loaded[table] ||
223
+ inflight.has(table) ||
224
+ (retryFailed && errors[table])
225
+ )
226
+ pending.add(table);
227
+ }
228
+ if (!pending.size || timer) return;
229
+ if (coalesceMs > 0) timer = setTimeout(flush, coalesceMs);
230
+ else flush();
231
+ }
232
+
233
+ function onChange(data: unknown): void {
234
+ const kind = String((data as { kind?: unknown } | null)?.kind ?? "");
235
+ invalidate(
236
+ options.dirtyTables ? options.dirtyTables(kind, data) : [kind],
237
+ );
238
+ }
239
+
240
+ function bind(): void {
241
+ const client = ys.client();
242
+ if (!client || offChange) return;
243
+ offChange = client.on(changeEvent, onChange);
244
+ // 断线期间的推送收不到:重连后补拉一次,上次加载失败的表也顺带重试。
245
+ offConnected = client.on("__connected", () => invalidate(names, true));
246
+ }
247
+
248
+ function reset(): void {
249
+ offChange?.();
250
+ offConnected?.();
251
+ offChange = undefined;
252
+ offConnected = undefined;
253
+ if (timer) clearTimeout(timer);
254
+ timer = null;
255
+ pending.clear();
256
+ inflight.clear();
257
+ for (const table of names) {
258
+ generation[table] += 1;
259
+ rows[table] = [] as unknown as Tables[Table];
260
+ loaded[table] = false;
261
+ loading[table] = false;
262
+ errors[table] = "";
263
+ }
264
+ }
265
+
266
+ return { rows, loaded, loading, errors, ensure, refresh, bind, reset };
267
+ });
268
+
269
+ return useStore as unknown as YsCatalogStoreDefinition<Tables>;
270
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,57 @@
1
+ /* @ysgroup/core —— 给用户看的错误文案,以及「结果未知」的判断。
2
+ *
3
+ * 用法:
4
+ * try { await store.call("save_school", data); }
5
+ * catch (error) {
6
+ * ElMessage.error(formatError(error, "保存失败"));
7
+ * if (isResultUnknown(error)) await catalog.refresh("schools"); // 先核对,不要自动重发
8
+ * }
9
+ */
10
+ import { YsConnectionLostError, YsRpcError, YsTimeoutError } from "./ws";
11
+
12
+ /** 「Error: 」「TypeError: 」「YsRpcError: 」这类类名前缀。 */
13
+ const NAME_PREFIX = /^(?:[A-Za-z_$][\w$]*)?Error:\s*/;
14
+ /** 开头的「[500] 」这类回执码。 */
15
+ const CODE_PREFIX = /^\[\d+\]\s*/;
16
+
17
+ function cleanText(text: string): string {
18
+ let out = text.trim();
19
+ let previous = "";
20
+ // 「Error: [500] YsRpcError: 文案」这种多层前缀逐层去掉。
21
+ while (previous !== out) {
22
+ previous = out;
23
+ out = out.replace(NAME_PREFIX, "").replace(CODE_PREFIX, "").trim();
24
+ }
25
+ return out;
26
+ }
27
+
28
+ function rawText(error: unknown): string {
29
+ if (error === null || error === undefined) return "";
30
+ if (typeof error === "string") return error;
31
+ // YsRpcError.message 就是展示文案(500 时已带编号)。
32
+ if (error instanceof YsRpcError || error instanceof Error)
33
+ return error.message;
34
+ if (typeof error === "object") {
35
+ const message = (error as { message?: unknown }).message;
36
+ return typeof message === "string" ? message : "";
37
+ }
38
+ return String(error);
39
+ }
40
+
41
+ /**
42
+ * 把任意错误变成给用户看的一句话:去掉「XxxError: 」「Error: 」前缀和开头的「[数字] 」,
43
+ * 得到空文案时用 fallback。YsRpcError 取它的展示文案(500 时带编号,便于对照日志)。
44
+ */
45
+ export function formatError(error: unknown, fallback = "操作失败"): string {
46
+ return cleanText(rawText(error)) || fallback;
47
+ }
48
+
49
+ /**
50
+ * 请求已经发出但不知道服务端有没有执行:连接中断(YsConnectionLostError)或等回复超时(YsTimeoutError)。
51
+ * 写操作遇到它不要自动重试,先刷新数据核对。请求没发出(YsOfflineError)和服务端明确拒绝(YsRpcError)都不算。
52
+ */
53
+ export function isResultUnknown(error: unknown): boolean {
54
+ return (
55
+ error instanceof YsConnectionLostError || error instanceof YsTimeoutError
56
+ );
57
+ }
package/src/index.ts CHANGED
@@ -8,6 +8,7 @@ export {
8
8
  YsRpcError,
9
9
  YsOfflineError,
10
10
  YsConnectionLostError,
11
+ YsTimeoutError,
11
12
  DEFAULT_CALL_TIMEOUT_MS,
12
13
  DEFAULT_OFFLINE_WAIT_MS,
13
14
  MIN_CALL_TIMEOUT_MS,
@@ -16,6 +17,7 @@ export {
16
17
  type YsDisconnectInfo,
17
18
  type YsWsClientOptions,
18
19
  } from "./ws";
20
+ export { formatAmount, formatNumber, splitAmount, type YsAmountParts, type YsAmountUnit, type YsNumberFormatOptions } from "./number";
19
21
  export {
20
22
  currentEntry,
21
23
  latestEntry,
@@ -74,6 +76,22 @@ export {
74
76
  export {
75
77
  normalizeSearchText,
76
78
  searchTokens,
79
+ ysFilter,
77
80
  ysMatch,
81
+ ysMatchDetail,
78
82
  ysSearchText,
83
+ type YsMatchDetail,
84
+ type YsMatchKind,
85
+ type YsMatchOptions,
79
86
  } from "./search";
87
+ export { formatError, isResultUnknown } from "./errors";
88
+ export { compareNatural, sortByNatural } from "./naturalSort";
89
+ export {
90
+ createYsCatalog,
91
+ type YsCatalogOptions,
92
+ type YsCatalogSource,
93
+ type YsCatalogState,
94
+ type YsCatalogActions,
95
+ type YsCatalogStore,
96
+ type YsCatalogStoreDefinition,
97
+ } from "./catalog";
@@ -0,0 +1,21 @@
1
+ /* @ysgroup/core —— 中文 + 数字自然序:同一串里的数字按数值比,避免「10号」排在「1号」前面。 */
2
+
3
+ const collator = new Intl.Collator("zh-CN", {
4
+ numeric: true,
5
+ sensitivity: "base",
6
+ });
7
+
8
+ /** 比较两个值(转成字符串,null / undefined 当空串),可直接给 Array.sort 或 el-table 的 sort-method。 */
9
+ export function compareNatural(left: unknown, right: unknown): number {
10
+ return collator.compare(String(left ?? ""), String(right ?? ""));
11
+ }
12
+
13
+ /** 按 key(item) 自然序排出新数组,不改原数组。 */
14
+ export function sortByNatural<T>(
15
+ items: readonly T[],
16
+ key: (item: T) => unknown,
17
+ ): T[] {
18
+ return [...items].sort((left, right) =>
19
+ compareNatural(key(left), key(right)),
20
+ );
21
+ }
package/src/number.ts ADDED
@@ -0,0 +1,85 @@
1
+ /** 表格里的数值显示(规范 8.5「数值列」)。
2
+ *
3
+ * 金额类(金额、市值、余额、成本、盈亏、价格等)按大小自动换单位,列名不写单位:
4
+ * formatAmount(1377) // "1,377.00"
5
+ * formatAmount(1234756.78) // "123.48万"
6
+ * formatAmount(356000000) // "3.56亿"
7
+ * formatAmount(1200, { signed: true }) // "+1,200.00"(盈亏、涨跌)
8
+ * 换算过的值悬停显示完整金额 splitAmount(v).full → "1,234,756.78";表格单元格直接用 @ysgroup/ui 的 YsAmount。
9
+ *
10
+ * 数量、人数等不换单位:formatNumber(12500, { digits: 0 }) → "12,500"。空值都显示「—」。 */
11
+
12
+ export type YsAmountUnit = "" | "万" | "亿";
13
+
14
+ export interface YsNumberFormatOptions {
15
+ /** 小数位,默认 2;数量、人数这类整数传 0。 */
16
+ digits?: number;
17
+ /** 正数前加「+」(盈亏、涨跌),0 不加。 */
18
+ signed?: boolean;
19
+ /** 空值显示,默认「—」。 */
20
+ empty?: string;
21
+ }
22
+
23
+ export interface YsAmountParts {
24
+ /** 换算后的数字部分,如 "123.48"(带符号时含 +/-)。 */
25
+ number: string;
26
+ /** "" | "万" | "亿"。 */
27
+ unit: YsAmountUnit;
28
+ /** 显示文字 = number + unit,如 "123.48万"。 */
29
+ text: string;
30
+ /** 完整金额,千分位,如 "1,234,756.78";悬停提示用。 */
31
+ full: string;
32
+ /** 按显示结果的正负:1、-1,舍入成 0 时为 0。 */
33
+ sign: -1 | 0 | 1;
34
+ }
35
+
36
+ function toNumber(value: unknown): number | null {
37
+ if (value === null || value === undefined || value === "") return null;
38
+ const number = typeof value === "number" ? value : Number(String(value).replace(/,/g, ""));
39
+ return Number.isFinite(number) ? number : null;
40
+ }
41
+
42
+ function round(value: number, digits: number): number {
43
+ const scale = 10 ** digits;
44
+ return Math.round(value * scale) / scale;
45
+ }
46
+
47
+ function fixed(value: number, digits: number, signed: boolean): string {
48
+ let text = value.toLocaleString("en-US", { minimumFractionDigits: digits, maximumFractionDigits: digits });
49
+ // 四舍五入成 0 的负数不显示「-0.00」
50
+ if (/^-0(\.0+)?$/.test(text)) text = text.slice(1);
51
+ if (signed && !text.startsWith("-") && !/^0(\.0+)?$/.test(text)) text = `+${text}`;
52
+ return text;
53
+ }
54
+
55
+ /** 不换单位的数值:千分位、固定小数位。 */
56
+ export function formatNumber(value: number | string | null | undefined, options: YsNumberFormatOptions = {}): string {
57
+ const { digits = 2, signed = false, empty = "—" } = options;
58
+ const number = toNumber(value);
59
+ return number === null ? empty : fixed(number, digits, signed);
60
+ }
61
+
62
+ /** 金额按大小拆成数字和单位:不足 1 万原样,满 1 万用「万」,满 1 亿用「亿」(按舍入后的显示值判断,不会出现 10,000.00万)。空值返回 null。 */
63
+ export function splitAmount(value: number | string | null | undefined, options: Omit<YsNumberFormatOptions, "empty"> = {}): YsAmountParts | null {
64
+ const { digits = 2, signed = false } = options;
65
+ const number = toNumber(value);
66
+ if (number === null) return null;
67
+ let unit: YsAmountUnit = "";
68
+ let scaled = number;
69
+ if (Math.abs(round(number, digits)) >= 1e4) {
70
+ unit = "万";
71
+ scaled = number / 1e4;
72
+ if (Math.abs(round(scaled, digits)) >= 1e4) {
73
+ unit = "亿";
74
+ scaled = number / 1e8;
75
+ }
76
+ }
77
+ const text = fixed(scaled, digits, signed);
78
+ const sign = /^[+-]?0(\.0+)?$/.test(text) ? 0 : number < 0 ? -1 : 1;
79
+ return { number: text, unit, text: `${text}${unit}`, full: fixed(number, digits, signed), sign };
80
+ }
81
+
82
+ /** 金额显示文字:splitAmount 的 text,空值显示 empty(默认「—」)。 */
83
+ export function formatAmount(value: number | string | null | undefined, options: YsNumberFormatOptions = {}): string {
84
+ return splitAmount(value, options)?.text ?? options.empty ?? "—";
85
+ }
package/src/search.ts CHANGED
@@ -10,6 +10,14 @@
10
10
  * - 「123.47万」这类显示值要原样传进 ysSearchText,123.47、123.47万 才能搜到;原值也传,1234756.78 同样能搜到。
11
11
  * - 纯字母关键词还按拼音匹配连续的汉字:xx、xuexiao、xuex、xxiao 都能搜到「学校」,zhs 能搜到「张三」。
12
12
  * 多音字任一读音都算。
13
+ *
14
+ * 模糊匹配(按需开启,{ fuzzy: true }):名称有通行简称的表(机构、银行、公司)才开,编号、金额为主的表不开。
15
+ * - 关键词里的字按顺序出现在同一个字段里就算命中,中间可以隔字:「建行」→「中国建设银行」,「浦发」→「上海浦东发展银行」。
16
+ * - 纯字母关键词每个字母当一个字的拼音首字母,同样按顺序:jh →「建…行」。
17
+ * - 噪声控制:至少 2 个字;带数字的词、汉字字母混写的词不做模糊;首尾跨度不超过关键词长度的 4 倍;顺序反了不算。
18
+ * - 排序:原文包含 > 连续拼音 > 模糊,模糊里字挨得越紧越靠前(「中行」时「中国银行」排在「中国建设银行」前)。
19
+ * 用 ysFilter(rows, keyword, textOf, { fuzzy: true }) 过滤并排序;ysMatchDetail 告诉你按哪种方式命中。
20
+ * 服务端 ys_base.search 的 ys_filter(..., fuzzy=True) 规则相同。
13
21
  */
14
22
  import { PINYIN_DATA } from "./pinyinData";
15
23
 
@@ -138,16 +146,109 @@ function pinyinIncludes(text: string, token: string): boolean {
138
146
  return false;
139
147
  }
140
148
 
141
- function tokenMatches(text: string, token: string): boolean {
142
- if (text.includes(token)) return true;
143
- return LETTERS.test(token) && pinyinIncludes(text, token);
149
+ export interface YsMatchOptions {
150
+ /** 开启模糊匹配(字按顺序出现即可,中间可以隔字),默认关闭。 */
151
+ fuzzy?: boolean;
152
+ }
153
+
154
+ /** 命中方式:原文包含、连续拼音、模糊。多个关键词时取最弱的一种。 */
155
+ export type YsMatchKind = "exact" | "pinyin" | "fuzzy";
156
+
157
+ export interface YsMatchDetail {
158
+ /** 越大越靠前:原文 3、拼音 2、模糊 1~2(字越紧越接近 2),多个关键词相加。 */
159
+ score: number;
160
+ kind: YsMatchKind;
161
+ }
162
+
163
+ /** 模糊:首尾跨度不超过关键词长度的这么多倍。 */
164
+ const FUZZY_SPAN_RATIO = 4;
165
+ const HAS_DIGIT = /\d/;
166
+ const HAS_LETTER = /[a-z]/;
167
+
168
+ /** 关键词里的一个字能否对上文本里的一个字:汉字、符号原样相同;字母模式下字母对汉字的拼音首字母。 */
169
+ function fuzzyCharMatches(char: string, want: string, letters: boolean): boolean {
170
+ if (!letters) return char === want;
171
+ const syllables = syllablesOf(char);
172
+ return !!syllables && syllables.some((syllable) => syllable[0] === want);
173
+ }
174
+
175
+ /** 在一个字段里找按顺序包含 token 各字的最短一段,返回跨度;找不到或太散返回 0。 */
176
+ function fuzzySpan(field: string, token: string, letters: boolean): number {
177
+ const limit = token.length * FUZZY_SPAN_RATIO;
178
+ let best = 0;
179
+ for (let start = 0; start < field.length; start += 1) {
180
+ if (!fuzzyCharMatches(field[start], token[0], letters)) continue;
181
+ let j = 1;
182
+ let i = start + 1;
183
+ for (; i < field.length && j < token.length && i - start < limit; i += 1) {
184
+ if (fuzzyCharMatches(field[i], token[j], letters)) j += 1;
185
+ }
186
+ if (j === token.length) {
187
+ const span = i - start;
188
+ if (!best || span < best) best = span;
189
+ if (best === token.length) break;
190
+ }
191
+ }
192
+ return best;
193
+ }
194
+
195
+ function fuzzyScore(text: string, token: string): number {
196
+ if (token.length < 2 || HAS_DIGIT.test(token)) return 0;
197
+ const letters = LETTERS.test(token);
198
+ // 汉字和字母混写的词不做模糊(拼音规则已经不认它)
199
+ if (!letters && HAS_LETTER.test(token)) return 0;
200
+ let best = 0;
201
+ for (const field of text.split(FIELD_SEPARATOR)) {
202
+ const span = fuzzySpan(field, token, letters);
203
+ if (span) best = Math.max(best, 1 + token.length / span);
204
+ }
205
+ return best;
206
+ }
207
+
208
+ function tokenDetail(text: string, token: string, fuzzy: boolean): YsMatchDetail | null {
209
+ if (text.includes(token)) return { score: 3, kind: "exact" };
210
+ if (LETTERS.test(token) && pinyinIncludes(text, token)) return { score: 2, kind: "pinyin" };
211
+ if (!fuzzy) return null;
212
+ const score = fuzzyScore(text, token);
213
+ return score ? { score, kind: "fuzzy" } : null;
214
+ }
215
+
216
+ const KIND_ORDER: Record<YsMatchKind, number> = { exact: 0, pinyin: 1, fuzzy: 2 };
217
+
218
+ /**
219
+ * 命中详情:没命中返回 null;关键词为空时 { score: 0, kind: "exact" }。
220
+ * 空格分隔的每个词都要命中(可分别命中不同字段),分数相加,kind 取最弱的一种。
221
+ */
222
+ export function ysMatchDetail(text: string, keyword: string, options: YsMatchOptions = {}): YsMatchDetail | null {
223
+ const result: YsMatchDetail = { score: 0, kind: "exact" };
224
+ for (const token of searchTokens(keyword)) {
225
+ const detail = tokenDetail(text, token, !!options.fuzzy);
226
+ if (!detail) return null;
227
+ result.score += detail.score;
228
+ if (KIND_ORDER[detail.kind] > KIND_ORDER[result.kind]) result.kind = detail.kind;
229
+ }
230
+ return result;
144
231
  }
145
232
 
146
233
  /**
147
234
  * text 用 ysSearchText 拼出;关键词为空时命中全部。
148
- * 空格分隔的每个词都要命中(可分别命中不同字段)。
235
+ * 空格分隔的每个词都要命中(可分别命中不同字段)。默认不做模糊匹配。
236
+ */
237
+ export function ysMatch(text: string, keyword: string, options: YsMatchOptions = {}): boolean {
238
+ return ysMatchDetail(text, keyword, options) !== null;
239
+ }
240
+
241
+ /**
242
+ * 按关键词过滤行,textOf(row) 返回 ysSearchText 拼出的文本(数据量大时自己先把文本存起来)。
243
+ * 关键词为空时原样返回全部;不开模糊时保持原顺序;开了模糊按命中程度排序(同分保持原顺序)。
149
244
  */
150
- export function ysMatch(text: string, keyword: string): boolean {
151
- const tokens = searchTokens(keyword);
152
- return tokens.every((token) => tokenMatches(text, token));
245
+ export function ysFilter<T>(rows: readonly T[], keyword: string, textOf: (row: T) => string, options: YsMatchOptions = {}): T[] {
246
+ if (!searchTokens(keyword).length) return [...rows];
247
+ const hits: { row: T; score: number; index: number }[] = [];
248
+ rows.forEach((row, index) => {
249
+ const detail = ysMatchDetail(textOf(row), keyword, options);
250
+ if (detail) hits.push({ row, score: detail.score, index });
251
+ });
252
+ if (options.fuzzy) hits.sort((a, b) => b.score - a.score || a.index - b.index);
253
+ return hits.map((hit) => hit.row);
153
254
  }
package/src/ws.ts CHANGED
@@ -46,6 +46,19 @@ export class YsConnectionLostError extends Error {
46
46
  }
47
47
  }
48
48
 
49
+ /**
50
+ * 请求已经发出,等到超时也没有回复:服务端可能已经执行,结果未知,不要自动重试写操作。
51
+ * 不改 name(仍是 Error):String(error) 还是「Error: 请求超时:…」,旧代码照常显示。
52
+ */
53
+ export class YsTimeoutError extends Error {
54
+ constructor(
55
+ public readonly event: string,
56
+ public readonly timeoutMs: number,
57
+ ) {
58
+ super(`请求超时:${event} 超过 ${timeoutMs / 1000} 秒没有返回`);
59
+ }
60
+ }
61
+
49
62
  /** 断开事件附带的信息。restarting 表示服务端主动重启(关闭码 1012 / 1001),多半是在部署新版本。 */
50
63
  export interface YsDisconnectInfo {
51
64
  code: number;
@@ -238,7 +251,7 @@ export class YsWsClient {
238
251
  return new Promise((resolve, reject) => {
239
252
  const timer = setTimeout(() => {
240
253
  this.pending.delete(id);
241
- reject(new Error(`请求超时:${event} 超过 ${limit / 1000} 秒没有返回`));
254
+ reject(new YsTimeoutError(event, limit));
242
255
  }, limit);
243
256
  this.pending.set(id, {
244
257
  resolve: (v) => {