Repository navigation
Expand file tree
/
Copy pathcontent.js
More file actions
1020 lines (1020 loc) · 45.9 KB
/
Copy pathcontent.js
File metadata and controls
1020 lines (1020 loc) · 45.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
(() => {
if (globalThis.docaContentScriptInstalled) return;
globalThis.docaContentScriptInstalled = true;
const messages = {
"zh": {
"dock.page": "收录当前页面",
"dock.selection": "收录选中区域",
"dock.assistant": "Doca 助手",
"dock.site": "打开 Doca 网站",
"dock.settings": "设置",
"dock.drag": "上下拖动工具条,也可使用方向键",
"dock.collapse": "收起工具条",
"dock.expand": "展开工具条",
"dock.close": "关闭",
"dock.rule": "收录规则",
"dock.confirm": "确认收录",
"dock.loading": "正在读取收录规则…",
"dock.saving": "正在收录…",
"dock.saved": "已保存到 Doca",
"dock.warnings": "有 {count} 处内容未完整处理,文档已保留占位",
"dock.open": "打开文档",
"dock.login": "登录 Doca",
"dock.setup": "打开设置",
"dock.noProfiles": "请先设置收录规则",
"dock.retry": "重试",
"dock.failed": "收录未完成,请重试",
"dock.failedWithCode": "收录未完成(错误代码:{code})",
"clipper_too_many_pending": "当前未完成的任务较多,请稍后重试。",
"dock.connectionFailed": "暂时无法连接 Doca,请重试",
"dock.selectionMissing": "请先选中需要收录的网页内容",
"dock.updated": "插件已更新,请刷新当前网页",
"dock.reload": "刷新网页",
"dock.positionFailed": "位置未能保存,可重试拖动",
"dock.images": "大图自动压缩,SVG 转为图片;无法保存的图片保留占位",
"dock.create": "新建文档",
"dock.append": "追加到文档",
"dock.personal": "个人文档",
"dock.default": "默认",
"dock.compressionFailed": "图片压缩失败,收录尚未完成,请重试",
"dock.animationLarge": "动图超过 20 MiB 或 2500 万像素,请选择更小的图片,不会转成静态图"
},
"en": {
"dock.page": "Capture this page",
"dock.selection": "Capture selection",
"dock.assistant": "Doca assistant",
"dock.site": "Open Doca website",
"dock.settings": "Settings",
"dock.drag": "Drag vertically or use the arrow keys",
"dock.collapse": "Collapse toolbar",
"dock.expand": "Expand toolbar",
"dock.close": "Close",
"dock.rule": "Capture rule",
"dock.confirm": "Confirm capture",
"dock.loading": "Loading capture rules…",
"dock.saving": "Capturing…",
"dock.saved": "Saved to Doca",
"dock.warnings": "{count} items could not be fully processed; placeholders were saved",
"dock.open": "Open document",
"dock.login": "Sign in to Doca",
"dock.setup": "Open settings",
"dock.noProfiles": "Set up a capture rule first",
"dock.retry": "Retry",
"dock.failed": "Capture incomplete. Please retry.",
"dock.failedWithCode": "Capture incomplete (error code: {code}).",
"clipper_too_many_pending": "Too many tasks are currently active. Please try again shortly.",
"dock.connectionFailed": "Could not connect to Doca. Please retry.",
"dock.selectionMissing": "Select the webpage content to capture first",
"dock.updated": "The extension was updated. Reload this page.",
"dock.reload": "Reload page",
"dock.positionFailed": "Could not save the position. Drag to retry.",
"dock.images": "Large images compressed; SVG converted; unavailable images marked",
"dock.create": "New document",
"dock.append": "Append to document",
"dock.personal": "Personal documents",
"dock.default": "Default",
"dock.compressionFailed": "Image compression failed. Capture is incomplete; please retry.",
"dock.animationLarge": "The animation exceeds 20 MiB or 25 million pixels. Choose a smaller image; it will not be flattened."
},
"zh-Hant": {
"dock.page": "收錄當前頁面",
"dock.selection": "收錄選中區域",
"dock.assistant": "Doca 助手",
"dock.site": "開啟 Doca 網站",
"dock.settings": "設定",
"dock.drag": "上下拖動工具條,也可使用方向鍵",
"dock.collapse": "收起工具條",
"dock.expand": "展開工具條",
"dock.close": "關閉",
"dock.rule": "收錄規則",
"dock.confirm": "確認收錄",
"dock.loading": "正在讀取收錄規則…",
"dock.saving": "正在收錄…",
"dock.saved": "已儲存到 Doca",
"dock.warnings": "有 {count} 處內容未完整處理,文件已保留佔位",
"dock.open": "開啟文件",
"dock.login": "登入 Doca",
"dock.setup": "開啟設定",
"dock.noProfiles": "請先設定收錄規則",
"dock.retry": "重試",
"dock.failed": "收錄未完成,請重試",
"dock.failedWithCode": "收錄未完成(錯誤程式碼:{code})",
"clipper_too_many_pending": "當前未完成的任務較多,請稍後重試。",
"dock.connectionFailed": "暫時無法連線 Doca,請重試",
"dock.selectionMissing": "請先選中需要收錄的網頁內容",
"dock.updated": "外掛已更新,請重新整理當前網頁",
"dock.reload": "重新整理網頁",
"dock.positionFailed": "位置未能儲存,可重試拖動",
"dock.images": "大圖自動壓縮,SVG 轉為圖片;無法儲存的圖片保留佔位",
"dock.create": "新建文件",
"dock.append": "追加到文件",
"dock.personal": "個人文件",
"dock.default": "預設",
"dock.compressionFailed": "圖片壓縮失敗,收錄尚未完成,請重試",
"dock.animationLarge": "動圖超過 20 MiB 或 2500 萬畫素,請選擇更小的圖片,不會轉成靜態圖"
},
"ja": {
"dock.page": "このページを保存する",
"dock.selection": "キャプチャ選択",
"dock.assistant": "ドカアシスタント",
"dock.site": "Docaのウェブサイトを開く",
"dock.settings": "設定",
"dock.drag": "垂直にドラッグするか、矢印キーを使う",
"dock.collapse": "コラボレートツールバーが崩壊",
"dock.expand": "ツールバーを拡大",
"dock.close": "閉じる",
"dock.rule": "キャプチャルール",
"dock.confirm": "捕獲が確認されました",
"dock.loading": "キャプチャルールの読み込み中…",
"dock.saving": "捕捉中…",
"dock.saved": "ドカに保存した",
"dock.warnings": "{count}件の項目が完全に処理できなかったため、プレースホルダーは保存された",
"dock.open": "文書を開く",
"dock.login": "Docaにログインする",
"dock.setup": "設定を開く",
"dock.noProfiles": "まずキャプチャルールを設定する",
"dock.retry": "再試行",
"dock.failed": "キャプチャが不完全です。再試行してください。",
"dock.failedWithCode": "不完全なキャプチャ(エラーコード:{code})。",
"clipper_too_many_pending": "現在、多くのタスクが実行中です。しばらくして再試行してください。",
"dock.connectionFailed": "Docaに接続できませんでした。再試行してください。",
"dock.selectionMissing": "まず、取得したいウェブページの内容を選択してください。",
"dock.updated": "拡張機能が更新されました。このページを再読み込みしてください。",
"dock.reload": "ページを再読み込み",
"dock.positionFailed": "位置を保存できませんでした。再試行するためにドラッグしてください。",
"dock.images": "大きな画像を圧縮;SVGに変換;利用できない画像はマークされている",
"dock.create": "新しい文書",
"dock.append": "文書に追加する",
"dock.personal": "個人文書",
"dock.default": "デフォルト",
"dock.compressionFailed": "画像圧縮に失敗しました。キャプチャが不完全です。再試行してください。",
"dock.animationLarge": "アニメーションのサイズが20MiB以上、または2500万ピクセル以上になっています。より小さな画像を選択してください。そうすれば圧縮されません。"
},
"fr": {
"dock.page": "Capture cette page",
"dock.selection": "Sélection de capture",
"dock.assistant": "Assistant Doca",
"dock.site": "Ouvrir le site de Doca",
"dock.settings": "Paramètres",
"dock.drag": "Déplacer verticalement ou utiliser les flèches.",
"dock.collapse": "Collapser de la barre d'outils",
"dock.expand": "Élargir la barre d'outils",
"dock.close": "Fermer",
"dock.rule": "Règle de capture",
"dock.confirm": "Confirmer la capture",
"dock.loading": "Chargement des règles de capture…",
"dock.saving": "Capturer…",
"dock.saved": "Sauvegardé à Doca",
"dock.warnings": "{count} éléments n’ont pas pu être traités complètement ; les placeholders ont été sauvés",
"dock.open": "Ouvrir le document",
"dock.login": "Connexion à Doca",
"dock.setup": "Ouvrir les paramètres",
"dock.noProfiles": "Définissez d’abord une règle de capture.",
"dock.retry": "Réessayer",
"dock.failed": "Capture incomplète. Veuillez réessayer.",
"dock.failedWithCode": "Capture incomplète (code d'erreur : {code}).",
"clipper_too_many_pending": "Trop de tâches sont actives actuellement. Veuillez réessayer bientôt.",
"dock.connectionFailed": "Impossible de se connecter à Doca. Veuillez réessayer.",
"dock.selectionMissing": "Sélectionner le contenu de la page web à capturer en premier",
"dock.updated": "L’extension a été mise à jour. Recharger cette page.",
"dock.reload": "Recharger la page",
"dock.positionFailed": "Impossible de sauvegarder la position. Déplacez-la pour réessayer.",
"dock.images": "Images de grande taille compressées ; SVG convertis ; images indisponibles marquées",
"dock.create": "Nouveau document",
"dock.append": "Ajouter à le document",
"dock.personal": "Documents personnels",
"dock.default": "Par défaut",
"dock.compressionFailed": "Compression de l’image a échoué. La capture est incomplète ; veuillez réessayer.",
"dock.animationLarge": "L’animation dépasse 20 MiB ou 25 millions de pixels. Choisissez une image plus petite ; elle ne sera pas flattée."
},
"ko": {
"dock.page": "이 페이지를 캡처하세요.",
"dock.selection": "캡처 선택",
"dock.assistant": "도카 어시스턴트",
"dock.site": "Doca 웹사이트를 열기",
"dock.settings": "설정",
"dock.drag": "수직으로 드래그하거나 화살표 키를 사용하세요.",
"dock.collapse": "도구 모음 닫기",
"dock.expand": "도구 모음 확장",
"dock.close": "닫기",
"dock.rule": "포착 규칙",
"dock.confirm": "포착 확인됨",
"dock.loading": "캡처 규칙 로딩 중…",
"dock.saving": "포착 중…",
"dock.saved": "도카에게 저장됨",
"dock.warnings": "{count} 개의 항목이 완전히 처리되지 않았습니다; 플레이스홀더는 저장되었습니다",
"dock.open": "문서 열기",
"dock.login": "Doca에 로그인하세요.",
"dock.setup": "설정 열기",
"dock.noProfiles": "먼저 캡처 규칙을 설정하세요.",
"dock.retry": "다시 시도",
"dock.failed": "불완전한 캡처입니다. 다시 시도해 주세요.",
"dock.failedWithCode": "불완전한 캡처 (오류 코드: {code}).",
"clipper_too_many_pending": "현재 너무 많은 작업이 활성화되어 있습니다. 잠시 후에 다시 시도해 주세요.",
"dock.connectionFailed": "Doca에 연결할 수 없습니다. 다시 시도해 주세요.",
"dock.selectionMissing": "먼저 캡처할 웹페이지 콘텐츠를 선택하세요.",
"dock.updated": "확장 기능이 업데이트되었습니다. 이 페이지를 다시 로드하세요.",
"dock.reload": "페이지 다시 로드",
"dock.positionFailed": "위치를 저장할 수 없음. 다시 드래그하여 시도하세요.",
"dock.images": "대형 이미지 압축됨; SVG 변환됨; 사용할 수 없는 이미지는 표시됨",
"dock.create": "새 문서",
"dock.append": "문서에 추가하기",
"dock.personal": "개인 문서",
"dock.default": "기본값",
"dock.compressionFailed": "이미지 압축에 실패했습니다. 캡처가 불완전합니다. 다시 시도해 주세요.",
"dock.animationLarge": "애니메이션의 크기가 20 MiB 또는 2500만 픽셀을 초과합니다. 더 작은 이미지를 선택하세요. 그러면 평면화되지 않습니다."
},
"es": {
"dock.page": "Capture esta página",
"dock.selection": "Selección de captura",
"dock.assistant": "Asistente de Doca",
"dock.site": "Abrir el sitio web de Doca",
"dock.settings": "Configuración",
"dock.drag": "Arrastre verticalmente o utilice las teclas de flecha.",
"dock.collapse": "Barra de herramientas de colapso",
"dock.expand": "Expandir la barra de herramientas",
"dock.close": "Cerrar",
"dock.rule": "Regla de captura",
"dock.confirm": "Confirmar captura",
"dock.loading": "Cargando reglas de captura…",
"dock.saving": "Capturar…",
"dock.saved": "Guardado en Doca",
"dock.warnings": "{count} artículos no pudieron ser procesados completamente; los marcadores se guardaron",
"dock.open": "Abrir documento",
"dock.login": "Inicie sesión en Doca",
"dock.setup": "Abrir configuraciones",
"dock.noProfiles": "Primero, establece una regla de captura.",
"dock.retry": "Reintentar",
"dock.failed": "Captura incompleta. Por favor, intenta de nuevo.",
"dock.failedWithCode": "Captura incompleta (código de error: {code}).",
"clipper_too_many_pending": "Hay demasiadas tareas activas en este momento. Por favor, intente de nuevo en breve.",
"dock.connectionFailed": "No se pudo conectar con Doca. Por favor, intenta de nuevo.",
"dock.selectionMissing": "Seleccione el contenido de la página web para capturar primero",
"dock.updated": "La extensión se actualizó. Recarga esta página.",
"dock.reload": "Recargar página",
"dock.positionFailed": "No se pudo guardar la posición. Arrastre para intentar de nuevo.",
"dock.images": "Imágenes grandes comprimidas; SVG convertidas; imágenes no disponibles marcadas",
"dock.create": "Documento nuevo",
"dock.append": "Añadir al documento",
"dock.personal": "Documentos personales",
"dock.default": "Predeterminado",
"dock.compressionFailed": "La compresión de imagen falló. La captura es incompleta; por favor, intente de nuevo.",
"dock.animationLarge": "La animación supera los 20 MiB o 25 millones de píxeles. Elija una imagen más pequeña; no se aplanará."
},
"ru": {
"dock.page": "Захватите эту страницу",
"dock.selection": "Выбор захвата",
"dock.assistant": "Дока-ассистент",
"dock.site": "Откройте сайт Doca",
"dock.settings": "Настройки",
"dock.drag": "Перетащите вертикально или использовать клавиши стрелок.",
"dock.collapse": "Разрушение инструментов управления",
"dock.expand": "Расширить панель инструментов",
"dock.close": "Закрыть",
"dock.rule": "Правило захвата",
"dock.confirm": "Подтвердить захват",
"dock.loading": "Загрузка правил захвата…",
"dock.saving": "Фиксация…",
"dock.saved": "Сохранено в Doca",
"dock.warnings": "{count} элементов не удалось полностью обработать; плейсхолдеры сохранены",
"dock.open": "Откройте документ",
"dock.login": "Войдите в Doca",
"dock.setup": "Открыть настройки",
"dock.noProfiles": "Сначала настройте правило захвата.",
"dock.retry": "Повторить",
"dock.failed": "Захват неполный. Пожалуйста, попробуйте снова.",
"dock.failedWithCode": "Захват неполный (код ошибки: {code}).",
"clipper_too_many_pending": "Сейчас слишком много задач активны. Пожалуйста, попробуйте снова в ближайшее время.",
"dock.connectionFailed": "Не удалось подключиться к Doca. Пожалуйста, попробуйте снова.",
"dock.selectionMissing": "Сначала выберите содержимое веб-страницы для захвата.",
"dock.updated": "Расширение обновлено. Перезагрузите эту страницу.",
"dock.reload": "Перезагрузить страницу",
"dock.positionFailed": "Не удалось сохранить позицию. Перетащите, чтобы попробовать снова.",
"dock.images": "Большие изображения сжаты; SVG конвертированы; неактивные изображения отмечены",
"dock.create": "Новый документ",
"dock.append": "Добавить в документ",
"dock.personal": "Личные документы",
"dock.default": "По умолчанию",
"dock.compressionFailed": "Сжатие изображения не удалось. Запись неполная; пожалуйста, попробуйте снова.",
"dock.animationLarge": "Анимация имеет размер более 20 МиБ или 25 миллионов пикселей. Выберите более маленький изображение; оно не будет выпрямлено."
}
};
let locale = "zh",
snapshot = null,
selectedRange = null,
mode = "page",
prepared = null,
preparedReady = false,
state = null,
busy = false,
panelGeneration = 0,
positionRatio = 0.5,
collapsed = false,
expandedHeight = 0,
positionTouched = false,
drag = null;
const t = (key) => messages[locale][key] ?? messages.en[key];
const send = async (message) => {
if (!chrome.runtime?.id) throw Error("Extension context invalidated");
const result = await chrome.runtime.sendMessage(message);
if (!result?.ok) throw Error(result?.error || "clipper_connection_failed");
return result.value;
};
const host = document.createElement("div");
host.dataset.docaCaptureUi = "true";
host.style.cssText =
"position:fixed;right:12px;top:40%;z-index:2147483646;pointer-events:none;visibility:hidden;";
const shadow = host.attachShadow({ mode: "closed" });
const style = document.createElement("style");
style.textContent = [
":host{all:initial;color-scheme:light;--blue:#3370ff;--text:#263040;--muted:#748096;--line:#e4e9f1;font:14px/1.55 -apple-system,BlinkMacSystemFont,'Segoe UI','PingFang SC',sans-serif}",
"*{box-sizing:border-box}[hidden]{display:none!important}button,select,a{font:inherit}button,a,select{pointer-events:auto}button{cursor:pointer}button:disabled,select:disabled{cursor:wait;opacity:.6}",
".dock{position:relative;width:44px;padding:4px;background:#fff;border:1px solid var(--line);border-radius:13px;box-shadow:0 4px 18px #2134521a;pointer-events:auto}:host(.ready) .dock{animation:dock-enter .24s ease-out}.actions{animation:dock-actions .16s ease-out}",
".tool,.handle,.collapse{position:relative;display:grid;place-items:center;width:34px;height:38px;padding:0;border:0;border-radius:8px;color:#64718a;background:transparent;transition:background .16s,color .16s,transform .12s}",
".tool:hover,.tool:focus-visible,.collapse:hover,.collapse:focus-visible{background:#edf3ff;color:var(--blue)}.tool:active,.collapse:active{transform:scale(.94)}.tool[aria-expanded=true]{background:#edf3ff;color:var(--blue)}.assistant{color:var(--blue)}",
".handle{height:24px;color:#5c6e88;background:#edf1f7;border:1px solid #dde4ee;cursor:grab;touch-action:none;transition:background .16s}.handle:hover{color:#405574;background:#e3eaf5}.handle:active{cursor:grabbing}.dragging .dock{box-shadow:0 8px 28px #21345230}.divider{height:1px;background:#edf0f5;margin:4px 2px}",
"svg{width:20px;height:20px;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}.handle svg{width:18px;height:18px;stroke-width:2.4}",
".collapse{margin-top:4px;border-top:1px solid #edf0f5;border-radius:0 0 8px 8px}.collapse svg{width:16px;height:16px}",
".tip{position:absolute;right:calc(100% + 14px);top:50%;transform:translateY(-50%) translateX(3px);padding:5px 9px;background:#263040;color:#fff;font-size:12px;line-height:1.5;border-radius:6px;white-space:nowrap;opacity:0;visibility:hidden;pointer-events:none;transition:opacity .13s,transform .13s}",
".tool:hover .tip,.tool:focus-visible .tip,.handle:focus-visible .tip{opacity:1;visibility:visible;transform:translateY(-50%) translateX(0)}.tool[aria-expanded=true] .tip{visibility:hidden}",
".panel{position:fixed;right:68px;width:min(300px,calc(100vw - 84px));max-height:calc(100vh - 24px);overflow:auto;padding:16px;background:#fff;color:var(--text);border:1px solid var(--line);border-radius:14px;box-shadow:0 12px 40px #24365024;pointer-events:auto;animation:panel-enter .18s ease-out;transform-origin:right center}",
".heading{display:flex;align-items:center;gap:8px;margin-bottom:14px}.heading strong{flex:1;font-size:15px;font-weight:600}.close{display:grid;place-items:center;border:0;border-radius:6px;width:25px;height:25px;padding:0;color:#8792a5;background:transparent}.close:hover{background:#f0f3f8}.close svg{width:16px;height:16px}",
"label{display:block;color:#68758b;font-size:12px;margin-bottom:6px}.doca-select{display:block;min-width:0}.doca-select-trigger{display:flex;align-items:center;justify-content:space-between;gap:10px;width:100%;height:40px;border:1px solid #dce3ee;border-radius:8px;padding:0 10px;background:#fff;color:var(--text);text-align:left}.doca-select-trigger>span:first-child{min-width:0;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.doca-select-arrow{width:6px;height:6px;border-right:1px solid #8792a5;border-bottom:1px solid #8792a5;transform:rotate(45deg);margin:-3px 3px 0 0;flex:none}.doca-select-trigger[aria-expanded=true]{border-color:var(--blue);box-shadow:0 0 0 3px #3370ff18}",
".doca-select-menu{position:fixed;z-index:20;padding:4px;border:1px solid var(--line);border-radius:9px;background:#fff;box-shadow:0 8px 24px #21345226;overflow:auto;pointer-events:auto;animation:dropdown-enter .14s ease-out}.doca-select-option{display:block;width:100%;min-height:34px;padding:7px 9px;text-align:left;border:0;border-radius:5px;background:#fff;color:var(--text);font-size:13px;line-height:1.5;overflow-wrap:anywhere}.doca-select-option.is-active,.doca-select-option:hover{background:#edf3ff}.doca-select-option[aria-selected=true]{color:var(--blue);font-weight:600}",
".detail{font-size:12px;line-height:1.6;color:var(--muted);margin:8px 0 14px;overflow-wrap:anywhere}.status{font-size:13px;line-height:1.6;overflow-wrap:anywhere;margin:0 0 12px}.status:empty{display:none}.status.success{color:#26815b}.status.error{color:#b0443d}.status a{display:inline-block;margin-left:8px;color:var(--blue);text-decoration:none}",
".confirm{width:100%;height:39px;border:0;border-radius:8px;background:var(--blue);color:#fff;font-weight:500;transition:background .16s,transform .12s}.confirm:hover{background:#2862e9}.confirm:active{transform:scale(.98)}button:focus-visible,a:focus-visible{outline:2px solid #3370ff;outline-offset:3px}",
"@keyframes dock-enter{from{opacity:0;transform:translateX(8px)}to{opacity:1;transform:translateX(0)}}@keyframes panel-enter{from{opacity:0;transform:translateX(5px) scale(.98)}to{opacity:1;transform:translateX(0) scale(1)}}@keyframes dropdown-enter{from{opacity:0;transform:translateY(3px)}to{opacity:1;transform:translateY(0)}}@keyframes dock-actions{from{opacity:0}to{opacity:1}}",
"@media(max-height:260px){.tool{height:30px}.handle{height:14px}.panel{padding:12px}.heading{margin-bottom:8px}}@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important}}",
].join("\n");
const svg = (paths) => {
const node = document.createElementNS("http://www.w3.org/2000/svg", "svg");
node.setAttribute("viewBox", "0 0 24 24");
node.setAttribute("aria-hidden", "true");
for (const [tag, attrs] of paths) {
const child = document.createElementNS(node.namespaceURI, tag);
for (const [key, value] of Object.entries(attrs))
child.setAttribute(key, value);
node.append(child);
}
return node;
};
const icons = {
page: [
["rect", { x: 3, y: 4, width: 18, height: 16, rx: 3 }],
["path", { d: "M3 9h18M7 6.5h.01M10 6.5h.01m-3 7h10m-10 3h7" }],
],
selection: [
[
"path",
{
d: "M8 3H4a1 1 0 0 0-1 1v4m13-5h4a1 1 0 0 1 1 1v4M3 16v4a1 1 0 0 0 1 1h4m8 0h4a1 1 0 0 0 1-1v-4M8 8h8v8H8Z",
},
],
],
assistant: [
[
"path",
{
d: "m12 3 2.6 6.4L21 12l-6.4 2.6L12 21l-2.6-6.4L3 12l6.4-2.6ZM20 2v4m-2-2h4",
},
],
],
site: [
[
"path",
{
d: "M14 3h7v7m0-7L11 13M10 3H6a3 3 0 0 0-3 3v12a3 3 0 0 0 3 3h12a3 3 0 0 0 3-3v-4",
},
],
],
settings: [
[
"path",
{
d: "m9 3-.6 2.2-1.7 1L4.5 6l-2 3.5L4 11v2l-1.5 1.5 2 3.5 2.2-.2 1.7 1L9 21h4l.6-2.2 1.7-1 2.2.2 2-3.5L18 13v-2l1.5-1.5-2-3.5-2.2.2-1.7-1L13 3Z",
},
],
["circle", { cx: 11, cy: 12, r: 3 }],
],
};
const dock = document.createElement("div");
dock.className = "dock";
dock.setAttribute("role", "toolbar");
dock.setAttribute("aria-label", "Doca");
const buttons = new Map();
const button = (name, paths, className = "tool") => {
const node = document.createElement("button");
node.type = "button";
node.className = className;
node.dataset.action = name;
const tip = document.createElement("span");
tip.className = "tip";
node.append(svg(paths), tip);
buttons.set(name, node);
return node;
};
const handle = button(
"drag",
[
[
"path",
{ d: "M9 6h.01M15 6h.01M9 12h.01M15 12h.01M9 18h.01M15 18h.01" },
],
],
"handle",
);
dock.append(handle);
const actions = document.createElement("div");
actions.className = "actions";
actions.id = "doca-dock-actions";
dock.append(actions);
for (const name of ["page", "selection", "assistant", "site", "settings"]) {
if (name === "site") {
const line = document.createElement("div");
line.className = "divider";
actions.append(line);
}
actions.append(
button(
name,
icons[name],
"tool" + (name === "assistant" ? " assistant" : ""),
),
);
}
const collapse = document.createElement("button");
collapse.type = "button";
collapse.className = "collapse";
collapse.dataset.action = "collapse";
collapse.setAttribute("aria-controls", actions.id);
dock.append(collapse);
const panel = document.createElement("div");
panel.className = "panel";
panel.hidden = true;
panel.setAttribute("role", "dialog");
panel.setAttribute("aria-labelledby", "doca-dock-heading");
const heading = document.createElement("div");
heading.className = "heading";
const title = document.createElement("strong");
title.id = "doca-dock-heading";
const close = document.createElement("button");
close.className = "close";
close.append(svg([["path", { d: "m6 6 12 12M6 18 18 6" }]]));
heading.append(title, close);
const fields = document.createElement("div");
const label = document.createElement("label");
label.htmlFor = "doca-dock-profile";
const profiles = document.createElement("select");
profiles.id = label.htmlFor;
const detail = document.createElement("p");
detail.className = "detail";
fields.append(label, profiles, detail);
const status = document.createElement("p");
status.className = "status";
status.setAttribute("role", "status");
status.setAttribute("aria-live", "polite");
const confirm = document.createElement("button");
confirm.className = "confirm";
panel.append(heading, fields, status, confirm);
shadow.append(style, dock, panel);
document.documentElement.append(host);
const dropdown = globalThis.DocaSelect.enhance(profiles);
function translate() {
host.lang = locale === "zh" ? "zh-CN" : locale;
for (const [name, node] of buttons) {
node.setAttribute("aria-label", t("dock." + name));
node.querySelector(".tip").textContent = t("dock." + name);
}
close.setAttribute("aria-label", t("dock.close"));
label.textContent = t("dock.rule");
profiles.setAttribute("aria-label", t("dock.rule"));
dropdown.sync();
collapse.setAttribute(
"aria-label",
t(collapsed ? "dock.expand" : "dock.collapse"),
);
collapse.setAttribute(
"title",
t(collapsed ? "dock.expand" : "dock.collapse"),
);
collapse.setAttribute("aria-expanded", String(!collapsed));
collapse.replaceChildren(
svg([["path", { d: collapsed ? "m6 9 6 6 6-6" : "m6 15 6-6 6 6" }]]),
);
}
function verticalSpace() {
if (!collapsed) expandedHeight = dock.getBoundingClientRect().height;
return Math.max(0, innerHeight - expandedHeight - 24);
}
function position() {
host.style.top = 12 + positionRatio * verticalSpace() + "px";
if (!panel.hidden) {
const anchor =
buttons.get(mode)?.getBoundingClientRect() ||
dock.getBoundingClientRect();
panel.style.top =
Math.max(
12,
Math.min(innerHeight - panel.offsetHeight - 12, anchor.top - 12),
) + "px";
}
}
function dismiss() {
if (busy) return;
dropdown.close();
panel.hidden = true;
panelGeneration++;
for (const node of buttons.values())
node.setAttribute("aria-expanded", "false");
}
collapse.onclick = (event) => {
if (!event.isTrusted || busy) return;
dismiss();
verticalSpace();
collapsed = !collapsed;
actions.hidden = collapsed;
dock.classList.toggle("collapsed", collapsed);
translate();
position();
};
function showStatus(message, error = false) {
status.textContent = message;
status.className = "status" + (error ? " error" : "");
position();
}
function rememberSelection() {
const selection = window.getSelection();
if (
selection?.rangeCount &&
!selection.isCollapsed &&
!host.contains(selection.anchorNode) &&
!shadow.contains(selection.anchorNode) &&
!selection.anchorNode?.parentElement?.closest(
"input,textarea,[contenteditable=true]",
)
) {
selectedRange = selection.getRangeAt(0).cloneRange();
} else if (panel.hidden) selectedRange = null;
}
function selectionCapture() {
const range = selectedRange;
if (!range || range.collapsed || !range.commonAncestorContainer.isConnected)
throw Error("clipper_selection_missing");
return globalThis.DocaCapture.capture("selection", range);
}
function errorText(error) {
if (/Extension context invalidated/i.test(error.message))
return t("dock.updated");
if (error.message === "clipper_selection_missing")
return t("dock.selectionMissing");
if (error.message === "clipper_connection_failed")
return t("dock.connectionFailed");
if (error.message === "clipper_image_compression_failed")
return t("dock.compressionFailed");
if (error.message === "clipper_animated_image_too_large")
return t("dock.animationLarge");
if (messages[locale][error.message]) return t(error.message);
return /^clipper_[a-z0-9_]{1,120}$/.test(error.message)
? t("dock.failedWithCode").replace("{code}", error.message)
: error.message;
}
function profileDetail() {
const profile = state?.profiles.find((row) => row.id === profiles.value);
detail.textContent = profile
? [
t(profile.strategy === "append" ? "dock.append" : "dock.create"),
profile.destinationTitle ||
(profile.libraryId || profile.targetId ? "" : t("dock.personal")),
t("dock.images"),
]
.filter(Boolean)
.join(" · ")
: "";
position();
}
const settings = () => send({ type: "openSettings" });
async function loadState() {
const generation = ++panelGeneration;
confirm.disabled = true;
profiles.disabled = true;
fields.hidden = false;
confirm.textContent = t("dock.confirm");
showStatus(t("dock.loading"));
try {
const next = await send({ type: "state" });
if (generation !== panelGeneration || panel.hidden) return;
state = next;
locale = Object.hasOwn(messages, next.locale) ? next.locale : "zh";
translate();
title.textContent = t("dock." + mode);
profiles.replaceChildren();
for (const profile of next.profiles) {
const option = document.createElement("option");
option.value = profile.id;
option.dataset.revision = String(profile.revision);
option.textContent =
profile.name + (profile.isDefault ? " · " + t("dock.default") : "");
profiles.append(option);
}
profiles.value =
next.profiles.find((row) => row.isDefault)?.id ||
next.profiles[0]?.id ||
"";
profiles.disabled = false;
confirm.disabled = false;
confirm.onclick = capture;
if (!next.connected) {
fields.hidden = true;
const needsSettings = [
"clipper_not_connected",
"clipper_invalid_config",
].includes(next.error);
confirm.textContent = t(needsSettings ? "dock.setup" : "dock.login");
showStatus(t("dock.connectionFailed"), true);
confirm.onclick = async (event) => {
if (!event.isTrusted) return;
confirm.disabled = true;
try {
if (needsSettings) await settings();
else {
await send({ type: "login" });
await loadState();
}
} catch (error) {
showStatus(errorText(error), true);
} finally {
confirm.disabled = false;
}
};
} else if (!next.profiles.length) {
fields.hidden = true;
showStatus(t("dock.noProfiles"));
confirm.textContent = t("dock.setup");
confirm.onclick = (event) => {
if (event.isTrusted)
void settings().catch((error) =>
showStatus(errorText(error), true),
);
};
} else {
confirm.textContent = t("dock.confirm");
showStatus("");
profileDetail();
}
} catch (error) {
if (generation !== panelGeneration || panel.hidden) return;
fields.hidden = true;
showStatus(errorText(error), true);
confirm.disabled = false;
const invalidated = /Extension context invalidated/i.test(error.message);
confirm.textContent = t(invalidated ? "dock.reload" : "dock.retry");
confirm.onclick = (event) => {
if (event.isTrusted) invalidated ? location.reload() : void loadState();
};
}
position();
}
async function capture(event) {
if (!event.isTrusted || busy) return;
const profile = state?.profiles.find((row) => row.id === profiles.value);
if (!profile) return;
busy = true;
handle.disabled = collapse.disabled = true;
dropdown.close();
confirm.disabled = profiles.disabled = true;
dropdown.sync();
confirm.textContent = t("dock.saving");
showStatus("");
try {
prepared ||= globalThis.DocaCapture.capture("page");
snapshot = prepared;
if (!preparedReady) {
prepared = await send({ type: "prepareCapture", capture: prepared });
snapshot = prepared;
preparedReady = true;
}
const result = await send({
type: "capture",
capture: prepared,
profileId: profile.id,
profileRevision: profile.revision,
});
fields.hidden = true;
status.textContent = t("dock.saved");
status.className = "status success";
const link = document.createElement("a");
link.href = result.url;
link.textContent = t("dock.open");
link.target = "_blank";
link.rel = "noopener noreferrer";
status.append(link);
if (result.warnings?.length) {
const details = document.createElement("details");
const summary = document.createElement("summary");
summary.textContent = t("dock.warnings").replace(
"{count}",
result.warnings.length,
);
const list = document.createElement("ul");
for (const warning of result.warnings) {
const item = document.createElement("li");
item.textContent = warning.message;
list.append(item);
}
details.append(summary, list);
status.append(details);
}
confirm.hidden = true;
} catch (error) {
showStatus(errorText(error), true);
confirm.textContent = t("dock.retry");
} finally {
busy = false;
handle.disabled = collapse.disabled = false;
confirm.disabled = profiles.disabled = false;
dropdown.sync();
position();
}
}
function openCapture(name, event) {
if (!event.isTrusted || busy) return;
if (!panel.hidden && mode === name) {
dismiss();
return;
}
rememberSelection();
mode = name;
prepared = null;
preparedReady = false;
panel.hidden = false;
fields.hidden = false;
confirm.hidden = false;
title.textContent = t("dock." + mode);
for (const [key, node] of buttons)
node.setAttribute("aria-expanded", String(key === name));
position();
if (name === "selection") {
try {
prepared = snapshot = selectionCapture();
} catch (error) {
panelGeneration++;
fields.hidden = true;
confirm.hidden = true;
showStatus(errorText(error), true);
return;
}
}
void loadState();
}
buttons.get("page").onclick = (event) => openCapture("page", event);
buttons.get("selection").onclick = (event) => openCapture("selection", event);
buttons.get("site").onclick = async (event) => {
if (!event.isTrusted) return;
dismiss();
try {
try {
await send({ type: "openSite" });
} catch (error) {
if (
![
"clipper_not_connected",
"clipper_invalid_config",
"clipper_invalid_origin",
].includes(error.message)
)
throw error;
await settings();
}
} catch (error) {
mode = "site";
panel.hidden = false;
fields.hidden = confirm.hidden = true;
title.textContent = t("dock.site");
showStatus(errorText(error), true);
}
};
buttons.get("settings").onclick = (event) => {
if (event.isTrusted)
void settings().catch((error) => {
mode = "settings";
panel.hidden = false;
fields.hidden = confirm.hidden = true;
title.textContent = t("dock.settings");
showStatus(errorText(error), true);
});
};
buttons.get("assistant").onclick = (event) => {
if (!event.isTrusted) return;
dismiss();
// The native side panel must open directly from this click, before any awaits.
void send({ type: "openAssistant" }).catch((error) => {
mode = "assistant";
panel.hidden = false;
fields.hidden = confirm.hidden = true;
title.textContent = t("dock.assistant");
showStatus(errorText(error), true);
});
};
close.onclick = dismiss;
profiles.onchange = profileDetail;
shadow.addEventListener("mousedown", (event) => {
if (
event.target instanceof Element &&
event.target.closest("button") &&
!event.target.closest('[role="combobox"],[role="option"]')
)
event.preventDefault();
});
document.addEventListener("selectionchange", rememberSelection);
document.addEventListener(
"pointerdown",
(event) => {
if (!event.composedPath().includes(host)) dismiss();
},
true,
);
document.addEventListener(
"keydown",
(event) => {
if (
event.key === "Escape" &&
shadow.querySelector(".doca-select-menu").hidden
)
dismiss();
},
true,
);
async function savePosition() {
try {
await send({
type: "dockPreferences",
operation: "set",
position: positionRatio,
});
} catch {
mode = "drag";
panel.hidden = false;
fields.hidden = confirm.hidden = true;
title.textContent = "Doca";
showStatus(t("dock.positionFailed"), true);
}
}
handle.onpointerdown = (event) => {
if (!event.isTrusted || event.button !== 0 || busy) return;
event.preventDefault();
dismiss();
positionTouched = true;
drag = {
pointerId: event.pointerId,
y: event.clientY,
top: host.getBoundingClientRect().top,
};
handle.setPointerCapture(event.pointerId);
host.classList.add("dragging");
};
handle.onpointermove = (event) => {
if (!drag || event.pointerId !== drag.pointerId) return;
const space = verticalSpace();
const top = Math.max(
12,
Math.min(12 + space, drag.top + event.clientY - drag.y),
);
positionRatio = space ? (top - 12) / space : 0;
position();
};
handle.onpointerup = handle.onpointercancel = (event) => {
if (!drag || event.pointerId !== drag.pointerId) return;
drag = null;
host.classList.remove("dragging");
if (handle.hasPointerCapture(event.pointerId))
handle.releasePointerCapture(event.pointerId);
void savePosition();
};
handle.onkeydown = (event) => {
if (!["ArrowUp", "ArrowDown", "Home", "End"].includes(event.key) || busy)
return;
event.preventDefault();
dismiss();
positionTouched = true;
const space = verticalSpace();
positionRatio =
event.key === "Home"
? 0
: event.key === "End"
? 1
: Math.max(
0,
Math.min(
1,
positionRatio +
(event.key === "ArrowUp" ? -20 : 20) / Math.max(1, space),
),
);
position();
void savePosition();
};
addEventListener("resize", () => {
dropdown.close();
position();
});
translate();
position();
void send({ type: "dockPreferences", operation: "get" })
.then((preferences) => {
locale = Object.hasOwn(messages, preferences.locale) ? preferences.locale : "zh";
translate();
if (!positionTouched && preferences.position !== null)
positionRatio = preferences.position;
position();
})
.catch(() => {})
.finally(() => {
host.style.visibility = "visible";
host.classList.add("ready");
});
chrome.runtime.onMessage.addListener((message, _sender, respond) => {
if (message.type === "snapshot") {
try {
rememberSelection();
snapshot = globalThis.DocaCapture.capture(
message.mode,
message.mode === "selection" ? selectedRange : null,
);
respond({ ok: true, value: snapshot });
} catch (error) {
respond({ ok: false, error: error.message });
}
}
if (message.type === "image") {
const image = snapshot?.images.find(
(image) => image.id === message.id && image.url === message.url,
);
if (!image) {
respond({ ok: false, error: "clipper_image_unlisted" });
return;
}
const respondImage = (bytes) => {
let binary = "";
for (let start = 0; start < bytes.length; start += 8192)
binary += String.fromCharCode(...bytes.subarray(start, start + 8192));
respond({ ok: true, value: btoa(binary) });
};
if (message.convertSvg) {
// Reuse extension-fetched bytes: page fetch would impose CDN CORS.
void (async () => {
if (
typeof message.source !== "string" ||
message.source.length > Math.ceil((32 * 1024 ** 2) / 3) * 4
)
throw Error("clipper_image_invalid");
const bytes = Uint8Array.from(atob(message.source), (char) =>
char.charCodeAt(0),
);
if (!bytes.length || bytes.length > 32 * 1024 ** 2)
throw Error("clipper_image_invalid");
respondImage(await globalThis.DocaSvgImage.rasterize(bytes));
})().catch((error) => respond({ ok: false, error: error.message }));
return true;
}
fetch(image.url, {
credentials: "include",
signal: AbortSignal.timeout(15000),
})
.then(async (response) => {
if (!response.ok) throw Error("clipper_image_failed");
const limit = 64 * 1024 ** 2;
if (
Number(response.headers.get("content-length")) > limit ||
!response.body
)
throw Error("clipper_image_invalid");
const reader = response.body.getReader(),
chunks = [];
let size = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
size += value.byteLength;
if (size > limit) {
await reader.cancel();