-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathshared.tsx
More file actions
1705 lines (1599 loc) · 61.6 KB
/
Copy pathshared.tsx
File metadata and controls
1705 lines (1599 loc) · 61.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
Button,
Device,
DragGesture,
GeometryReader,
HStack,
Image,
Link,
ProgressView,
ScrollView,
SVG,
Text,
useRef,
VStack,
ZStack,
} from "scripting"
declare function fetch(input: string, init?: any): Promise<any>
type DictToken = {
id: string
text: string
index: number
}
type TokenHitTarget = {
token: DictToken
x: number
y: number
width: number
height: number
}
type TokenRow = {
y: number
tokens: Array<{ token: DictToken; width: number }>
targets: TokenHitTarget[]
}
type ZdicResult = {
query: string
url: string
title: string
sections: ZdicSection[]
}
type ZdicSection = {
title: string
lines: string[]
}
type ImageFilter = {
onlyAlt?: string
allowedAlts?: string[]
labelPrefix?: string
}
type LineTone = "meta" | "example" | "translation" | "quote" | "definition"
type InlineLinkToken = {
url: string
label: string
}
const HAN_RE = /[\u3400-\u9fff\uf900-\ufaff]/
const PURE_HAN_RE = /^[\u3400-\u9fff\uf900-\ufaff]+$/
function summarizeText(text: string, maxLength = 48) {
const normalized = String(text ?? "").replace(/\s+/g, " ").trim()
if (!normalized) return ""
return normalized.length > maxLength
? `${normalized.slice(0, maxLength)}...`
: normalized
}
function logZDictEvent(message: string, payload?: Record<string, unknown>) {
if (payload) {
console.log(`[ZDict] ${message}`, payload)
return
}
console.log(`[ZDict] ${message}`)
}
function logZDictError(message: string, payload?: Record<string, unknown>) {
if (payload) {
console.error(`[ZDict] ${message}`, payload)
return
}
console.error(`[ZDict] ${message}`)
}
function hapticLight() {
try {
HapticFeedback.lightImpact()
} catch {}
}
function hapticSuccess() {
try {
HapticFeedback.notificationSuccess()
} catch {}
}
function languageHint(text: string): NaturalLanguage.Language | undefined {
if (HAN_RE.test(text)) {
return /[繫臺後萬與專業開關]/.test(text) ? "zh-Hant" : "zh-Hans"
}
try {
const detected = NaturalLanguage.dominantLanguage(text)
if (detected) return detected
} catch {}
return undefined
}
function splitGraphemes(text: string): string[] {
const Segmenter = (globalThis as any).Intl?.Segmenter
if (Segmenter) {
try {
const segmenter = new Segmenter(undefined, { granularity: "grapheme" })
return Array.from(segmenter.segment(text) as Iterable<any>)
.map((item: any) => String(item?.segment ?? ""))
.filter(Boolean)
} catch {}
}
return Array.from(text)
}
function pushRawToken(result: DictToken[], text: string) {
if (!text) return
result.push({
id: `${result.length}-${text.length}-${text}`,
text,
index: result.length,
})
}
function pushCjkChunks(result: DictToken[], text: string) {
let buffer = ""
for (const char of Array.from(text)) {
buffer += char
if (Array.from(buffer).length >= 2) {
pushRawToken(result, buffer)
buffer = ""
}
}
pushRawToken(result, buffer)
}
function pushMixedRun(result: DictToken[], text: string) {
let buffer = ""
let bufferKind: "cjk" | "alnum" | null = null
const flush = () => {
if (!buffer || !bufferKind) return
if (bufferKind === "cjk" && Array.from(buffer).length > 4) {
pushCjkChunks(result, buffer)
} else {
pushRawToken(result, buffer)
}
buffer = ""
bufferKind = null
}
for (const part of splitGraphemes(text)) {
if (/^\s+$/.test(part)) {
flush()
continue
}
const kind = /^[\u3400-\u9fff\uf900-\ufaff]+$/.test(part)
? "cjk"
: /^[A-Za-z0-9]+$/.test(part)
? "alnum"
: null
if (!kind) {
flush()
pushRawToken(result, part)
} else if (bufferKind === kind) {
buffer += part
} else {
flush()
buffer = part
bufferKind = kind
}
}
flush()
}
function pushTextParts(result: DictToken[], text: string) {
const matcher = /\S+/g
let match: RegExpExecArray | null
while ((match = matcher.exec(text))) {
const part = match[0]
if (!HAN_RE.test(part) || Array.from(part).length <= 4) {
pushMixedRun(result, part)
continue
}
const Segmenter = (globalThis as any).Intl?.Segmenter
if (Segmenter) {
try {
const segmenter = new Segmenter("zh-Hans", { granularity: "word" })
const pieces = Array.from(segmenter.segment(part) as Iterable<any>)
.map((item: any) => String(item?.segment ?? ""))
.filter(Boolean)
if (pieces.length > 1) {
pieces.forEach((piece) => pushMixedRun(result, piece))
continue
}
} catch {}
}
pushMixedRun(result, part)
}
}
function tokenizeWords(text: string): DictToken[] {
const source = String(text ?? "")
if (!source.trim()) return []
try {
const language = languageHint(source)
const tokens = NaturalLanguage.tokenize(source, {
unit: "word",
...(language ? { language } : {}),
})
const result: DictToken[] = []
for (const token of tokens) {
pushTextParts(result, token.text)
}
logZDictEvent("系统分词完成", {
sourceLength: Array.from(source).length,
language: language ?? "(auto)",
tokenCount: result.length,
tokensPreview: result.slice(0, 12).map((token) => token.text).join(" / "),
})
return result
} catch (error: any) {
logZDictError("系统分词失败,使用备用分词", {
sourcePreview: summarizeText(source),
error: String(error?.message ?? error ?? "unknown"),
})
const result: DictToken[] = []
pushTextParts(result, source)
logZDictEvent("备用分词完成", {
sourceLength: Array.from(source).length,
tokenCount: result.length,
tokensPreview: result.slice(0, 12).map((token) => token.text).join(" / "),
})
return result
}
}
function selectedTokenText(tokens: DictToken[], selectedIds: string[]): string {
const byId = new Map(tokens.map((token) => [token.id, token.text]))
return selectedIds.map((id) => byId.get(id) ?? "").join("")
}
function estimatedTokenWidth(text: string, compact: boolean): number {
let width = compact ? 28 : 34
for (const char of Array.from(text)) {
if (HAN_RE.test(char)) width += compact ? 16 : 19
else if (/[A-Z0-9]/.test(char)) width += compact ? 10 : 12
else if (/[a-z]/.test(char)) width += compact ? 9 : 11
else width += compact ? 12 : 14
}
return Math.max(compact ? 32 : 40, width)
}
function layoutTokens(tokens: DictToken[], width: number, compact: boolean) {
const spacing = 8
const rowHeight = compact ? 32 : 40
const maxWidth = Math.max(120, width)
const maxTokenWidth = Math.max(80, Math.min(maxWidth, compact ? 180 : 240))
const rows: TokenRow[] = []
let current: TokenRow = { y: 0, tokens: [], targets: [] }
let x = 0
for (const token of tokens) {
const tokenWidth = Math.min(maxTokenWidth, estimatedTokenWidth(token.text, compact))
if (current.tokens.length && x + tokenWidth > maxWidth) {
rows.push(current)
current = { y: rows.length * (rowHeight + spacing), tokens: [], targets: [] }
x = 0
}
current.tokens.push({ token, width: tokenWidth })
current.targets.push({ token, x, y: current.y, width: tokenWidth, height: rowHeight })
x += tokenWidth + spacing
}
if (current.tokens.length) rows.push(current)
return { rows, rowHeight, spacing }
}
function hitToken(targets: TokenHitTarget[], x: number, y: number): DictToken | null {
for (const target of targets) {
if (x >= target.x && x <= target.x + target.width && y >= target.y && y <= target.y + target.height) {
return target.token
}
}
return null
}
function pointNumber(value: unknown): number {
const number = Number(value)
return Number.isFinite(number) ? number : -1
}
function decodeHtmlEntities(text: string): string {
const named: Record<string, string> = {
amp: "&",
lt: "<",
gt: ">",
quot: "\"",
apos: "'",
nbsp: " ",
middot: "·",
}
return text.replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z]+);/g, (_all, body) => {
if (body[0] === "#") {
const hex = body[1]?.toLowerCase() === "x"
const value = Number.parseInt(hex ? body.slice(2) : body.slice(1), hex ? 16 : 10)
return Number.isFinite(value) ? String.fromCodePoint(value) : ""
}
return named[body] ?? ""
})
}
function stripHtmlToLines(html: string): string[] {
const withoutNoise = html
.replace(/<script[\s\S]*?<\/script>/gi, "")
.replace(/<style[\s\S]*?<\/style>/gi, "")
.replace(/<noscript[\s\S]*?<\/noscript>/gi, "")
.replace(/<svg[\s\S]*?<\/svg>/gi, "")
.replace(/<button[\s\S]*?<\/button>/gi, "")
.replace(/<ins[\s\S]*?<\/ins>/gi, "")
.replace(/<figure[\s\S]*?<\/figure>/gi, "")
.replace(/<!--[\s\S]*?-->/g, "")
const text = withoutNoise
.replace(/<span\b[^>]*class="[^"]*(meta-badge|xxjs-block-label|jbjs-item__eg-label)[^"]*"[^>]*>([\s\S]*?)<\/span>/gi, "\n$2 ")
.replace(/<span\b[^>]*class="[^"]*(meta-pinyin|meta-zhuyin|word-pronun-text|jbjs-reading__py|jbjs-reading__zy|xxjs-reading__py|xxjs-reading__zy|gy-reading__py|gy-reading__zy|xxjs-english__text)[^"]*"[^>]*>([\s\S]*?)<\/span>/gi, "$2")
.replace(/<li\b[^>]*>/gi, "\n- ")
.replace(/<(h[1-6]|p|div|section|article|tr|br|dd|dt|blockquote|header|ol|ul)\b[^>]*>/gi, "\n")
.replace(/<\/(h[1-6]|p|div|section|article|li|tr|dd|dt|blockquote)>/gi, "\n")
.replace(/<[^>]+>/g, "")
const rawLines = decodeHtmlEntities(text)
.split(/\n+/)
.map((line) => line.replace(/\s+/g, " ").trim())
.filter((line) => line.length >= 2)
.filter((line) => {
if (/^(登录|注册|汉典|首页|搜索|反馈|客户端|二维码|Copyright|©)/i.test(line)) return false
if (/^(加载中|取消|提交|纠错反馈|反馈类型|昵称或联系方式)$/.test(line)) return false
if (!shouldKeepZdicLine(line)) return false
return true
})
const seen = new Set<string>()
return postProcessZdicLines(rawLines).filter((line) => {
if (seen.has(line)) return false
seen.add(line)
return true
})
}
function stripHtmlToAnyLines(html: string, dedupe = true): string[] {
const text = html
.replace(/<script[\s\S]*?<\/script>/gi, "")
.replace(/<style[\s\S]*?<\/style>/gi, "")
.replace(/<svg[\s\S]*?<\/svg>/gi, "")
.replace(/<button[\s\S]*?<\/button>/gi, "")
.replace(/<ins[\s\S]*?<\/ins>/gi, "")
.replace(/<!--[\s\S]*?-->/g, "")
.replace(/<a\b[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/gi, (_all, href, text) => {
const label = String(text).replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim()
return `[[LINK|${absoluteZdicUrl(String(href))}|${label}]]`
})
.replace(/\s*]]\s*」/g, "]]」")
.replace(/<span\b[^>]*class="[^"]*(xxjs-pos|gy-pos|gy-sense__pos)[^"]*"[^>]*>([\s\S]*?)<\/span>/gi, "\n$2\n")
.replace(/<span\b[^>]*class="[^"]*(xxjs-block-label|jbjs-item__eg-label)[^"]*"[^>]*>([\s\S]*?)<\/span>/gi, "\n$2\n")
.replace(/<(h[1-6]|p|div|section|article|tr|br|dd|dt|blockquote|header|ol|ul|li)\b[^>]*>/gi, "\n")
.replace(/<\/(h[1-6]|p|div|section|article|li|tr|dd|dt|blockquote)>/gi, "\n")
.replace(/<[^>]+>/g, "")
const seen = new Set<string>()
return decodeHtmlEntities(text)
.split(/\n+/)
.map((line) => line.replace(/\s+/g, " ").trim())
.filter((line) => line.length >= 2)
.filter((line) => !/^(反馈|加载中|取消|提交|纠错反馈|反馈类型|昵称或联系方式)$/.test(line))
.filter((line) => {
if (!dedupe) return true
if (seen.has(line)) return false
seen.add(line)
return true
})
}
function shouldKeepZdicLine(line: string): boolean {
if (HAN_RE.test(line)) return true
if (/^\d+\.$/.test(line)) return true
if (/^-\s*\d+\.$/.test(line)) return true
if (/^[-\d.、\s]*[a-zA-Z][a-zA-Z\s;,.()[\]'-]+$/.test(line)) return true
if (/^[ㄅ-ㄩˊˇˋ˙\s]+$/.test(line)) return true
if (/^[a-züāáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜńňǹḿ\s]+$/i.test(line)) return true
return false
}
function postProcessZdicLines(lines: string[]): string[] {
const result: string[] = []
const mergeLabels = /^(拼音|注音|英文|英语|德语|法语|日语|韩语|书证|近义词|反义词|例如|部首|部外|总笔画|统一码|笔顺|字形结构|字形分析)$/
for (let index = 0; index < lines.length; index += 1) {
const line = lines[index].replace(/^-\s*(\d+\.)$/, "$1")
const next = lines[index + 1]
if (/^\d+\.$/.test(line) && next) {
result.push(`${line} ${next}`)
index += 1
continue
}
if (mergeLabels.test(line) && next && !mergeLabels.test(next)) {
result.push(`${line} ${next}`)
index += 1
continue
}
if (result.length && /^(.+)$/.test(line)) {
result[result.length - 1] = `${result[result.length - 1]} ${line}`
continue
}
if (result.length && (isPinyinLine(line) || isZhuyinLine(line))) {
result[result.length - 1] = `${result[result.length - 1]} ${line}`
continue
}
result.push(line)
}
return result.filter((line) => !/^(书证|英文|英语|德语|法语|日语|韩语|近义词|反义词|例如)$/.test(line))
}
function isPinyinLine(line: string): boolean {
return /^[a-züāáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜńňǹḿ\s]+$/i.test(line)
}
function isZhuyinLine(line: string): boolean {
return /^[ㄅ-ㄩˊˇˋ˙\s]+$/.test(line)
}
function lineTone(line: string): LineTone {
if (/^词性\s+/.test(line)) return "meta"
if (/^(拼音|注音|部首|部外|总笔画|统一码|笔顺|字形结构|字形分析|繁体|异体)/.test(line)) return "meta"
if (/^(英文|英语|德语|法语|日语|韩语)/.test(line)) return "translation"
if (/^(例如|如:|如:)/.test(line)) return "example"
if (/^(书证)/.test(line)) return "quote"
if (/^(近义词|反义词)/.test(line)) return "example"
return "definition"
}
function displayUrl(url: string): string {
try {
return decodeURI(url)
} catch {
return url
}
}
function parseInlineLinks(line: string): { text: string; links: InlineLinkToken[] } | null {
if (!line.includes("[[LINK|")) return null
const links: InlineLinkToken[] = []
const text = normalizeZdicTextSpacing(line.replace(/\[\[LINK\|(https?:\/\/[^|\]]+)\|([^\]]+)]]/g, (_all, url, label) => {
links.push({ url: String(url), label: String(label) })
return String(label)
}))
return links.length ? { text, links } : null
}
function stripNoise(html: string): string {
return html
.replace(/<script[\s\S]*?<\/script>/gi, "")
.replace(/<style[\s\S]*?<\/style>/gi, "")
.replace(/<nav[\s\S]*?<\/nav>/gi, "")
.replace(/<ins[\s\S]*?<\/ins>/gi, "")
}
function firstMatch(html: string, pattern: RegExp): string {
return html.match(pattern)?.[1] ?? ""
}
function normalizeZdicTextSpacing(text: string): string {
return text
.replace(/\s+/g, " ")
.replace(/\s+([,。;:?!)》」』】、])/g, "$1")
.replace(/\s+([(《「『【])/g, "$1")
.replace(/([(《「『【])\s+/g, "$1")
.replace(/([)》」』】])\s+/g, "$1")
.trim()
}
function htmlInlineText(html: string): string {
const text = decodeHtmlEntities(String(html ?? "")
.replace(/<script[\s\S]*?<\/script>/gi, "")
.replace(/<style[\s\S]*?<\/style>/gi, "")
.replace(/<svg[\s\S]*?<\/svg>/gi, "")
.replace(/<button[\s\S]*?<\/button>/gi, "")
.replace(/<a\b[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/gi, (_all, href, text) => {
const label = String(text).replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim()
return `[[LINK|${absoluteZdicUrl(String(href))}|${label}]]`
})
.replace(/\s*]]\s*」/g, "]]」")
.replace(/<br\s*\/?>/gi, " ")
.replace(/<[^>]+>/g, " ")
).replace(/\s+/g, " ")
.trim()
.replace(/\[\[LINK\|/g, " [[LINK|")
.replace(/]]/g, "]] ")
.replace(/\s+/g, " ")
return normalizeZdicTextSpacing(text)
}
function absoluteZdicUrl(url: string): string {
if (!url) return ""
if (url.startsWith("//")) return `https:${url}`
if (url.startsWith("/")) return `https://zdic.net${url}`
return url
}
function extractImages(html: string, options?: ImageFilter): string[] {
const rows: string[] = []
const imagePattern = /<img\b[^>]*>/gi
let imageMatch: RegExpExecArray | null
while ((imageMatch = imagePattern.exec(html))) {
const tag = imageMatch[0]
const src = absoluteZdicUrl(firstMatch(tag, /\bsrc="([^"]+)"/i))
const alt = htmlInlineText(firstMatch(tag, /\balt="([^"]*)"/i)) || "字形"
if (options?.onlyAlt && alt !== options.onlyAlt) continue
if (options?.allowedAlts?.length && !options.allowedAlts.includes(alt)) continue
if (src && /\.svg(?:$|\?)/i.test(src)) rows.push(`SVG ${options?.labelPrefix ?? alt} ${src}`)
}
return rows
}
function extractImageAlts(html: string): string[] {
const alts: string[] = []
const imagePattern = /<img\b[^>]*>/gi
let imageMatch: RegExpExecArray | null
while ((imageMatch = imagePattern.exec(html))) {
const alt = htmlInlineText(firstMatch(imageMatch[0], /\balt="([^"]*)"/i))
if (alt) alts.push(alt)
}
return Array.from(new Set(alts))
}
function extractZdicLinkLabels(html: string): string[] {
const labels: string[] = []
const linkPattern = /<a\b[^>]*href="\/hans\/[^"]+"[^>]*>([\s\S]*?)<\/a>/gi
let linkMatch: RegExpExecArray | null
while ((linkMatch = linkPattern.exec(html))) {
const label = htmlInlineText(linkMatch[1])
if (label && PURE_HAN_RE.test(label) && Array.from(label).length <= 4) labels.push(label)
}
return Array.from(new Set(labels))
}
function extractTagTexts(html: string, pattern: RegExp): string[] {
const result: string[] = []
let match: RegExpExecArray | null
while ((match = pattern.exec(html))) {
const text = decodeHtmlEntities(String(match[1] ?? "").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim())
if (text) result.push(text)
}
return result
}
function extractCharMetaRows(articleHtml: string): string[] {
const rows: string[] = []
const metaBlocks = extractBalancedBlocks(articleHtml, "div", "meta-row")
for (const block of metaBlocks) {
const badgePattern = /<span\b[^>]*class="[^"]*meta-badge[^"]*"[^>]*>([\s\S]*?)<\/span>/gi
const badges: Array<{ label: string; valueStart: number; badgeStart: number }> = []
let badgeMatch: RegExpExecArray | null
while ((badgeMatch = badgePattern.exec(block))) {
const label = htmlInlineText(badgeMatch[1])
if (!label) continue
badges.push({
label,
valueStart: badgePattern.lastIndex,
badgeStart: badgeMatch.index,
})
}
for (let index = 0; index < badges.length; index += 1) {
const item = badges[index]
const nextStart = badges[index + 1]?.badgeStart ?? block.length
const value = htmlInlineText(block.slice(item.valueStart, nextStart))
if (value) rows.push(`${item.label} ${value}`)
}
}
return rows
}
function parseCharInfoSection(articleHtml: string, query: string): string[] {
const rows: string[] = []
rows.push(...extractImages(articleHtml, { onlyAlt: query, labelPrefix: query }).slice(0, 1))
const headword = htmlInlineText(firstMatch(articleHtml, /<div\b[^>]*class="[^"]*word-headword-row[^"]*"[^>]*>([\s\S]*?)<\/div>/i))
if (headword) rows.push(headword)
rows.push(...extractCharMetaRows(articleHtml))
const pronunRows = extractTagTexts(articleHtml, /<div\b[^>]*class="[^"]*word-pronun-row[^"]*"[^>]*>([\s\S]*?)<\/div>/gi)
rows.push(...pronunRows)
if (!rows.length) rows.push(...stripHtmlToLines(articleHtml).slice(0, 20))
const seen = new Set<string>()
return rows.filter((row) => {
if (!row || seen.has(row)) return false
seen.add(row)
return true
})
}
function extractReadingLine(sectionHtml: string, className: string): string {
const html = firstMatch(sectionHtml, new RegExp(`<(?:div|header)\\b[^>]*class="[^"]*${className}[^"]*"[^>]*>([\\s\\S]*?)<\\/(?:div|header)>`, "i"))
return htmlInlineText(html)
}
function classTokenPattern(className: string): string {
return `(?:[^"]*\\s)?${className}(?:\\s[^"]*)?`
}
function extractClassBlockHtml(html: string, className: string): string {
const startPattern = new RegExp(`<([a-zA-Z][\\w:-]*)\\b[^>]*class="${classTokenPattern(className)}"[^>]*>`, "i")
const match = startPattern.exec(html)
if (!match) return ""
const tagName = match[1]
const tagPattern = new RegExp(`</?${tagName}\\b[^>]*>`, "gi")
tagPattern.lastIndex = match.index + match[0].length
let depth = 1
let tagMatch: RegExpExecArray | null
while ((tagMatch = tagPattern.exec(html))) {
if (tagMatch[0].startsWith("</")) depth -= 1
else depth += 1
if (depth === 0) return html.slice(match.index, tagPattern.lastIndex)
}
return html.slice(match.index)
}
function extractBlockText(html: string, className: string): string {
return htmlInlineText(extractClassBlockHtml(html, className))
}
function extractBalancedBlocks(html: string, tagName: string, className: string): string[] {
const blocks: string[] = []
const startPattern = className
? new RegExp(`<${tagName}\\b[^>]*class="[^"]*${className}[^"]*"[^>]*>`, "gi")
: new RegExp(`<${tagName}\\b[^>]*>`, "gi")
let match: RegExpExecArray | null
while ((match = startPattern.exec(html))) {
let cursor = startPattern.lastIndex
let depth = 1
const tagPattern = new RegExp(`</?${tagName}\\b[^>]*>`, "gi")
tagPattern.lastIndex = cursor
let tagMatch: RegExpExecArray | null
while ((tagMatch = tagPattern.exec(html))) {
if (tagMatch[0].startsWith("</")) depth -= 1
else depth += 1
if (depth === 0) {
blocks.push(html.slice(match.index, tagPattern.lastIndex))
startPattern.lastIndex = tagPattern.lastIndex
break
}
}
}
return blocks
}
function extractCitationLines(html: string): string[] {
const citations: string[] = []
const itemPattern = /<li\b[^>]*class="[^"]*(?:xxjs-citation__item|gy-sense__cit-item)[^"]*"[^>]*>([\s\S]*?)<\/li>/gi
let itemMatch: RegExpExecArray | null
while ((itemMatch = itemPattern.exec(html))) {
const text = htmlInlineText(itemMatch[1])
if (text) citations.push(`书证 ${text}`)
}
return citations
}
function extractAlsoLines(html: string): string[] {
const lines: string[] = []
const alsoPattern = /<div\b[^>]*class="[^"]*xxjs-also[^"]*"[^>]*>([\s\S]*?)(?=<div\b[^>]*class="[^"]*xxjs-also|<\/div>\s*<\/div>|<\/li>|<\/section>)/gi
let alsoMatch: RegExpExecArray | null
while ((alsoMatch = alsoPattern.exec(html))) {
const block = alsoMatch[1]
const label = htmlInlineText(firstMatch(block, /<span\b[^>]*class="[^"]*xxjs-block-label[^"]*"[^>]*>([\s\S]*?)<\/span>/i))
const textBlock = firstMatch(block, /<span\b[^>]*class="[^"]*xxjs-also__text[^"]*"[^>]*>([\s\S]*)/i)
.replace(/<\/span>[\s\S]*$/i, (suffix) => suffix.replace(/<\/span>/i, ""))
const text = htmlInlineText(textBlock)
if (label && text) lines.push(`${label} ${text}`)
}
return lines
}
function parseWordExplanationSection(sectionHtml: string): string[] {
const lines: string[] = []
const reading = extractReadingLine(sectionHtml, "xxjs-reading-head")
if (reading) lines.push(reading)
const itemPattern = /<li\b[^>]*class="[^"]*xxjs-item[^"]*"[^>]*>([\s\S]*?)(?=<li\b[^>]*class="[^"]*xxjs-item|<\/ol>)/gi
let itemMatch: RegExpExecArray | null
let itemIndex = 0
while ((itemMatch = itemPattern.exec(sectionHtml))) {
itemIndex += 1
const itemHtml = itemMatch[1]
const isNoNum = /xxjs-item--nonum/.test(itemMatch[0])
const def = extractBlockText(itemHtml, "xxjs-item__def")
if (def) lines.push(isNoNum ? def : `${itemIndex}. ${def}`)
lines.push(...extractCitationLines(itemHtml))
lines.push(...extractAlsoLines(itemHtml))
const english = extractBlockText(itemHtml, "xxjs-english__text")
if (english) lines.push(`英文 ${english}`)
}
return lines
}
function parseGuoyuSection(sectionHtml: string): string[] {
const structured = parseGySenseSection(sectionHtml)
if (structured.length) return structured
if (sectionHtml.includes("gy-reading__head") && sectionHtml.includes("gy-sense-list")) {
const fullLines = stripHtmlToAnyLines(sectionHtml, false)
.filter((line) => !/^(国语辞典|书证|反馈)$/.test(line))
if (fullLines.some((line) => isPartOfSpeechLine(line))) return formatDictionaryDetailLines(fullLines)
}
const lines: string[] = []
const reading = extractReadingLine(sectionHtml, "gy-reading__head")
if (reading) lines.push(reading)
const sensePattern = /<div\b[^>]*class="[^"]*\bgy-sense\b[^"]*"[^>]*>([\s\S]*?)(?=<div\b[^>]*class="[^"]*\bgy-sense\b[^"]*"|<\/div>\s*<\/div>\s*<\/div>\s*<\/div>)/gi
let senseMatch: RegExpExecArray | null
let senseIndex = 0
while ((senseMatch = sensePattern.exec(sectionHtml))) {
const senseHtml = senseMatch[1]
if (/gy-sense__body/.test(senseHtml) === false) continue
senseIndex += 1
const num = extractBlockText(senseHtml, "gy-sense__num") || (senseIndex > 1 ? `${senseIndex}.` : "")
const def = extractBlockText(senseHtml, "gy-sense__def")
if (def) lines.push(num ? `${num} ${def}` : def)
lines.push(...extractCitationLines(senseHtml))
lines.push(...extractAlsoLines(senseHtml))
}
return lines
}
function parseGySenseSection(sectionHtml: string): string[] {
const lines: string[] = []
const reading = extractReadingLine(sectionHtml, "gy-reading__head")
if (reading) lines.push(reading)
const senseGuoyu = firstMatch(sectionHtml, /<div\b[^>]*id="sense-guoyu"[^>]*>([\s\S]*)/i) || sectionHtml
const posSections = extractBalancedBlocks(senseGuoyu, "section", "")
if (posSections.length) {
for (const section of posSections) {
const explicitPos = extractBlockText(section, "gy-pos-badge")
const fallbackPos = htmlInlineText(firstMatch(section, /<span\b[^>]*>([\s\S]*?)<\/span>/i))
const pos = explicitPos || (isPartOfSpeechLine(fallbackPos) ? fallbackPos : "")
if (pos) lines.push(`词性 ${pos}`)
const body = firstMatch(section, /<div\b[^>]*>([\s\S]*)<\/div>/i) || section
const senses = extractBalancedBlocks(body, "div", "gy-sense").filter((block) => /gy-sense__body|gy-sense__def/.test(block))
senses.forEach((sense, index) => {
const num = extractBlockText(sense, "gy-sense__num") || (senses.length > 1 ? `${index + 1}.` : "")
const def = extractBlockText(sense, "gy-sense__def")
if (def) lines.push(num ? `${num} ${def}` : def)
lines.push(...extractCitationLines(sense))
lines.push(...extractAlsoLines(sense))
})
}
return lines.length > (reading ? 1 : 0) ? lines : []
}
const senses = extractBalancedBlocks(sectionHtml, "div", "gy-sense").filter((block) => /gy-sense__body/.test(block))
senses.forEach((sense, index) => {
const pos = extractBlockText(sense, "gy-sense__pos") || extractBlockText(sense, "gy-pos-badge")
if (pos) lines.push(`词性 ${pos}`)
const num = extractBlockText(sense, "gy-sense__num") || (senses.length > 1 ? `${index + 1}.` : "")
const def = extractBlockText(sense, "gy-sense__def")
if (def) lines.push(num ? `${num} ${def}` : def)
lines.push(...extractCitationLines(sense))
lines.push(...extractAlsoLines(sense))
})
return lines.length > (reading ? 1 : 0) ? lines : []
}
function parseBasicCharSection(sectionHtml: string): string[] {
const lines: string[] = []
const reading = extractReadingLine(sectionHtml, "jbjs-reading__head")
if (reading) lines.push(reading)
const itemPattern = /<li\b[^>]*class="[^"]*jbjs-item[^"]*"[^>]*>([\s\S]*?)<\/li>/gi
let itemMatch: RegExpExecArray | null
let index = 0
while ((itemMatch = itemPattern.exec(sectionHtml))) {
index += 1
const itemHtml = itemMatch[1]
const def = extractBlockText(itemHtml, "jbjs-item__def")
if (def) lines.push(`${index}. ${def}`)
const example = extractBlockText(itemHtml, "jbjs-item__eg")
if (example) lines.push(`例如 ${example}`)
}
return lines
}
function parseDetailedCharSection(sectionHtml: string): string[] {
const structured = parseXxjsPosBadgeSections(sectionHtml)
if (structured.length) return structured
return formatDictionaryDetailLines(stripHtmlToAnyLines(sectionHtml, false)
.filter((line) => !/^(详细解释|书证|反馈)$/.test(line))
)
}
function parseXxjsPosBadgeSections(sectionHtml: string): string[] {
const lines: string[] = []
const reading = extractReadingLine(sectionHtml, "xxjs-reading__head")
if (reading) lines.push(reading)
const body = extractBalancedBlocks(sectionHtml, "div", "xxjs-body")[0] || sectionHtml
const sections = extractBalancedBlocks(body, "section", "xxjs-pos-section")
for (const section of sections) {
const pos = extractBlockText(section, "xxjs-pos-badge")
if (pos) lines.push(`词性 ${pos}`)
const items = extractBalancedBlocks(section, "li", "xxjs-item")
items.forEach((item, index) => {
const def = extractBlockText(item, "xxjs-item__def") || htmlInlineText(item)
if (def) lines.push(`${index + 1}. ${def}`)
lines.push(...extractCitationLines(item))
lines.push(...extractAlsoLines(item))
const english = extractBlockText(item, "xxjs-english__text")
if (english) lines.push(`英文 ${english}`)
})
}
return lines.length > (reading ? 1 : 0) ? lines : []
}
function isPartOfSpeechLine(line: string): boolean {
return /^(名|动|形|副|代|介|连|助|叹|量|数|拟声|区别)$/.test(line)
}
function splitInlineReadingPartOfSpeech(line: string): { reading: string; partOfSpeech: string; rest: string } | null {
const match = line.match(/^(.+?)\s+(名|动|形|副|代|介|连|助|叹|量|数|拟声|区别)(?:\s+(.*))?$/)
if (!match) return null
if (!isSectionInlineReading(match[1]) && Array.from(match[1]).length > 4) return null
return { reading: match[1].trim(), partOfSpeech: match[2], rest: String(match[3] ?? "").trim() }
}
function isSectionInlineReading(line: string): boolean {
return HAN_RE.test(line) && /[a-züāáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜ]/i.test(line) && /[ㄅ-ㄩ]/.test(line)
}
function formatDictionaryDetailLines(lines: string[]): string[] {
const result: string[] = []
const skipLabels = new Set(["书证", "例如", "英文"])
for (let index = 0; index < lines.length; index += 1) {
const line = lines[index]
if (!line || skipLabels.has(line)) {
const next = lines[index + 1]
if (line === "书证" && next) {
result.push(`书证 ${next.replace(/^[-*]\s*/, "")}`)
index += 1
} else if ((line === "例如" || line === "英文") && next) {
result.push(`${line} ${next}`)
index += 1
}
continue
}
const inline = splitInlineReadingPartOfSpeech(line)
if (inline) {
result.push(inline.reading)
result.push(`词性 ${inline.partOfSpeech}`)
if (inline.rest) result.push(inline.rest)
continue
}
const posWithRest = line.match(/^(名|动|形|副|代|介|连|助|叹|量|数|拟声|区别)\s+(.+)$/)
if (posWithRest) {
result.push(`词性 ${posWithRest[1]}`)
result.push(posWithRest[2])
continue
}
if (isPartOfSpeechLine(line)) {
result.push(`词性 ${line}`)
continue
}
if (/^\d+\.$/.test(line)) {
const next = lines[index + 1]
if (next) {
result.push(`${line} ${next}`)
index += 1
}
continue
}
if (/^[-*]\s*/.test(line)) {
result.push(`书证 ${line.replace(/^[-*]\s*/, "")}`)
continue
}
if (/^英文\s*/.test(line) || /^例如\s*/.test(line)) {
result.push(line)
continue
}
if (isSectionInlineReading(line)) {
result.push(line)
continue
}
result.push(line)
}
return result
}
function parseAncientSection(sectionHtml: string, query: string, allowedAlts: string[]): string[] {
const sectionId = firstMatch(sectionHtml, /\bid="([^"]+)"/i)
const imageLimit = sectionId === "zyzx" ? 12 : 2
const ancientAlts = Array.from(new Set([query, ...allowedAlts, ...extractZdicLinkLabels(sectionHtml)]))
const images = extractImages(sectionHtml, sectionId === "zyzx" ? undefined : { allowedAlts: ancientAlts, labelPrefix: query }).slice(0, imageLimit)
if (sectionId === "zyzx") return images
const lines = stripHtmlToLines(sectionHtml)
.filter((line) => !/^(康熙字典|说文解字|音韵方言|字源字形)$/.test(line))
.map((line) => line.replace(/^-\s*/, ""))
return [...images, ...lines]
}
function parsePhonologySection(sectionHtml: string): string[] {
const rows: string[] = []
const rowPattern = /<div\b[^>]*class="[^"]*phon-defs__row[^"]*"[^>]*>([\s\S]*?)(?=<div\b[^>]*class="[^"]*phon-defs__row|<\/div>\s*<\/div>)/gi
let rowMatch: RegExpExecArray | null
while ((rowMatch = rowPattern.exec(sectionHtml))) {
const rowHtml = rowMatch[1]
const label = htmlInlineText(firstMatch(rowHtml, /<[^>]+class="[^"]*phon-defs__label[^"]*"[^>]*>([\s\S]*?)<\/[^>]+>/i))
const value = htmlInlineText(firstMatch(rowHtml, /<[^>]+class="[^"]*phon-defs__value[^"]*"[^>]*>([\s\S]*?)<\/[^>]+>/i))
if (label && value) rows.push(`${label} ${value}`)
}
if (rows.length) return rows
const lines = stripHtmlToAnyLines(sectionHtml)
.filter((line) => !/^(音韵方言|概览|韵书|方言|上古音系|中古音|上古音|音标 & 周边语言|方言读音(旧版简文)|音系简文|反馈)$/.test(line))
const result: string[] = []
for (let index = 0; index < lines.length; index += 1) {
const label = lines[index]
const value = lines[index + 1]
if (value && !/[::;;]/.test(label) && label.length <= 12) {
result.push(`${label} ${value}`)
index += 1
}
}
return result.length ? result : lines
}
function parseSynonymSection(sectionHtml: string): string[] {
const rows: string[] = []
const rowPattern = /<div\b[^>]*class="[^"]*synonym-row[^"]*"[^>]*>([\s\S]*?)<\/div>/gi
let rowMatch: RegExpExecArray | null
while ((rowMatch = rowPattern.exec(sectionHtml))) {
const rowHtml = rowMatch[1]
const label = decodeHtmlEntities(firstMatch(rowHtml, /<span\b[^>]*class="[^"]*synonym-label[^"]*"[^>]*>([\s\S]*?)<\/span>/i).replace(/<[^>]+>/g, " ").trim())
const words = extractTagTexts(rowHtml, /<a\b[^>]*class="[^"]*synonym-tag[^"]*"[^>]*>([\s\S]*?)<\/a>/gi)
if (label && words.length) rows.push(`${label} ${words.join(" ")}`)
}
return rows
}
function parseTranslationSection(sectionHtml: string): string[] {
const rows: string[] = []
const rowPattern = /<div\b[^>]*class="[^"]*word-trans__row[^"]*"[^>]*>([\s\S]*?)<\/div>/gi
let rowMatch: RegExpExecArray | null
while ((rowMatch = rowPattern.exec(sectionHtml))) {
const rowHtml = rowMatch[1]
const lang = decodeHtmlEntities(firstMatch(rowHtml, /<dt\b[^>]*class="[^"]*word-trans__lang[^"]*"[^>]*>([\s\S]*?)<\/dt>/i).replace(/<[^>]+>/g, " ").trim())
const text = decodeHtmlEntities(firstMatch(rowHtml, /<dd\b[^>]*class="[^"]*word-trans__text[^"]*"[^>]*>([\s\S]*?)<\/dd>/i).replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim())
if (lang && text) rows.push(`${lang} ${text}`)
}
return rows
}
function parseZdicSections(html: string, fallbackTitle: string, query: string): ZdicSection[] {
const source = stripNoise(html)
const sections: ZdicSection[] = []
const head = firstMatch(source, /<article\b[^>]*class="[^"]*char-card[^"]*"[^>]*>([\s\S]*?)<\/article>/i)
const allowedImageAlts = Array.from(new Set([query, ...extractImageAlts(head)]))
if (head) {
const lines = parseCharInfoSection(head, query)
if (lines.length) {
sections.push({ title: "字词信息", lines })
}
}
const dictSections = extractDictSections(source)
logZDictEvent("解析汉典页面结构", {
query,
hasCharInfo: Boolean(head),
dictSectionCount: dictSections.length,
})
for (const sectionHtml of dictSections) {
const dataTitle = decodeHtmlEntities(firstMatch(sectionHtml, /\bdata-section="([^"]+)"/i)).trim()
const h2Title = decodeHtmlEntities(firstMatch(sectionHtml, /<h2\b[^>]*>([\s\S]*?)<\/h2>/i).replace(/<[^>]+>/g, " ")).replace(/\s+/g, " ").trim()
const title = dataTitle || h2Title || "解释"
const sectionId = firstMatch(sectionHtml, /\bid="([^"]+)"/i)
const specializedLines =
sectionId === "jbjs" ? parseBasicCharSection(sectionHtml)
: sectionId === "xxjs" ? (sectionHtml.includes("xxjs-reading__head") ? parseDetailedCharSection(sectionHtml) : parseWordExplanationSection(sectionHtml))
: sectionId === "gyjs" ? parseGuoyuSection(sectionHtml)
: sectionId === "syn" ? parseSynonymSection(sectionHtml)
: sectionId === "trans" ? parseTranslationSection(sectionHtml)
: sectionId === "yyfy" ? parsePhonologySection(sectionHtml)
: sectionId === "kxzd" || sectionId === "swjz" || sectionId === "zyzx" ? parseAncientSection(sectionHtml, query, allowedImageAlts)
: []
const lines = (specializedLines.length ? specializedLines : stripHtmlToLines(sectionHtml))