forked from tinbreaker/Tangut-Script-Annotation-Tool
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1091 lines (946 loc) · 37.9 KB
/
app.js
File metadata and controls
1091 lines (946 loc) · 37.9 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
// 加载字典数据
async function loadDictionary() {
try {
const response = await fetch('dictionary.js');
const data = await response.json();
// 初始化词典
wordDictionary = data.WORD_DATA.reduce((acc, entry) => {
acc[entry.word] = entry;
return acc;
}, {});
// 初始化字典
dictionary = data.CHARACTER_DATA.reduce((acc, entry) => {
acc[entry.character] = entry;
return acc;
}, {});
} catch (error) {
alert('加载字典文件时出错:' + error);
}
}
// 检查是否在词典中存在该词
function checkWordInDictionary(chars) {
// 如果输入是数组,将其合并为字符串
const word = Array.isArray(chars) ? chars.join('') : chars;
return wordDictionary[word] ? true : false;
}
// 获取词的解释
function getWordExplanation(word, lang) {
const entry = wordDictionary[word];
return entry ? entry[`explanation${lang}`] || '' : '';
}
// 检查是否为有效字符(非符号)
function isValidChar(char) {
// 如果包含连接符,检查连接符前后的字符
if (char && (char.includes('-') || char.includes('='))) {
const parts = char.split(/[-=]/);
return parts.some(part => part && !/[\p{P}\s]/u.test(part));
}
return char && !/[\p{P}\s]/u.test(char);
}
const COMBINE_RULES = {
characters: {
// 定义通用的连接规则模板
COMBINE_TEMPLATES: {
PREV_EQUAL: {
combineWithPrevious: true,
connector: '='
},
PREV_HYPHEN: {
combineWithPrevious: true,
connector: '-'
},
NEXT_HYPHEN: {
combineWithNext: true,
connector: '-'
}
},
// 特殊规则(需要单独定义的变体规则)
'𗧓': {
variants: [
{
type: 'standalone',
condition: (prev, next) => !isValidChar(prev),
explanationEN: 'I',
explanationCN: '我',
},
{
type: 'combineWithPrevious',
connector: '-',
condition: (prev, next) => isValidChar(prev),
explanationEN: '𝟣ꜱɢ',
explanationCN: '𝟣ꜱɢ',
},
]
},
'𘄢': {
variants: [
{
type: 'standalone',
condition: (prev, next) => !isValidChar(prev) & !isValidChar,
explanationEN: 'Yes',
explanationCN: '是',
},
{
type: 'combineWithPrevious',
connector: '=',
condition: (prev, next) => isValidChar(prev),
explanationEN: 'ɪɴᴛʀɢ.ʀᴛʜ',
explanationCN: 'ɪɴᴛʀɢ.ʀᴛʜ',
},
]
},
'𘃞': {
variants: [
{
type: 'standalone',
condition: (prev, next) => !isValidChar(prev),
explanationEN: '=',
explanationCN: '=',
},
{
type: 'combineWithPrevious',
connector: '=',
condition: (prev, next) => isValidChar(prev),
explanationEN: 'ᴇxʟᴀᴍ',
explanationCN: 'ᴇxʟᴀᴍ',
},
]
},
'𗭪': {
combineWithPrevious: true,
connector: '-='
},
// 使用规则模板的字符
PREV_EQUAL_CHARS: [
'𗫂', '𗅁', '𘆄', '𗇋', '𗗙', '𗦇', '𘏚', '𗑠', '𘋩', '𗳒',
'𗸒', '𗖵', '𘔼', '𗏣', '𘕿', '𗀔', '𗯴', '𘂤', '𗙼', '𘅍',
'𘝨', '𗍊', '𗗂', '𘃡'
],
PREV_HYPHEN_CHARS: [
'𘉞', '𗐱', '𗗟', '𗫶', '𘂆','𗣬'
],
NEXT_HYPHEN_CHARS: [
'𗅋', '𗷝', '𘖑', '𘅇', '𗈪', '𗱢', '𗋚', '𘙌', '𘙇', '𗞞',
'𗌽', '𗭊', '𘀆', '𗘯', '𘊐', '𗏺', '𘗐', '𗋸'
]
}
};
// 在代码初始化时展开模板
function expandCombineRules(rules) {
const { COMBINE_TEMPLATES, PREV_EQUAL_CHARS, PREV_HYPHEN_CHARS, NEXT_HYPHEN_CHARS, ...specificRules } = rules.characters;
const expandedRules = { ...specificRules };
// 展开使用等号连接前面字符的规则
PREV_EQUAL_CHARS.forEach(char => {
expandedRules[char] = { ...COMBINE_TEMPLATES.PREV_EQUAL };
});
// 展开使用连字符连接前面字符的规则
PREV_HYPHEN_CHARS.forEach(char => {
expandedRules[char] = { ...COMBINE_TEMPLATES.PREV_HYPHEN };
});
// 展开使用连字符连接后面字符的规则
NEXT_HYPHEN_CHARS.forEach(char => {
expandedRules[char] = { ...COMBINE_TEMPLATES.NEXT_HYPHEN };
});
return {
characters: expandedRules
};
}
// 初始化时展开规则
const EXPANDED_COMBINE_RULES = expandCombineRules(COMBINE_RULES);
// 获取解释的逻辑
function getExplanation(char, lang, prevChar, nextChar) {
// 检查是否有变体规则
const rules = EXPANDED_COMBINE_RULES.characters[char];
if (rules?.variants) {
const variant = rules.variants.find(v => v.condition(prevChar, nextChar));
if (variant) {
const explanation = variant[`explanation${lang}`];
return explanation || '';
}
}
// 检查是否包含连接符
if (char.includes('-') || char.includes('=')) {
const connectors = char.match(/[-=]/g);
const parts = char.split(/[-=]/);
let explanation = '';
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
// 为每个部分正确传递上下文
const prevPart = i > 0 ? parts[i - 1] : prevChar;
const nextPart = i < parts.length - 1 ? parts[i + 1] : nextChar;
// 先检查这个部分是否有变体规则
const partRules = EXPANDED_COMBINE_RULES.characters[part];
if (partRules?.variants) {
const variant = partRules.variants.find(v => v.condition(prevPart, nextPart));
if (variant) {
explanation += variant[`explanation${lang}`] || '';
} else {
explanation += dictionary[part] ? dictionary[part][`explanation${lang}`] || '' : '';
}
} else {
explanation += dictionary[part] ? dictionary[part][`explanation${lang}`] || '' : '';
}
if (connectors && connectors[i]) {
explanation += connectors[i];
}
}
return explanation;
}
// 查询字典
const dictExplanation = dictionary[char] ? dictionary[char][`explanation${lang}`] || '' : '';
return dictExplanation;
}
// 定义输出格式的分隔符
const FORMAT_SEPARATORS = {
typst: {
items: ', '
},
obsidian: {
items: ' '
},
plaintext: {
items: ' ',
vertical: '\n',
padding: ' '
}
};
function processCombination(items) {
const result = [];
let i = 0;
while (i < items.length) {
const currentItem = items[i];
// 如果是标点符号,直接处理
if (/[\p{P}\s]/u.test(currentItem)) {
result.push(currentItem);
i++;
continue;
}
let handled = false;
const rules = EXPANDED_COMBINE_RULES.characters;
// 查找所有以当前字符开头的词组
const possibleWords = findWordsStartingWith(currentItem);
// 如果找到词组,检查是否完全匹配
if (possibleWords.length > 0) {
const matchedWord = findExactMatch(items, i, possibleWords);
if (matchedWord) {
// 获取词组的格式信息
const wordEntry = wordDictionary[matchedWord.word];
let formattedWord = matchedWord.word;
if (wordEntry && wordEntry.format && wordEntry.format.prefix) {
formattedWord = wordEntry.format.prefix + formattedWord;
}
// 检查是否需要与前一个字符组合
if (result.length > 0 && rules[matchedWord.word[0]]?.combineWithPrevious) {
const connector = rules[matchedWord.word[0]].connector;
result[result.length - 1] = `${result[result.length - 1]}${connector}${formattedWord}`;
} else {
result.push(formattedWord);
}
i += matchedWord.length;
handled = true;
continue;
}
}
// 如果没有找到词组匹配,处理单字的组合规则
if (!handled) {
// 处理向后组合的规则
if (rules[currentItem]?.combineWithNext) {
const connector = rules[currentItem].connector;
if (i + 1 < items.length) {
let combinedStr = currentItem;
let nextIndex = i + 1;
// 首先检查后续字符是否构成词组
const remainingItems = items.slice(nextIndex);
const possibleWords = findWordsStartingWith(remainingItems[0]);
const matchedWord = findExactMatch(remainingItems, 0, possibleWords);
if (matchedWord) {
// 如果找到词组,只添加当前字符和连接符
result.push(combinedStr + connector);
i++;
continue; // 让主循环继续处理词组
}
// 如果没找到词组,处理连续的向后连接
while (nextIndex < items.length) {
const nextItem = items[nextIndex];
// 检查下一个位置开始是否构成词组
const nextPossibleWords = findWordsStartingWith(nextItem);
const nextMatchedWord = findExactMatch(items, nextIndex, nextPossibleWords);
if (nextMatchedWord) {
// 如果发现词组,添加连接符并退出循环
combinedStr += connector;
result.push(combinedStr);
i = nextIndex;
break;
}
// 添加连接符和下一个字符
combinedStr += connector + nextItem;
// 如果下一个字符也有向后组合规则且不是最后一个字符,继续处理
if (rules[nextItem]?.combineWithNext && nextIndex < items.length - 1) {
nextIndex++;
} else {
// 如果是最后一个字符或下一个字符没有向后组合规则
result.push(combinedStr);
i = nextIndex + 1; // 更新索引到下一个位置
break;
}
}
handled = true;
continue;
}
}
// 处理与前一个字符组合的规则
if (result.length > 0) {
let shouldCombine = false;
let connector = '';
if (rules[currentItem]?.variants) {
const variant = rules[currentItem].variants.find(v => {
return v.type === 'combineWithPrevious' &&
v.condition(result[result.length - 1], items[i + 1]);
});
if (variant) {
shouldCombine = true;
connector = variant.connector;
}
} else if (rules[currentItem]?.combineWithPrevious) {
shouldCombine = true;
connector = rules[currentItem].connector;
}
if (shouldCombine) {
result[result.length - 1] = `${result[result.length - 1]}${connector}${currentItem}`;
i++;
handled = true;
continue;
}
}
}
// 如果没有被处理,作为单个字符添加
if (!handled) {
result.push(currentItem);
i++;
}
}
return result;
}
// 查找以指定字符开头的所有词组
function findWordsStartingWith(char) {
const matches = [];
for (const word in wordDictionary) {
// 将词组转换为字符数组进行比较
if ([...word][0] === char) { // 使用数组解构来正确处理 Unicode 字符
matches.push({
word,
length: [...word].length, // 使用数组长度来获取正确的字符数
priority: wordDictionary[word].priority || 0
});
}
}
// 按优先级和长度排序
return matches.sort((a, b) => {
if (a.priority !== b.priority) {
return b.priority - a.priority;
}
return b.length - a.length;
});
}
// 检查是否完全匹配
function findExactMatch(items, startIndex, possibleWords) {
for (const wordInfo of possibleWords) {
const { word, length } = wordInfo;
if (startIndex + length > items.length) continue;
// 直接比较字符串
const candidate = items.slice(startIndex, startIndex + length).join('');
if (candidate === word) {
return wordInfo;
}
}
return null;
}
function processTypstBrackets(text) {
if (!text) {
return '[]';
}
const bracketMatch = text.match(/^\[(.*)\]$/);
if (bracketMatch) {
return `[${bracketMatch[1]}]`;
}
return `[${text}]`;
}
function generate() {
// 添加开始时间记录
const startTime = performance.now();
const inputText = document.getElementById('output').value.trim();
if (!inputText) {
alert('请输入要查询的字符!');
return;
}
const lang = document.querySelector('input[name="lang"]:checked').value.toUpperCase();
const readingSystem = document.querySelector('input[name="reading"]:checked').value;
const outputFormat = document.querySelector('input[name="format"]:checked').value;
const lines = inputText.split('\n');
const outputs = lines
.map(line => line.trim())
.filter(line => line)
.map(line => generateFormattedOutput(line, lang, readingSystem, outputFormat));
document.getElementById('output-text').value = outputs.join('\n\n');
// 计算并输出总用时
const endTime = performance.now();
const totalTime = endTime - startTime;
console.log(`处理完成,总用时: ${totalTime.toFixed(2)}ms`);
}
function generateFormattedOutput(chars, lang, readingSystem, outputFormat) {
if (outputFormat === 'typst') {
return generateTypstOutput(chars, lang, readingSystem);
} else if (outputFormat === 'obsidian') {
return generateObsidianOutput(chars, lang, readingSystem);
} else {
return generatePlainTextOutput(chars, lang, readingSystem);
}
}
function generateTypstOutput(chars, lang, readingSystem) {
const separator = FORMAT_SEPARATORS.typst.items;
const processedChars = processCombination([...chars]);
// 合并连接的项
function mergeConnectedItems(items) {
const result = [];
let currentGroup = '';
items.forEach((item, index) => {
if (index === 0) {
currentGroup = item;
} else {
// 如果当前项以连接符开始或前一组以连接符结束
if (/^[=-]/.test(item) || /[=-]$/.test(currentGroup)) {
currentGroup += item;
} else {
result.push(currentGroup);
currentGroup = item;
}
}
});
if (currentGroup) {
result.push(currentGroup);
}
return result;
}
// 处理源字符
const charList = mergeConnectedItems(processedChars).map(char => processTypstBrackets(char));
// 处理读音
const rawReadings = processedChars.map((char, index) => {
// 首先检查是否在词典中
if (wordDictionary[char]) {
const reading = readingSystem === 'GX' ? wordDictionary[char].GX : wordDictionary[char].GHC;
// 检查是否需要添加前缀
const entry = wordDictionary[char];
if (entry.format && entry.format.prefix) {
return entry.format.prefix + reading.replace(/[\[\]]/g, '');
}
return reading ? reading.replace(/[\[\]]/g, '') : '';
}
// 如果不在词典中,按原来的方式处理
if (char.includes('-') || char.includes('=')) {
const parts = char.split(/[-=]/);
const connectors = char.match(/[-=]/g);
return parts.map((part, idx) => {
let reading = '';
// 检查是否是词组
if (wordDictionary[part]) {
reading = readingSystem === 'GX' ? wordDictionary[part].GX : wordDictionary[part].GHC;
reading = reading.replace(/[\[\]]/g, '');
} else if (dictionary[part]) {
reading = readingSystem === 'GX' ? dictionary[part].GX : dictionary[part].GHC;
}
return idx < parts.length - 1 ?
`${reading || ''}${connectors[idx]}` : (reading || '');
}).join('');
}
if (dictionary[char]) {
const reading = readingSystem === 'GX' ? dictionary[char].GX : dictionary[char].GHC;
return reading || '';
} else if (/[\p{P}\s]/u.test(char)) {
return char;
}
return '';
});
// 合并连接的读音
const readings = mergeConnectedItems(rawReadings).map(reading => processTypstBrackets(reading));
// 处理词义解释
const rawMorphemes = processedChars.map((char, index, array) => {
// 首先检查是否在词典中
if (wordDictionary[char]) {
return processTypstBrackets(wordDictionary[char][`explanation${lang}`] || '');
}
const prevChar = index > 0 ? array[index - 1] : null;
const nextChar = index < array.length - 1 ? array[index + 1] : null;
if (char.includes('-') || char.includes('=')) {
// 处理多个字符连接的情况
const parts = char.split(/[-=]/);
const connectors = char.match(/[-=]/g);
const explanations = parts.map((part, idx) => {
// 检查是否是词组
if (wordDictionary[part]) {
return wordDictionary[part][`explanation${lang}`] || '';
}
const prevPart = idx > 0 ? parts[idx - 1] : prevChar;
const nextPart = idx < parts.length - 1 ? parts[idx + 1] : nextChar;
return getExplanation(part, lang, prevPart, nextPart);
});
return explanations.map((exp, idx) =>
idx < explanations.length - 1 ?
`${exp}${connectors[idx]}` : exp
).join('');
}
const explanation = getExplanation(char, lang, prevChar, nextChar);
if (explanation) {
return explanation;
} else if (/[\p{P}\s]/u.test(char)) {
return char;
}
return '';
});
// 合并连接的词义解释
const morphemes = mergeConnectedItems(rawMorphemes).map(morpheme => processTypstBrackets(morpheme));
return `#gloss(\n` +
`header: ${processTypstBrackets(chars)},\n` +
`source: (${charList.join(separator)}),\n` +
`transliteration: (${readings.join(separator)}),\n` +
`morphemes: (${morphemes.join(separator)}),\n` +
`translation: ""\n)`;
}
function generateObsidianOutput(chars, lang, readingSystem) {
const separator = FORMAT_SEPARATORS.obsidian.items;
const processedChars = processCombination([...chars]);
// 处理音读部分
const rawReadings = processedChars.map((char, index) => {
// 首先检查是否在词典中
if (wordDictionary[char]) {
const reading = readingSystem === 'GX' ? wordDictionary[char].GX : wordDictionary[char].GHC;
// 检查是否需要添加前缀
const entry = wordDictionary[char];
if (entry.format && entry.format.prefix) {
return entry.format.prefix + reading.replace(/[\[\]]/g, '');
}
return reading ? reading.replace(/[\[\]]/g, '') : '';
}
// 如果不在词典中,按原来的方式处理
if (char.includes('-') || char.includes('=')) {
const parts = char.split(/[-=]/);
const connectors = char.match(/[-=]/g);
return parts.map((part, idx) => {
let reading = '';
// 检查是否是词组
if (wordDictionary[part]) {
reading = readingSystem === 'GX' ? wordDictionary[part].GX : wordDictionary[part].GHC;
reading = reading.replace(/[\[\]]/g, '');
} else if (dictionary[part]) {
reading = readingSystem === 'GX' ? dictionary[part].GX : dictionary[part].GHC;
}
return idx < parts.length - 1 ?
`${reading || ''}${connectors[idx]}` : (reading || '');
}).join('');
}
if (dictionary[char]) {
const reading = readingSystem === 'GX' ? dictionary[char].GX : dictionary[char].GHC;
return reading || '';
} else if (/[\p{P}\s]/u.test(char)) {
return char;
}
return '';
});
// 处理词义解释部分
const morphemes = processedChars.map((char, index, array) => {
// 首先检查是否在词典中
if (wordDictionary[char]) {
const explanation = wordDictionary[char][`explanation${lang}`] || '';
// 检查是否需要添加前缀
const entry = wordDictionary[char];
if (entry.format && entry.format.prefix) {
return entry.format.prefix + explanation;
}
return explanation;
}
const prevChar = index > 0 ? array[index - 1] : null;
const nextChar = index < array.length - 1 ? array[index + 1] : null;
if (char.includes('-') || char.includes('=')) {
// 处理多个字符连接的情况
const parts = char.split(/[-=]/);
const connectors = char.match(/[-=]/g);
const explanations = parts.map((part, idx) => {
// 检查是否是词组
if (wordDictionary[part]) {
return wordDictionary[part][`explanation${lang}`] || '';
}
const prevPart = idx > 0 ? parts[idx - 1] : prevChar;
const nextPart = idx < parts.length - 1 ? parts[idx + 1] : nextChar;
return getExplanation(part, lang, prevPart, nextPart);
});
return explanations.map((exp, idx) =>
idx < explanations.length - 1 ?
`${exp}${connectors[idx]}` : exp
).join('');
}
const explanation = getExplanation(char, lang, prevChar, nextChar);
if (explanation) {
return explanation;
} else if (/[\p{P}\s]/u.test(char)) {
return char;
}
return '';
});
// 处理标点符号前的空格
function joinWithSmartSpacing(items) {
return items.reduce((result, current, index) => {
if (index === 0) return current;
// 如果当前项以连接符开始,不添加空格
if (/^[=-]/.test(current)) {
return result + current;
}
// 如果前一项以连接符结束,不添加空格
if (/[=-]$/.test(result)) {
return result + current;
}
// 如果当前项是标点符号,不添加空格
if (/^[\p{P}]/u.test(current)) {
return result + current;
}
// 其他情况添加空格
return result + separator + current;
}, '');
}
// 过滤掉空字符串并使用新的连接方法
const readingsText = joinWithSmartSpacing(rawReadings.filter(r => r));
const morphemesText = joinWithSmartSpacing(morphemes.filter(m => m));
// 返回Obsidian格式的输出
return '```gloss\n' +
'\\set exstyle big\n' +
`\\ex ${chars}\n` +
`\\gla ${readingsText}\n` +
`\\glb ${morphemesText}\n` +
'\\ft \n' +
'```';
}
function generatePlainTextOutput(chars, lang, readingSystem) {
const processedChars = processCombination([...chars]);
// 获取字符、读音和词义
const charGroups = [];
const readingGroups = [];
const morphemeGroups = [];
let currentCharGroup = '';
let currentReadingGroup = '';
let currentMorphemeGroup = '';
processedChars.forEach((char, index, array) => {
// 处理字符
if (index > 0 && !char.startsWith('-') && !char.startsWith('=') &&
!currentCharGroup.endsWith('-') && !currentCharGroup.endsWith('=')) {
charGroups.push(currentCharGroup);
readingGroups.push(currentReadingGroup);
morphemeGroups.push(currentMorphemeGroup);
currentCharGroup = '';
currentReadingGroup = '';
currentMorphemeGroup = '';
}
currentCharGroup += char;
// 处理读音
let reading = '';
if (wordDictionary[char]) {
reading = readingSystem === 'GX' ? wordDictionary[char].GX : wordDictionary[char].GHC;
reading = reading.replace(/[\[\]]/g, '');
} else if (char.includes('-') || char.includes('=')) {
reading = getConnectedReading(char, readingSystem);
} else if (dictionary[char]) {
reading = readingSystem === 'GX' ? dictionary[char].GX : dictionary[char].GHC;
}
currentReadingGroup += reading;
// 处理词义
let morpheme = '';
if (wordDictionary[char]) {
morpheme = wordDictionary[char][`explanation${lang}`] || '';
} else {
const prevChar = index > 0 ? array[index - 1] : null;
const nextChar = index < array.length - 1 ? array[index + 1] : null;
morpheme = getExplanation(char, lang, prevChar, nextChar);
}
currentMorphemeGroup += morpheme;
});
// 添加最后一组
if (currentCharGroup) {
charGroups.push(currentCharGroup);
readingGroups.push(currentReadingGroup);
morphemeGroups.push(currentMorphemeGroup);
}
// 计算每列的最大宽度
const columnWidths = charGroups.map((char, index) => {
const lengths = [
getStringWidth(char),
getStringWidth(readingGroups[index]),
getStringWidth(morphemeGroups[index])
];
return Math.max(...lengths);
});
// 生成对齐的输出
const lines = [
charGroups.map((char, i) => padString(char, columnWidths[i])).join(' '),
readingGroups.map((reading, i) => padString(reading, columnWidths[i])).join(' '),
morphemeGroups.map((morpheme, i) => padString(morpheme, columnWidths[i])).join(' ')
];
return lines.join('\n');
}
// 辅助函数:计算字符串显示宽度(考虑CJK字符)
function getStringWidth(str) {
return [...str].reduce((width, char) => {
// CJK字符通常是全角宽度(占用2个半角字符的空间)
if (/[\u4e00-\u9fff\u3400-\u4dbf\u{20000}-\u{2a6df}\u{2a700}-\u{2b73f}\u{2b740}-\u{2b81f}\u{2b820}-\u{2ceaf}\u{2ceb0}-\u{2ebef}]/u.test(char)) {
return width + 2;
}
return width + 1;
}, 0);
}
// 辅助函数:使用空格填充字符串至指定宽度
function padString(str, width) {
const currentWidth = getStringWidth(str);
return str + ' '.repeat(Math.max(0, width - currentWidth));
}
// 辅助函数:获取连接字符的读音
function getConnectedReading(char, readingSystem) {
const parts = char.split(/[-=]/);
const connectors = char.match(/[-=]/g);
return parts.map((part, idx) => {
let reading = '';
if (wordDictionary[part]) {
reading = readingSystem === 'GX' ? wordDictionary[part].GX : wordDictionary[part].GHC;
reading = reading.replace(/[\[\]]/g, '');
} else if (dictionary[part]) {
reading = readingSystem === 'GX' ? dictionary[part].GX : dictionary[part].GHC;
}
return idx < parts.length - 1 ?
`${reading || ''}${connectors[idx]}` : (reading || '');
}).join('');
}
function clearAll() {
document.getElementById('output').value = '';
document.getElementById('output-text').value = '';
}
function copyOutput() {
const output = document.getElementById('output-text');
if (!output.value) {
alert('没有可复制的内容');
return;
}
output.select();
document.execCommand('copy');
const copyBtn = document.getElementById('copy-btn');
copyBtn.textContent = '已复制';
setTimeout(() => {
copyBtn.textContent = '复制';
}, 1000);
}
function handleGenerate() {
const input = document.getElementById('output');
if (!input.value.trim() && input.placeholder) {
input.value = input.placeholder;
}
generate();
}
const strokeData = [
{ code: 'A', alt: '一' },
{ code: 'B', alt: '丨' },
{ code: 'C', alt: '丿' },
{ code: 'D', alt: '丶' },
{ code: 'E', alt: '𠃍' },
{ code: 'F', alt: '㇈' },
{ code: 'G', alt: '㇇' },
{ code: 'H', alt: '𘠄' },
{ code: 'I', alt: '𘠅' },
{ code: 'J', alt: '𠄎' },
{ code: 'K', alt: '㇍' },
{ code: 'L', alt: '𠄌' },
{ code: 'M', alt: '乚' },
{ code: 'N', alt: '㇊' },
{ code: 'O', alt: '𘠈' },
{ code: 'P', alt: '𡿨' },
{ code: 'Q', alt: '㇏' },
{ code: '.', alt: '.' },
{ code: '*', alt: '*' }
];
function createStrokeButtons() {
const container = document.getElementById('stroke-buttons');
// 清空容器,防止重复添加
container.innerHTML = '';
strokeData.forEach(stroke => {
const button = document.createElement('button');
button.className = 'stroke-button';
button.onclick = () => insertStroke(stroke.code);
button.textContent = stroke.alt;
const tooltip = document.createElement('span');
tooltip.className = 'tooltip';
tooltip.textContent = stroke.code;
button.appendChild(tooltip);
container.appendChild(button);
});
}
// 监听笔画输入框的变化
document.getElementById('stroke-entry-field').addEventListener('input', (e) => {
updateSearchResults(e.target.value);
});
// 切换复选框状态的函数
function toggleCheckbox(id) {
const checkbox = document.getElementById(id);
checkbox.checked = !checkbox.checked;
updateSearchResults(document.getElementById('stroke-entry-field').value);
}
// 清除笔画输入
function clearStrokeEntryField() {
document.getElementById('stroke-entry-field').value = '';
document.getElementById('result-list').innerHTML = '';
}
// 添加清除所有功能
function clearAll() {
document.getElementById('output').value = '';
document.getElementById('output-text').value = '';
document.getElementById('stroke-entry-field').value = '';
document.getElementById('result-list').innerHTML = '';
// 重置复选框
document.getElementById('stroke-begins-with').checked = false;
document.getElementById('stroke-ends-with').checked = false;
}
// 添加 updateSearchResults 函数定义
function updateSearchResults(value) {
const resultList = document.getElementById('result-list');
resultList.innerHTML = ''; // 清空现有结果
if (!value) return; // 如果没有输入值,直接返回
// 更新笔画输入(这会触发 txglook.js 中的 updateStrokeEntry 函数)
updateStrokeEntry();
// 获取结果列表(resultList 应该是由 txglook.js 中的 updateResultsList 函数设置的全局变量)
if (window.resultList && window.resultList.length > 0) {
window.resultList.forEach(char => {
const li = document.createElement('li');
li.className = 'results-item';
li.textContent = char;
// 添加点击事件
li.setAttribute('onclick', `insertAtCursor('output', '${char}')`);
resultList.appendChild(li);
});
}
}
// 修改页面加载初始化代码
document.addEventListener('DOMContentLoaded', () => {
createStrokeButtons();
// 初始化笔画输入字段的事件监听器
const strokeEntryField = document.getElementById('stroke-entry-field');
if (strokeEntryField) {
strokeEntryField.addEventListener('input', (e) => {
updateSearchResults(e.target.value);
});
}
});
// 多语言文本数据
const i18nData = {
zh: {
"title": "西夏文<br>自动标注工具 α",
"input-label": "输入字符:",
"generate": "生成",
"clear": "清除",
"language-choice": "语言选择:",
"chinese": "中文",
"english": "English",
"reading-system": "读音系统:",
"gongxun": "龚勋",
"gonghuangcheng": "龚煌城",
"output-format": "输出格式:",
"format-output": "格式输出:",
"copy-clipboard": "复制到剪贴板",
"plain-text": "纯文本",
},
en: {
"title": "Tangut Script<br>Annotation Tool α",
"input-label": "Input Characters:",
"generate": "Generate",
"clear": "Clear",
"language-choice": "Language:",
"chinese": "Chinese",
"english": "English",
"reading-system": "Reading System:",
"gongxun": "GX",