-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathcontent.js
More file actions
1302 lines (1146 loc) · 44.2 KB
/
Copy pathcontent.js
File metadata and controls
1302 lines (1146 loc) · 44.2 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
let siyuanLangReady = siyuanInitLanguageFromStorage();
chrome.storage.onChanged.addListener((changes, area) => {
if (area === "sync" && changes.langCode) {
siyuanLangReady = siyuanLoadLanguageFile(changes.langCode.newValue);
}
});
const eventDispatcher = async (request, sender, sendResponse) => {
if ("tip" === request.func && request.tip) {
siyuanShowTip(request.msg, undefined, request.timeout);
return;
}
if ("tipKey" === request.func && request.tip) {
void siyuanShowTipByKey(request.msg, request.timeout);
return;
}
if ("copy2Clipboard" === request.func) {
await copyToClipboard(request.data);
return;
}
if ("reload" === request.func) {
window.location.reload();
return;
}
if ("siyuanGetReadability" === request.func) {
siyuanGetReadability(request.tabId);
return;
}
if ("copy" !== request.func) {
return;
}
const clipSettings = await siyuanEnsureClipReady();
if (!clipSettings) {
return;
}
const selection = window.getSelection();
if (selection && 0 < selection.rangeCount) {
const range = selection.getRangeAt(0);
const tempElement = document.createElement("div");
tempElement.appendChild(range.cloneContents());
siyuanSendUpload(tempElement, request.tabId, request.srcUrl, "part", undefined, undefined, clipSettings);
} else {
void siyuanShowTipByKey("tip_no_selection", 3000);
}
};
document.addEventListener("DOMContentLoaded", function () {
chrome.runtime.onMessage.removeListener(eventDispatcher);
chrome.runtime.onMessage.addListener(eventDispatcher);
});
/**
* 页面顶部提示(#siyuanmessage)状态机。
*
* 模式({@link TIP_BEHAVIOR}):
* - progress:保持显示,直到下一个状态替换
* - transient:超时后自动隐藏(默认 5000 ms)
*
* 动画:首次弹出 / 收起时有 transition;progress 状态下仅更新 innerHTML,保持连贯。
*
* 剪藏典型流转:tip_clipping → tip_clip_img → tip_clipping → tip_clip_ok
*
* @typedef {'progress' | 'transient'} TipModeValue
* @typedef {'tip_clipping' | 'tip_clip_img' | 'tip_clip_ok' | 'tip_token_miss' | 'tip_token_invalid' | 'tip_save_path_miss' | 'tip_siyuan_kernel_unavailable' | 'tip_no_selection' | 'tip_readability_failed'} TipKey
*/
const TIP_MODE = {
PROGRESS: "progress",
TRANSIENT: "transient",
};
/** @type {Record<TipKey, TipModeValue>} */
const TIP_BEHAVIOR = {
tip_clipping: TIP_MODE.PROGRESS,
tip_clip_img: TIP_MODE.PROGRESS,
tip_clip_ok: TIP_MODE.TRANSIENT,
tip_token_miss: TIP_MODE.TRANSIENT,
tip_token_invalid: TIP_MODE.TRANSIENT,
tip_save_path_miss: TIP_MODE.TRANSIENT,
tip_siyuan_kernel_unavailable: TIP_MODE.TRANSIENT,
tip_no_selection: TIP_MODE.TRANSIENT,
tip_readability_failed: TIP_MODE.TRANSIENT,
};
/** @type {ReturnType<typeof setTimeout> | null} */
let tipTimeoutId;
/** @type {ReturnType<typeof setTimeout> | null} */
let tipHideAnimTimeoutId;
const siyuanCancelTipHideAnimation = () => {
if (tipHideAnimTimeoutId) {
clearTimeout(tipHideAnimTimeoutId);
tipHideAnimTimeoutId = null;
}
};
/** @param {HTMLElement} tip */
const siyuanAnimateTipIn = (tip) => {
requestAnimationFrame(() => {
requestAnimationFrame(() => {
tip.style.transform = "translate3d(-50%, 0, 0) scale(0.8)";
tip.style.opacity = "1";
});
});
};
/**
* @param {string} msg
* @returns {HTMLElement}
*/
const siyuanMountTipElement = (msg) => {
siyuanCancelTipHideAnimation();
document.getElementById("siyuanmessage")?.remove();
const tip = document.createElement("div");
tip.id = "siyuanmessage";
tip.style.cssText =
"position:fixed;top:16px;left:50%;z-index:999999999;line-height:20px;border-radius:4px;padding:8px 16px;color:#fff;font-size:inherit;background-color:#4285f4;box-sizing:border-box;box-shadow:0 3px 5px -1px rgba(0,0,0,0.2),0 6px 10px 0 rgba(0,0,0,0.14),0 1px 18px 0 rgba(0,0,0,0.12);transition:opacity 0.15s cubic-bezier(0,0,0.2,1) 0ms,transform 0.15s cubic-bezier(0,0,0.2,1) 0ms;word-break:break-word;max-width:80vw;";
tip.innerHTML = msg;
tip.style.transform = "translate3d(-50%, -100px, 0) scale(0.8)";
tip.style.opacity = "0";
document.body.appendChild(tip);
siyuanAnimateTipIn(tip);
return tip;
};
/**
* @param {string} msg 提示文案(HTML)
* @param {TipKey | string} [key] 查 {@link TIP_BEHAVIOR},省略时为 transient
* @param {number} [timeout] transient 隐藏延迟(毫秒)
*/
const siyuanShowTip = (msg, key, timeout) => {
const isProgress = key && TIP_BEHAVIOR[key] === TIP_MODE.PROGRESS;
const existingTip = document.getElementById("siyuanmessage");
siyuanCancelTipHideAnimation();
if (existingTip && existingTip.style.opacity !== "0") {
// progress 或 tip_clip_ok 等:同一轮展示中只换文案,不重新弹出
existingTip.innerHTML = msg;
} else {
siyuanMountTipElement(msg);
}
if (tipTimeoutId) {
clearTimeout(tipTimeoutId);
tipTimeoutId = null;
}
if (isProgress) {
return;
}
tipTimeoutId = setTimeout(() => {
siyuanClearTip();
}, timeout || 5000);
};
// Add i18n support https://github.com/siyuan-note/siyuan/issues/13559
/**
* @param {TipKey | string} msgKey
* @param {number} [timeout]
* @param {(msg: string) => string} [format]
*/
const siyuanShowTipByKey = async (msgKey, timeout, format) => {
await siyuanLangReady;
const msg = format ? format(siyuanGetMessage(msgKey)) : siyuanGetMessage(msgKey);
siyuanShowTip(msg, msgKey, timeout);
};
/** 收起动画结束后移除元素,并清除 transient 定时器 */
const siyuanClearTip = () => {
if (tipTimeoutId) {
clearTimeout(tipTimeoutId);
tipTimeoutId = null;
}
const tip = document.getElementById("siyuanmessage");
if (!tip) {
return;
}
siyuanCancelTipHideAnimation();
tip.style.transform = "translate3d(-50%, -100px, 0) scale(0.8)";
tip.style.opacity = "0";
tipHideAnimTimeoutId = setTimeout(() => {
tip.remove();
tipHideAnimTimeoutId = null;
}, 150);
};
const siyuanConvertBlobToBase64 = (blob) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onerror = reject;
reader.onload = () => resolve(reader.result);
reader.readAsDataURL(blob);
});
const SIYUAN_CLIP_IMAGE_INDEX_ATTR = "data-siyuan-clip-image-index";
const siyuanIsYuquePage = () => {
return window.location.hostname === "yuque.com" || window.location.hostname.endsWith(".yuque.com");
};
const siyuanGetImageSource = (image) => {
const source = image.getAttribute("src") ||
image.currentSrc ||
image.getAttribute("data-src") ||
image.getAttribute("data-original") ||
image.getAttribute("data-origin-src") ||
image.getAttribute("data-lazy-src");
if (!source) {
return "";
}
try {
return new URL(source, document.baseURI).href;
} catch (e) {
return source;
}
};
const siyuanIsYuqueCardReady = (card) => {
if (card.getAttribute("data-card-name") === "codeblock") {
return !!card.querySelector(".cm-content");
}
const image = card.querySelector("img");
return !!image && "" !== siyuanGetImageSource(image);
};
const siyuanWaitForYuqueCard = (card, timeout = 2000) => {
if (siyuanIsYuqueCardReady(card)) {
return Promise.resolve(true);
}
return new Promise((resolve) => {
let completed = false;
const complete = (ready) => {
if (completed) {
return;
}
completed = true;
observer.disconnect();
clearTimeout(timer);
resolve(ready);
};
const observer = new MutationObserver(() => {
if (siyuanIsYuqueCardReady(card)) {
complete(true);
}
});
const timer = setTimeout(() => complete(siyuanIsYuqueCardReady(card)), timeout);
observer.observe(card, {
attributes: true,
attributeFilter: ["src", "data-src", "data-original", "data-origin-src", "data-lazy-src"],
childList: true,
subtree: true,
});
card.scrollIntoView({behavior: "auto", block: "center", inline: "nearest"});
});
};
const siyuanPrepareYuqueCards = async (doc) => {
if (!siyuanIsYuquePage()) {
return {cards: 0, initiallyReady: 0, rendered: 0, unresolved: 0};
}
const cards = Array.from(doc.querySelectorAll(
'ne-card[data-card-name="image"], ne-card[data-card-name="codeblock"]'
));
const scrollX = window.scrollX;
const scrollY = window.scrollY;
let initiallyReady = 0;
let rendered = 0;
try {
for (const card of cards) {
if (siyuanIsYuqueCardReady(card)) {
initiallyReady++;
continue;
}
if (await siyuanWaitForYuqueCard(card)) {
rendered++;
}
}
} finally {
window.scrollTo(scrollX, scrollY);
await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
}
return {
cards: cards.length,
initiallyReady,
rendered,
unresolved: cards.filter((card) => !siyuanIsYuqueCardReady(card)).length,
};
};
const siyuanPrepareYuqueImages = (sourceDoc, clonedDoc) => {
if (!siyuanIsYuquePage()) {
return [];
}
const selector = ".yuque-doc-content img";
const sourceImages = Array.from(sourceDoc.querySelectorAll(selector));
const clonedImages = Array.from(clonedDoc.querySelectorAll(selector));
return sourceImages.map((sourceImage, index) => {
const src = siyuanGetImageSource(sourceImage);
const clonedImage = clonedImages[index];
if (clonedImage) {
clonedImage.setAttribute(SIYUAN_CLIP_IMAGE_INDEX_ATTR, index.toString());
if (src) {
clonedImage.setAttribute("src", src);
}
}
return {
src,
alt: sourceImage.getAttribute("alt") || "",
};
});
};
const siyuanNormalizeYuqueCodeBlocks = (doc) => {
if (!siyuanIsYuquePage()) {
return {normalized: 0, unresolved: 0};
}
let normalized = 0;
let unresolved = 0;
doc.querySelectorAll('ne-card[data-card-name="codeblock"]').forEach((card) => {
const content = card.querySelector(".cm-content");
if (!content) {
unresolved++;
return;
}
const lines = Array.from(content.querySelectorAll(".cm-line"));
const codeText = 0 < lines.length
? lines.map((line) => line.textContent).join("\n")
: content.textContent;
const pre = doc.createElement("pre");
const code = doc.createElement("code");
code.textContent = codeText;
pre.appendChild(code);
card.replaceWith(pre);
normalized++;
});
return {normalized, unresolved};
};
const siyuanRestoreYuqueImages = (root, imageSources) => {
if (!siyuanIsYuquePage() || 0 === imageSources.length) {
return 0;
}
const sourcesByAlt = new Map();
imageSources.forEach((source, index) => {
if (!source.src || !source.alt) {
return;
}
const sources = sourcesByAlt.get(source.alt) || [];
sources.push({index, src: source.src});
sourcesByAlt.set(source.alt, sources);
});
const usedSourceIndexes = new Set();
let restored = 0;
root.querySelectorAll("img").forEach((image) => {
if (siyuanGetImageSource(image)) {
image.removeAttribute(SIYUAN_CLIP_IMAGE_INDEX_ATTR);
return;
}
const sourceIndex = Number.parseInt(image.getAttribute(SIYUAN_CLIP_IMAGE_INDEX_ATTR), 10);
let source = Number.isInteger(sourceIndex) ? imageSources[sourceIndex] : undefined;
if (!source?.src) {
const altSources = sourcesByAlt.get(image.getAttribute("alt") || "") || [];
const altSource = altSources.find((item) => !usedSourceIndexes.has(item.index));
if (altSource) {
source = altSource;
usedSourceIndexes.add(altSource.index);
}
} else {
usedSourceIndexes.add(sourceIndex);
}
if (source?.src) {
image.setAttribute("src", source.src);
restored++;
}
image.removeAttribute(SIYUAN_CLIP_IMAGE_INDEX_ATTR);
});
return restored;
};
// 网页换行用 span 样式 word-break 的特殊处理 https://github.com/siyuan-note/siyuan/issues/13195
// 递归查找父元素直到找到 pre、code、span、math 或 math相关标签
function isIgnoredElement(element) {
// 递归查找父元素直到找到 pre、code、span、math 或 math相关标签
while (element) {
let tagName = element.tagName.toLowerCase();
const className = String(element.className || "").toLowerCase();
if (
tagName === "math" ||
className.includes("math") ||
className.includes("mathjax") ||
className.includes("latex") ||
className.includes("katex") ||
className.includes("mjx") ||
className.includes("mathml") ||
className.includes("equation") ||
className.includes("formula")
) {
return true;
}
element = element.parentElement; // 移动到父元素
if (!element) {
break;
}
tagName = element.tagName.toLowerCase();
// 如果父元素是 pre、code、span、math 或与数学相关的类名
if (["pre", "code", "span", "section"].includes(tagName)) {
return true;
} else if (["div", "p"].includes(tagName)) {
return false; // 找到 div、p 直接返回
}
}
return false; // 没找到时返回 false
}
// span元素的换行处理优化:https://github.com/siyuan-note/siyuan/issues/14775
// 规范:https://developer.mozilla.org/zh-CN/docs/Web/CSS/white-space
function siyuanProcessTextByWhiteSpace(element) {
const text = element.textContent;
const whiteSpace = getComputedStyle(element).whiteSpace;
const brTag = "<br>";
switch (whiteSpace) {
case "normal":
case "nowrap":
// 合并所有空白字符为一个空格;换行为 <br>;去除行末空格
return text
.replace(/[ \t\r\f\v]+/g, " ") // 合并空格和制表符
.replace(/[ \t]+\n/g, "\n") // 去除行末空格
.replace(/\n+/g, brTag) // 合并换行并转为 <br>
.trim();
case "pre":
// 保留所有空白和换行,换行转为 <br>
return text.replace(/\n/g, brTag);
case "pre-wrap":
// 保留空白字符,换行转为 <br>,不处理行末空格(挂起)
return text.replace(/\n+/g, brTag);
case "pre-line":
// 合并空格,保留换行符,换行转为 <br>,移除行末空格
return text
.replace(/[ \t\r\f\v]+/g, " ")
.replace(/[ \t]+\n/g, "\n")
.replace(/\n+/g, brTag)
.trim();
case "break-spaces":
// 保留所有空白字符和换行符,换行为 <br>
return text.replace(/\n/g, brTag);
default:
// 默认处理和 normal 相同
return text
.replace(/[ \t\r\f\v]+/g, " ")
.replace(/[ \t]+\n/g, "\n")
.replace(/\n+/g, brTag)
.trim();
}
}
// 处理会换行的 span 后添加 <br>,让内核能识别到换行
function siyuanSpansAddBr(tempElement) {
const spans = tempElement.querySelectorAll("span");
if (!spans || spans.length === 0) {
console.log("No span elements found.");
return;
}
// 用于存储符合条件的 span 元素
const matchedSpans = [];
spans.forEach((span) => {
const style = window.getComputedStyle(span);
// 现有的条件判断,判断是否满足换行条件
if (
(style.whiteSpace.trim().toLowerCase() === "normal" ||
style.whiteSpace.trim().toLowerCase() === "pre-wrap") &&
(style.wordWrap.trim().toLowerCase() === "break-word" ||
style.overflowWrap.trim().toLowerCase() === "break-word" ||
style.wordBreak.trim().toLowerCase() === "break-word")
) {
// 检查父元素是否是 pre、code 或 span
if (isIgnoredElement(span)) {
console.log("Skipping span due to parent being pre, code or span.");
return; // 如果父元素是 pre、code 或 span 或者数学公式,跳过该 span
}
span.innerHTML = siyuanProcessTextByWhiteSpace(span);
// 添加到符合条件的数组中
matchedSpans.push(span);
}
});
if (matchedSpans.length > 0) {
console.log(`Added <br> for ${matchedSpans.length} span elements.(Total span: ${spans.length})`);
console.log("Matched span elements:", matchedSpans);
} else {
console.log("No span elements matched the criteria.");
}
}
// 替换粗体样式为内核可识别<b>标签 https://github.com/siyuan-note/siyuan/issues/13306
function siyuanProcessBoldStyle(tempElement) {
// 获取所有应用了 font-weight: bold 的元素
const boldElements = tempElement.querySelectorAll("*");
boldElements.forEach((element) => {
const style = window.getComputedStyle(element);
if (["B", "STRONG"].includes(element.tagName)) {
return; // 如果元素本身是 <b> 或 <strong> 标签,跳过
}
if (parentContainsBold(element)) {
return; // 如果元素的父元素是 <b> 或 <strong> 标签,跳过
}
// 判断是否具有 font-weight: bold
if (style.fontWeight === "bold" || style.fontWeight === "700") {
// '700' 是 bold 的常见数值
// 将 element 中的各个元素使用 <b> 标签包裹
const children = element.childNodes;
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (child.nodeType === Node.TEXT_NODE) {
// 如果是文本节点,直接包裹在 <b> 标签中
const text = child.nodeValue;
const textElement = document.createElement("b");
textElement.textContent = text;
element.replaceChild(textElement, child);
} else if (child.nodeType === Node.ELEMENT_NODE) {
// 如果是元素节点,递归处理
const childElement = child;
const childTagName = childElement.tagName.toLowerCase();
if (["b", "strong"].includes(childTagName)) {
continue; // 如果是 <b> 或 <strong> 标签,跳过
}
if (parentContainsBold(childElement)) {
continue; // 如果元素的父元素是 <b> 或 <strong> 标签,跳过
}
// 递归处理
siyuanProcessBoldStyle(childElement);
}
}
}
});
}
function parentContainsBold(element) {
let parent = element.parentElement;
while (parent) {
if (["B", "STRONG", "H1", "H2", "H3", "H4", "H5", "H6"].includes(parent.tagName)) {
return true;
}
parent = parent.parentElement;
}
return false;
}
// 替换斜体样式为内核可识别 <i> 标签 https://github.com/siyuan-note/siyuan/issues/13306
function siyuanProcessItalicStyle(tempElement) {
// 获取所有元素
const allElements = tempElement.querySelectorAll("*");
allElements.forEach((element) => {
const style = window.getComputedStyle(element);
if (["I", "EM"].includes(element.tagName)) {
return; // 如果元素本身是 <i> 或 <em> 标签,跳过
}
if (parentContainsItalic(element)) {
return; // 如果元素的父元素是 I 或 EM 标签,跳过
}
// 判断是否具有 font-style: italic
if (style.fontStyle === "italic") {
// 将 element 中的各个元素使用 <i> 标签包裹
const children = element.childNodes;
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (child.nodeType === Node.TEXT_NODE) {
// 如果是文本节点,直接包裹在 <i> 标签中
const text = child.nodeValue;
const textElement = document.createElement("i");
textElement.textContent = text;
element.replaceChild(textElement, child);
} else if (child.nodeType === Node.ELEMENT_NODE) {
// 如果是元素节点,递归处理
const childElement = child;
const childTagName = childElement.tagName.toLowerCase();
if (["i", "em"].includes(childTagName)) {
continue; // 如果是 <i> 或 <em> 标签,跳过
}
if (parentContainsItalic(childElement)) {
continue; // 如果元素的父元素是 I 或 EM 标签,跳过
}
// 递归处理
siyuanProcessItalicStyle(childElement);
}
}
}
});
}
function parentContainsItalic(element) {
let parent = element.parentElement;
while (parent) {
if (["I", "EM"].includes(parent.tagName)) {
return true;
}
parent = parent.parentElement;
}
return false;
}
function siyuanProcessUnderlineStyle(tempElement) {
// 获取所有元素
const allElements = tempElement.querySelectorAll("*");
allElements.forEach((element) => {
const style = window.getComputedStyle(element);
if (element.tagName === "U") {
return; // 如果元素本身是 <u> 标签,跳过
}
if (parentContainsUnderline(element)) {
return; // 如果元素的父元素是 U 标签,跳过
}
// 判断是否具有 text-decoration: underline
if (style.textDecorationLine.includes("underline")) {
// 将 element 中的各个元素使用 <u> 标签包裹
const children = element.childNodes;
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (child.nodeType === Node.TEXT_NODE) {
// 如果是文本节点,直接包裹在 <u> 标签中
const text = child.nodeValue;
const textElement = document.createElement("u");
textElement.textContent = text;
element.replaceChild(textElement, child);
} else if (child.nodeType === Node.ELEMENT_NODE) {
// 如果是元素节点,递归处理
const childElement = child;
const childTagName = childElement.tagName.toLowerCase();
if (childTagName === "u") {
continue; // 如果是 <u> 标签,跳过
}
if (parentContainsUnderline(childElement)) {
continue; // 如果元素的父元素是 U 标签,跳过
}
// 递归处理
siyuanProcessUnderlineStyle(childElement);
}
}
}
});
function parentContainsUnderline(element) {
let parent = element.parentElement;
while (parent) {
if (parent.tagName === "U") {
return true;
}
parent = parent.parentElement;
}
return false;
}
}
const FORMULA_SELECTOR = "[data-formula]";
function simplifyNestedTags(root, tagName) {
let elements = root.querySelectorAll(tagName);
let hasNested = true;
while (hasNested) {
hasNested = false;
elements.forEach((element) => {
if (!element.closest(FORMULA_SELECTOR) && simplifyElement(element, tagName)) {
hasNested = true;
}
});
elements = root.querySelectorAll(tagName);
}
function simplifyElement(element, tagName) {
let nestedFound = false;
Array.from(element.children).forEach((child) => {
if (child.matches(FORMULA_SELECTOR)) {
return;
}
if (child.tagName === tagName) {
nestedFound = true;
while (child.firstChild) {
element.insertBefore(child.firstChild, child);
}
child.remove();
} else {
nestedFound = simplifyElement(child, tagName) || nestedFound;
}
});
return nestedFound;
}
}
// 移除图片链接 https://github.com/siyuan-note/siyuan/issues/13941
function siyuanRemoveImgLink(tempElement) {
const images = tempElement.querySelectorAll("img");
images.forEach((image) => {
const parent = image.parentElement;
if (!parent) {
return;
}
if (parent.tagName === "A") {
const grandParent = parent.parentElement;
if (!grandParent) {
return;
}
grandParent.insertBefore(image, parent);
parent.remove();
}
});
}
// 将 SVG 转换为 Base64 编码的 Data URI https://github.com/siyuan-note/siyuan/issues/14523
// 修复网页内嵌SVG包含非Latin字符导致剪藏报错 https://github.com/siyuan-note/siyuan/issues/14669
async function siyuanSvgToBase64(svgNode) {
const serializer = new XMLSerializer();
let svgStr = serializer.serializeToString(svgNode);
if (!svgStr.startsWith("<?xml")) {
svgStr = '<?xml version="1.0" encoding="UTF-8"?>' + svgStr;
}
const svgBlob = new Blob([svgStr], {type: "image/svg+xml"});
const dataUrl = await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(svgBlob);
});
return dataUrl; // 返回 base64 编码的 data URL
}
async function siyuanSvgToImg(tempElement) {
const svgElements = tempElement.querySelectorAll("svg");
console.log(`Found ${svgElements.length} SVG elements`);
for (const svg of svgElements) {
const img = document.createElement("img");
img.src = await siyuanSvgToBase64(svg);
img.style.cssText = window.getComputedStyle(svg).cssText;
svg.parentNode.replaceChild(img, svg);
}
}
function adaptMSN(tempDoc) {
if (tempDoc.documentURI.indexOf("msn.cn") !== -1) {
// 删除掉其他不相关文章
const articles = tempDoc.querySelectorAll(".consumption-page-gridarea_content");
articles.forEach((article) => {
const shadowHost = article.querySelector("views-header-wc");
if (!shadowHost) {
return;
}
if (!shadowHost.shadowRoot) {
return;
}
const titleEle = shadowHost.shadowRoot.querySelector("h1");
if (!titleEle) {
return;
}
if (titleEle.innerText.indexOf(tempDoc.title) === -1) {
article.remove();
}
});
// 将 Shadow DOM 展开
const shadowHosts = tempDoc.querySelectorAll("cp-article");
shadowHosts.forEach((element) => {
const shadowRoot = element.shadowRoot;
if (!shadowRoot) {
return;
}
const slots = shadowRoot.querySelectorAll("slot");
slots.forEach((slot) => {
const slotName = slot.getAttribute("name");
element.querySelectorAll(`[slot="${slotName}"]`).forEach((slotElement) => {
const imgEle = slotElement.querySelector("cp-article-image");
if (!imgEle) {
return;
}
const imgShadowRoot = imgEle.shadowRoot;
if (!imgShadowRoot) {
return;
}
const imgs = imgShadowRoot.querySelectorAll("img");
if (!imgs || imgs.length === 0) {
return;
}
slotElement.innerHTML = "";
imgs.forEach((img) => {
slotElement.appendChild(img.cloneNode(true));
});
slot.innerHTML = slotElement.innerHTML;
});
});
const shadowContent = shadowRoot.innerHTML;
const newDiv = tempDoc.createElement("div");
newDiv.innerHTML = shadowContent;
element.parentNode.replaceChild(newDiv, element);
});
}
}
// Readability 前处理 https://github.com/siyuan-note/siyuan/issues/13306
async function siyuanGetCloneNode(tempDoc) {
let items;
try {
items = await new Promise((resolve, reject) => {
chrome.storage.sync.get(siyuanStorageDefaultsFor(SIYUAN_EXP_STORAGE_KEYS), (result) => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
} else {
resolve(result);
}
});
});
} catch (error) {
console.error("获取失败,错误信息:", error);
items = siyuanStorageDefaultsFor(SIYUAN_EXP_STORAGE_KEYS);
}
// 适配 MSN 页面 https://github.com/siyuan-note/siyuan/issues/14197
adaptMSN(tempDoc);
if (items.expBold) {
// 替换粗体样式为内核可识别 <b> 标签 https://github.com/siyuan-note/siyuan/issues/13306
siyuanProcessBoldStyle(tempDoc);
}
if (items.expItalic) {
// 替换斜体样式为内核可识别 <i> 标签 https://github.com/siyuan-note/siyuan/issues/13306
siyuanProcessItalicStyle(tempDoc);
}
if (items.expUnderline) {
// 替换下划线样式为内核可识别 <u> 标签
siyuanProcessUnderlineStyle(tempDoc);
}
if (items.expRemoveImgLink) {
// 移除图片链接 https://github.com/siyuan-note/siyuan/issues/13941
siyuanRemoveImgLink(tempDoc);
}
if (items.expSpan) {
// 网页换行用 span 样式 word-break 的特殊处理 https://github.com/siyuan-note/siyuan/issues/13195
// 处理会换行的 span 后添加 <br>,让内核能识别到换行
siyuanSpansAddBr(tempDoc);
}
if (items.expSvgToImg) {
// 将网页内嵌的 SVG 节点转换成内嵌的 IMG 节点
// https://github.com/siyuan-note/siyuan/issues/14523
await siyuanSvgToImg(tempDoc);
}
// 合并嵌套的标签
simplifyNestedTags(tempDoc, "STRONG");
simplifyNestedTags(tempDoc, "B");
simplifyNestedTags(tempDoc, "I");
simplifyNestedTags(tempDoc, "EM");
// 如果公式被嵌套包裹,则去掉外层包裹 https://github.com/siyuan-note/siyuan/issues/14382
const mathElements = tempDoc.querySelectorAll(".ztext-math");
mathElements.forEach((mathElement) => {
const mathParent = mathElement.parentElement;
if (mathParent && ["B", "STRONG", "I", "EM"].includes(mathParent.tagName)) {
const parent = mathParent;
while (parent.firstChild) {
parent.parentNode.insertBefore(parent.firstChild, parent);
}
parent.remove();
}
});
// 如果行级标签包含了块级标签,则将该行级标签改为 div
fixInvalidNesting(tempDoc);
const clonedDoc = document.cloneNode(true);
return clonedDoc;
}
/**
* 修复 HTML 结构:将包含块级元素的行级标签改为 div
* @param {Document|Element} doc - 需要处理的 DOM 文档或元素节点
*/
function fixInvalidNesting(doc) {
const inlineTags = ["span", "strong", "b", "i", "em", "a"];
// 注意:code 建议移出行内标签列表,因为它通常被视为行内元素
const blockTags = [
"div",
"p",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"ul",
"ol",
"li",
"table",
"tr",
"td",
"th",
"blockquote",
"section",
"article",
];
const ownerDocument = doc.ownerDocument || doc;
const inlineSelector = inlineTags.join(",");
const blockSelector = blockTags.join(",");
// 标题元素只能包含行内内容,先将第一个块级后代及其后续内容移到标题外
const invalidHeadings = Array.from(doc.querySelectorAll("h1, h2, h3, h4, h5, h6"))
.filter((heading) => heading.querySelector(blockSelector));
invalidHeadings.forEach((heading) => {
const firstBlock = heading.querySelector(blockSelector);
if (!firstBlock || !heading.parentNode) {
return;
}
const range = ownerDocument.createRange();
range.selectNodeContents(heading);
range.setEndBefore(firstBlock);
const normalizedHeading = heading.cloneNode(false);
normalizedHeading.appendChild(range.extractContents());
const trailingContent = ownerDocument.createDocumentFragment();
while (heading.firstChild) {
trailingContent.appendChild(heading.firstChild);
}
const parent = heading.parentNode;
parent.insertBefore(normalizedHeading, heading);
parent.insertBefore(trailingContent, heading);
heading.remove();
});
// 1. 获取所有可能是行内的元素
const allInlines = Array.from(doc.querySelectorAll(inlineSelector));
// 2. 过滤出真正包含块级子元素的行内元素
// 使用 reverse() 从 DOM 树的最深层开始处理,防止父级先被替换导致子级丢失
const targets = allInlines.filter((el) => el.querySelector(blockSelector)).reverse();
targets.forEach((oldEl) => {
// 再次检查 oldEl 是否还在 DOM 树中(防止在之前的循环中已被父级替换)
if (!oldEl.parentNode) return;
const newDiv = ownerDocument.createElement("div");