-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmindmap.py
More file actions
2887 lines (2650 loc) · 129 KB
/
Copy pathmindmap.py
File metadata and controls
2887 lines (2650 loc) · 129 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
"""
title: Smart Mind Map
author: Fu-Jie
author_url: https://github.com/Fu-Jie/openwebui-extensions
funding_url: https://github.com/open-webui
version: 1.0.0
openwebui_id: 3094c59a-b4dd-4e0c-9449-15e2dd547dc4
icon_url: data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiPjxyZWN0IHg9IjE2IiB5PSIxNiIgd2lkdGg9IjYiIGhlaWdodD0iNiIgcng9IjEiLz48cmVjdCB4PSIyIiB5PSIxNiIgd2lkdGg9IjYiIGhlaWdodD0iNiIgcng9IjEiLz48cmVjdCB4PSI5IiB5PSIyIiB3aWR0aD0iNiIgaGVpZ2h0PSI2IiByeD0iMSIvPjxwYXRoIGQ9Ik01IDE2di0zYTEgMSAwIDAgMSAxLTFoMTJhMSAxIDAgMCAxIDEgMXYzIi8+PHBhdGggZD0iTTEyIDEyVjgiLz48L3N2Zz4=
description: Intelligently analyzes text content and generates interactive mind maps to help users structure and visualize knowledge.
"""
import asyncio
import logging
import os
import re
import time
import json
from datetime import datetime, timezone
from typing import Any, Callable, Awaitable, Dict, Optional
from zoneinfo import ZoneInfo
from fastapi import Request
from pydantic import BaseModel, Field
from open_webui.utils.chat import generate_chat_completion
from open_webui.models.users import Users
try:
from open_webui.env import VERSION as open_webui_version
except ImportError:
open_webui_version = "0.0.0"
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
TRANSLATIONS = {
"en-US": {
"status_starting": "Smart Mind Map is starting, generating mind map for you...",
"error_no_content": "Unable to retrieve valid user message content.",
"error_text_too_short": "Text content is too short ({len} characters), unable to perform effective analysis. Please provide at least {min_len} characters of text.",
"status_analyzing": "Smart Mind Map: Analyzing text structure in depth...",
"status_drawing": "Smart Mind Map: Drawing completed!",
"notification_success": "Mind map has been generated, {user_name}!",
"error_processing": "Smart Mind Map processing failed: {error}",
"error_user_facing": "Sorry, Smart Mind Map encountered an error during processing: {error}.\nPlease check the Open WebUI backend logs for more details.",
"status_failed": "Smart Mind Map: Processing failed.",
"notification_failed": "Smart Mind Map generation failed, {user_name}!",
"status_rendering_image": "Smart Mind Map: Rendering image...",
"status_image_generated": "Smart Mind Map: Image generated!",
"notification_image_success": "Mind map image has been generated, {user_name}!",
"ui_title": "🧠 Smart Mind Map",
"ui_user": "User:",
"ui_time": "Time:",
"ui_download_png": "PNG",
"ui_download_svg": "SVG",
"ui_download_md": "Markdown",
"ui_zoom_out": "-",
"ui_zoom_reset": "Reset",
"ui_zoom_in": "+",
"ui_depth_select": "Expand Level",
"ui_depth_all": "Expand All",
"ui_depth_2": "Level 2",
"ui_depth_3": "Level 3",
"ui_fullscreen": "Fullscreen",
"ui_theme": "Theme",
"ui_footer": "<b>Powered by</b> <a href='https://markmap.js.org/' target='_blank' rel='noopener noreferrer'>Markmap</a>",
"html_error_missing_content": "⚠️ Unable to load mind map: Missing valid content.",
"html_error_load_failed": "⚠️ Resource loading failed, please try again later.",
"js_done": "Done",
"js_failed": "Failed",
"js_generating": "Generating...",
"js_filename": "mindmap.png",
"js_upload_failed": "Upload failed: ",
"md_image_alt": "🧠 Mind Map",
},
"zh-CN": {
"status_starting": "思维导图已启动,正在为您生成思维导图...",
"error_no_content": "无法获取有效的用户消息内容。",
"error_text_too_short": "文本内容过短({len}字符),无法进行有效分析。请提供至少{min_len}字符的文本。",
"status_analyzing": "思维导图:深入分析文本结构...",
"status_drawing": "思维导图:绘制完成!",
"notification_success": "思维导图已生成,{user_name}!",
"error_processing": "思维导图处理失败:{error}",
"error_user_facing": "抱歉,思维导图在处理时遇到错误:{error}。\n请检查Open WebUI后端日志获取更多详情。",
"status_failed": "思维导图:处理失败。",
"notification_failed": "思维导图生成失败,{user_name}!",
"status_rendering_image": "思维导图:正在渲染图片...",
"status_image_generated": "思维导图:图片已生成!",
"notification_image_success": "思维导图图片已生成,{user_name}!",
"ui_title": "🧠 智能思维导图",
"ui_user": "用户:",
"ui_time": "时间:",
"ui_download_png": "PNG",
"ui_download_svg": "SVG",
"ui_download_md": "Markdown",
"ui_zoom_out": "缩小",
"ui_zoom_reset": "重置",
"ui_zoom_in": "放大",
"ui_depth_select": "展开层级",
"ui_depth_all": "全部展开",
"ui_depth_2": "展开 2 级",
"ui_depth_3": "展开 3 级",
"ui_fullscreen": "全屏",
"ui_theme": "主题",
"ui_footer": "<b>Powered by</b> <a href='https://markmap.js.org/' target='_blank' rel='noopener noreferrer'>Markmap</a>",
"html_error_missing_content": "⚠️ 无法加载思维导图:缺少有效内容。",
"html_error_load_failed": "⚠️ 资源加载失败,请稍后重试。",
"js_done": "完成",
"js_failed": "失败",
"js_generating": "生成中...",
"js_filename": "思维导图.png",
"js_upload_failed": "上传失败:",
"md_image_alt": "🧠 思维导图",
},
"zh-HK": {
"status_starting": "思維導圖已啟動,正在為您生成思維導圖...",
"error_no_content": "無法獲取有效的用戶消息內容。",
"error_text_too_short": "文本內容過短({len}字元),無法進行有效分析。請提供至少{min_len}字元的文本。",
"status_analyzing": "思維導圖:深入分析文本結構...",
"status_drawing": "思維導圖:繪製完成!",
"notification_success": "思維導圖已生成,{user_name}!",
"error_processing": "思維導圖處理失敗:{error}",
"error_user_facing": "抱歉,思維導圖在處理時遇到錯誤:{error}。\n請檢查Open WebUI後端日誌獲取更多詳情。",
"status_failed": "思維導圖:處理失敗。",
"notification_failed": "思維導圖生成失敗,{user_name}!",
"status_rendering_image": "思維導圖:正在渲染圖片...",
"status_image_generated": "思維導圖:圖片已生成!",
"notification_image_success": "思維導圖圖片已生成,{user_name}!",
"ui_title": "🧠 智能思維導圖",
"ui_user": "用戶:",
"ui_time": "時間:",
"ui_download_png": "PNG",
"ui_download_svg": "SVG",
"ui_download_md": "Markdown",
"ui_zoom_out": "縮小",
"ui_zoom_reset": "重置",
"ui_zoom_in": "放大",
"ui_depth_select": "展開層級",
"ui_depth_all": "全部展開",
"ui_depth_2": "展開 2 級",
"ui_depth_3": "展開 3 級",
"ui_fullscreen": "全屏",
"ui_theme": "主題",
"ui_footer": "<b>Powered by</b> <a href='https://markmap.js.org/' target='_blank' rel='noopener noreferrer'>Markmap</a>",
"html_error_missing_content": "⚠️ 無法加載思維導圖:缺少有效內容。",
"html_error_load_failed": "⚠️ 資源加載失敗,請稍後重試。",
"js_done": "完成",
"js_failed": "失敗",
"js_generating": "生成中...",
"js_filename": "思維導圖.png",
"js_upload_failed": "上傳失敗:",
"md_image_alt": "🧠 思維導圖",
},
"zh-TW": {
"status_starting": "思維導圖已啟動,正在為您生成思維導圖...",
"error_no_content": "無法獲取有效的用戶消息內容。",
"error_text_too_short": "文本內容過短({len}字元),無法進行有效分析。請提供至少{min_len}字元的文本。",
"status_analyzing": "思維導圖:深入分析文本結構...",
"status_drawing": "思維導圖:繪製完成!",
"notification_success": "思維導圖已生成,{user_name}!",
"error_processing": "思維導圖處理失敗:{error}",
"error_user_facing": "抱歉,思維導圖在處理時遇到錯誤:{error}。\n請檢查Open WebUI後端日誌獲取更多詳情。",
"status_failed": "思維導圖:處理失敗。",
"notification_failed": "思維導圖生成失敗,{user_name}!",
"status_rendering_image": "思維導圖:正在渲染圖片...",
"status_image_generated": "思維導圖:圖片已生成!",
"notification_image_success": "思維導圖圖片已生成,{user_name}!",
"ui_title": "🧠 智能思維導圖",
"ui_user": "用戶:",
"ui_time": "時間:",
"ui_download_png": "PNG",
"ui_download_svg": "SVG",
"ui_download_md": "Markdown",
"ui_zoom_out": "縮小",
"ui_zoom_reset": "重置",
"ui_zoom_in": "放大",
"ui_depth_select": "展開層級",
"ui_depth_all": "全部展開",
"ui_depth_2": "展開 2 級",
"ui_depth_3": "展開 3 級",
"ui_fullscreen": "全屏",
"ui_theme": "主題",
"ui_footer": "<b>Powered by</b> <a href='https://markmap.js.org/' target='_blank' rel='noopener noreferrer'>Markmap</a>",
"html_error_missing_content": "⚠️ 無法加載思維導圖:缺少有效內容。",
"html_error_load_failed": "⚠️ 資源加載失敗,請稍後重試。",
"js_done": "完成",
"js_failed": "失敗",
"js_generating": "生成中...",
"js_filename": "思維導圖.png",
"js_upload_failed": "上傳失敗:",
"md_image_alt": "🧠 思維導圖",
},
"ko-KR": {
"status_starting": "스마트 마인드맵이 시작되었습니다, 마인드맵을 생성 중입니다...",
"error_no_content": "유효한 사용자 메시지 내용을 가져올 수 없습니다.",
"error_text_too_short": "텍스트 내용이 너무 짧아({len}자), 효과적인 분석을 수행할 수 없습니다. 최소 {min_len}자 이상의 텍스트를 제공해 주세요.",
"status_analyzing": "스마트 마인드맵: 텍스트 구조 심층 분석 중...",
"status_drawing": "스마트 마인드맵: 그리기 완료!",
"notification_success": "마인드맵이 생성되었습니다, {user_name}님!",
"error_processing": "스마트 마인드맵 처리 실패: {error}",
"error_user_facing": "죄송합니다, 스마트 마인드맵 처리 중 오류가 발생했습니다: {error}.\n자세한 내용은 Open WebUI 백엔드 로그를 확인해 주세요.",
"status_failed": "스마트 마인드맵: 처리 실패.",
"notification_failed": "스마트 마인드맵 생성 실패, {user_name}님!",
"status_rendering_image": "스마트 마인드맵: 이미지 렌더링 중...",
"status_image_generated": "스마트 마인드맵: 이미지 생성됨!",
"notification_image_success": "마인드맵 이미지가 생성되었습니다, {user_name}님!",
"ui_title": "🧠 스마트 마인드맵",
"ui_user": "사용자:",
"ui_time": "시간:",
"ui_download_png": "PNG",
"ui_download_svg": "SVG",
"ui_download_md": "Markdown",
"ui_zoom_out": "-",
"ui_zoom_reset": "초기화",
"ui_zoom_in": "+",
"ui_depth_select": "레벨 확장",
"ui_depth_all": "모두 확장",
"ui_depth_2": "레벨 2",
"ui_depth_3": "레벨 3",
"ui_fullscreen": "전체 화면",
"ui_theme": "테마",
"ui_footer": "<b>Powered by</b> <a href='https://markmap.js.org/' target='_blank' rel='noopener noreferrer'>Markmap</a>",
"html_error_missing_content": "⚠️ 마인드맵을 로드할 수 없습니다: 유효한 내용이 없습니다.",
"html_error_load_failed": "⚠️ 리소스 로드 실패, 나중에 다시 시도해 주세요.",
"js_done": "완료",
"js_failed": "실패",
"js_generating": "생성 중...",
"js_filename": "mindmap.png",
"js_upload_failed": "업로드 실패: ",
"md_image_alt": "🧠 마인드맵",
},
"ja-JP": {
"status_starting": "スマートマインドマップが起動しました。マインドマップを生成しています...",
"error_no_content": "有効なユーザーメッセージの内容を取得できませんでした。",
"error_text_too_short": "テキストの内容が短すぎるため({len}文字)、効果的な分析を実行できません。少なくとも{min_len}文字のテキストを提供してください。",
"status_analyzing": "スマートマインドマップ:テキスト構造を詳細に分析中...",
"status_drawing": "スマートマインドマップ:描画完了!",
"notification_success": "マインドマップが生成されました、{user_name}さん!",
"error_processing": "スマートマインドマップ処理失敗:{error}",
"error_user_facing": "申し訳ありません、スマートマインドマップの処理中にエラーが発生しました:{error}。\n詳細については、Open WebUIバックエンドログを確認してください。",
"status_failed": "スマートマインドマップ:処理失敗。",
"notification_failed": "スマートマインドマップ生成失敗、{user_name}さん!",
"status_rendering_image": "スマートマインドマップ:画像レンダリング中...",
"status_image_generated": "スマートマインドマップ:画像生成完了!",
"notification_image_success": "マインドマップ画像が生成されました、{user_name}さん!",
"ui_title": "🧠 スマートマインドマップ",
"ui_user": "ユーザー:",
"ui_time": "時間:",
"ui_download_png": "PNG",
"ui_download_svg": "SVG",
"ui_download_md": "Markdown",
"ui_zoom_out": "-",
"ui_zoom_reset": "リセット",
"ui_zoom_in": "+",
"ui_depth_select": "レベル展開",
"ui_depth_all": "すべて展開",
"ui_depth_2": "レベル2",
"ui_depth_3": "レベル3",
"ui_fullscreen": "全画面",
"ui_theme": "テーマ",
"ui_footer": "<b>Powered by</b> <a href='https://markmap.js.org/' target='_blank' rel='noopener noreferrer'>Markmap</a>",
"html_error_missing_content": "⚠️ マインドマップを読み込めません:有効なコンテンツがありません。",
"html_error_load_failed": "⚠️ リソースの読み込みに失敗しました。後でもう一度お試しください。",
"js_done": "完了",
"js_failed": "失敗",
"js_generating": "生成中...",
"js_filename": "mindmap.png",
"js_upload_failed": "アップロード失敗:",
"md_image_alt": "🧠 マインドマップ",
},
"fr-FR": {
"status_starting": "Smart Mind Map démarre, génération de la carte heuristique en cours...",
"error_no_content": "Impossible de récupérer le contenu valide du message utilisateur.",
"error_text_too_short": "Le contenu du texte est trop court ({len} caractères), impossible d'effectuer une analyse efficace. Veuillez fournir au moins {min_len} caractères de texte.",
"status_analyzing": "Smart Mind Map : Analyse approfondie de la structure du texte...",
"status_drawing": "Smart Mind Map : Dessin terminé !",
"notification_success": "La carte heuristique a été générée, {user_name} !",
"error_processing": "Échec du traitement de Smart Mind Map : {error}",
"error_user_facing": "Désolé, Smart Mind Map a rencontré une erreur lors du traitement : {error}.\nVeuillez vérifier les journaux backend d'Open WebUI pour plus de détails.",
"status_failed": "Smart Mind Map : Échec du traitement.",
"notification_failed": "Échec de la génération de la carte heuristique, {user_name} !",
"status_rendering_image": "Smart Mind Map : Rendu de l'image...",
"status_image_generated": "Smart Mind Map : Image générée !",
"notification_image_success": "L'image de la carte heuristique a été générée, {user_name} !",
"ui_title": "🧠 Smart Mind Map",
"ui_user": "Utilisateur :",
"ui_time": "Heure :",
"ui_download_png": "PNG",
"ui_download_svg": "SVG",
"ui_download_md": "Markdown",
"ui_zoom_out": "-",
"ui_zoom_reset": "Rénitialiser",
"ui_zoom_in": "+",
"ui_depth_select": "Niveau d'expansion",
"ui_depth_all": "Tout développer",
"ui_depth_2": "Niveau 2",
"ui_depth_3": "Niveau 3",
"ui_fullscreen": "Plein écran",
"ui_theme": "Thème",
"ui_footer": "<b>Powered by</b> <a href='https://markmap.js.org/' target='_blank' rel='noopener noreferrer'>Markmap</a>",
"html_error_missing_content": "⚠️ Impossible de charger la carte heuristique : contenu valide manquant.",
"html_error_load_failed": "⚠️ Échec du chargement des ressources, veuillez réessayer plus tard.",
"js_done": "Terminé",
"js_failed": "Échec",
"js_generating": "Génération...",
"js_filename": "carte_heuristique.png",
"js_upload_failed": "Échec du téléchargement : ",
"md_image_alt": "🧠 Carte Heuristique",
},
"de-DE": {
"status_starting": "Smart Mind Map startet, Mindmap wird für Sie erstellt...",
"error_no_content": "Gültiger Inhalt der Benutzernachricht konnte nicht abgerufen werden.",
"error_text_too_short": "Der Textinhalt ist zu kurz ({len} Zeichen), eine effektive Analyse ist nicht möglich. Bitte geben Sie mindestens {min_len} Zeichen Text an.",
"status_analyzing": "Smart Mind Map: Detaillierte Analyse der Textstruktur...",
"status_drawing": "Smart Mind Map: Zeichnen abgeschlossen!",
"notification_success": "Mindmap wurde erstellt, {user_name}!",
"error_processing": "Smart Mind Map Verarbeitung fehlgeschlagen: {error}",
"error_user_facing": "Entschuldigung, bei der Verarbeitung von Smart Mind Map ist ein Fehler aufgetreten: {error}.\nBitte überprüfen Sie die Open WebUI Backend-Protokolle für weitere Details.",
"status_failed": "Smart Mind Map: Verarbeitung fehlgeschlagen.",
"notification_failed": "Erstellung der Mindmap fehlgeschlagen, {user_name}!",
"status_rendering_image": "Smart Mind Map: Bild wird gerendert...",
"status_image_generated": "Smart Mind Map: Bild erstellt!",
"notification_image_success": "Mindmap-Bild wurde erstellt, {user_name}!",
"ui_title": "🧠 Smart Mind Map",
"ui_user": "Benutzer:",
"ui_time": "Zeit:",
"ui_download_png": "PNG",
"ui_download_svg": "SVG",
"ui_download_md": "Markdown",
"ui_zoom_out": "-",
"ui_zoom_reset": "Zurücksetzen",
"ui_zoom_in": "+",
"ui_depth_select": "Ebene erweitern",
"ui_depth_all": "Alles erweitern",
"ui_depth_2": "Ebene 2",
"ui_depth_3": "Ebene 3",
"ui_fullscreen": "Vollbild",
"ui_theme": "Thema",
"ui_footer": "<b>Powered by</b> <a href='https://markmap.js.org/' target='_blank' rel='noopener noreferrer'>Markmap</a>",
"html_error_missing_content": "⚠️ Mindmap kann nicht geladen werden: Gültiger Inhalt fehlt.",
"html_error_load_failed": "⚠️ Ressourcenladen fehlgeschlagen, bitte versuchen Sie es später erneut.",
"js_done": "Fertig",
"js_failed": "Fehlgeschlagen",
"js_generating": "Generiere...",
"js_filename": "mindmap.png",
"js_upload_failed": "Upload fehlgeschlagen: ",
"md_image_alt": "🧠 Mindmap",
},
"es-ES": {
"status_starting": "Smart Mind Map se está iniciando, generando mapa mental para usted...",
"error_no_content": "No se puede recuperar el contenido válido del mensaje del usuario.",
"error_text_too_short": "El contenido del texto es demasiado corto ({len} caracteres), no se puede realizar un análisis efectivo. Proporcione al menos {min_len} caracteres de texto.",
"status_analyzing": "Smart Mind Map: Analizando la estructura del texto en profundidad...",
"status_drawing": "Smart Mind Map: ¡Dibujo completado!",
"notification_success": "¡El mapa mental ha sido generado, {user_name}!",
"error_processing": "Falló el procesamiento de Smart Mind Map: {error}",
"error_user_facing": "Lo sentimos, Smart Mind Map encontró un error durante el procesamiento: {error}.\nConsulte los registros del backend de Open WebUI para más detalles.",
"status_failed": "Smart Mind Map: Procesamiento fallido.",
"notification_failed": "¡La generación del mapa mental falló, {user_name}!",
"status_rendering_image": "Smart Mind Map: Renderizando imagen...",
"status_image_generated": "Smart Mind Map: ¡Imagen generada!",
"notification_image_success": "¡La imagen del mapa mental ha sido generada, {user_name}!",
"ui_title": "🧠 Smart Mind Map",
"ui_user": "Usuario:",
"ui_time": "Hora:",
"ui_download_png": "PNG",
"ui_download_svg": "SVG",
"ui_download_md": "Markdown",
"ui_zoom_out": "-",
"ui_zoom_reset": "Restablecer",
"ui_zoom_in": "+",
"ui_depth_select": "Expandir Nivel",
"ui_depth_all": "Expandir Todo",
"ui_depth_2": "Nivel 2",
"ui_depth_3": "Nivel 3",
"ui_fullscreen": "Pantalla completa",
"ui_theme": "Tema",
"ui_footer": "<b>Powered by</b> <a href='https://markmap.js.org/' target='_blank' rel='noopener noreferrer'>Markmap</a>",
"html_error_missing_content": "⚠️ No se puede cargar el mapa mental: Falta contenido válido.",
"html_error_load_failed": "⚠️ Falló la carga de recursos, inténtelo de nuevo más tarde.",
"js_done": "Hecho",
"js_failed": "Fallido",
"js_generating": "Generando...",
"js_filename": "mapa_mental.png",
"js_upload_failed": "Carga fallida: ",
"md_image_alt": "🧠 Mapa Mental",
},
"it-IT": {
"status_starting": "Smart Mind Map si sta avviando, generazione mappa mentale in corso...",
"error_no_content": "Impossibile recuperare il contenuto valido del messaggio utente.",
"error_text_too_short": "Il testo è troppo breve ({len} caratteri), impossibile eseguire un'analisi efficace. Fornire almeno {min_len} caratteri di testo.",
"status_analyzing": "Smart Mind Map: Analisi approfondita della struttura del testo...",
"status_drawing": "Smart Mind Map: Disegno completato!",
"notification_success": "La mappa mentale è stata generata, {user_name}!",
"error_processing": "Elaborazione Smart Mind Map fallita: {error}",
"error_user_facing": "Spiacenti, Smart Mind Map ha riscontrato un errore durante l'elaborazione: {error}.\nControllare i log del backend di Open WebUI per ulteriori dettagli.",
"status_failed": "Smart Mind Map: Elaborazione fallita.",
"notification_failed": "Generazione mappa mentale fallita, {user_name}!",
"status_rendering_image": "Smart Mind Map: Rendering immagine...",
"status_image_generated": "Smart Mind Map: Immagine generata!",
"notification_image_success": "L'immagine della mappa mentale è stata generata, {user_name}!",
"ui_title": "🧠 Smart Mind Map",
"ui_user": "Utente:",
"ui_time": "Ora:",
"ui_download_png": "PNG",
"ui_download_svg": "SVG",
"ui_download_md": "Markdown",
"ui_zoom_out": "-",
"ui_zoom_reset": "Reimposta",
"ui_zoom_in": "+",
"ui_depth_select": "Espandi Livello",
"ui_depth_all": "Espandi Tutto",
"ui_depth_2": "Livello 2",
"ui_depth_3": "Livello 3",
"ui_fullscreen": "Schermo intero",
"ui_theme": "Tema",
"ui_footer": "<b>Powered by</b> <a href='https://markmap.js.org/' target='_blank' rel='noopener noreferrer'>Markmap</a>",
"html_error_missing_content": "⚠️ Impossibile caricare la mappa mentale: Contenuto valido mancante.",
"html_error_load_failed": "⚠️ Caricamento risorse fallito, riprovare più tardi.",
"js_done": "Fatto",
"js_failed": "Fallito",
"js_generating": "Generazione...",
"js_filename": "mappa_mentale.png",
"js_upload_failed": "Caricamento fallito: ",
"md_image_alt": "🧠 Mappa Mentale",
},
"vi-VN": {
"status_starting": "Smart Mind Map đang khởi động, đang tạo sơ đồ tư duy cho bạn...",
"error_no_content": "Không thể lấy nội dung tin nhắn người dùng hợp lệ.",
"error_text_too_short": "Nội dung văn bản quá ngắn ({len} ký tự), không thể thực hiện phân tích hiệu quả. Vui lòng cung cấp ít nhất {min_len} ký tự văn bản.",
"status_analyzing": "Smart Mind Map: Phân tích sâu cấu trúc văn bản...",
"status_drawing": "Smart Mind Map: Vẽ hoàn tất!",
"notification_success": "Sơ đồ tư duy đã được tạo, {user_name}!",
"error_processing": "Xử lý Smart Mind Map thất bại: {error}",
"error_user_facing": "Xin lỗi, Smart Mind Map đã gặp lỗi trong quá trình xử lý: {error}.\nVui lòng kiểm tra nhật ký backend Open WebUI để biết thêm chi tiết.",
"status_failed": "Smart Mind Map: Xử lý thất bại.",
"notification_failed": "Tạo sơ đồ tư duy thất bại, {user_name}!",
"status_rendering_image": "Smart Mind Map: Đang render hình ảnh...",
"status_image_generated": "Smart Mind Map: Hình ảnh đã tạo!",
"notification_image_success": "Hình ảnh sơ đồ tư duy đã được tạo, {user_name}!",
"ui_title": "🧠 Smart Mind Map",
"ui_user": "Người dùng:",
"ui_time": "Thời gian:",
"ui_download_png": "PNG",
"ui_download_svg": "SVG",
"ui_download_md": "Markdown",
"ui_zoom_out": "-",
"ui_zoom_reset": "Đặt lại",
"ui_zoom_in": "+",
"ui_depth_select": "Mở rộng Cấp độ",
"ui_depth_all": "Mở rộng Tất cả",
"ui_depth_2": "Cấp độ 2",
"ui_depth_3": "Cấp độ 3",
"ui_fullscreen": "Toàn màn hình",
"ui_theme": "Chủ đề",
"ui_footer": "<b>Powered by</b> <a href='https://markmap.js.org/' target='_blank' rel='noopener noreferrer'>Markmap</a>",
"html_error_missing_content": "⚠️ Không thể tải sơ đồ tư duy: Thiếu nội dung hợp lệ.",
"html_error_load_failed": "⚠️ Tải tài nguyên thất bại, vui lòng thử lại sau.",
"js_done": "Xong",
"js_failed": "Thất bại",
"js_generating": "Đang tạo...",
"js_filename": "sodo_tuduy.png",
"js_upload_failed": "Tải lên thất bại: ",
"md_image_alt": "🧠 Sơ đồ Tư duy",
},
"id-ID": {
"status_starting": "Smart Mind Map sedang dimulai, membuat peta pikiran untuk Anda...",
"error_no_content": "Tidak dapat mengambil konten pesan pengguna yang valid.",
"error_text_too_short": "Konten teks terlalu pendek ({len} karakter), tidak dapat melakukan analisis efektif. Harap berikan setidaknya {min_len} karakter teks.",
"status_analyzing": "Smart Mind Map: Menganalisis struktur teks secara mendalam...",
"status_drawing": "Smart Mind Map: Menggambar selesai!",
"notification_success": "Peta pikiran telah dibuat, {user_name}!",
"error_processing": "Pemrosesan Smart Mind Map gagal: {error}",
"error_user_facing": "Maaf, Smart Mind Map mengalami kesalahan saat memproses: {error}.\nSilakan periksa log backend Open WebUI untuk detail lebih lanjut.",
"status_failed": "Smart Mind Map: Pemrosesan gagal.",
"notification_failed": "Pembuatan peta pikiran gagal, {user_name}!",
"status_rendering_image": "Smart Mind Map: Merender gambar...",
"status_image_generated": "Smart Mind Map: Gambar dibuat!",
"notification_image_success": "Gambar peta pikiran telah dibuat, {user_name}!",
"ui_title": "🧠 Smart Mind Map",
"ui_user": "Pengguna:",
"ui_time": "Waktu:",
"ui_download_png": "PNG",
"ui_download_svg": "SVG",
"ui_download_md": "Markdown",
"ui_zoom_out": "-",
"ui_zoom_reset": "Atur Ulang",
"ui_zoom_in": "+",
"ui_depth_select": "Perluas Level",
"ui_depth_all": "Perluas Semua",
"ui_depth_2": "Level 2",
"ui_depth_3": "Level 3",
"ui_fullscreen": "Layar Penuh",
"ui_theme": "Tema",
"ui_footer": "<b>Powered by</b> <a href='https://markmap.js.org/' target='_blank' rel='noopener noreferrer'>Markmap</a>",
"html_error_missing_content": "⚠️ Tidak dapat memuat peta pikiran: Konten valid hilang.",
"html_error_load_failed": "⚠️ Gagal memuat sumber daya, silakan coba lagi nanti.",
"js_done": "Selesai",
"js_failed": "Gagal",
"js_generating": "Membuat...",
"js_filename": "peta_pikiran.png",
"js_upload_failed": "Unggah gagal: ",
"md_image_alt": "🧠 Peta Pikiran",
},
}
SYSTEM_PROMPT_MINDMAP_ASSISTANT = """
You are a professional mind map generation assistant, capable of efficiently analyzing long-form text provided by users and structuring its core themes, key concepts, branches, and sub-branches into standard Markdown list syntax for rendering by Markmap.js.
Please strictly follow these guidelines:
- **Language**: All output must be in the exact same language as the input text (the text you are analyzing).
- **Format Consistency**: Even if this system prompt is in English, if the user input is in Chinese, the mind map content must be in Chinese. If input is Japanese, output Japanese.
- **Format**: Your output must strictly be in Markdown list format, wrapped with ```markdown and ```.
- Use `#` to define the central theme (root node).
- Use `-` with two-space indentation to represent branches and sub-branches.
- **Root Node (Central Theme) — Strict Length Limits**:
- The `#` root node must be an ultra-compact title, like a newspaper headline. It should be a keyword or short phrase, NEVER a full sentence.
- **CJK scripts (Chinese, Japanese, Korean)**: Maximum **10 characters** (e.g., `# 老人缓解呼吸困难方法` ✓ / `# 老人在家时感到呼吸困难的缓解方法` ✗)
- **Latin-script languages (English, Spanish, French, Italian, Portuguese)**: Maximum **5 words or 35 characters** (e.g., `# Methods to Relieve Dyspnea` ✓ / `# How Elderly People Can Relieve Breathing Difficulty at Home` ✗)
- **German, Dutch or languages with long compound words**: Maximum **4 words or 30 characters**
- **Arabic, Hebrew and other RTL scripts**: Maximum **5 words or 25 characters**
- **All other languages**: Maximum **5 words or 30 characters**
- If the identified theme would exceed the limit, distill it further into the single most essential keyword or 2-3 word phrase.
- **Branch Node Content**:
- Identify main concepts as first-level list items.
- Identify supporting details or sub-concepts as nested list items.
- Node content should be concise and clear, avoiding verbosity.
- **Output Markdown syntax only**: Do not include any additional greetings, explanations, or guiding text.
- **If text is too short or cannot generate a valid mind map**: Output a simple Markdown list indicating inability to generate, for example:
```markdown
# Unable to Generate Mind Map
- Reason: Insufficient or unclear text content
```
- **Awareness of Target Audience Layout**: You will be provided `Target Rendering Mode`.
- If `Target Rendering Mode` is `direct`: The client has massive horizontal space but limited scrolling vertically. Extract more first-level concepts to make the mind map spread wide like a sprawling fan, rather than deep single columns.
- If `Target Rendering Mode` is `legacy`: The client uses a narrow, portrait sidebar. Extract fewer top-level nodes, and break points into deeper, tighter sub-branches so the map grows vertically downwards.
"""
USER_PROMPT_GENERATE_MINDMAP = """
Please analyze the following long-form text and structure its core themes, key concepts, branches, and sub-branches into standard Markdown list syntax for Markmap.js rendering.
---
**User Context Information:**
User Name: {user_name}
Current Date & Time: {current_date_time_str}
Current Weekday: {current_weekday}
Current Timezone: {current_timezone_str}
User Language: {user_language}
Target Rendering Mode: Auto-adapting (Dynamic width based on viewport)
---
**Long-form Text Content:**
{long_text_content}
"""
HTML_WRAPPER_TEMPLATE = """
<!-- OPENWEBUI_PLUGIN_OUTPUT -->
<!DOCTYPE html>
<html lang="{lang}">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
margin: 0;
padding: 2px;
background-color: transparent;
}
#main-container {
display: flex;
flex-direction: column;
gap: 20px;
align-items: stretch;
width: 100%;
}
.plugin-item {
width: 100%;
border-radius: 12px;
overflow: visible;
transition: all 0.3s ease;
}
.plugin-item:hover {
transform: translateY(-2px);
}
/* STYLES_INSERTION_POINT */
</style>
</head>
<body>
<div id="main-container">
<!-- CONTENT_INSERTION_POINT -->
</div>
<!-- SCRIPTS_INSERTION_POINT -->
</body>
</html>
"""
CSS_TEMPLATE_MINDMAP = """
:root {
--primary-color: #1e88e5;
--secondary-color: #43a047;
--background-color: #f4f6f8;
--card-bg-color: #ffffff;
--text-color: #000000;
--link-color: #546e7a;
--node-stroke-color: #90a4ae;
--muted-text-color: #546e7a;
--border-color: #e0e0e0;
--header-gradient: linear-gradient(135deg, var(--secondary-color), var(--primary-color));
--shadow: 0 10px 20px rgba(0, 0, 0, 0.06);
--border-radius: 12px;
--font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}
.theme-dark {
--primary-color: #64b5f6;
--secondary-color: #81c784;
--background-color: #111827;
--card-bg-color: #1f2937;
--text-color: #ffffff;
--link-color: #cbd5e1;
--node-stroke-color: #94a3b8;
--muted-text-color: #9ca3af;
--border-color: #374151;
--header-gradient: linear-gradient(135deg, #0ea5e9, #22c55e);
--shadow: 0 10px 20px rgba(0, 0, 0, 0.3);
}
html, body {
margin: 0;
padding: 0;
width: 100vw;
height: 100vh;
background: var(--card-bg-color);
overflow: hidden;
}
.mindmap-container-wrapper {
font-family: var(--font-family);
line-height: 1.6;
color: var(--text-color);
margin: 0;
padding: 0;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
display: flex;
flex-direction: column;
background: var(--card-bg-color);
width: 100vw;
height: 100vh;
box-sizing: border-box;
overflow: hidden;
border: none;
border-radius: 0;
box-shadow: none;
}
.header {
background: var(--card-bg-color);
color: var(--text-color);
padding: 12px 16px;
display: flex;
flex-direction: column;
gap: 12px;
flex-shrink: 0;
border-bottom: 1px solid var(--border-color);
z-index: 10;
}
.header-top {
display: flex;
align-items: center;
gap: 12px;
}
.header h1 {
margin: 0;
font-size: 1.2em;
font-weight: 600;
letter-spacing: 0.5px;
display: flex;
align-items: center;
gap: 8px;
}
.header-credits {
font-size: 0.8em;
color: var(--muted-text-color);
opacity: 0.8;
white-space: nowrap;
}
.header-credits a {
color: var(--primary-color);
text-decoration: none;
border-bottom: 1px dotted var(--link-color);
}
.star-btn {
background: transparent !important;
border: none !important;
color: #fbbf24 !important;
display: inline-flex !important;
align-items: center;
justify-content: center;
padding: 4px 8px !important;
cursor: pointer;
transition: all 0.2s ease;
text-decoration: none;
height: 28px;
}
.star-btn:hover {
color: #f59e0b !important;
transform: scale(1.15);
filter: drop-shadow(0 0 4px rgba(251, 191, 36, 0.5));
}
.star-btn svg {
width: 18px !important;
height: 18px !important;
fill: currentColor !important;
}
.content-area {
padding: 0;
flex: 1 1 0;
background: var(--card-bg-color);
position: relative;
overflow: hidden;
width: 100%;
min-height: 0;
/* Height will be computed dynamically by JS below */
}
.markmap-container {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: var(--card-bg-color);
}
.markmap-container svg {
width: 100%;
height: 100%;
display: block;
}
.markmap-container svg text {
fill: var(--text-color) !important;
font-family: var(--font-family);
}
.markmap-container svg foreignObject,
.markmap-container svg .markmap-foreign,
.markmap-container svg .markmap-foreign div {
color: var(--text-color) !important;
font-family: var(--font-family);
}
.markmap-container svg .markmap-link {
stroke: var(--link-color) !important;
stroke-opacity: 0.6;
}
.theme-dark .markmap-node circle {
fill: var(--card-bg-color) !important;
}
.markmap-container svg .markmap-node circle,
.markmap-container svg .markmap-node rect {
stroke: var(--node-stroke-color) !important;
}
.control-rows {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 12px;
margin-left: auto; /* Push controls to the right */
}
.btn-group {
display: inline-flex;
gap: 4px;
align-items: center;
border: 1px solid var(--border-color);
border-radius: 6px;
padding: 2px;
background: var(--background-color);
}
.control-btn {
background-color: transparent;
color: var(--text-color);
border: none;
padding: 4px 10px;
border-radius: 4px;
font-size: 0.85em;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease;
display: inline-flex;
align-items: center;
justify-content: center;
height: 28px;
box-sizing: border-box;
opacity: 0.8;
}
.control-btn:hover {
background-color: var(--card-bg-color);
opacity: 1;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.control-btn:active {
transform: translateY(1px);
}
.control-btn.primary {
background-color: var(--primary-color);
color: white;
opacity: 1;
}
.control-btn.primary:hover {
box-shadow: 0 2px 5px rgba(30,136,229,0.3);
}
select.control-btn {
appearance: none;
padding-right: 28px;
background-image: url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22292.4%22%20height%3D%22292.4%22%3E%3Cpath%20fill%3D%22%23FFFFFF%22%20d%3D%22M287%2069.4a17.6%2017.6%200%200%200-13-5.4H18.4c-5%200-9.3%201.8-12.9%205.4A17.6%2017.6%200%200%200%200%2082.2c0%205%201.8%209.3%205.4%2012.9l128%20127.9c3.6%203.6%207.8%205.4%2012.8%205.4s9.2-1.8%2012.8-5.4L287%2095c3.5-3.5%205.4-7.8%205.4-12.8%200-5-1.9-9.2-5.5-12.8z%22%2F%3E%3C%2Fsvg%3E");
background-repeat: no-repeat;
background-position: right 8px center;
background-size: 10px;
}
.control-btn option {
background-color: var(--card-bg-color);
color: var(--text-color);
}
.error-message {
color: #c62828;
background-color: #ffcdd2;
border: 1px solid #ef9a9a;
padding: 14px;
border-radius: 8px;
font-weight: 500;
font-size: 1em;
margin: 10px;
}
/* Mobile Responsive Adjustments */
@media screen and (max-width: 768px) {
.mindmap-container-wrapper {
min-height: 400px;
height: 80vh;
}
.header {
flex-direction: column;
gap: 10px;
}
.btn-group {
padding: 2px;
}
.control-btn {
padding: 4px 6px;
font-size: 0.75em;
height: 28px;
}
select.control-btn {
padding-right: 20px;
background-position: right 4px center;
}
}
"""
CONTENT_TEMPLATE_MINDMAP = """
<div class="mindmap-container-wrapper">
<div class="header">
<div class="header-top">
<h1>{t_ui_title}</h1>
<div class="header-credits">
<span>{t_ui_footer}</span>
</div>
<div class="control-rows">
<div class="btn-group">
<button id="download-png-btn-{unique_id}" class="control-btn primary" title="{t_ui_download_png}">PNG</button>
<button id="download-svg-btn-{unique_id}" class="control-btn" title="{t_ui_download_svg}">SVG</button>
<button id="download-md-btn-{unique_id}" class="control-btn" title="{t_ui_download_md}">MD</button>
<a href="https://github.com/Fu-Jie/openwebui-extensions" target="_blank" rel="noopener noreferrer" title="Star on GitHub" class="control-btn star-btn">
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" style="width: 18px; height: 18px;">
<path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" fill="currentColor"/>
</svg>
</a>
</div>
<div class="btn-group">
<button id="zoom-out-btn-{unique_id}" class="control-btn" title="{t_ui_zoom_out}">-</button>
<button id="zoom-reset-btn-{unique_id}" class="control-btn" title="{t_ui_zoom_reset}">↺</button>
<button id="zoom-in-btn-{unique_id}" class="control-btn" title="{t_ui_zoom_in}">+</button>
</div>
<div class="btn-group">
<select id="depth-select-{unique_id}" class="control-btn" title="{t_ui_depth_select}">
<option value="0" selected>{t_ui_depth_all}</option>
<option value="2">{t_ui_depth_2}</option>
<option value="3">{t_ui_depth_3}</option>
</select>
<button id="fullscreen-btn-{unique_id}" class="control-btn" title="{t_ui_fullscreen}">⛶</button>
<button id="theme-toggle-btn-{unique_id}" class="control-btn" title="{t_ui_theme}">◑</button>
</div>
</div>
</div>
</div>
<div class="content-area">
<div class="markmap-container" id="markmap-container-{unique_id}"></div>
</div>
</div>
<script type="text/template" id="markdown-source-{unique_id}">{markdown_syntax}</script>
"""
SCRIPT_TEMPLATE_MINDMAP = """
<script>
(function() {
const uniqueId = {unique_id_json};
const i18n = {i18n_json};
const loadScriptOnce = (src, checkFn) => {
if (checkFn()) return Promise.resolve();
return new Promise((resolve, reject) => {
const existing = document.querySelector(`script[data-src="${src}"]`);
if (existing) {
existing.addEventListener('load', () => resolve());
existing.addEventListener('error', () => reject(new Error('Loading failed: ' + src)));
return;
}
const script = document.createElement('script');
script.src = src;
script.async = true;
script.dataset.src = src;
script.onload = () => resolve();
script.onerror = () => reject(new Error('Loading failed: ' + src));
document.head.appendChild(script);
});
};
const ensureMarkmapReady = () =>
loadScriptOnce('https://cdn.jsdelivr.net/npm/d3@7', () => window.d3)
.then(() => loadScriptOnce('https://cdn.jsdelivr.net/npm/markmap-lib@0.17', () => window.markmap && window.markmap.Transformer))
.then(() => loadScriptOnce('https://cdn.jsdelivr.net/npm/markmap-view@0.17', () => window.markmap && window.markmap.Markmap));
const parseColorLuma = (colorStr) => {
if (!colorStr) return null;
// hex #rrggbb or rrggbb
let m = colorStr.match(/^#?([0-9a-f]{6})$/i);
if (m) {
const hex = m[1];
const r = parseInt(hex.slice(0, 2), 16);
const g = parseInt(hex.slice(2, 4), 16);
const b = parseInt(hex.slice(4, 6), 16);
return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
}
// rgb(r, g, b) or rgba(r, g, b, a)
m = colorStr.match(/rgba?\\s*\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)/i);
if (m) {
const r = parseInt(m[1], 10);
const g = parseInt(m[2], 10);
const b = parseInt(m[3], 10);
return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
}
return null;
};
const getThemeFromMeta = (doc, scope = 'self') => {
const metas = Array.from((doc || document).querySelectorAll('meta[name="theme-color"]'));
if (!metas.length) return null;
const color = metas[metas.length - 1].content.trim();
const luma = parseColorLuma(color);
if (luma === null) return null;
return luma < 0.5 ? 'dark' : 'light';
};
const getParentDocumentSafe = () => {
try {
if (!window.parent || window.parent === window) return null;
const pDoc = window.parent.document;
void pDoc.title;
return pDoc;
} catch (err) {
return null;
}
};
const getThemeFromParentClass = () => {
try {
if (!window.parent || window.parent === window) return null;
const pDoc = window.parent.document;
const html = pDoc.documentElement;
const body = pDoc.body;
const htmlClass = html ? html.className : '';
const bodyClass = body ? body.className : '';
const htmlDataTheme = html ? html.getAttribute('data-theme') : '';
if (htmlDataTheme === 'dark' || bodyClass.includes('dark') || htmlClass.includes('dark')) return 'dark';
if (htmlDataTheme === 'light' || bodyClass.includes('light') || htmlClass.includes('light')) return 'light';
return null;
} catch (err) {
return null;
}
};
const setTheme = (wrapperEl, explicitTheme) => {
const parentDoc = getParentDocumentSafe();
const metaThemeParent = parentDoc ? getThemeFromMeta(parentDoc, 'parent') : null;
const parentClassTheme = getThemeFromParentClass();
const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
const chosen = explicitTheme || metaThemeParent || parentClassTheme || (prefersDark ? 'dark' : 'light');
wrapperEl.classList.toggle('theme-dark', chosen === 'dark');
return chosen;