@ysgroup/core 0.1.27 → 0.1.29

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.27",
3
+ "version": "0.1.29",
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.3.0"
26
+ "@ysgroup/theme": "^0.3.1"
27
27
  }
28
28
  }
@@ -8,6 +8,12 @@ export const FILE_CHUNK_SIZE = 1024 * 1024;
8
8
  /** 单块上传、读取、finish 的默认超时:一块 1 MiB 的 base64,慢网下也够。 */
9
9
  export const FILE_CHUNK_TIMEOUT_MS = 60_000;
10
10
 
11
+ /**
12
+ * 同一文件同时在途的块数上限(默认 3)。实际取它和服务端 begin 回的 max_inflight 的较小值;
13
+ * 旧服务端不回 max_inflight 时按 1(严格逐块)发送。高延迟网络下比逐块等待快一到两倍。
14
+ */
15
+ export const FILE_CHUNK_INFLIGHT = 3;
16
+
11
17
  /** 计算 sha256 时每次从文件读出的字节数(不把整个文件读进内存)。 */
12
18
  export const FILE_HASH_SLICE_SIZE = 1024 * 1024;
13
19
 
@@ -30,6 +36,12 @@ export type YsFileCall = (
30
36
  /** 上传的阶段:`hash` 计算整份 sha256,`upload` 发块(秒传时没有 upload 阶段)。 */
31
37
  export type YsFilePhase = "hash" | "upload";
32
38
 
39
+ /**
40
+ * onPhase 报告的阶段:`hash` 计算校验、`upload` 发块、`finish` 块已发完,等服务端核对整份内容、按文件规范检查和转换
41
+ * (大图转 WebP 要一两秒,页面据此显示「处理中」)、`prove` 秒传的持有验证。
42
+ */
43
+ export type YsUploadStage = "hash" | "upload" | "finish" | "prove";
44
+
33
45
  /**
34
46
  * 进度回调。ratio 为总进度 0~1,只增不减。uploadChunked 另传 phase 与本阶段进度 phaseRatio(0~1);
35
47
  * readChunked 只传 ratio。只写 `(ratio) => …` 的旧回调不受影响。
@@ -185,6 +197,10 @@ export interface YsUploadChunkedOptions {
185
197
  idKey?: string;
186
198
  /** 进度:`(ratio, phase, phaseRatio)`,见 YsFileProgress 与 FILE_HASH_PROGRESS_WEIGHT。 */
187
199
  onProgress?: YsFileProgress;
200
+ /** 进入新阶段时调用一次,见 YsUploadStage(用来显示「校验中 / 上传中 / 处理中」)。 */
201
+ onPhase?: (stage: YsUploadStage) => void;
202
+ /** 同时在途的块数,默认 FILE_CHUNK_INFLIGHT;不超过服务端 begin 回的 max_inflight(没回时为 1)。 */
203
+ inflight?: number;
188
204
  /**
189
205
  * begin 返回同内容的已有文件时调用(列表由服务端按权限过滤)。返回 false 或抛错则中止上传
190
206
  * (已建的上传会话发 cancel;返回 false 时抛 name 为 AbortError 的错误),可返回 Promise(如等用户确认)。
@@ -252,6 +268,12 @@ export async function uploadChunked<T = unknown>(
252
268
  reported = ratio;
253
269
  options.onProgress?.(ratio, phase, phaseRatio);
254
270
  };
271
+ let stage: YsUploadStage | "" = "";
272
+ const enter = (next: YsUploadStage) => {
273
+ if (stage === next) return;
274
+ stage = next;
275
+ options.onPhase?.(next);
276
+ };
255
277
  const cancel = () => {
256
278
  if (resumeKey) removeRecord(resumeKey);
257
279
  if (cancelled || !id) return;
@@ -263,6 +285,7 @@ export async function uploadChunked<T = unknown>(
263
285
  };
264
286
 
265
287
  try {
288
+ enter("hash");
266
289
  const checksum = await sha256Hex(file, {
267
290
  signal,
268
291
  onProgress: (ratio) =>
@@ -318,6 +341,7 @@ export async function uploadChunked<T = unknown>(
318
341
  }
319
342
 
320
343
  if (session.status === "challenge") {
344
+ enter("prove");
321
345
  const ranges = Array.isArray(session.ranges)
322
346
  ? (session.ranges as { start: number; length: number }[])
323
347
  : [];
@@ -355,8 +379,16 @@ export async function uploadChunked<T = unknown>(
355
379
  phaseRatio,
356
380
  );
357
381
  };
382
+ enter("upload");
358
383
  uploadReport(start);
359
- for (let index = start; index < count; index += 1) {
384
+ const windowSize = Math.max(
385
+ 1,
386
+ Math.min(
387
+ options.inflight ?? FILE_CHUNK_INFLIGHT,
388
+ positive(session.max_inflight) ?? 1,
389
+ ),
390
+ );
391
+ const sendChunk = async (index: number) => {
360
392
  const piece = file.slice(index * chunkSize, (index + 1) * chunkSize);
361
393
  const data = await abortable(blobToBase64(piece), signal);
362
394
  await withRetry(
@@ -373,8 +405,27 @@ export async function uploadChunked<T = unknown>(
373
405
  retryDelayMs,
374
406
  signal,
375
407
  );
376
- uploadReport(index + 1);
408
+ };
409
+ // 滑动窗口:最多 windowSize 块同时在途,按序确认;服务端让先到的后面块等前面块写完。
410
+ const pending: Promise<void>[] = [];
411
+ let confirmed = start;
412
+ for (let index = start; index < count; index += 1) {
413
+ const sending = sendChunk(index);
414
+ // 前面的块失败时后面的结果不再等待,避免未处理的拒绝。
415
+ sending.catch(() => undefined);
416
+ pending.push(sending);
417
+ if (pending.length >= windowSize) {
418
+ await pending.shift();
419
+ confirmed += 1;
420
+ uploadReport(confirmed);
421
+ }
422
+ }
423
+ while (pending.length) {
424
+ await pending.shift();
425
+ confirmed += 1;
426
+ uploadReport(confirmed);
377
427
  }
428
+ enter("finish");
378
429
  const result = await abortable(
379
430
  call(options.finishEvent, { [idKey]: id, checksum }, { timeoutMs }),
380
431
  signal,
package/src/index.ts CHANGED
@@ -17,6 +17,7 @@ export {
17
17
  type YsDisconnectInfo,
18
18
  type YsWsClientOptions,
19
19
  } from "./ws";
20
+ export { formatAmount, formatNumber, splitAmount, type YsAmountParts, type YsAmountUnit, type YsNumberFormatOptions } from "./number";
20
21
  export {
21
22
  currentEntry,
22
23
  latestEntry,
@@ -48,6 +49,7 @@ export {
48
49
  type PasswordWrap,
49
50
  } from "./password";
50
51
  export {
52
+ FILE_CHUNK_INFLIGHT,
51
53
  FILE_CHUNK_RETRIES,
52
54
  FILE_CHUNK_SIZE,
53
55
  FILE_CHUNK_TIMEOUT_MS,
@@ -71,12 +73,18 @@ export {
71
73
  type YsUploadChunkedOptions,
72
74
  type YsUploadResult,
73
75
  type YsUploadResumeOptions,
76
+ type YsUploadStage,
74
77
  } from "./fileTransfer";
75
78
  export {
76
79
  normalizeSearchText,
77
80
  searchTokens,
81
+ ysFilter,
78
82
  ysMatch,
83
+ ysMatchDetail,
79
84
  ysSearchText,
85
+ type YsMatchDetail,
86
+ type YsMatchKind,
87
+ type YsMatchOptions,
80
88
  } from "./search";
81
89
  export { formatError, isResultUnknown } from "./errors";
82
90
  export { compareNatural, sortByNatural } from "./naturalSort";
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
  }