-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtts-userscript.js
More file actions
6236 lines (5716 loc) · 206 KB
/
Copy pathtts-userscript.js
File metadata and controls
6236 lines (5716 loc) · 206 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
// ==UserScript==
// @name 本地划词听译助手
// @name:zh-CN 本地划词听译助手
// @name:en Local Selection Read & Translate
// @namespace https://github.com/Yan-ShiBo/LocalReadTranslate
// @version 1.15.8
// @description 使用本地中介服务发现真实可用模型,朗读或翻译网页选中文本。
// @description:zh-CN 使用本地中介服务发现真实可用模型,朗读或翻译网页选中文本。
// @description:en Read or translate selected text using models discovered through the local mediator.
// @author Yan-ShiBo
// @license MIT
// @match *://*/*
// @homepageURL https://github.com/Yan-ShiBo/LocalReadTranslate
// @supportURL https://github.com/Yan-ShiBo/LocalReadTranslate/issues
// @downloadURL https://raw.githubusercontent.com/Yan-ShiBo/LocalReadTranslate/main/tts-userscript.js
// @updateURL https://raw.githubusercontent.com/Yan-ShiBo/LocalReadTranslate/main/tts-userscript.js
// @grant GM_xmlhttpRequest
// @grant GM_addStyle
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_setClipboard
// @connect 127.0.0.1
// @compatible chrome Requires Tampermonkey and the local API server.
// @compatible edge Requires Tampermonkey and the local API server.
// @compatible brave Requires Tampermonkey and the local API server.
// @run-at document-end
// @noframes
// ==/UserScript==
function createSelectionTools(document, window = document.defaultView) {
const MATH_SELECTOR = 'math, mjx-container, script[type^="math/tex"], .MathJax, .katex, .katex-display, [data-latex], [data-tex], [data-math], [data-mathml], [data-math-source], [role="math"]';
const SOURCE_ATTRIBUTES = ["data-math-source", "data-latex", "data-tex", "data-math", "data-mathml"];
const SOURCE_SELECTOR = SOURCE_ATTRIBUTES.map((name) => `[${name}]`).join(", ");
function isSourceMathWrapper(element) {
if (!element || element.nodeType !== 1) return false;
if (String(element.getAttribute("data-math-source") || "").trim()) return true;
if (element.getAttribute("role") !== "math") return false;
const label = String(element.getAttribute("aria-label") || "").trim();
if (!label || /^math$/i.test(label)) return false;
// A role/label is only a fallback. Do not let an empty or descriptive
// outer shell swallow independent MathML/MathJax or explicit child sources.
if (element.querySelector('math, mjx-container, mjx-math, script[type^="math/tex"]')) return false;
return !Array.from(element.querySelectorAll(SOURCE_SELECTOR)).some((child) =>
SOURCE_ATTRIBUTES.some((name) => String(child.getAttribute(name) || "").trim())
);
}
function normalizeSelectionOutput(text) {
return String(text || "")
.replace(/\r\n?/g, "\n")
.replace(/[ \t]+\n/g, "\n")
.replace(/\n[ \t]+/g, "\n")
.replace(/[ \t]{2,}/g, " ")
.replace(/\n{3,}/g, "\n\n")
.trim();
}
function normalizeMathFormulaText(text) {
return String(text || "")
.replace(/\r\n?/g, "\n")
.replace(/\s+/g, " ")
.replace(/\s*([{}_^=,+*/()])\s*/g, "$1")
.replace(/\s*(->|→|⇒|↦|\\to|\\rightarrow|\\mapsto)\s*/g, " \\to ")
.replace(/\s+/g, " ")
.trim();
}
function mathOperatorToTex(value) {
const operator = String(value || "").trim();
const operators = {
"→": "\\to",
"⇒": "\\Rightarrow",
"↦": "\\mapsto",
"−": "-",
"×": "\\times",
"÷": "\\div",
"≤": "\\le",
"≥": "\\ge",
"≠": "\\ne",
"≈": "\\approx",
"∈": "\\in",
"∑": "\\sum",
"∫": "\\int",
};
return operators[operator] || operator;
}
function mathMlChildrenToTex(element) {
return Array.from(element.childNodes || [])
.map(mathMlNodeToTex)
.filter(Boolean)
.join(" ");
}
function mathMlNodeToTex(node) {
if (!node) return "";
if (node.nodeType === 3) {
return String(node.nodeValue || "").trim();
}
if (node.nodeType !== 1) return "";
const element = node;
const tag = (element.localName || element.tagName || "").toLowerCase();
const children = Array.from(element.childNodes || []);
const child = (index) => mathMlNodeToTex(children[index]);
if (tag === "annotation") return "";
if (tag === "semantics") {
const visible = children.find((item) => {
const name = (item.localName || item.tagName || "").toLowerCase();
return name !== "annotation" && name !== "annotation-xml";
});
return mathMlNodeToTex(visible);
}
if (tag === "math" || tag === "mrow" || tag === "mpadded" || tag === "mstyle") {
return mathMlChildrenToTex(element);
}
if (tag === "mi" || tag === "mn" || tag === "mtext") {
return String(element.textContent || "").trim();
}
if (tag === "mo") {
return mathOperatorToTex(element.textContent);
}
if (tag === "msub") {
return `${child(0)}_{${child(1)}}`;
}
if (tag === "msup") {
return `${child(0)}^{${child(1)}}`;
}
if (tag === "msubsup") {
return `${child(0)}_{${child(1)}}^{${child(2)}}`;
}
if (tag === "mfrac") {
return `\\frac{${child(0)}}{${child(1)}}`;
}
if (tag === "msqrt") {
return `\\sqrt{${mathMlChildrenToTex(element)}}`;
}
if (tag === "mroot") {
return `\\sqrt[${child(1)}]{${child(0)}}`;
}
if (tag === "mfenced") {
const open = element.getAttribute("open") || "(";
const close = element.getAttribute("close") || ")";
return `${open}${mathMlChildrenToTex(element)}${close}`;
}
if (tag === "mtable") {
const rows = children.map(mathMlNodeToTex).filter(Boolean);
return `\\begin{matrix}${rows.join(" \\\\ ")}\\end{matrix}`;
}
if (tag === "mtr" || tag === "mlabeledtr") {
return children.map(mathMlNodeToTex).filter(Boolean).join(" & ");
}
if (tag === "mtd") {
return mathMlChildrenToTex(element);
}
return mathMlChildrenToTex(element);
}
function mathJaxChtmlChildrenToTex(element) {
return Array.from(element.childNodes || [])
.map(mathJaxChtmlNodeToTex)
.filter(Boolean)
.join(" ");
}
function isKatexElement(element) {
return Boolean(
element &&
element.nodeType === 1 &&
element.classList &&
(element.classList.contains("katex") || element.classList.contains("katex-display"))
);
}
function closestKatexRoot(element) {
if (!element || element.nodeType !== 1 || !element.closest) return null;
return element.closest(".katex-display") || element.closest(".katex");
}
function normalizeMathGlyphChar(char) {
if (!char) return "";
const cp = char.codePointAt(0);
if (cp >= 0x1d434 && cp <= 0x1d44d) return String.fromCharCode(65 + cp - 0x1d434);
if (cp >= 0x1d44e && cp <= 0x1d467) return String.fromCharCode(97 + cp - 0x1d44e);
if (cp >= 0x1d7ce && cp <= 0x1d7d7) return String(cp - 0x1d7ce);
const greek = {
"𝛼": "\\alpha", "𝛽": "\\beta", "𝛾": "\\gamma", "𝛿": "\\delta",
"𝜃": "\\theta", "𝜆": "\\lambda", "𝜇": "\\mu", "𝜋": "\\pi",
"𝜎": "\\sigma", "𝜔": "\\omega",
};
return greek[char] || char;
}
function mathJaxGlyphToText(element) {
const className = String(element.getAttribute("class") || "");
const match = className.match(/\bmjx-c([0-9A-Fa-f]+)\b/);
if (!match) return "";
const codePoint = Number.parseInt(match[1], 16);
if (!Number.isFinite(codePoint)) return "";
try {
return normalizeMathGlyphChar(String.fromCodePoint(codePoint));
} catch (e) {
return "";
}
}
function meaningfulMathJaxChildren(element) {
return Array.from(element.childNodes || []).filter((child) => {
if (!child) return false;
if (child.nodeType === 3) return Boolean(String(child.nodeValue || "").trim());
if (child.nodeType !== 1) return false;
const tag = (child.localName || child.tagName || "").toLowerCase();
return tag !== "mjx-assistive-mml" && tag !== "mjx-itable";
});
}
function mathJaxChtmlNodeToTex(node) {
if (!node) return "";
if (node.nodeType === 3) {
return String(node.nodeValue || "").trim();
}
if (node.nodeType !== 1) return "";
const element = node;
const tag = (element.localName || element.tagName || "").toLowerCase();
const children = meaningfulMathJaxChildren(element);
const child = (index) => mathJaxChtmlNodeToTex(children[index]);
const joined = () => children.map(mathJaxChtmlNodeToTex).filter(Boolean).join(" ");
if (tag === "mjx-c") {
return String(element.textContent || "").trim() || mathJaxGlyphToText(element);
}
if (tag === "mjx-assistive-mml") return "";
if (tag === "mjx-container" || tag === "mjx-math" || tag === "mjx-mrow" || tag === "mjx-texatom" || tag === "mjx-script" || tag === "mjx-box") {
return joined();
}
if (tag === "mjx-mi" || tag === "mjx-mn" || tag === "mjx-mtext") {
return String(element.textContent || "").trim() || joined();
}
if (tag === "mjx-mo") {
return mathOperatorToTex(String(element.textContent || "").trim() || joined());
}
if (tag === "mjx-msub") {
return `${child(0)}_{${child(children.length - 1)}}`;
}
if (tag === "mjx-msup") {
return `${child(0)}^{${child(children.length - 1)}}`;
}
if (tag === "mjx-msubsup") {
return `${child(0)}_{${child(1)}}^{${child(children.length - 1)}}`;
}
if (tag === "mjx-mfrac") {
return `\\frac{${child(0)}}{${child(1)}}`;
}
if (tag === "mjx-msqrt") {
return `\\sqrt{${joined()}}`;
}
if (tag === "mjx-mover" || tag === "mjx-over") {
const base = child(0);
const accent = children.slice(1).map(mathJaxChtmlNodeToTex).join(" ");
if (/[-_‾¯]/.test(accent)) return `\\bar{${base}}`;
if (/[~˜]/.test(accent)) return `\\tilde{${base}}`;
return `\\hat{${base}}`;
}
return String(element.textContent || "").trim() || joined();
}
function findTexAnnotation(element) {
const annotations = Array.from(element.querySelectorAll ? element.querySelectorAll("annotation") : []);
for (const annotation of annotations) {
const encoding = String(annotation.getAttribute("encoding") || "").toLowerCase();
if (encoding.includes("tex") || encoding.includes("latex")) {
const value = normalizeMathFormulaText(annotation.textContent);
if (value) return value;
}
}
return "";
}
function extractMathFormula(element) {
if (!element || element.nodeType !== 1) return "";
const tag = (element.localName || element.tagName || "").toLowerCase();
if (tag === "script" && /^math\/tex/i.test(element.getAttribute("type") || "")) {
return normalizeMathFormulaText(element.textContent);
}
for (const name of SOURCE_ATTRIBUTES) {
// ChatGPT keeps the original TeX on an outer wrapper. Do not normalize
// it like rendered glyphs: spaces inside commands such as \text matter.
const value = name === "data-math-source"
? String(element.getAttribute(name) || "").trim()
: normalizeMathFormulaText(element.getAttribute(name));
if (value) return value;
}
const annotation = findTexAnnotation(element);
if (annotation) return annotation;
const script = element.querySelector && element.querySelector('script[type^="math/tex"]');
if (script) {
const value = normalizeMathFormulaText(script.textContent);
if (value) return value;
}
const mathElement = tag === "math" ? element : element.querySelector && element.querySelector("math");
if (mathElement) {
const value = normalizeMathFormulaText(mathMlNodeToTex(mathElement));
if (value) return value;
}
if (tag === "mjx-container" || (element.querySelector && element.querySelector("mjx-math, mjx-msub, mjx-msup, mjx-mover"))) {
const value = normalizeMathFormulaText(mathJaxChtmlNodeToTex(element));
if (value) return value;
}
if (isKatexElement(element) || (element.querySelector && element.querySelector(".katex-mathml, .katex-html"))) {
const katexRoot = closestKatexRoot(element) || element;
const mathMl = katexRoot.querySelector && katexRoot.querySelector(".katex-mathml math");
if (mathMl) {
const value = normalizeMathFormulaText(mathMlNodeToTex(mathMl));
if (value) return value;
}
const texAnnotation = katexRoot.querySelector && katexRoot.querySelector('annotation[encoding*="TeX"], annotation[encoding*="tex"], annotation[encoding*="latex"]');
if (texAnnotation) {
const value = normalizeMathFormulaText(texAnnotation.textContent);
if (value) return value;
}
}
const aria = isSourceMathWrapper(element)
? String(element.getAttribute("aria-label") || "").trim()
: normalizeMathFormulaText(element.getAttribute("aria-label"));
if (aria && !/^math$/i.test(aria)) return aria;
return normalizeMathFormulaText(element.textContent);
}
function isSemanticMathElement(element) {
if (!element || element.nodeType !== 1) return false;
if (isSourceMathWrapper(element)) return true;
const tag = (element.localName || element.tagName || "").toLowerCase();
if (tag === "math" || tag === "mjx-container") return true;
if (tag === "script" && /^math\/tex/i.test(element.getAttribute("type") || "")) return true;
if (element.classList && element.classList.contains("MathJax")) return true;
if (isKatexElement(element)) return true;
return ["data-latex", "data-tex", "data-math", "data-mathml"].some((name) =>
element.hasAttribute && element.hasAttribute(name)
);
}
function isDisplayMathElement(element) {
if (!element || element.nodeType !== 1) return false;
const tag = (element.localName || element.tagName || "").toLowerCase();
const type = String(element.getAttribute && element.getAttribute("type") || "");
const display = String(element.getAttribute && element.getAttribute("display") || "");
if (tag === "script" && /mode\s*=\s*display/i.test(type)) return true;
if (tag === "math" && /^block$/i.test(display)) return true;
if (tag === "mjx-container" && /^(?:true|block)$/i.test(display)) return true;
// The source owner can be outside KaTeX's display container. Inline
// style and descendants survive cloneContents(), unlike computed style.
if (isSourceMathWrapper(element) && (
(element.style && element.style.display === "block") ||
element.querySelector('.katex-display, .MathJax_Display, math[display="block"], mjx-container[display="true"]')
)) return true;
if (
element.classList &&
(element.classList.contains("katex-display") ||
element.classList.contains("MathJax_Display"))
) {
return true;
}
return Boolean(
element.closest &&
element.closest(".katex-display, .MathJax_Display")
);
}
function closestSemanticMathElement(node) {
let element = null;
let nearestMath = null;
if (!node) return null;
if (node.nodeType === 1) {
element = node;
} else {
element = node.parentElement || node.parentNode;
}
while (element && element.nodeType === 1) {
// Retain the source-bearing owner before cloning a partial selection,
// even if a KaTeX glyph or an intermediate layout div is closer.
if (isSourceMathWrapper(element)) return element;
if (!nearestMath && isSemanticMathElement(element)) nearestMath = element;
element = element.parentElement;
}
return nearestMath;
}
function rectsOverlap(a, b) {
if (!a || !b) return false;
if (a.width <= 0 || a.height <= 0 || b.width <= 0 || b.height <= 0) return false;
const horizontal = Math.min(a.right, b.right) - Math.max(a.left, b.left);
const vertical = Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top);
if (horizontal <= 0 || vertical <= 0) return false;
const overlapArea = horizontal * vertical;
const smallerArea = Math.min(a.width * a.height, b.width * b.height);
return overlapArea / Math.max(smallerArea, 1) >= 0.08;
}
function rangeBoundaryIsInsideElement(range, element) {
return Boolean(
range &&
element &&
(element.contains(range.startContainer) || element.contains(range.endContainer))
);
}
function rangeLooksLikeMathOnly(range, mathEl) {
if (!range || !mathEl) return false;
const selected = String(range.toString() || "").replace(/\s+/g, "");
const mathText = String(mathEl.textContent || "").replace(/\s+/g, "");
if (!selected) return true;
if (!mathText) return selected.length <= 12;
return selected.length <= Math.max(12, Math.ceil(mathText.length * 0.55));
}
function serializeSelectionNode(node) {
if (!node) return "";
if (node.nodeType === 3) return node.nodeValue || "";
if (node.nodeType !== 1 && node.nodeType !== 11) return "";
if (node.nodeType === 1) {
const element = node;
const tag = (element.localName || element.tagName || "").toLowerCase();
if (tag === "style" || tag === "noscript") return "";
if (isSemanticMathElement(element)) {
const formula = extractMathFormula(element);
const wrapper = isDisplayMathElement(element) ? "MATH_BLOCK" : "MATH";
return formula ? ` [[${wrapper}: ${formula}]] ` : "";
}
if (tag === "br") return "\n";
if (tag === "script") return "";
}
const text = Array.from(node.childNodes || []).map(serializeSelectionNode).join("");
if (node.nodeType !== 1) return text;
const blockTags = new Set([
"address", "article", "aside", "blockquote", "div", "dl", "figcaption",
"figure", "footer", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hr",
"li", "main", "nav", "ol", "p", "pre", "section", "table", "tr", "ul",
]);
const tag = (node.localName || node.tagName || "").toLowerCase();
return blockTags.has(tag) ? `\n${text}\n` : text;
}
function expandRangeToContainMath(range) {
if (!range) return range;
const newRange = range.cloneRange();
const selectedRect = range.getBoundingClientRect ? range.getBoundingClientRect() : null;
const startMath = closestSemanticMathElement(range.startContainer);
const endMath = closestSemanticMathElement(range.endContainer);
try {
if (startMath && startMath.parentNode) {
newRange.setStartBefore(startMath);
}
if (endMath && endMath.parentNode) {
newRange.setEndAfter(endMath);
}
} catch (e) {
// Continue with query-based expansion below.
}
const common = range.commonAncestorContainer;
if (!common) return newRange;
const root = common.nodeType === 1 ? common : (common.parentElement || common.parentNode);
if (!root || typeof root.querySelectorAll !== "function") return newRange;
let mathElements = [];
try {
const scanRoot = root.closest && root.closest("p, li, div, section, article, body")
? root.closest("p, li, div, section, article, body")
: root;
mathElements = Array.from(scanRoot.querySelectorAll(MATH_SELECTOR)).filter(isSemanticMathElement);
if (isSemanticMathElement(scanRoot)) {
mathElements.push(scanRoot);
}
if (mathElements.length === 0 && selectedRect && document.querySelectorAll) {
mathElements = Array.from(document.querySelectorAll(MATH_SELECTOR)).filter(isSemanticMathElement).filter((mathEl) => {
try {
return rectsOverlap(selectedRect, mathEl.getBoundingClientRect());
} catch (e) {
return false;
}
});
}
} catch (e) {
return newRange;
}
for (const mathEl of mathElements) {
try {
const intersectsDom = newRange.intersectsNode(mathEl);
const intersectsRect = selectedRect && rectsOverlap(selectedRect, mathEl.getBoundingClientRect());
if (intersectsDom || intersectsRect) {
if (mathEl.contains(newRange.startContainer)) {
newRange.setStartBefore(mathEl);
}
if (mathEl.contains(newRange.endContainer)) {
newRange.setEndAfter(mathEl);
}
if (
intersectsRect &&
!intersectsDom &&
!rangeBoundaryIsInsideElement(newRange, mathEl) &&
rangeLooksLikeMathOnly(range, mathEl)
) {
newRange.setStartBefore(mathEl);
newRange.setEndAfter(mathEl);
}
}
} catch (e) {
// Ignore errors on specific nodes
}
}
return newRange;
}
function getSelectedText() {
const selection = window.getSelection();
if (!selection) return "";
const plainText = selection.toString().trim();
const semanticParts = [];
for (let index = 0; index < selection.rangeCount; index += 1) {
const range = selection.getRangeAt(index);
const expandedRange = expandRangeToContainMath(range);
semanticParts.push(serializeSelectionNode(expandedRange.cloneContents()));
}
const semanticText = normalizeSelectionOutput(semanticParts.join("\n"));
return semanticText || plainText;
}
return { getSelectedText, expandRangeToContainMath, serializeSelectionNode };
}
const KokoroTTSCore = (() => {
const WEBM_OPUS_MIME = 'audio/webm; codecs="opus"';
const OGG_OPUS_MIME = 'audio/ogg; codecs="opus"';
const OGG_MIME = "audio/ogg";
const WAV_MIME = "audio/wav";
const CJK_PATTERN = /[\u3400-\u9FFF\uF900-\uFAFF]/;
const FORMULA_PLACEHOLDER_PREFIX = "__LOCAL_READ_FORMULA_";
const DEFAULT_TARGET_LANGUAGE = "Simplified Chinese";
const SUPPORTED_TARGET_LANGUAGES = Object.freeze([
"Simplified Chinese",
"Traditional Chinese",
"English",
"Japanese",
"Korean",
]);
function createRequestGate() {
let generation = 0;
let request = null;
function abortRequest() {
if (request) {
request.abort();
request = null;
}
}
return {
begin() {
generation += 1;
abortRequest();
return generation;
},
attach(id, nextRequest) {
if (id !== generation) {
nextRequest.abort();
return false;
}
request = nextRequest;
return true;
},
isCurrent(id) {
return id === generation;
},
finish(id) {
if (id === generation) request = null;
},
cancel() {
generation += 1;
abortRequest();
},
};
}
function releaseAudio(audio, urlApi = URL) {
if (!audio) return;
if (audio._cleanup) {
const cleanup = audio._cleanup;
audio._cleanup = null;
cleanup();
}
audio.pause();
audio.src = "";
if (audio._blobUrl) {
urlApi.revokeObjectURL(audio._blobUrl);
audio._blobUrl = null;
}
}
function supportsWebMOpus(mediaSourceApi) {
if (
!mediaSourceApi ||
typeof mediaSourceApi.isTypeSupported !== "function"
) {
return false;
}
try {
return mediaSourceApi.isTypeSupported(WEBM_OPUS_MIME) === true;
} catch {
return false;
}
}
function sameOrigin(currentOrigin, apiOrigin) {
return !!currentOrigin && !!apiOrigin && currentOrigin === apiOrigin;
}
function choosePlaybackMode(mediaSourceApi, currentOrigin, apiOrigin) {
if (!sameOrigin(currentOrigin, apiOrigin)) return "ogg";
return supportsWebMOpus(mediaSourceApi) ? "stream" : "ogg";
}
function translationModelSource(value, explicitSource = "") {
const source = String(explicitSource || "").trim();
if (source) return source;
const model = String(value || "").trim();
if (!model.startsWith("remote:")) return model ? "local" : "";
const parts = model.split(":", 3);
return parts.length === 3 ? parts[1] : "";
}
function translationModelName(value, explicitModel = "") {
const model = String(explicitModel || "").trim();
if (model) return model;
const selected = String(value || "").trim();
if (!selected.startsWith("remote:")) return selected;
const first = selected.indexOf(":");
const second = selected.indexOf(":", first + 1);
return second >= 0 ? selected.slice(second + 1) : selected;
}
function getTranslationModelOptions(payload, sourceId = "") {
const options = [];
const seen = new Set();
const requestedSource = String(sourceId || "").trim();
const discovered =
payload && Array.isArray(payload.available_model_options)
? payload.available_model_options
: [];
for (const option of discovered) {
const value = String(option && option.value || "").trim();
if (!value || seen.has(value)) continue;
seen.add(value);
const normalized = {
value,
label: String(option && option.label || value).trim() || value,
source: translationModelSource(value, option && option.source),
sourceName: String(option && option.source_name || "").trim(),
model: translationModelName(value, option && option.model),
};
if (!requestedSource || normalized.source === requestedSource) {
options.push(normalized);
}
}
return options;
}
function chooseTranslationModel(payload, selectedValue, selectedSource = "") {
const requestedSource = String(selectedSource || "").trim();
const options = getTranslationModelOptions(payload, requestedSource);
const selected = String(selectedValue || "").trim();
if (!options.length) return "";
if (options.some((option) => option.value === selected)) return selected;
if (requestedSource) return options[0].value;
const inferredSource = translationModelSource(selected);
const sameSource = options.find((option) => option.source === inferredSource);
return (sameSource || options[0]).value;
}
function normalizeTranslationPreferences(saved = {}) {
const candidate = saved && typeof saved === "object" ? saved : {};
const legacyModel = typeof candidate.translateModel === "string"
? candidate.translateModel.trim()
: "";
const legacySource = translationModelSource(legacyModel);
const requestedSource = typeof candidate.translationSource === "string"
? candidate.translationSource.trim()
: "";
const validSource = (value) => /^[a-z0-9][a-z0-9._-]*$/i.test(value);
const translationSource = validSource(requestedSource)
? requestedSource
: validSource(legacySource)
? legacySource
: "local";
const translationModels = {};
const storedModels = candidate.translationModels;
if (storedModels && typeof storedModels === "object" && !Array.isArray(storedModels)) {
for (const [source, rawModel] of Object.entries(storedModels)) {
const model = typeof rawModel === "string" ? rawModel.trim() : "";
if (
validSource(source) &&
model &&
translationModelSource(model) === source
) {
translationModels[source] = model;
}
}
}
if (legacyModel && validSource(legacySource) && !translationModels[legacySource]) {
translationModels[legacySource] = legacyModel;
}
return {
translationSource,
translationModels,
translateModel: translationModels[translationSource] || "",
};
}
function normalizeTranslationHealthSnapshot(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) {
return null;
}
if (value.version !== 1 || typeof value.mediatorOnline !== "boolean") {
return null;
}
const savedAt = Number(value.savedAt);
if (!Number.isFinite(savedAt) || savedAt < 0) {
return null;
}
const payload = value.payload;
if (
payload !== null &&
(!payload || typeof payload !== "object" || Array.isArray(payload))
) {
return null;
}
const healthError = typeof value.healthError === "string"
? value.healthError.trim()
: "";
return {
version: 1,
savedAt,
mediatorOnline: value.mediatorOnline,
payload,
healthError,
};
}
function mergeTranslationModelOptions(_baseOptions, payload, _selectedValue) {
return getTranslationModelOptions(payload).map(({ value, label }) => ({ value, label }));
}
function chooseTranslationModelFallback(payload, selectedValue, _defaultValue) {
return chooseTranslationModel(payload, selectedValue);
}
function normalizeTargetLanguage(value) {
const target = String(value || "").trim();
return SUPPORTED_TARGET_LANGUAGES.includes(target)
? target
: DEFAULT_TARGET_LANGUAGE;
}
function buildTranslationRequest({
text,
context = "",
model,
source = "",
targetLanguage = DEFAULT_TARGET_LANGUAGE,
} = {}) {
const selectedModel = String(model || "").trim();
if (!selectedModel) {
throw new Error("No translation model is available.");
}
const selectedSource = String(source || "").trim();
if (selectedSource && translationModelSource(selectedModel) !== selectedSource) {
throw new Error("The selected model does not belong to the selected source.");
}
const sourceText = normalizeLlmSourceText(text);
const contextText = normalizeLlmSourceText(context);
const target = normalizeTargetLanguage(targetLanguage);
const request = {
text: sourceText,
model: selectedModel,
target_language: target,
};
if (contextText) request.context = contextText;
return request;
}
function getLocalServiceControlState({ online = false, starting = false } = {}) {
if (online) {
return { label: "Local service running", icon: "\u2705", disabled: true };
}
if (starting) {
return { label: "Starting local service...", icon: "\u23F3", disabled: true };
}
return { label: "Start local service", icon: "\u25B6", disabled: false };
}
function deriveTranslationSettingsView({
mediatorOnline = false,
starting = false,
healthError = "",
payload = null,
selectedSource = "",
selectedModel = "",
} = {}) {
const hiddenSourceState = {
activeSource: "",
sourceRows: [],
modelOptions: [],
showSourceRows: false,
showSourceMessage: false,
showStartOllama: false,
showConnectServer: false,
};
if (!mediatorOnline) {
return {
...hiddenSourceState,
mode: "offline",
statusLabel: "Offline",
sourceLabel: "",
message: "Local service is not running.",
showSourceMessage: true,
selectedModel: "",
showStartService: true,
showModelSelect: false,
showTestTranslation: false,
showAdvanced: false,
showTranslationOutput: false,
showReadAloud: false,
keepAction: { visible: false, label: "Load & keep" },
unloadAction: { visible: false, label: "Unload" },
startAction: getLocalServiceControlState({ online: false, starting }),
};
}
if (healthError) {
return {
...hiddenSourceState,
mode: "unavailable",
statusLabel: "Unavailable",
sourceLabel: "",
message: String(healthError),
showSourceMessage: true,
selectedModel: "",
showStartService: false,
showModelSelect: false,
showTestTranslation: false,
showAdvanced: false,
showTranslationOutput: false,
showReadAloud: true,
keepAction: { visible: false, label: "Load & keep" },
unloadAction: { visible: false, label: "Unload" },
startAction: getLocalServiceControlState({ online: true, starting }),
};
}
if (!payload || typeof payload !== "object") {
return {
...hiddenSourceState,
mode: "checking",
statusLabel: "Checking",
sourceLabel: "",
message: "Checking translation sources...",
showSourceMessage: true,
selectedModel: "",
showStartService: false,
showModelSelect: false,
showTestTranslation: false,
showAdvanced: false,
showTranslationOutput: false,
showReadAloud: true,
keepAction: { visible: false, label: "Load & keep" },
unloadAction: { visible: false, label: "Unload" },
startAction: getLocalServiceControlState({ online: true, starting }),
};
}
const sourceMap = new Map();
const discoveredSources = Array.isArray(payload.sources) ? payload.sources : [];
for (const item of discoveredSources) {
const id = String(item && item.id || "").trim();
if (!id || sourceMap.has(id)) continue;
sourceMap.set(id, {
id,
name: String(item.name || id).trim() || id,
kind: item.kind === "remote" || id !== "local" ? "remote" : "local",
configured: item.configured !== false,
reachable: Boolean(item.reachable),
models: Array.isArray(item.models) ? item.models : [],
});
}
if (!sourceMap.has("local")) {
sourceMap.set("local", {
id: "local",
name: "Local Ollama",
kind: "local",
configured: true,
reachable: false,
models: [],
});
}
const hasRemote = Array.from(sourceMap.values()).some((item) => item.kind === "remote");
if (!hasRemote) {
sourceMap.set("project-server", {
id: "project-server",
name: "Project Server",
kind: "remote",
configured: false,
reachable: false,
models: [],
});
}
const sources = Array.from(sourceMap.values()).sort((left, right) => {
if (left.id === "local") return -1;
if (right.id === "local") return 1;
return 0;
});
const requestedSource = String(
selectedSource || translationModelSource(selectedModel) || "local"
).trim();
const activeSourceState = sourceMap.get(requestedSource) || sourceMap.get("local") || sources[0];
const activeSource = activeSourceState.id;
const sourceRows = sources.map((source) => {
const selected = source.id === activeSource;
const actionType = source.kind === "local" ? "start-ollama" : "connect-server";
const actionLabel = source.kind === "local" ? "Start" : "Connect";
return {
id: source.id,
name: source.name,
kind: source.kind,
selected,
configured: source.configured,
reachable: source.reachable,
statusLabel: source.reachable
? source.kind === "local" ? "Running" : "Connected"
: source.kind === "local" ? "Offline" : source.configured ? "Unavailable" : "Not connected",
action: {
visible: selected && !source.reachable,
type: actionType,
label: actionLabel,
},
};
});
const sourceView = {
activeSource,
sourceRows,
showSourceRows: true,
showStartOllama: activeSourceState.kind === "local" && !activeSourceState.reachable,
showConnectServer: activeSourceState.kind === "remote" && !activeSourceState.reachable,
};
if (!activeSourceState.reachable) {
const remoteMessage = activeSourceState.configured
? `${activeSourceState.name} is unavailable. Open Remote Service to reconnect.`
: `${activeSourceState.name} is not connected.`;
return {
...sourceView,
modelOptions: [],
mode: "source-offline",
statusLabel: activeSourceState.kind === "local" ? "Local offline" : "Connect server",
sourceLabel: `${activeSourceState.name} · ${activeSourceState.kind === "local" ? "offline" : "not connected"}`,
message: activeSourceState.kind === "local"
? "Local Ollama is not running."
: remoteMessage,
showSourceMessage: true,
selectedModel: "",
showStartService: false,
showModelSelect: false,
showTestTranslation: false,
showAdvanced: false,
showTranslationOutput: false,
showReadAloud: true,
keepAction: { visible: false, label: "Load & keep" },
unloadAction: { visible: false, label: "Unload" },
startAction: getLocalServiceControlState({ online: true, starting }),
};
}
const options = getTranslationModelOptions(payload, activeSource);
const selected = chooseTranslationModel(payload, selectedModel, activeSource);