File size: 48,703 Bytes
294a0b9
 
 
 
 
 
 
 
 
 
 
32ff6d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294a0b9
 
 
 
 
 
 
 
 
 
 
 
32ff6d9
294a0b9
 
32ff6d9
 
 
 
 
294a0b9
32ff6d9
 
 
294a0b9
 
 
 
 
 
 
 
32ff6d9
294a0b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32ff6d9
 
294a0b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32ff6d9
294a0b9
 
 
32ff6d9
294a0b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32ff6d9
294a0b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32ff6d9
 
294a0b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32ff6d9
294a0b9
 
 
 
 
32ff6d9
 
294a0b9
 
 
 
 
 
 
32ff6d9
294a0b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32ff6d9
294a0b9
 
 
 
32ff6d9
294a0b9
 
 
 
 
 
 
32ff6d9
294a0b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32ff6d9
 
 
294a0b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4eef79
 
 
 
 
 
 
294a0b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4eef79
 
 
294a0b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32ff6d9
294a0b9
 
 
 
 
 
32ff6d9
294a0b9
32ff6d9
 
294a0b9
 
 
 
 
32ff6d9
 
 
 
 
 
 
 
 
 
 
294a0b9
 
c4eef79
 
294a0b9
 
 
 
 
 
 
 
 
 
 
 
c4eef79
294a0b9
 
 
 
32ff6d9
294a0b9
 
 
 
 
 
 
 
 
 
 
 
c4eef79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294a0b9
 
 
 
 
 
 
 
 
 
 
c4eef79
294a0b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4eef79
294a0b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4eef79
 
294a0b9
 
 
c4eef79
294a0b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4eef79
 
 
294a0b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4eef79
 
 
 
 
 
 
 
 
294a0b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4eef79
294a0b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Jeveration Studio</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500&display=swap" rel="stylesheet" />
<style>
  :root {
    --bg: #ffffff; --panel: #ffffff; --panel2: #fafafa; --raised: #f5f5f5;
    --border: #e4e4e4; --hairline: #ececec;
    --text: #111111; --muted: #666666; --dim: #929292;
    --accent: #111111; --accent2: #315efb; --accent-soft: rgba(49,94,251,0.08);
    --lavender: #111111; --link: #315efb;
    --glow: none;
    --stage-base: #fafafa; --stage-square: #efefef; --thumb-bg: #f5f5f5;
    --button-text: #ffffff;
    --radius: 12px;
  }
  body.dark {
    --bg: #111111; --panel: #171717; --panel2: #1d1d1d; --raised: #262626;
    --border: #383838; --hairline: #2c2c2c;
    --text: #f7f7f7; --muted: #b0b0b0; --dim: #7d7d7d;
    --accent: #f4f4f4; --accent2: #82a2ff; --accent-soft: rgba(130,162,255,0.12);
    --lavender: #f4f4f4; --link: #9db5ff;
    --glow: none;
    --stage-base: #131313; --stage-square: #1c1c1c; --thumb-bg: #202020;
    --button-text: #111111;
  }
  * { margin: 0; padding: 0; box-sizing: border-box; }
  [hidden] { display: none !important; }
  body {
    font-family: "Inter", ui-sans-serif, system-ui, sans-serif;
    background: var(--bg); background-image: var(--glow); background-repeat: no-repeat;
    background-attachment: fixed;
    color: var(--text); height: 100vh;
    display: flex; flex-direction: column; overflow: hidden;
    font-size: 13px; -webkit-font-smoothing: antialiased;
  }
  .topbar {
    display: flex; align-items: center; gap: 14px; padding: 12px 24px;
    background: var(--panel); border-bottom: 1px solid var(--hairline); flex-shrink: 0;
  }
  .brand { font-weight: 700; font-size: 1.35rem; white-space: nowrap; letter-spacing: -0.055em; display: flex; align-items: center; }
  .brand .j { color: #f05f67; }
  .brand .e { color: #35b878; }
  .brand .v { color: #4585ed; }
  .brand .rest { color: var(--text); }
  .studio-badge {
    font-size: 0.58rem; font-weight: 650; letter-spacing: 0.14em; text-transform: uppercase;
    color: var(--muted); border: 1px solid var(--border); border-radius: 999px;
    padding: 3px 9px; margin-left: 12px; background: transparent;
  }
  .mode-tabs { display: flex; gap: 2px; background: var(--panel2); border: 1px solid var(--border); border-radius: 9px; padding: 3px; }
  .mode-tabs button {
    border: none; border-radius: 7px; padding: 6px 16px; font-weight: 550; font-size: 0.82rem;
    background: transparent; color: var(--muted); cursor: pointer; transition: color 0.15s, background 0.15s;
    font-family: inherit;
  }
  .mode-tabs button:hover { color: var(--text); }
  .mode-tabs button.active { background: var(--accent); color: var(--button-text); box-shadow: none; }
  .spacer { flex: 1; }
  .ml-badge { color: var(--muted); text-decoration: none; font-size: 0.8rem; font-weight: 500; transition: color 0.15s; white-space: nowrap; }
  .ml-badge:hover { color: var(--text); }
  .ml-badge-img { display: inline-flex; align-items: center; }
  .ml-badge-img img { height: 20px; display: block; }
  .ml-badge-img:hover { opacity: 0.85; }
  .theme-toggle {
    width: 34px; height: 34px; border: 1px solid var(--border); border-radius: 9px;
    background: transparent; color: var(--muted); cursor: pointer; flex-shrink: 0;
    display: inline-flex; align-items: center; justify-content: center;
    transition: color 0.15s, background 0.15s;
  }
  .theme-toggle:hover { color: var(--text); background: var(--panel2); }
  .theme-toggle svg { width: 17px; height: 17px; }
  .theme-toggle .theme-icon-moon { display: none; }
  .theme-toggle[data-mode="light"] .theme-icon-sun { display: none; }
  .theme-toggle[data-mode="light"] .theme-icon-moon { display: block; }
  .main { display: flex; flex: 1; min-height: 0; }
  .rail {
    width: 52px; flex-shrink: 0; display: flex; flex-direction: column; align-items: center;
    gap: 6px; padding: 10px 0; background: var(--panel); border-right: 1px solid var(--hairline);
  }
  .rail button {
    width: 38px; height: 38px; border: 1px solid transparent; border-radius: 8px;
    background: transparent; color: var(--muted); cursor: pointer;
    display: flex; align-items: center; justify-content: center;
    transition: color 0.15s, background 0.15s;
  }
  .rail button:hover { background: var(--panel2); color: var(--text); }
  .viewport { flex: 1; min-width: 0; display: flex; flex-direction: column; overflow: auto; position: relative; }
  .workflow-view { position: absolute; inset: 0; padding: 16px; background: var(--bg); }
  .workflow-view iframe { width: 100%; height: 100%; border: 1px solid var(--border); border-radius: 12px; background: var(--panel); }
  .doc-grid { flex: 1; min-height: 0; display: flex; gap: 16px; width: 100%; align-items: stretch; justify-content: center; padding: 20px 20px 10px; }
  .doc {
    flex: 1; min-width: 0; max-width: 560px; display: flex; flex-direction: column;
    background: var(--panel); border: 1px solid var(--border); border-radius: 10px; overflow: hidden;
  }
  .doc figcaption {
    padding: 8px 12px; font-size: 0.62rem; font-weight: 650; letter-spacing: 0.12em;
    color: var(--dim); border-bottom: 1px solid var(--hairline); text-transform: uppercase;
    display: flex; align-items: center;
  }
  .doc .stage {
    position: relative; flex: 1; min-height: 0; display: flex; align-items: center; justify-content: center;
    overflow: hidden; background-color: var(--stage-base);
    background-image:
      linear-gradient(45deg, var(--stage-square) 25%, transparent 25%),
      linear-gradient(-45deg, var(--stage-square) 25%, transparent 25%),
      linear-gradient(45deg, transparent 75%, var(--stage-square) 75%),
      linear-gradient(-45deg, transparent 75%, var(--stage-square) 75%);
    background-size: 20px 20px;
    background-position: 0 0, 0 10px, 10px -10px, -10px 0;
  }
  .doc img { max-width: 100%; max-height: 100%; object-fit: contain; display: block; }
  .doc img.zoomed { max-width: none; max-height: none; }
  .doc .stage.scrollable { overflow: auto; justify-content: flex-start; align-items: flex-start; }
  .drop-hint { color: var(--dim); font-size: 0.85rem; text-align: center; padding: 20px; }
  .drop-hint b { color: var(--muted); display: block; margin-bottom: 6px; }
  .zoom-btn {
    margin-left: auto; border: 1px solid var(--border); background: transparent; color: var(--muted);
    border-radius: 5px; font-size: 0.62rem; padding: 2px 8px; cursor: pointer; letter-spacing: 0.08em;
    font-family: inherit;
  }
  .zoom-btn:hover { color: var(--text); border-color: var(--accent); }
  .doc-bar {
    display: flex; align-items: center; gap: 10px; padding: 6px 12px;
    border-top: 1px solid var(--hairline); background: var(--panel);
    font-size: 0.72rem; color: var(--muted); flex-shrink: 0;
  }
  .doc-bar button {
    border: 1px solid var(--border); background: transparent; color: var(--muted);
    border-radius: 5px; padding: 3px 10px; font-size: 0.68rem; cursor: pointer; letter-spacing: 0.06em;
    font-family: inherit;
  }
  .doc-bar button:hover, .doc-bar button.active { color: var(--text); border-color: var(--accent); }
  .doc-bar button.active { background: var(--accent-soft); color: var(--lavender); }
  .split-wrap { position: absolute; inset: 0; overflow: hidden; }
  .split-wrap img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; }
  .split-divider {
    position: absolute; top: 0; bottom: 0; width: 3px; background: var(--accent);
    cursor: ew-resize; z-index: 5; box-shadow: 0 0 8px rgba(17,17,17,0.18);
  }
  .split-divider::after {
    content: "◂ ▸"; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%);
    background: var(--accent); color: var(--button-text); border-radius: 999px; padding: 4px 7px;
    font-size: 0.6rem; white-space: nowrap;
  }
  .history-strip {
    display: flex; gap: 8px; padding: 8px 12px; overflow-x: auto; flex-shrink: 0;
    background: var(--panel); border-top: 1px solid var(--hairline); align-items: center;
  }
  .history-strip .hlabel { font-size: 0.62rem; font-weight: 650; letter-spacing: 0.14em; color: var(--dim); text-transform: uppercase; white-space: nowrap; }
  .history-chip {
    width: 52px; height: 52px; border-radius: 6px; border: 1px solid var(--border);
    overflow: hidden; cursor: pointer; flex-shrink: 0; position: relative;
  }
  .history-chip:hover { border-color: var(--accent); }
  .history-chip img { width: 100%; height: 100%; object-fit: cover; }
  .history-chip .hseed {
    position: absolute; bottom: 0; left: 0; right: 0; background: rgba(0,0,0,0.65);
    color: #ddd; font-size: 0.52rem; padding: 1px 3px; text-align: center;
  }
  body.dark .history-chip .hseed { background: rgba(0,0,0,0.72); color: #eeeeee; }
  .panels {
    width: 320px; flex-shrink: 0; display: flex; flex-direction: column; gap: 10px;
    padding: 12px; overflow-y: auto; background: var(--panel); border-left: 1px solid var(--hairline);
  }
  .panel { background: var(--panel2); border: 1px solid var(--border); border-radius: var(--radius); padding: 12px; }
  .panel-title { font-size: 0.62rem; font-weight: 650; letter-spacing: 0.12em; color: var(--dim); text-transform: uppercase; margin-bottom: 10px; cursor: pointer; user-select: none; display: flex; align-items: center; justify-content: space-between; }
  .panel .panel-title::after { content: "▾"; font-size: 0.7rem; color: var(--dim); }
  .panel.collapsed .panel-title::after { content: "▸"; }
  .panel.collapsed .panel-body { display: none; }
  .panel label { display: block; font-size: 0.72rem; font-weight: 550; color: var(--muted); margin: 10px 0 4px; }
  .panel label:first-of-type { margin-top: 0; }
  textarea, input[type="text"], input[type="number"], select {
    width: 100%; background: var(--raised); color: var(--text); border: 1px solid var(--border);
    border-radius: 7px; padding: 8px 10px; font-family: inherit; font-size: 0.83rem; resize: vertical;
    transition: border-color 0.15s, box-shadow 0.15s;
  }
  select { appearance: none; background-image: linear-gradient(45deg, transparent 50%, var(--muted) 50%), linear-gradient(135deg, var(--muted) 50%, transparent 50%); background-position: calc(100% - 16px) 50%, calc(100% - 11px) 50%; background-size: 5px 5px; background-repeat: no-repeat; }
  textarea:focus, input:focus, select:focus { outline: none; border-color: var(--accent2); box-shadow: 0 0 0 3px var(--accent-soft); }
  textarea.code { font-family: "IBM Plex Mono", ui-monospace, monospace; font-size: 0.72rem; }
  textarea[readonly] { color: var(--muted); }
  .row { display: flex; gap: 8px; align-items: center; }
  .row > * { flex: 1; }
  .switch { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; }
  .switch input { display: none; }
  .switch .sw {
    display: inline-block;
    width: 34px; height: 20px; border-radius: 999px; background: var(--raised);
    border: 1px solid var(--border); position: relative; flex-shrink: 0; transition: background 0.18s, border-color 0.18s;
  }
  .switch .sw::after {
    content: ""; position: absolute; top: 2px; left: 2px; width: 14px; height: 14px;
    border-radius: 50%; background: var(--muted); transition: transform 0.18s, background 0.18s;
  }
  .switch input:checked + .sw { background: var(--accent); border-color: var(--accent); }
  .switch input:checked + .sw::after { transform: translateX(14px); background: #fff; }
  .switch .sw-label { font-size: 0.75rem; color: var(--muted); }
  .hint { font-size: 0.68rem; color: var(--dim); margin-top: 8px; line-height: 1.4; }
  #examples { display: flex; flex-direction: column; gap: 6px; max-height: 260px; overflow-y: auto; }
  .ex-chip {
    border: 1px solid var(--border); border-radius: 8px; cursor: pointer; flex-shrink: 0;
    background: var(--raised); padding: 7px 10px; text-align: left;
    display: flex; align-items: center; justify-content: space-between; gap: 8px;
    transition: border-color 0.15s; font-family: inherit;
  }
  .ex-chip:hover { border-color: var(--accent); }
  .ex-chip .ex-label { font-size: 0.75rem; color: var(--text); font-weight: 550; }
  .ex-chip .ex-aspect { font-size: 0.62rem; color: var(--lavender); font-family: "IBM Plex Mono", ui-monospace, monospace; }
  #run-btn {
    margin-top: 4px; padding: 12px; border: 1px solid var(--accent); border-radius: 999px; cursor: pointer;
    background: var(--accent); color: var(--button-text); box-shadow: none;
    font-weight: 600; font-size: 0.9rem; letter-spacing: 0.01em; font-family: inherit;
    transition: filter 0.15s, transform 0.05s;
  }
  #run-btn:hover { filter: brightness(1.12); }
  #run-btn:active { transform: translateY(1px); }
  #run-btn:disabled { opacity: 0.5; cursor: wait; }
  .statusbar {
    display: flex; align-items: center; gap: 16px; padding: 7px 16px; flex-shrink: 0;
    background: var(--panel); border-top: 1px solid var(--hairline);
    font-size: 0.75rem; color: var(--muted);
  }
  .statusbar .pulse { width: 8px; height: 8px; border-radius: 50%; background: #4fd1a5; }
  .statusbar.busy .pulse { background: var(--accent2); animation: pulse 1s infinite alternate; }
  @keyframes pulse { from { opacity: 0.4; } to { opacity: 1; } }
  .foot-links { display: flex; gap: 12px; align-items: center; }
  .foot-links a { color: var(--dim); text-decoration: none; font-size: 0.72rem; font-weight: 500; }
  .foot-links a:hover { color: var(--link); }
  #file-input { display: none; }
  @media (max-width: 860px) {
    html, body { height: auto !important; overflow: visible !important; }
    body { display: block; }
    .topbar { flex-wrap: wrap; gap: 8px; padding: 8px 12px; }
    .brand { font-size: 1.1rem; }
    .topbar .ml-badge, .topbar .ml-badge-img { display: none; }
    .main { display: block; height: auto; min-height: 0; }
    .rail {
      flex-direction: row; width: 100%; justify-content: center; gap: 10px;
      padding: 6px 10px; border-right: none; border-bottom: 1px solid var(--hairline);
    }
    .rail button { width: 44px; height: 44px; }
    .viewport { display: block; padding: 10px; overflow: visible; }
    .workflow-view { position: static; height: 78vh; padding: 0 0 10px; }
    .doc-grid { flex-direction: column; align-items: stretch; height: auto; }
    .doc { max-width: 100%; width: 100%; }
    .doc .stage { min-height: 220px; }
    .panels {
      width: 100%; border-left: none; border-top: 1px solid var(--hairline);
      padding: 10px 12px; overflow-y: visible;
    }
    .mode-tabs button { padding: 6px 13px; font-size: 0.8rem; }
    .foot-links { display: none; }
    .statusbar { position: sticky; bottom: 0; }
  }
</style>
</head>
<body>
  <header class="topbar">
    <div class="brand"><span class="j">J</span><span class="e">e</span><span class="v">v</span><span class="rest">eration</span><span class="studio-badge">System One Studio</span></div>
    <div class="mode-tabs">
      <button id="mode-generate" class="active">Generate</button>
      <button id="mode-edit">Edit</button>
      <button id="mode-dense">Dense</button>
      <button id="mode-workflow">Workflow</button>
    </div>
    <div class="spacer"></div>
    <a class="ml-badge-img" href="https://hf.co/chat?mode=ml-intern" target="_blank" rel="noopener">
      <img src="https://huggingface.co/datasets/huggingface/badges/resolve/main/built-with-ml-intern-md.svg" alt="Built with ML Intern" />
    </a>
    <a class="ml-badge" href="https://huggingface.co/linlinlinlinsdada/Jeveration" target="_blank" rel="noopener">Model card</a>
    <a class="ml-badge" href="https://arxiv.org/abs/2611.24738" target="_blank" rel="noopener">Paper</a>
    <button type="button" class="theme-toggle" id="theme-toggle" data-mode="light" aria-label="Switch to dark mode" title="Switch to dark mode">
      <svg class="theme-icon-sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
        <circle cx="12" cy="12" r="4"></circle>
        <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"></path>
      </svg>
      <svg class="theme-icon-moon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
        <path d="M21 14.5A8.5 8.5 0 1 1 9.5 3 7 7 0 0 0 21 14.5z"></path>
      </svg>
    </button>
  </header>

  <div class="main">
    <div class="rail">
      <button id="tool-upload" title="Upload an image"><svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg></button>
      <button id="tool-clear-doc" title="Clear document"><svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg></button>
    </div>

    <div class="viewport">
      <div class="workflow-view" id="workflow-view" hidden>
        <iframe src="/workflow/?ui=canvas" title="Jeveration workflow canvas"></iframe>
      </div>
      <div class="doc-grid">
        <figure class="doc" id="doc-before">
          <figcaption id="before-caption">Source</figcaption>
          <div class="stage" id="before-stage">
            <img id="source-img" alt="" hidden />
            <div class="drop-hint" id="source-hint"><b>No image</b>Use the upload tool or drop a file here</div>
          </div>
        </figure>
        <figure class="doc" id="doc-after">
          <figcaption>Result</figcaption>
          <div class="stage" id="after-stage">
            <img id="result-img" alt="" hidden />
            <div class="split-wrap" id="split-wrap" hidden>
              <img id="split-source" alt="" style="clip-path: inset(0 50% 0 0)" />
              <div class="split-divider" id="split-divider" style="left:50%"></div>
            </div>
            <div class="drop-hint" id="result-hint"><b>Nothing yet</b>Run to see the result</div>
          </div>
          <div class="doc-bar">
            <span id="result-meta">—</span>
            <div class="spacer"></div>
            <button id="split-toggle" hidden>SPLIT</button>
          </div>
        </figure>
        <figure class="doc" id="doc-seg" hidden>
          <figcaption>Segmentation</figcaption>
          <div class="stage" id="seg-stage">
            <img id="seg-img" alt="" hidden />
            <div class="drop-hint" id="seg-hint"><b>Nothing yet</b>Run to see the segmentation</div>
          </div>
        </figure>
        <figure class="doc" id="doc-depth" hidden>
          <figcaption>Depth (nearer is brighter)</figcaption>
          <div class="stage" id="depth-stage">
            <img id="depth-img" alt="" hidden />
            <div class="drop-hint" id="depth-hint"><b>Nothing yet</b>Run to see the depth map</div>
          </div>
        </figure>
        <figure class="doc" id="doc-normal" hidden>
          <figcaption>Surface normals</figcaption>
          <div class="stage" id="normal-stage">
            <img id="normal-img" alt="" hidden />
            <div class="drop-hint" id="normal-hint"><b>Nothing yet</b>Run to see the normals</div>
          </div>
        </figure>
      </div>
      <div class="history-strip" id="history-strip"><span class="hlabel">History</span></div>
    </div>

    <aside class="panels">
      <section class="panel">
        <div class="panel-title">Examples</div>
        <div id="examples"></div>
      </section>
      <section class="panel" id="prompt-panel">
        <div class="panel-title" id="prompt-title">Prompt</div>
        <div class="panel-body">
          <textarea id="prompt" rows="6" placeholder="Describe the image…"></textarea>
          <div class="hint" id="prompt-hint">One 512 × 512 image per run, in a single forward pass.</div>
        </div>
      </section>
      <section class="panel" id="task-panel" hidden>
        <div class="panel-title">Task</div>
        <div class="panel-body">
          <label for="task">Task</label>
          <select id="task"></select>
          <div class="row" style="margin-top:10px">
            <label class="switch"><input type="checkbox" id="from-photo" /><span class="sw"></span><span class="sw-label">Input is a photo: compute its edge / depth map first</span></label>
          </div>
          <div class="hint" id="task-hint"></div>
        </div>
      </section>
      <section class="panel" id="live-panel">
        <div class="panel-title">Realtime</div>
        <div class="panel-body">
          <label class="switch"><input type="checkbox" id="live-toggle" /><span class="sw"></span><span class="sw-label">⚡ Live preview</span></label>
          <div class="hint" id="live-hint">Holds the GPU for ~85 s and re-renders as you type — a fresh 512 × 512 frame whenever the prompt, task or source changes. Full-quality runs queue behind the window; toggle Live off for those.</div>
        </div>
      </section>
      <section class="panel">
        <div class="panel-title">Advanced</div>
        <div class="panel-body">
          <div class="row">
            <div><label for="seed">Seed</label><input type="number" id="seed" value="0" min="0" /></div>
            <label class="switch"><input type="checkbox" id="randomize" checked /><span class="sw"></span><span class="sw-label">Randomize</span></label>
          </div>
        </div>
      </section>
      <section class="panel">
        <div class="panel-title">Run info</div>
        <div class="panel-body">
          <textarea id="run-info" class="code" rows="4" readonly placeholder="Time on the device, depth range and classes appear here after a run."></textarea>
        </div>
      </section>
      <button id="run-btn">Generate</button>
    </aside>
  </div>

  <footer class="statusbar" id="statusbar">
    <div class="pulse"></div>
    <span id="status">Idle</span>
    <div class="spacer"></div>
    <span class="foot-links">
      <a href="https://arxiv.org/abs/2611.24738" target="_blank" rel="noopener">arXiv</a>
      <a href="https://github.com/Carol-lyh/Jeveration" target="_blank" rel="noopener">GitHub</a>
      <a href="https://carol-lyh.github.io/Jeveration/" target="_blank" rel="noopener">Project page</a>
    </span>
    <span id="seed-out"></span>
  </footer>

  <input type="file" id="file-input" accept="image/*" />

<script type="module">
  import { client } from "https://cdn.jsdelivr.net/npm/@gradio/client@2.7.1/dist/index.min.js";

  const $ = (id) => document.getElementById(id);
  const state = { mode: "generate", sourcePath: null, app: null, sid: null, liveJob: null, liveOn: false, liveFrames: 0 };
  const docState = { source: null, result: null };
  const histories = { generate: [], edit: [], dense: [] };   // one history per tab, app-side

  const TASKS = ["hed", "depth", "colorize", "anime", "ghibli", "watercolor"];
  const TASK_HELP = {
    hed: "Input: a soft edge map (white edges on black), or a photo with the switch below on. Add a caption.",
    depth: "Input: a depth map (bright = near), or a photo with the switch below on. Add a caption.",
    colorize: "Input: a photo. It is read as a grey picture and colorized.",
    anime: "Input: a photo.", ghibli: "Input: a photo.", watercolor: "Input: a photo.",
  };
  const T2I_EXAMPLES = [
    "An oil painting of sunflowers in a blue ceramic vase, thick brush strokes.",
    "An owl with bright yellow eyes perched on a mossy branch at twilight, warm golden backlight, detailed feathers.",
    "An impressionist oil painting of a bouquet of peonies in a vase.",
    "A stone cottage with a thatched roof and a flower garden in the countryside.",
    "A watercolor painting of a sailboat on a calm sea at sunset.",
    "A lone pine tree on a small island in a calm lake at dawn.",
    "A watercolor painting of a snowy village at dusk with warm lit windows.",
    "A burger with melted cheese, lettuce and tomato on a wooden board, close-up.",
    "A painting in the style of Van Gogh of a starry night over a quiet village with a swirling sky.",
    "A small white chapel on a green alpine meadow with snowy peaks behind.",
    "A spirit fox made of glowing blue flames sitting in a dark forest, magical atmosphere.",
    "A river winding through a green valley with snowy mountains in the distance.",
    "An oil painting of a mountain lake in autumn with golden trees, visible brush strokes.",
    "A bouquet of tulips in a glass vase on a windowsill, soft morning light.",
    "A lion's face with a golden mane at sunset, savanna grass, cinematic lighting.",
    "A waterfall cascading into an emerald pool in a tropical jungle, sun rays through the mist.",
    "A Chinese ink wash painting of misty mountains and a lone boat on a river.",
    "A stack of fluffy pancakes with blueberries and maple syrup dripping down, butter on top, morning light.",
    "A snowy mountain cabin with warm glowing windows at blue hour, surrounded by pine trees.",
    "A close-up portrait of a woman wearing a flower crown in a meadow, dreamy pastel tones.",
  ];
  const I2I_EXAMPLES = [
    { file: "hed_puppy.png", task: "hed", caption: "A fluffy white Samoyed puppy smiling in a field of yellow flowers on a sunny afternoon.", photo: false },
    { file: "hed_tulips.png", task: "hed", caption: "A bouquet of tulips in a glass vase on a windowsill, soft morning light.", photo: false },
    { file: "photo_owl.jpg", task: "hed", caption: "An owl with bright yellow eyes perched on a mossy branch at twilight, warm golden backlight, detailed feathers.", photo: true },
    { file: "depth_pancakes.png", task: "depth", caption: "A stack of fluffy pancakes with blueberries and maple syrup dripping down, butter on top, morning light.", photo: false },
    { file: "photo_croissant.jpg", task: "depth", caption: "A golden croissant on a marble table next to a cup of coffee, soft morning light.", photo: true },
    { file: "gray_burger.jpg", task: "colorize", caption: "", photo: false },
    { file: "gray_pancakes.jpg", task: "colorize", caption: "", photo: false },
    { file: "photo_boathouse.jpg", task: "anime", caption: "", photo: false },
    { file: "photo_waterfall.jpg", task: "anime", caption: "", photo: false },
    { file: "photo_pine.jpg", task: "ghibli", caption: "", photo: false },
    { file: "photo_valley.jpg", task: "ghibli", caption: "", photo: false },
    { file: "photo_chapel.jpg", task: "watercolor", caption: "", photo: false },
    { file: "photo_snowcabin.jpg", task: "watercolor", caption: "", photo: false },
  ];
  const DENSE_EXAMPLES = ["room_1.png", "room_2.png", "room_3.png", "room_4.png"];

  async function getApp() {
    if (!state.app) state.app = await client(location.origin);
    return state.app;
  }

  async function uploadFile(file) {
    const form = new FormData();
    form.append("files", file);
    const resp = await fetch("/gradio_api/upload", { method: "POST", body: form });
    if (!resp.ok) throw new Error(`Upload failed (${resp.status})`);
    const paths = await resp.json();
    return Array.isArray(paths) ? paths[0] : paths;
  }

  async function uploadExampleUrl(url, name) {
    const resp = await fetch(url);
    if (!resp.ok) throw new Error(`Could not load ${name} (${resp.status})`);
    const blob = await resp.blob();
    return uploadFile(new File([blob], name, { type: blob.type || "image/png" }));
  }

  function setStatus(text, busy = false) {
    $("status").textContent = text;
    $("statusbar").classList.toggle("busy", busy);
    $("run-btn").disabled = busy;
  }

  // ---------- theme ----------
  const themeBtn = $("theme-toggle");
  function applyTheme(mode) {
    document.body.classList.toggle("dark", mode === "dark");
    themeBtn.dataset.mode = mode;
    const label = mode === "dark" ? "Switch to light mode" : "Switch to dark mode";
    themeBtn.setAttribute("aria-label", label);
    themeBtn.setAttribute("title", label);
    try { localStorage.setItem("jeveration-theme", mode); } catch (e) {}
  }
  themeBtn.onclick = () => applyTheme(document.body.classList.contains("dark") ? "light" : "dark");
  (function initTheme() {
    let mode = "light";
    try { if (localStorage.getItem("jeveration-theme") === "dark") mode = "dark"; } catch (e) {}
    applyTheme(mode);
  })();

  function setMode(mode) {
    state.mode = mode;
    for (const m of ["generate", "edit", "dense", "workflow"]) $(`mode-${m}`).classList.toggle("active", mode === m);
    const workflow = mode === "workflow";
    $("workflow-view").hidden = !workflow;
    document.querySelector(".doc-grid").style.display = workflow ? "none" : "";
    document.querySelector(".rail").style.display = workflow ? "none" : "";
    document.querySelector(".panels").style.display = workflow ? "none" : "";
    $("history-strip").style.display = workflow ? "none" : "";
    if (workflow) {
      setStatus("Chain Generate, Edit and Dense nodes into one pipeline");
      return;
    }
    const dense = mode === "dense";
    const edit = mode === "edit";
    if ((dense || mode === "workflow") && state.liveOn) setLive(false);   // live preview is a generate/edit tool
    $("live-panel").hidden = dense || mode === "workflow";
    $("doc-before").style.display = "";
    $("doc-after").style.display = dense ? "none" : "";
    for (const id of ["doc-seg", "doc-depth", "doc-normal"]) $(id).style.display = dense ? "" : "none";
    $("task-panel").hidden = !edit;
    $("prompt-title").textContent = edit ? "Caption" : "Prompt";
    $("prompt").placeholder = edit ? "Caption of the wanted image (hed / depth)" : "Describe the image…";
    $("prompt-hint").textContent = edit
      ? "A caption is used by the hed and depth tasks; the other tasks read the input alone."
      : "One 512 × 512 image per run, in a single forward pass.";
    $("run-btn").textContent = dense ? "Predict" : edit ? "Generate Edit" : "Generate";
    $("split-toggle").hidden = !(edit && !$("result-img").hidden && !$("source-img").hidden);
    renderExamples();
    renderHistory();
  }
  $("mode-generate").onclick = () => setMode("generate");
  $("mode-edit").onclick = () => setMode("edit");
  $("mode-dense").onclick = () => setMode("dense");
  $("mode-workflow").onclick = () => setMode("workflow");

  // ---------- task select ----------
  const taskSel = $("task");
  for (const t of TASKS) {
    const opt = document.createElement("option");
    opt.value = t;
    opt.textContent = t;
    taskSel.appendChild(opt);
  }
  taskSel.value = "hed";
  taskSel.onchange = () => { $("task-hint").textContent = TASK_HELP[taskSel.value]; };

  // ---------- realtime live preview ----------
  // The pattern from akhaliq/p-h3-image-2step: a held-GPU session on the app streams a fresh
  // frame whenever the session's request changes; edits here just rewrite the request channel
  // (/live_push, no GPU). The window starts only when the toggle flips — never on page load.
  function getSid() {
    if (!state.sid) state.sid = (crypto.randomUUID ? crypto.randomUUID()
                                                   : String(Math.random()).slice(2) + Date.now());
    return state.sid;
  }
  let livePushTimer = null;
  async function pushLive() {
    if (!state.liveOn) return;
    try {
      const app = await getApp();
      await app.predict("/live_push", {
        prompt: $("prompt").value.trim(),
        task: taskSel.value,
        caption: $("prompt").value.trim(),
        from_photo: $("from-photo").checked,
        seed: parseInt($("seed").value, 10) || 0,
        source: state.sourcePath || "",
        sid: getSid(),
      });
    } catch (err) { /* the next change retries */ }
  }
  function queueLivePush() {
    if (!state.liveOn) return;
    clearTimeout(livePushTimer);
    livePushTimer = setTimeout(pushLive, 300);
  }
  function applyLiveFrame(payload) {
    if (typeof payload.image_data === "string") {
      const img = $("result-img");
      img.src = payload.image_data;
      img.hidden = false;
      $("result-hint").style.display = "none";
      docState.result = payload.image_data;
    }
    if (typeof payload.source_data === "string" && state.mode === "edit") {
      showSourceImage(payload.source_data);
      $("before-caption").textContent = "Input as the model reads it (512 × 512)";
    }
    if (payload.seed != null) $("seed-out").textContent = "seed " + payload.seed;
    $("result-meta").textContent = (payload.info || "") + " · live";
    $("run-info").value = payload.info || "";
    state.liveFrames += 1;
    setStatus(`Live · ${state.liveFrames} frame${state.liveFrames === 1 ? "" : "s"} this window`, true);
  }
  async function setLive(on) {
    state.liveOn = on;
    $("live-toggle").checked = on;
    if (on) {
      if (state.mode !== "generate" && state.mode !== "edit") return;
      state.liveFrames = 0;
      setStatus("Starting the live window…", true);
      await pushLive();
      try {
        const app = await getApp();
        const job = app.submit("/live_session", { sid: getSid(), realtime_on: true });
        state.liveJob = job;
        for await (const msg of job) {
          const payload = Array.isArray(msg?.data) ? msg.data[0] : msg?.data;
          if (payload && typeof payload === "object" && payload.image_data) applyLiveFrame(payload);
        }
        state.liveOn = false;
        $("live-toggle").checked = false;
        setStatus(`Live window ended after ${state.liveFrames} frame${state.liveFrames === 1 ? "" : "s"} — toggle Live again for a new one`);
      } catch (err) {
        if (state.liveOn) setStatus(err?.message || String(err));
      } finally {
        state.liveJob = null;
      }
    } else {
      clearTimeout(livePushTimer);
      try { await state.liveJob?.cancel?.(); } catch (e) {}
      state.liveJob = null;
      setStatus("Idle");
    }
  }
  $("live-toggle").onchange = () => setLive($("live-toggle").checked);
  $("prompt").addEventListener("input", queueLivePush);
  taskSel.addEventListener("change", queueLivePush);
  $("from-photo").addEventListener("change", queueLivePush);
  $("seed").addEventListener("input", queueLivePush);

  // ---------- uploads ----------
  $("tool-upload").onclick = () => { $("file-input").click(); };
  $("file-input").onchange = async (e) => {
    const file = e.target.files[0];
    e.target.value = "";
    if (!file) return;
    setStatus("Uploading…", true);
    try {
      state.sourcePath = await uploadFile(file);
      showLocalSource(file);
      if (state.mode === "generate") setMode("edit");
      queueLivePush();
      setStatus("Idle");
    } catch (err) {
      setStatus(String(err));
    }
  };
  $("before-stage").addEventListener("dragover", (e) => e.preventDefault());
  $("before-stage").addEventListener("drop", async (e) => {
    e.preventDefault();
    const file = e.dataTransfer.files[0];
    if (!file) return;
    setStatus("Uploading…", true);
    try {
      state.sourcePath = await uploadFile(file);
      showLocalSource(file);
      if (state.mode === "generate") setMode("edit");
      queueLivePush();
      setStatus("Idle");
    } catch (err) {
      setStatus(String(err));
    }
  });

  function showLocalSource(file) {
    showSourceImage(URL.createObjectURL(file));
    $("before-caption").textContent = "Source";
  }
  function showSourceImage(src) {
    const img = $("source-img");
    img.src = src;
    img.hidden = false;
    $("source-hint").style.display = "none";
    docState.source = src;
  }

  $("tool-clear-doc").onclick = () => {
    state.sourcePath = null;
    docState.source = null;
    docState.result = null;
    $("source-img").hidden = true;
    $("source-hint").style.display = "";
    $("result-img").hidden = true;
    $("result-hint").style.display = "";
    $("result-meta").textContent = "—";
    $("seed-out").textContent = "";
    $("run-info").value = "";
    $("split-toggle").hidden = true;
    $("split-wrap").hidden = true;
    for (const [img, hint] of [["seg-img", "seg-hint"], ["depth-img", "depth-hint"], ["normal-img", "normal-hint"]]) {
      $(img).hidden = true;
      $(hint).style.display = "";
    }
  };

  // ---------- history ----------
  // Each tab renders only its own history: a chip restores its run into its own tab only,
  // so a Dense input never shows up as an Edit source or a Generate prompt.
  function renderHistory() {
    const strip = $("history-strip");
    strip.innerHTML = '<span class="hlabel">History</span>';
    (histories[state.mode] || []).forEach((h) => {
      const chip = document.createElement("div");
      chip.className = "history-chip";
      chip.title = h.prompt || h.info || "";
      const img = document.createElement("img");
      img.src = h.thumb;
      const tag = document.createElement("div");
      tag.className = "hseed";
      tag.textContent = h.seed ?? "";
      chip.appendChild(img);
      chip.appendChild(tag);
      chip.onclick = () => restoreRun(h);
      strip.appendChild(chip);
    });
  }
  function pushHistory(entry) {
    const list = histories[entry.mode] || (histories[entry.mode] = []);
    list.unshift(entry);
    if (list.length > 8) list.pop();
    renderHistory();
  }

  function restoreRun(h) {
    setMode(h.mode);
    if (h.mode !== "dense") {
      $("prompt").value = h.prompt || "";
      if (h.source_uri) showSourceImage(h.source_uri);
      else { $("source-img").hidden = true; $("source-hint").style.display = ""; }
      docState.result = h.result_uri;
      const img = $("result-img");
      img.src = h.result_uri;
      img.hidden = false;
      $("result-hint").style.display = "none";
      $("result-meta").textContent = h.info || "—";
      $("split-toggle").hidden = !h.source_uri;
    } else {
      if (h.source_uri) { showSourceImage(h.source_uri); $("before-caption").textContent = "Input"; }
      for (const [img, hint, uri] of [["seg-img", "seg-hint", h.seg_uri], ["depth-img", "depth-hint", h.depth_uri], ["normal-img", "normal-hint", h.normal_uri]]) {
        const el = $(img);
        if (uri) { el.src = uri; el.hidden = false; $(hint).style.display = "none"; }
      }
    }
    if (h.task) { taskSel.value = h.task; $("task-hint").textContent = TASK_HELP[h.task]; }
    if (h.from_photo != null) $("from-photo").checked = h.from_photo;
    if (h.seed != null) { $("seed").value = h.seed; $("randomize").checked = false; }
    $("run-info").value = h.info || "";
  }

  // ---------- before/after split view ----------
  let splitOn = false;
  $("split-toggle").onclick = () => {
    if ($("result-img").hidden) return;
    splitOn = !splitOn;
    $("split-toggle").classList.toggle("active", splitOn);
    $("split-wrap").hidden = !splitOn;
    if (splitOn && !$("source-img").hidden) $("split-source").src = $("source-img").src;
  };
  (function () {
    const divider = $("split-divider");
    let dragging = false;
    divider.addEventListener("pointerdown", (e) => { dragging = true; e.preventDefault(); });
    window.addEventListener("pointermove", (e) => {
      if (!dragging) return;
      const stage = $("after-stage").getBoundingClientRect();
      const pct = Math.min(97, Math.max(3, ((e.clientX - stage.left) / stage.width) * 100));
      divider.style.left = pct + "%";
      $("split-source").style.clipPath = `inset(0 ${100 - pct}% 0 0)`;
    });
    window.addEventListener("pointerup", () => { dragging = false; });
  })();

  // ---------- zoom ----------
  document.querySelectorAll(".doc figcaption").forEach((caption) => {
    const btn = document.createElement("button");
    btn.className = "zoom-btn";
    btn.textContent = "FIT";
    btn.onclick = () => {
      const img = caption.parentElement.querySelector("img");
      const stage = caption.parentElement.querySelector(".stage");
      const zoomed = img.classList.toggle("zoomed");
      stage.classList.toggle("scrollable", zoomed);
      btn.textContent = zoomed ? "1:1" : "FIT";
    };
    caption.appendChild(btn);
  });

  // ---------- collapsible panels ----------
  document.querySelectorAll(".panel .panel-title").forEach((title) => {
    const body = document.createElement("div");
    body.className = "panel-body";
    [...title.parentElement.children].forEach((child) => {
      if (child !== title) body.appendChild(child);
    });
    title.parentElement.appendChild(body);
    title.onclick = () => title.parentElement.classList.toggle("collapsed");
  });

  // ---------- examples ----------
  function renderExamples() {
    const exRow = $("examples");
    exRow.innerHTML = "";
    if (state.mode === "generate") {
      T2I_EXAMPLES.forEach((prompt) => {
        const chip = document.createElement("button");
        chip.className = "ex-chip";
        const label = document.createElement("span");
        label.className = "ex-label";
        label.textContent = prompt.length > 56 ? prompt.slice(0, 54) + "…" : prompt;
        const tag = document.createElement("span");
        tag.className = "ex-aspect";
        tag.textContent = "512²";
        chip.appendChild(label);
        chip.appendChild(tag);
        chip.onclick = () => {
          // ---------- ZeroGPU quota handshake for the workflow canvas ----------
  // The canvas iframe can't complete gradio's postMessage handshake with huggingface.co, so its
  // GPU calls would bill the Space's anonymous allowance (the quota error on the Workflow tab).
  // The studio page's own @gradio/client calls carry the visitor's x-ip-token; /handshake
  // stashes it server-side per client IP for the canvas's runs to re-attach.
  getApp().then((app) => app.predict("/handshake", {})).catch(() => {});
  setInterval(() => { getApp().then((app) => app.predict("/handshake", {})).catch(() => {}); }, 60000);

  setMode("generate");
          $("prompt").value = prompt;
          setStatus("Example loaded — hit Generate");
        };
        exRow.appendChild(chip);
      });
    } else if (state.mode === "edit") {
      I2I_EXAMPLES.forEach((ex) => {
        const chip = document.createElement("button");
        chip.className = "ex-chip";
        const label = document.createElement("span");
        label.className = "ex-label";
        label.textContent = `${ex.task} — ${ex.file}`;
        const tag = document.createElement("span");
        tag.className = "ex-aspect";
        tag.textContent = ex.photo ? "photo" : "map";
        chip.appendChild(label);
        chip.appendChild(tag);
        chip.onclick = async () => {
          setMode("edit");
          taskSel.value = ex.task;
          $("task-hint").textContent = TASK_HELP[ex.task];
          $("from-photo").checked = ex.photo;
          $("prompt").value = ex.caption;
          setStatus("Loading example…", true);
          try {
            state.sourcePath = await uploadExampleUrl(`/examples/${ex.file}`, ex.file);
            showSourceImage(`/examples/${ex.file}`);
            $("before-caption").textContent = "Source";
            queueLivePush();
            setStatus("Example loaded — hit Generate Edit");
          } catch (err) {
            setStatus(String(err));
          }
        };
        exRow.appendChild(chip);
      });
    } else {
      DENSE_EXAMPLES.forEach((file) => {
        const chip = document.createElement("button");
        chip.className = "ex-chip";
        const label = document.createElement("span");
        label.className = "ex-label";
        label.textContent = file;
        chip.appendChild(label);
        chip.onclick = async () => {
          setMode("dense");
          setStatus("Loading example…", true);
          try {
            state.sourcePath = await uploadExampleUrl(`/examples/${file}`, file);
            showSourceImage(`/examples/${file}`);
            $("before-caption").textContent = "Input";
            setStatus("Example loaded — hit Predict");
          } catch (err) {
            setStatus(String(err));
          }
        };
        exRow.appendChild(chip);
      });
    }
  }

  // ---------- result handling ----------
  function unwrap(result) {
    const data = Array.isArray(result?.data) ? result.data[0] : result?.data;
    return data ?? {};
  }

  $("run-btn").onclick = async () => {
    const app = await getApp();
    const prompt = $("prompt").value.trim();
    const seed = parseInt($("seed").value, 10) || 0;
    const randomize = $("randomize").checked;
    try {
      if (state.mode === "generate") {
        if (!prompt) { setStatus("Write a prompt first."); return; }
        setStatus("Rendering one 512 × 512 image in a single pass…", true);
        const payload = unwrap(await app.predict("/generate", { prompt, seed, randomize }));
        const uri = typeof payload.image_data === "string" ? payload.image_data : null;
        if (!uri) { setStatus("Run finished but no image came back (see console)."); return; }
        showResult(uri, payload);
        pushHistory({ mode: "generate", thumb: uri, result_uri: uri, source_uri: null, seed: payload.seed,
                      prompt, info: payload.info });
      } else if (state.mode === "edit") {
        if (!state.sourcePath) { setStatus("Upload an image first."); return; }
        setStatus("Editing…", true);
        const payload = unwrap(await app.predict("/edit", {
          source: state.sourcePath,
          task: taskSel.value,
          caption: prompt,
          from_photo: $("from-photo").checked,
          seed, randomize,
        }));
        const uri = typeof payload.image_data === "string" ? payload.image_data : null;
        if (!uri) { setStatus("Run finished but no image came back (see console)."); return; }
        const preparedUri = typeof payload.source_data === "string" ? payload.source_data : null;
        if (preparedUri) { showSourceImage(preparedUri); $("before-caption").textContent = "Input as the model reads it (512 × 512)"; }
        showResult(uri, payload);
        pushHistory({ mode: "edit", thumb: uri, result_uri: uri, source_uri: preparedUri, seed: payload.seed,
                      prompt, task: taskSel.value, from_photo: $("from-photo").checked, info: payload.info });
      } else {
        if (!state.sourcePath) { setStatus("Upload a picture first."); return; }
        setStatus("Predicting segmentation, depth and normals…", true);
        const payload = unwrap(await app.predict("/dense", { image: state.sourcePath }));
        const uris = {
          seg: payload.seg_data, depth: payload.depth_data, normal: payload.normal_data,
        };
        let any = false;
        for (const [img, hint, key] of [["seg-img", "seg-hint", "seg"], ["depth-img", "depth-hint", "depth"], ["normal-img", "normal-hint", "normal"]]) {
          const uri = typeof uris[key] === "string" ? uris[key] : null;
          const el = $(img);
          if (uri) { el.src = uri; el.hidden = false; $(hint).style.display = "none"; any = true; }
          else { el.hidden = true; $(hint).style.display = ""; }
        }
        if (!any) { setStatus("Run finished but no outputs came back (see console)."); return; }
        $("result-meta").textContent = payload.info || "Done";
        $("run-info").value = payload.info || "";
        $("seed-out").textContent = "";
        pushHistory({ mode: "dense", thumb: uris.seg, seg_uri: uris.seg, depth_uri: uris.depth, normal_uri: uris.normal,
                      source_uri: $("source-img").src, info: payload.info });
      }
      setStatus("Done");
    } catch (err) {
      setStatus(err?.message || String(err));
    }
  };

  function showResult(uri, payload) {
    const img = $("result-img");
    img.src = uri;
    img.hidden = false;
    $("result-hint").style.display = "none";
    docState.result = uri;
    if (payload.seed != null) $("seed-out").textContent = "seed " + payload.seed;
    $("result-meta").textContent = payload.info || "Done";
    $("run-info").value = payload.info || "";
    splitOn = false;
    $("split-wrap").hidden = true;
    $("split-toggle").classList.remove("active");
    $("split-toggle").hidden = !(state.mode === "edit" && !$("source-img").hidden);
  }

  setMode("generate");
</script>
</body>
</html>