-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathtool.py
More file actions
2262 lines (2107 loc) · 95.9 KB
/
tool.py
File metadata and controls
2262 lines (2107 loc) · 95.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
"""
title: Inline Visualizer v2
author: Classic298
version: 2.0.0
description: Renders interactive HTML/SVG visualizations inline in chat. Requires "iframe Sandbox Allow Same Origin" to be enabled in Open WebUI Settings -> Interface. For design instructions, the model should call view_skill("visualize").
"""
import re
from typing import Literal
# Build marker embedded into the rendered iframe so the running
# version can be verified at runtime (search DevTools for
# `data-iv-build` on <html>). Bump on every protocol-level change
# so stale cached iframes can be spotted immediately.
_IV_BUILD = "2.0.0"
from fastapi.responses import HTMLResponse
from pydantic import BaseModel, Field
# ---------------------------------------------------------------------------
# Injected CSS — Theme variables (light default, dark via data-theme)
# ---------------------------------------------------------------------------
THEME_CSS = """
:root {
--color-text-primary: #1F2937;
--color-text-secondary: #6B7280;
--color-text-tertiary: #9CA3AF;
--color-text-info: #2563EB;
--color-text-success: #059669;
--color-text-warning: #D97706;
--color-text-danger: #DC2626;
--color-bg-primary: #FFFFFF;
--color-bg-secondary: #F9FAFB;
--color-bg-tertiary: #F3F4F6;
--color-border-tertiary: rgba(0,0,0,0.15);
--color-border-secondary: rgba(0,0,0,0.3);
--color-border-primary: rgba(0,0,0,0.4);
--font-sans: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
--font-mono: 'SF Mono', Menlo, Consolas, monospace;
--radius-md: 8px;
--radius-lg: 12px;
--radius-xl: 16px;
/* --- Color ramp variables (light) --- */
--ramp-purple-fill:#EEEDFE; --ramp-purple-stroke:#534AB7; --ramp-purple-th:#3C3489; --ramp-purple-ts:#534AB7;
--ramp-teal-fill:#E1F5EE; --ramp-teal-stroke:#0F6E56; --ramp-teal-th:#085041; --ramp-teal-ts:#0F6E56;
--ramp-coral-fill:#FAECE7; --ramp-coral-stroke:#993C1D; --ramp-coral-th:#712B13; --ramp-coral-ts:#993C1D;
--ramp-pink-fill:#FBEAF0; --ramp-pink-stroke:#993556; --ramp-pink-th:#72243E; --ramp-pink-ts:#993556;
--ramp-gray-fill:#F1EFE8; --ramp-gray-stroke:#5F5E5A; --ramp-gray-th:#444441; --ramp-gray-ts:#5F5E5A;
--ramp-blue-fill:#E6F1FB; --ramp-blue-stroke:#185FA5; --ramp-blue-th:#0C447C; --ramp-blue-ts:#185FA5;
--ramp-green-fill:#EAF3DE; --ramp-green-stroke:#3B6D11; --ramp-green-th:#27500A; --ramp-green-ts:#3B6D11;
--ramp-amber-fill:#FAEEDA; --ramp-amber-stroke:#854F0B; --ramp-amber-th:#633806; --ramp-amber-ts:#854F0B;
--ramp-red-fill:#FCEBEB; --ramp-red-stroke:#A32D2D; --ramp-red-th:#791F1F; --ramp-red-ts:#A32D2D;
/* --- Common aliases (catch hallucinated variable names) --- */
/* Text */
--fg: var(--color-text-primary);
--text: var(--color-text-primary);
--foreground: var(--color-text-primary);
--text-primary: var(--color-text-primary);
--text-color: var(--color-text-primary);
--color-text: var(--color-text-primary);
--color-foreground: var(--color-text-primary);
--body-color: var(--color-text-primary);
--muted: var(--color-text-secondary);
--muted-foreground: var(--color-text-secondary);
--text-muted: var(--color-text-secondary);
--text-secondary: var(--color-text-secondary);
--secondary: var(--color-text-secondary);
--subtle: var(--color-text-tertiary);
--text-tertiary: var(--color-text-tertiary);
/* Backgrounds */
--bg: var(--color-bg-primary);
--background: var(--color-bg-primary);
--bg-primary: var(--color-bg-primary);
--body-bg: var(--color-bg-primary);
--color-bg: var(--color-bg-primary);
--surface: var(--color-bg-secondary);
--surface-1: var(--color-bg-secondary);
--surface-2: var(--color-bg-tertiary);
--card: var(--color-bg-secondary);
--card-bg: var(--color-bg-secondary);
--card-foreground: var(--color-text-primary);
--card-background: var(--color-bg-secondary);
--popover: var(--color-bg-secondary);
--popover-foreground: var(--color-text-primary);
--hover: rgba(0,0,0,0.04);
/* Borders */
--border: var(--color-border-tertiary);
--border-color: var(--color-border-tertiary);
--divider: var(--color-border-tertiary);
--separator: var(--color-border-tertiary);
--input: var(--color-border-tertiary);
--ring: var(--color-border-secondary);
/* Accent / Primary (AI uses --accent as brand color, not surface) */
--primary: #6c2eb9;
--primary-foreground: #ffffff;
--accent: #6c2eb9;
--accent-foreground: #ffffff;
}
:root[data-theme="dark"] {
--color-text-primary: #E5E7EB;
--color-text-secondary: #9CA3AF;
--color-text-tertiary: #6B7280;
--color-text-info: #60A5FA;
--color-text-success: #34D399;
--color-text-warning: #FBBF24;
--color-text-danger: #F87171;
--color-bg-primary: #1A1A1A;
--color-bg-secondary: #262626;
--color-bg-tertiary: #111111;
--color-border-tertiary: rgba(255,255,255,0.15);
--color-border-secondary: rgba(255,255,255,0.3);
--color-border-primary: rgba(255,255,255,0.4);
--ramp-purple-fill:#3C3489; --ramp-purple-stroke:#AFA9EC; --ramp-purple-th:#CECBF6; --ramp-purple-ts:#AFA9EC;
--ramp-teal-fill:#085041; --ramp-teal-stroke:#5DCAA5; --ramp-teal-th:#9FE1CB; --ramp-teal-ts:#5DCAA5;
--ramp-coral-fill:#712B13; --ramp-coral-stroke:#F0997B; --ramp-coral-th:#F5C4B3; --ramp-coral-ts:#F0997B;
--ramp-pink-fill:#72243E; --ramp-pink-stroke:#ED93B1; --ramp-pink-th:#F4C0D1; --ramp-pink-ts:#ED93B1;
--ramp-gray-fill:#444441; --ramp-gray-stroke:#B4B2A9; --ramp-gray-th:#D3D1C7; --ramp-gray-ts:#B4B2A9;
--ramp-blue-fill:#0C447C; --ramp-blue-stroke:#85B7EB; --ramp-blue-th:#B5D4F4; --ramp-blue-ts:#85B7EB;
--ramp-green-fill:#27500A; --ramp-green-stroke:#97C459; --ramp-green-th:#C0DD97; --ramp-green-ts:#97C459;
--ramp-amber-fill:#633806; --ramp-amber-stroke:#EF9F27; --ramp-amber-th:#FAC775; --ramp-amber-ts:#EF9F27;
--ramp-red-fill:#791F1F; --ramp-red-stroke:#F09595; --ramp-red-th:#F7C1C1; --ramp-red-ts:#F09595;
/* --- Common aliases (dark overrides) --- */
--text: var(--color-text-primary);
--foreground: var(--color-text-primary);
--text-primary: var(--color-text-primary);
--text-color: var(--color-text-primary);
--color-text: var(--color-text-primary);
--body-color: var(--color-text-primary);
--muted: var(--color-text-secondary);
--muted-foreground: var(--color-text-secondary);
--text-muted: var(--color-text-secondary);
--text-secondary: var(--color-text-secondary);
--secondary: var(--color-text-secondary);
--subtle: var(--color-text-tertiary);
--text-tertiary: var(--color-text-tertiary);
--bg: var(--color-bg-primary);
--background: var(--color-bg-primary);
--bg-primary: var(--color-bg-primary);
--body-bg: var(--color-bg-primary);
--color-bg: var(--color-bg-primary);
--surface: var(--color-bg-secondary);
--surface-1: var(--color-bg-secondary);
--surface-2: var(--color-bg-tertiary);
--card: var(--color-bg-secondary);
--card-bg: var(--color-bg-secondary);
--card-foreground: var(--color-text-primary);
--card-background: var(--color-bg-secondary);
--popover: var(--color-bg-secondary);
--popover-foreground: var(--color-text-primary);
--hover: rgba(255,255,255,0.06);
--border: var(--color-border-tertiary);
--border-color: var(--color-border-tertiary);
--divider: var(--color-border-tertiary);
--separator: var(--color-border-tertiary);
--input: var(--color-border-tertiary);
--ring: var(--color-border-secondary);
--primary: #a78bfa;
--primary-foreground: #1A1A1A;
--accent: #a78bfa;
--accent-foreground: #ffffff;
}
"""
# ---------------------------------------------------------------------------
# Injected CSS — SVG utility classes + color ramp selectors
# ---------------------------------------------------------------------------
SVG_CLASSES = """
/* --- Text --- */
.t { font: 400 14px/1.4 var(--font-sans); fill: var(--color-text-primary); }
.ts { font: 400 12px/1.4 var(--font-sans); fill: var(--color-text-secondary); }
.th { font: 500 14px/1.4 var(--font-sans); fill: var(--color-text-primary); }
/* --- Shapes --- */
.box { fill: var(--color-bg-secondary); stroke: var(--color-border-tertiary); stroke-width: 0.5; }
.node { cursor: pointer; }
.node:hover { opacity: 0.85; }
.arr { stroke: var(--color-border-secondary); stroke-width: 1.5; fill: none; }
.leader { stroke: var(--color-text-tertiary); stroke-width: 0.5; stroke-dasharray: 3 2; fill: none; }
/* --- Color ramp selectors (fill/stroke adapt via CSS vars) --- */
.c-purple>rect,.c-purple>circle,.c-purple>ellipse{fill:var(--ramp-purple-fill);stroke:var(--ramp-purple-stroke);stroke-width:.5}
.c-purple>.th{fill:var(--ramp-purple-th)!important} .c-purple>.ts{fill:var(--ramp-purple-ts)!important}
.c-teal>rect,.c-teal>circle,.c-teal>ellipse{fill:var(--ramp-teal-fill);stroke:var(--ramp-teal-stroke);stroke-width:.5}
.c-teal>.th{fill:var(--ramp-teal-th)!important} .c-teal>.ts{fill:var(--ramp-teal-ts)!important}
.c-coral>rect,.c-coral>circle,.c-coral>ellipse{fill:var(--ramp-coral-fill);stroke:var(--ramp-coral-stroke);stroke-width:.5}
.c-coral>.th{fill:var(--ramp-coral-th)!important} .c-coral>.ts{fill:var(--ramp-coral-ts)!important}
.c-pink>rect,.c-pink>circle,.c-pink>ellipse{fill:var(--ramp-pink-fill);stroke:var(--ramp-pink-stroke);stroke-width:.5}
.c-pink>.th{fill:var(--ramp-pink-th)!important} .c-pink>.ts{fill:var(--ramp-pink-ts)!important}
.c-gray>rect,.c-gray>circle,.c-gray>ellipse{fill:var(--ramp-gray-fill);stroke:var(--ramp-gray-stroke);stroke-width:.5}
.c-gray>.th{fill:var(--ramp-gray-th)!important} .c-gray>.ts{fill:var(--ramp-gray-ts)!important}
.c-blue>rect,.c-blue>circle,.c-blue>ellipse{fill:var(--ramp-blue-fill);stroke:var(--ramp-blue-stroke);stroke-width:.5}
.c-blue>.th{fill:var(--ramp-blue-th)!important} .c-blue>.ts{fill:var(--ramp-blue-ts)!important}
.c-green>rect,.c-green>circle,.c-green>ellipse{fill:var(--ramp-green-fill);stroke:var(--ramp-green-stroke);stroke-width:.5}
.c-green>.th{fill:var(--ramp-green-th)!important} .c-green>.ts{fill:var(--ramp-green-ts)!important}
.c-amber>rect,.c-amber>circle,.c-amber>ellipse{fill:var(--ramp-amber-fill);stroke:var(--ramp-amber-stroke);stroke-width:.5}
.c-amber>.th{fill:var(--ramp-amber-th)!important} .c-amber>.ts{fill:var(--ramp-amber-ts)!important}
.c-red>rect,.c-red>circle,.c-red>ellipse{fill:var(--ramp-red-fill);stroke:var(--ramp-red-stroke);stroke-width:.5}
.c-red>.th{fill:var(--ramp-red-th)!important} .c-red>.ts{fill:var(--ramp-red-ts)!important}
"""
# ---------------------------------------------------------------------------
# Injected CSS — Base resets & interactive element styles
# ---------------------------------------------------------------------------
BASE_STYLES = """
* { box-sizing: border-box; margin: 0; font-family: var(--font-sans); }
html, body { overflow: hidden; }
body { background: transparent; color: var(--color-text-primary); line-height: 1.5; padding: 8px; }
svg { overflow: visible; }
svg text { fill: var(--color-text-primary); }
h1 { font-size: 22px; font-weight: 500; color: var(--color-text-primary); margin-bottom: 12px; }
h2 { font-size: 18px; font-weight: 500; color: var(--color-text-primary); margin-bottom: 8px; }
h3 { font-size: 16px; font-weight: 500; color: var(--color-text-primary); margin-bottom: 6px; }
p { font-size: 14px; color: var(--color-text-secondary); margin-bottom: 8px; }
button {
background: transparent; border: 0.5px solid var(--color-border-secondary);
border-radius: var(--radius-md); padding: 6px 14px; font-size: 13px;
color: var(--color-text-primary); cursor: pointer; font-family: var(--font-sans);
}
button:hover { background: var(--color-bg-secondary); }
button.active { background: var(--color-bg-secondary); border-color: var(--color-border-primary); }
input[type="range"] {
-webkit-appearance: none; width: 100%; height: 4px;
background: var(--color-border-tertiary); border-radius: 2px; outline: none;
}
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none; width: 18px; height: 18px; border-radius: 50%;
background: var(--color-bg-primary); border: 0.5px solid var(--color-border-secondary); cursor: pointer;
}
select {
background: var(--color-bg-secondary); border: 0.5px solid var(--color-border-tertiary);
border-radius: var(--radius-md); padding: 6px 10px; font-size: 13px;
color: var(--color-text-primary); font-family: var(--font-sans);
}
code {
font-family: var(--font-mono); font-size: 13px; background: var(--color-bg-tertiary);
padding: 2px 6px; border-radius: 4px;
}
#iv-dl-wrap{position:fixed;top:4px;right:4px;z-index:9999}
#iv-dl-btn{width:26px;height:26px;padding:0;display:flex;align-items:center;justify-content:center;
opacity:0.3;border-color:var(--color-border-tertiary);background:var(--color-bg-primary)}
#iv-dl-btn:hover{opacity:0.9;background:var(--color-bg-secondary)}
#iv-dl-btn svg{width:14px;height:14px;stroke:var(--color-text-secondary);fill:none;
stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round}
/* --- Print ---
* overflow:hidden on html/body clips content in print (needed on screen
* for iframe sizing). Chart.js canvas scaling is handled by JS beforeprint
* handler in BODY_SCRIPTS — it directly mutates inline styles that CSS
* cannot reliably override in Chrome's print engine.
*/
@media print {
@page { margin: 12mm; }
html, body { overflow: visible !important; height: auto !important;
background: #fff !important; }
body { padding: 4px !important; }
#iv-dl-wrap { display: none !important; }
* { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
}
"""
# ---------------------------------------------------------------------------
# Injected JavaScript — theme detection (head), height reporting & bridges (body)
# ---------------------------------------------------------------------------
# Theme script runs in <head> before user content so CSS vars are resolved
# when model scripts read them at parse time.
THEME_DETECTION_SCRIPT = """
<script>
(function() {
function detectTheme(root) {
return root.classList.contains('dark')
|| root.getAttribute('data-theme') === 'dark'
|| getComputedStyle(root).colorScheme === 'dark';
}
function applyTheme(isDark) {
var theme = isDark ? 'dark' : 'light';
if (document.documentElement.getAttribute('data-theme') === theme) return;
document.documentElement.setAttribute('data-theme', theme);
if (window.Chart && Chart.instances) {
var s = getComputedStyle(document.documentElement);
var tc = s.getPropertyValue('--color-text-secondary').trim();
var gc = s.getPropertyValue('--color-border-tertiary').trim();
Chart.defaults.color = tc;
Chart.defaults.borderColor = gc;
Object.values(Chart.instances).forEach(function(chart) {
Object.values(chart.options.scales || {}).forEach(function(scale) {
if (scale.ticks) scale.ticks.color = tc;
if (scale.grid) scale.grid.color = gc;
});
var leg = (chart.options.plugins || {}).legend;
if (leg && leg.labels) leg.labels.color = tc;
chart.update();
});
}
}
try {
var p = parent.document.documentElement;
applyTheme(detectTheme(p));
new MutationObserver(function() {
applyTheme(detectTheme(p));
}).observe(p, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] });
} catch(e) {
// No same-origin access — fall back to OS preference.
var mq = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)');
if (mq) {
applyTheme(mq.matches);
mq.addEventListener('change', function(e) { applyTheme(e.matches); });
}
}
})();
</script>
"""
BODY_SCRIPTS = """
<script>
// --- Height reporting ---
var _rh_last = 0; // last reported height
var _rh_consecutive = 0; // consecutive small-growth reports
var _rh_raf = 0; // rAF id for debouncing ResizeObserver
function reportHeight() {
var b = document.body;
// Measure SVG overflow before the body collapse below — getBBox
// needs normal layout.
var svgOverflow = 0;
document.querySelectorAll('svg[viewBox]').forEach(function(svg) {
try {
var bbox = svg.getBBox();
var vb = svg.viewBox.baseVal;
if (vb && vb.width > 0 && vb.height > 0) {
var overflow = bbox.y + bbox.height - (vb.y + vb.height);
if (overflow > 0) {
var scale = svg.getBoundingClientRect().width / vb.width;
svgOverflow += Math.ceil(overflow * scale);
}
}
} catch(e) {}
});
// Force height:auto on body + direct children — vh in an auto-sized
// iframe tracks iframe height, creating a feedback loop.
var savedBody = b.style.cssText;
b.style.setProperty('height', 'auto', 'important');
b.style.setProperty('overflow', 'visible', 'important');
b.style.setProperty('display', 'block', 'important');
var saved = [];
Array.from(b.children).forEach(function(el) {
if (el.nodeType !== 1) return;
saved.push({ el: el, css: el.style.cssText });
el.style.setProperty('height', 'auto', 'important');
el.style.setProperty('max-height', 'none', 'important');
el.style.setProperty('min-height', '0', 'important');
el.style.setProperty('overflow', 'visible', 'important');
});
var h = b.scrollHeight + svgOverflow;
b.style.cssText = savedBody;
saved.forEach(function(s) { s.el.style.cssText = s.css; });
// Loop guard: 3+ consecutive small monotonic increases → stop.
var delta = h - _rh_last;
if (_rh_last > 0 && delta > 0 && delta < 50) {
_rh_consecutive++;
if (_rh_consecutive >= 3) return;
} else {
_rh_consecutive = 0;
}
_rh_last = h;
parent.postMessage({ type: 'iframe:height', height: h }, '*');
}
window.addEventListener('load', reportHeight);
window.addEventListener('resize', reportHeight);
// rAF-debounced ResizeObserver avoids tight synchronous loops.
new ResizeObserver(function() {
cancelAnimationFrame(_rh_raf);
_rh_raf = requestAnimationFrame(reportHeight);
}).observe(document.body);
// <details> toggle — ResizeObserver misses this in some browsers.
document.addEventListener('toggle', function() {
_rh_consecutive = 0;
setTimeout(reportHeight, 50);
}, true);
// Dynamic content swaps (innerHTML assignments, SPA-style updates).
var _rh_mutRaf = 0;
new MutationObserver(function() {
_rh_consecutive = 0;
cancelAnimationFrame(_rh_mutRaf);
_rh_mutRaf = requestAnimationFrame(reportHeight);
}).observe(document.body, { childList: true, subtree: true });
// Click covers custom expand/collapse via style.display / class swaps.
document.addEventListener('click', function() {
_rh_consecutive = 0;
cancelAnimationFrame(_rh_mutRaf);
_rh_mutRaf = requestAnimationFrame(reportHeight);
}, true);
// --- Post-render fixes (theme defaults, overlap prevention) ---
window.addEventListener('load', function() {
// Chart.js theme defaults + legend overflow prevention
if (window.Chart) {
var s = getComputedStyle(document.documentElement);
var textColor = s.getPropertyValue('--color-text-secondary').trim();
var gridColor = s.getPropertyValue('--color-border-tertiary').trim();
Chart.defaults.color = textColor;
Chart.defaults.borderColor = gridColor;
Chart.defaults.plugins.legend.labels.color = textColor;
Chart.defaults.plugins.legend.maxHeight = 120;
Chart.defaults.plugins.legend.labels.boxWidth = 12;
Chart.defaults.plugins.legend.labels.font = { size: 11 };
Object.values(Chart.instances || {}).forEach(function(chart) {
var leg = chart.options.plugins && chart.options.plugins.legend;
if (leg) {
leg.maxHeight = leg.maxHeight || 120;
if (leg.labels) {
leg.labels.boxWidth = leg.labels.boxWidth || 12;
}
}
chart.update();
});
}
// De-overlap SVG axis labels only — add data-no-stagger on a <svg>
// to opt out.
document.querySelectorAll('svg').forEach(function(svg) {
if (svg.hasAttribute('data-no-stagger')) return;
var texts = Array.from(svg.querySelectorAll('text'));
if (texts.length < 4) return;
var items = [];
texts.forEach(function(t) {
var r = t.getBoundingClientRect();
if (r.width < 1) return;
items.push({ el: t, rect: r, cx: r.left + r.width / 2, cy: r.top + r.height / 2 });
});
if (items.length < 4) return;
// Only touch texts in a narrow y-band (axis labels). Diagrams with
// texts spread across the canvas are left alone.
var minY = Infinity, maxY = -Infinity;
items.forEach(function(it) {
if (it.cy < minY) minY = it.cy;
if (it.cy > maxY) maxY = it.cy;
});
var ySpan = maxY - minY;
if (ySpan < 1) return;
// Pick the densest y-band (likely the axis row).
var bandSize = 30;
var bestBand = [], bestCount = 0;
items.forEach(function(anchor) {
var band = items.filter(function(it) { return Math.abs(it.cy - anchor.cy) < bandSize; });
if (band.length > bestCount) { bestCount = band.length; bestBand = band; }
});
if (bestBand.length < 3 || bestBand.length === items.length && ySpan > 60) return;
var groups = [];
bestBand.forEach(function(it) {
for (var i = 0; i < groups.length; i++) {
if (Math.abs(groups[i].cx - it.cx) < 15) {
groups[i].items.push(it);
return;
}
}
groups.push({ cx: it.cx, items: [it] });
});
if (groups.length < 3) return;
groups.sort(function(a, b) { return a.cx - b.cx; });
var needsStagger = false;
for (var i = 0; i < groups.length - 1; i++) {
var maxR = 0, minL = Infinity;
groups[i].items.forEach(function(it) { if (it.rect.right > maxR) maxR = it.rect.right; });
groups[i+1].items.forEach(function(it) { if (it.rect.left < minL) minL = it.rect.left; });
if (maxR > minL - 2) { needsStagger = true; break; }
}
if (needsStagger) {
for (var i = 1; i < groups.length; i += 2) {
groups[i].items.forEach(function(it) {
var cy = parseFloat(it.el.getAttribute('y') || 0);
it.el.setAttribute('y', String(cy + 18));
});
}
}
});
setTimeout(reportHeight, 100);
});
// --- sendPrompt bridge (requires iframe Sandbox Allow Same Origin) ---
function sendPrompt(text) {
try {
// Open WebUI's native prompt-submit postMessage — queues if the
// model is mid-generation.
parent.postMessage({ type: 'input:prompt:submit', text: text }, '*');
} catch(e) { /* iframe sandbox restriction */ }
}
// --- Open link in parent window ---
function openLink(url) {
try { parent.window.open(url, '_blank'); }
catch(e) { window.open(url, '_blank'); }
}
// --- navigator.vibrate silencer ---
// Chrome spams `[Intervention] Blocked call to navigator.vibrate…` on
// every call without a prior user gesture. Replace with a no-op so the
// block path never runs.
try {
if (typeof navigator !== 'undefined' && navigator.vibrate) {
navigator.vibrate = function() { return false; };
}
} catch(e) {}
// --- Toast bridge ---
// Floating auto-dismissing top-right banner. kind = success/info/warn/error.
function toast(msg, kind) {
kind = kind || 'success';
var color = kind === 'error' ? 'var(--color-text-danger)'
: kind === 'info' ? 'var(--color-text-info)'
: kind === 'warn' ? 'var(--color-text-warning)'
: 'var(--color-text-success)';
var wrap = document.getElementById('iv-toast-wrap');
if (!wrap) {
wrap = document.createElement('div');
wrap.id = 'iv-toast-wrap';
wrap.style.cssText =
'position:fixed;top:4px;right:38px;z-index:9998;' +
'display:flex;flex-direction:column;gap:4px;pointer-events:none;' +
'max-width:280px;';
document.body.appendChild(wrap);
}
var el = document.createElement('div');
el.style.cssText =
'padding:6px 12px;border-radius:var(--radius-md);' +
'background:var(--color-bg-secondary);' +
'border:0.5px solid var(--color-border-tertiary);' +
'color:' + color + ';font-size:12px;line-height:1.4;' +
'font-family:var(--font-sans);font-weight:500;' +
'opacity:0;transform:translateY(-4px);transition:all 0.2s ease;' +
'pointer-events:auto;white-space:nowrap;' +
'overflow:hidden;text-overflow:ellipsis;';
el.textContent = String(msg == null ? '' : msg);
wrap.appendChild(el);
requestAnimationFrame(function() {
el.style.opacity = '1';
el.style.transform = 'none';
});
setTimeout(function() {
el.style.opacity = '0';
el.style.transform = 'translateY(-4px)';
setTimeout(function() { if (el.parentNode) el.parentNode.removeChild(el); }, 220);
}, 2200);
}
// --- copyText bridge ---
// Async Clipboard API with execCommand fallback (Open WebUI's iframe
// sandbox lacks allow-clipboard-write). Toast fires unconditionally —
// execCommand can silently fail and swallowing feedback leaves the user
// confused. silent=true suppresses the toast.
function copyText(text, silent) {
var s = String(text == null ? '' : text);
var label = (typeof _ivCopiedStr !== 'undefined' &&
(_ivCopiedStr[_ivLang] || _ivCopiedStr.en)) || 'Copied';
function fire() { if (!silent) try { toast(label, 'success'); } catch(e) {} }
function legacy() {
try {
var ta = document.createElement('textarea');
ta.value = s;
ta.setAttribute('readonly', '');
ta.style.cssText =
'position:fixed;left:-9999px;top:-9999px;opacity:0;';
document.body.appendChild(ta);
ta.focus();
ta.select();
try { ta.setSelectionRange(0, s.length); } catch(e) {}
try { document.execCommand('copy'); } catch(e) {}
ta.remove();
} catch(e) {}
fire();
}
try {
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(s).then(fire, legacy);
return;
}
} catch(e) {}
legacy();
}
// --- saveState / loadState bridges ---
// parent.localStorage proxy scoped to the assistant message id — state
// persists across reloads but never leaks between chats / messages.
// Silent no-op if localStorage / parent is unreachable.
function _ivStatePrefix() {
try {
var f = window.frameElement;
var msg = f && f.closest && f.closest('[id^="message-"]');
return 'iv-state:' + ((msg && msg.id) || 'global') + ':';
} catch(e) { return 'iv-state:global:'; }
}
function saveState(key, value) {
try {
parent.localStorage.setItem(
_ivStatePrefix() + String(key),
JSON.stringify(value === undefined ? null : value)
);
} catch(e) {}
}
function loadState(key, fallback) {
try {
var v = parent.localStorage.getItem(_ivStatePrefix() + String(key));
if (v == null) return fallback === undefined ? null : fallback;
return JSON.parse(v);
} catch(e) { return fallback === undefined ? null : fallback; }
}
/*__CHIME_BLOCK__*/
// --- Print fix for Chart.js canvases ---
// Chart.js writes explicit pixel widths as inline styles that CSS
// max-width can't override in Chrome's print engine. Mutate inline
// styles before print, restore after.
(function() {
window.addEventListener('beforeprint', function() {
document.querySelectorAll('canvas').forEach(function(c) {
c.setAttribute('data-print-style', c.style.cssText);
c.style.setProperty('width', '100%', 'important');
c.style.setProperty('max-width', '100%', 'important');
c.style.setProperty('height', 'auto', 'important');
var p = c.parentElement;
if (p) {
p.setAttribute('data-print-style', p.style.cssText);
p.style.setProperty('width', '100%', 'important');
p.style.setProperty('max-width', '100%', 'important');
}
});
});
window.addEventListener('afterprint', function() {
document.querySelectorAll('[data-print-style]').forEach(function(el) {
el.style.cssText = el.getAttribute('data-print-style');
el.removeAttribute('data-print-style');
});
});
})();
// --- Download visualization as self-contained HTML ---
var _ivLang = 'en';
var _ivStr = {
// Required languages
en: 'Download as HTML',
de: 'Als HTML herunterladen',
cs: 'Stáhnout jako HTML',
hu: 'Letöltés HTML-ként',
hr: 'Preuzmi kao HTML',
pl: 'Pobierz jako HTML',
fr: 'Télécharger en HTML',
nl: 'Downloaden als HTML',
// Western & Southern European
es: 'Descargar como HTML',
pt: 'Baixar como HTML',
it: 'Scarica come HTML',
ca: 'Baixa com a HTML',
gl: 'Descargar como HTML',
eu: 'Deskargatu HTML gisa',
// Northern European
da: 'Download som HTML',
sv: 'Ladda ner som HTML',
no: 'Last ned som HTML',
fi: 'Lataa HTML-tiedostona',
is: 'Hlaða niður sem HTML',
// Eastern European & Slavic
sk: 'Stiahnuť ako HTML',
sl: 'Prenesi kot HTML',
sr: 'Преузми као HTML',
bs: 'Preuzmi kao HTML',
bg: 'Изтегли като HTML',
mk: 'Преземи како HTML',
uk: 'Завантажити як HTML',
ru: 'Скачать как HTML',
be: 'Спампаваць як HTML',
// Baltic
lt: 'Atsisiųsti kaip HTML',
lv: 'Lejupielādēt kā HTML',
et: 'Laadi alla HTML-ina',
// Other European
ro: 'Descarcă ca HTML',
el: 'Λήψη ως HTML',
sq: 'Shkarko si HTML',
// Middle Eastern
tr: 'HTML olarak indir',
ar: 'تحميل كـ HTML',
he: 'הורד כ-HTML',
// East & South Asian
zh: '下载为HTML',
ja: 'HTMLでダウンロード',
ko: 'HTML로 다운로드',
vi: 'Tải xuống dạng HTML',
th: 'ดาวน์โหลดเป็น HTML',
id: 'Unduh sebagai HTML',
ms: 'Muat turun sebagai HTML',
hi: 'HTML के रूप में डाउनलोड करें',
bn: 'HTML হিসেবে ডাউনলোড করুন',
// African
sw: 'Pakua kama HTML'
};
// Loader label (shown while waiting for the first content chunk).
var _ivLoadStr = {
en: 'Rendering visualization\u2026',
de: 'Visualisierung wird erstellt\u2026',
cs: 'Vykresluje se vizualizace\u2026',
hu: 'Vizualizáció renderelése\u2026',
hr: 'Iscrtavanje vizualizacije\u2026',
pl: 'Renderowanie wizualizacji\u2026',
fr: 'Rendu de la visualisation\u2026',
nl: 'Visualisatie renderen\u2026',
es: 'Renderizando visualización\u2026',
pt: 'Renderizando visualização\u2026',
it: 'Rendering della visualizzazione\u2026',
ca: 'Renderitzant visualització\u2026',
gl: 'Renderizando visualización\u2026',
eu: 'Bistaratzea errendatzen\u2026',
da: 'Gengiver visualisering\u2026',
sv: 'Renderar visualisering\u2026',
no: 'Gjengir visualisering\u2026',
fi: 'Renderöidään visualisointia\u2026',
is: 'Teiknar sjónræna framsetningu\u2026',
sk: 'Vykresľuje sa vizualizácia\u2026',
sl: 'Upodabljanje vizualizacije\u2026',
sr: 'Исцртавање визуализације\u2026',
bs: 'Iscrtavanje vizualizacije\u2026',
bg: 'Изчертаване на визуализацията\u2026',
mk: 'Исцртување на визуализацијата\u2026',
uk: 'Відображення візуалізації\u2026',
ru: 'Отрисовка визуализации\u2026',
be: 'Адмалёўка візуалізацыі\u2026',
lt: 'Atvaizduojama vizualizacija\u2026',
lv: 'Vizualizācijas renderēšana\u2026',
et: 'Visualiseeringu renderdamine\u2026',
ro: 'Randare vizualizare\u2026',
el: 'Απόδοση οπτικοποίησης\u2026',
sq: 'Duke renderuar vizualizimin\u2026',
tr: 'Görselleştirme oluşturuluyor\u2026',
ar: 'جارٍ عرض التصور\u2026',
he: 'מציג הדמיה\u2026',
zh: '正在渲染可视化\u2026',
ja: 'ビジュアライゼーションを描画中\u2026',
ko: '시각화 렌더링 중\u2026',
vi: 'Đang kết xuất hình ảnh\u2026',
th: 'กำลังแสดงผลการแสดงภาพ\u2026',
id: 'Merender visualisasi\u2026',
ms: 'Memaparkan visualisasi\u2026',
hi: 'विज़ुअलाइज़ेशन रेंडर हो रहा है\u2026',
bn: 'ভিজ্যুয়ালাইজেশন রেন্ডার হচ্ছে\u2026',
sw: 'Inarendi taswira\u2026'
};
// "Streaming visualization unavailable" title + body, shown only when
// the iframe cannot reach parent.document (Allow Same Origin disabled).
var _ivErrTitleStr = {
en: 'Streaming visualization unavailable',
de: 'Streaming-Visualisierung nicht verfügbar',
cs: 'Streamovaná vizualizace není dostupná',
hu: 'A streamelt vizualizáció nem érhető el',
hr: 'Streaming vizualizacija nije dostupna',
pl: 'Strumieniowa wizualizacja niedostępna',
fr: 'Visualisation en streaming indisponible',
nl: 'Streaming visualisatie niet beschikbaar',
es: 'Visualización en streaming no disponible',
pt: 'Visualização em streaming indisponível',
it: 'Visualizzazione in streaming non disponibile',
ca: 'Visualització en streaming no disponible',
gl: 'Visualización en streaming non dispoñíbel',
eu: 'Streaming bistaratzea ez dago erabilgarri',
da: 'Streaming-visualisering utilgængelig',
sv: 'Strömmande visualisering otillgänglig',
no: 'Streaming-visualisering utilgjengelig',
fi: 'Suoratoistettu visualisointi ei käytettävissä',
is: 'Streymandi sjónræn framsetning ekki tiltæk',
sk: 'Streamovaná vizualizácia nie je dostupná',
sl: 'Pretočna vizualizacija ni na voljo',
sr: 'Стриминг визуализација није доступна',
bs: 'Streaming vizualizacija nije dostupna',
bg: 'Поточната визуализация е недостъпна',
mk: 'Стриминг визуализација недостапна',
uk: 'Потокова візуалізація недоступна',
ru: 'Потоковая визуализация недоступна',
be: 'Струменевая візуалізацыя недаступная',
lt: 'Srautinė vizualizacija nepasiekiama',
lv: 'Straumētā vizualizācija nav pieejama',
et: 'Voogedastuse visualiseering pole saadaval',
ro: 'Vizualizarea în streaming indisponibilă',
el: 'Η ροή οπτικοποίησης δεν είναι διαθέσιμη',
sq: 'Vizualizimi i transmetimit i padisponueshëm',
tr: 'Akış görselleştirmesi kullanılamıyor',
ar: 'التصور المتدفق غير متاح',
he: 'הדמיה בסטרימינג אינה זמינה',
zh: '流式可视化不可用',
ja: 'ストリーミングビジュアライゼーションは利用できません',
ko: '스트리밍 시각화를 사용할 수 없습니다',
vi: 'Hình ảnh trực quan phát trực tuyến không khả dụng',
th: 'การแสดงผลแบบสตรีมไม่พร้อมใช้งาน',
id: 'Visualisasi streaming tidak tersedia',
ms: 'Visualisasi strim tidak tersedia',
hi: 'स्ट्रीमिंग विज़ुअलाइज़ेशन अनुपलब्ध',
bn: 'স্ট্রিমিং ভিজ্যুয়ালাইজেশন অনুপলব্ধ',
sw: 'Taswira ya utiririshaji haipatikani'
};
// Confirmation toast shown after copyText() succeeds.
var _ivCopiedStr = {
en: 'Copied', de: 'Kopiert', cs: 'Zkopírováno', hu: 'Másolva',
hr: 'Kopirano', pl: 'Skopiowano', fr: 'Copié', nl: 'Gekopieerd',
es: 'Copiado', pt: 'Copiado', it: 'Copiato', ca: 'Copiat',
gl: 'Copiado', eu: 'Kopiatuta',
da: 'Kopieret', sv: 'Kopierat', no: 'Kopiert', fi: 'Kopioitu',
is: 'Afritað',
sk: 'Skopírované', sl: 'Kopirano', sr: 'Копирано', bs: 'Kopirano',
bg: 'Копирано', mk: 'Копирано', uk: 'Скопійовано', ru: 'Скопировано',
be: 'Скапіявана',
lt: 'Nukopijuota', lv: 'Nokopēts', et: 'Kopeeritud',
ro: 'Copiat', el: 'Αντιγράφηκε', sq: 'U kopjua',
tr: 'Kopyalandı', ar: 'تم النسخ', he: 'הועתק',
zh: '已复制', ja: 'コピーしました', ko: '복사됨',
vi: 'Đã sao chép', th: 'คัดลอกแล้ว', id: 'Disalin', ms: 'Disalin',
hi: 'कॉपी किया गया', bn: 'অনুলিপি করা হয়েছে',
sw: 'Imenakiliwa'
};
// Shown as a top-right toast when streaming completes and the
// visualization has finished rendering. Only appears if we actually
// witnessed live streaming — refreshes of completed messages stay silent.
var _ivDoneStr = {
en: 'Visualization ready',
de: 'Visualisierung bereit',
cs: 'Vizualizace připravena',
hu: 'Vizualizáció kész',
hr: 'Vizualizacija spremna',
pl: 'Wizualizacja gotowa',
fr: 'Visualisation prête',
nl: 'Visualisatie klaar',
es: 'Visualización lista',
pt: 'Visualização pronta',
it: 'Visualizzazione pronta',
ca: 'Visualització llesta',
gl: 'Visualización lista',
eu: 'Bistaratzea prest',
da: 'Visualisering klar',
sv: 'Visualisering klar',
no: 'Visualisering klar',
fi: 'Visualisointi valmis',
is: 'Sjónræn framsetning tilbúin',
sk: 'Vizualizácia pripravená',
sl: 'Vizualizacija pripravljena',
sr: 'Визуализација спремна',
bs: 'Vizualizacija spremna',
bg: 'Визуализацията е готова',
mk: 'Визуализацијата е подготвена',
uk: 'Візуалізація готова',
ru: 'Визуализация готова',
be: 'Візуалізацыя гатовая',
lt: 'Vizualizacija paruošta',
lv: 'Vizualizācija gatava',
et: 'Visualiseering valmis',
ro: 'Vizualizare gata',
el: 'Η οπτικοποίηση είναι έτοιμη',
sq: 'Vizualizimi gati',
tr: 'Görselleştirme hazır',
ar: 'التصور جاهز',
he: 'ההדמיה מוכנה',
zh: '可视化已完成',
ja: 'ビジュアライゼーション完成',
ko: '시각화 완료',
vi: 'Hình ảnh đã sẵn sàng',
th: 'การแสดงภาพพร้อมแล้ว',
id: 'Visualisasi siap',
ms: 'Visualisasi sedia',
hi: 'विज़ुअलाइज़ेशन तैयार',
bn: 'ভিজ্যুয়ালাইজেশন প্রস্তুত',
sw: 'Taswira tayari'
};
var _ivErrBodyStr = {
en: 'Open User Settings \u2192 Interface, scroll down, and enable "Allow iframe same origin" to use streaming mode.',
de: 'Öffne Benutzereinstellungen \u2192 Oberfläche, scrolle nach unten und aktiviere „Allow iframe same origin" für den Streaming-Modus.',
cs: 'Otevřete Uživatelská nastavení \u2192 Rozhraní, sjeďte dolů a zapněte „Allow iframe same origin" pro režim streamování.',
hu: 'Nyissa meg a Felhasználói beállítások \u2192 Felület menüt, görgessen le, és kapcsolja be az „Allow iframe same origin" opciót a streamelési módhoz.',
hr: 'Otvorite Korisničke postavke \u2192 Sučelje, pomaknite se prema dolje i uključite „Allow iframe same origin" za streaming način.',
pl: 'Otwórz Ustawienia użytkownika \u2192 Interfejs, przewiń w dół i włącz „Allow iframe same origin" dla trybu strumieniowego.',
fr: 'Ouvrez Paramètres utilisateur \u2192 Interface, faites défiler vers le bas et activez « Allow iframe same origin » pour le mode streaming.',
nl: 'Open Gebruikersinstellingen \u2192 Interface, scrol omlaag en schakel "Allow iframe same origin" in voor streamingmodus.',
es: 'Abre Configuración de usuario \u2192 Interfaz, desplázate hacia abajo y activa "Allow iframe same origin" para el modo streaming.',
pt: 'Abra Configurações do usuário \u2192 Interface, role para baixo e ative "Allow iframe same origin" para o modo streaming.',
it: 'Apri Impostazioni utente \u2192 Interfaccia, scorri in basso e attiva "Allow iframe same origin" per la modalità streaming.',
ca: 'Obre Configuració d\u2019usuari \u2192 Interfície, desplaça\u2019t avall i activa "Allow iframe same origin" per al mode streaming.',
gl: 'Abre Configuración de usuario \u2192 Interface, desprázate cara abaixo e activa "Allow iframe same origin" para o modo streaming.',
eu: 'Ireki Erabiltzaile-ezarpenak \u2192 Interfazea, egin behera eta gaitu "Allow iframe same origin" streaming modua erabiltzeko.',
da: 'Åbn Brugerindstillinger \u2192 Grænseflade, rul ned, og aktivér "Allow iframe same origin" for streamingtilstand.',
sv: 'Öppna Användarinställningar \u2192 Gränssnitt, rulla ner och aktivera "Allow iframe same origin" för strömningsläge.',
no: 'Åpne Brukerinnstillinger \u2192 Grensesnitt, rull ned og aktiver "Allow iframe same origin" for streamingmodus.',
fi: 'Avaa Käyttäjäasetukset \u2192 Käyttöliittymä, vieritä alas ja ota "Allow iframe same origin" käyttöön suoratoistotilaa varten.',
is: 'Opnaðu Notandastillingar \u2192 Viðmót, skrunaðu niður og kveiktu á "Allow iframe same origin" fyrir streymisstillingu.',
sk: 'Otvorte Používateľské nastavenia \u2192 Rozhranie, posuňte sa nadol a zapnite „Allow iframe same origin" pre režim streamovania.',
sl: 'Odprite Uporabniške nastavitve \u2192 Vmesnik, pomaknite se navzdol in omogočite "Allow iframe same origin" za pretočni način.',
sr: 'Отворите Корисничка подешавања \u2192 Интерфејс, померите надоле и омогућите „Allow iframe same origin" за стриминг режим.',
bs: 'Otvorite Korisničke postavke \u2192 Sučelje, skrolajte prema dolje i uključite "Allow iframe same origin" za streaming mod.',
bg: 'Отворете Потребителски настройки \u2192 Интерфейс, превъртете надолу и активирайте „Allow iframe same origin" за поточен режим.',
mk: 'Отворете Кориснички поставки \u2192 Интерфејс, листајте надолу и овозможете „Allow iframe same origin" за стриминг режим.',
uk: 'Відкрийте Налаштування користувача \u2192 Інтерфейс, прокрутіть униз і ввімкніть «Allow iframe same origin» для потокового режиму.',
ru: 'Откройте Настройки пользователя \u2192 Интерфейс, прокрутите вниз и включите «Allow iframe same origin» для режима потоковой передачи.',
be: 'Адкрыйце Налады карыстальніка \u2192 Інтэрфейс, прагартайце ўніз і ўключыце «Allow iframe same origin» для струменевага рэжыму.',
lt: 'Atidarykite Naudotojo nustatymai \u2192 Sąsaja, slinkite žemyn ir įjunkite „Allow iframe same origin" srautiniam režimui.',
lv: 'Atveriet Lietotāja iestatījumi \u2192 Saskarne, ritiniet lejup un iespējojiet "Allow iframe same origin" straumēšanas režīmam.',
et: 'Ava Kasutaja seaded \u2192 Liides, keri alla ja luba „Allow iframe same origin" voogedastusrežiimi jaoks.',
ro: 'Deschide Setări utilizator \u2192 Interfață, derulează în jos și activează "Allow iframe same origin" pentru modul streaming.',
el: 'Ανοίξτε Ρυθμίσεις χρήστη \u2192 Διεπαφή, κυλήστε προς τα κάτω και ενεργοποιήστε το «Allow iframe same origin» για λειτουργία ροής.',
sq: 'Hapni Cilësimet e përdoruesit \u2192 Ndërfaqja, rrëshqitni poshtë dhe aktivizoni "Allow iframe same origin" për modalitetin e transmetimit.',
tr: 'Kullanıcı Ayarları \u2192 Arayüz\u2019ü açın, aşağı kaydırın ve akış modu için "Allow iframe same origin" seçeneğini etkinleştirin.',
ar: 'افتح إعدادات المستخدم \u2190 الواجهة، مرر لأسفل وفعّل "Allow iframe same origin" لاستخدام وضع التدفق.',
he: 'פתח הגדרות משתמש \u2190 ממשק, גלול מטה והפעל את "Allow iframe same origin" למצב סטרימינג.',
zh: '打开 用户设置 \u2192 界面,向下滚动并启用"Allow iframe same origin"以使用流式模式。',
ja: 'ユーザー設定 \u2192 インターフェースを開き、下にスクロールして「Allow iframe same origin」を有効にするとストリーミングモードを使用できます。',
ko: '사용자 설정 \u2192 인터페이스를 열고 아래로 스크롤하여 "Allow iframe same origin"을 활성화하면 스트리밍 모드를 사용할 수 있습니다.',
vi: 'Mở Cài đặt người dùng \u2192 Giao diện, cuộn xuống và bật "Allow iframe same origin" để sử dụng chế độ phát trực tiếp.',
th: 'เปิดการตั้งค่าผู้ใช้ \u2192 อินเทอร์เฟซ เลื่อนลงและเปิดใช้งาน "Allow iframe same origin" เพื่อใช้โหมดสตรีม',
id: 'Buka Pengaturan Pengguna \u2192 Antarmuka, gulir ke bawah dan aktifkan "Allow iframe same origin" untuk mode streaming.',
ms: 'Buka Tetapan Pengguna \u2192 Antara Muka, tatal ke bawah dan dayakan "Allow iframe same origin" untuk mod strim.',
hi: 'उपयोगकर्ता सेटिंग्स \u2192 इंटरफ़ेस खोलें, नीचे स्क्रॉल करें और स्ट्रीमिंग मोड के लिए "Allow iframe same origin" सक्षम करें।',
bn: 'ব্যবহারকারী সেটিংস \u2192 ইন্টারফেস খুলুন, নিচে স্ক্রোল করুন এবং স্ট্রিমিং মোডের জন্য "Allow iframe same origin" সক্ষম করুন।',
sw: 'Fungua Mipangilio ya Mtumiaji \u2192 Kiolesura, sogeza chini na washa "Allow iframe same origin" kwa hali ya utiririshaji.'
};
(function() {
function detectLang() {
// 1. Pre-detected via __event_call__ (baked into HTML by the tool)
var pre = document.documentElement.getAttribute('data-iv-lang');
if (pre && _ivStr[pre]) return pre;
// 2. Fallback: parent localStorage (needs same-origin)
try {
var s = parent.localStorage.getItem('locale')
|| parent.localStorage.getItem('language')
|| parent.localStorage.getItem('i18nextLng');
if (s) { var l = s.split('-')[0].toLowerCase(); if (_ivStr[l]) return l; }
} catch(e) {}
// 3. Fallback: browser language (standalone HTML / no same-origin)
try {
var bl = (navigator.language || navigator.userLanguage || 'en').split('-')[0].toLowerCase();
if (_ivStr[bl]) return bl;
} catch(e) {}
return 'en';
}
_ivLang = detectLang();
var btn = document.getElementById('iv-dl-btn');
if (btn) btn.title = _ivStr[_ivLang] || _ivStr.en;
// Swap the server-baked English loader label for the detected locale.
var loadLabel = document.querySelector('.iv-loading-label');
if (loadLabel) loadLabel.textContent = _ivLoadStr[_ivLang] || _ivLoadStr.en;
})();
// ---------------------------------------------------------------------------
// Download as self-contained HTML
// ---------------------------------------------------------------------------
// Desktop / Android: blob + <a download> + target="_blank" safety net
// (gracefully opens in a new tab if the iframe sandbox blocks downloads).
// iOS: NO target="_blank" (would strand PWA users on a blob page with no
// back button), setTimeout(0) deferral avoids a synchronous WebKit
// "Load failed" throw, and error listeners suppress the residual toast
// for 60s. iOS detection also catches iPadOS via MacIntel+touchpoints.
// ---------------------------------------------------------------------------
var _ivIsIOS = /iPad|iPhone|iPod/.test(navigator.userAgent)
|| (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
function _ivDownload() {
// Strip download button + overflow:hidden for standalone use.
var w = document.getElementById('iv-dl-wrap');
if (w) w.remove();
var html = '<!DOCTYPE html>\\n' + document.documentElement.outerHTML;
if (w) document.body.appendChild(w);
html = html.replace('html, body { overflow: hidden; }', '');
var fname = (document.title || 'visualization').replace(/[<>:"\\/|?*]+/g, '-').replace(/\s+/g, ' ').trim();
if (!fname) fname = 'visualization';
// Cap at 200 chars to stay under the Windows 255-char filename limit.
if (fname.length > 200) fname = fname.substring(0, 200).trim();
fname += '.html';
var blob = new Blob([html], {type: 'text/html;charset=utf-8'});
var url = URL.createObjectURL(blob);
if (_ivIsIOS) {
// iOS — deferred click + "Load failed" error suppression.
setTimeout(function() {
var _origOnerror = window.onerror;
window.onerror = function(msg) {
if (typeof msg === 'string' && msg.indexOf('Load failed') !== -1) return true;
if (_origOnerror) return _origOnerror.apply(this, arguments);
};