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 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
function set_theme(theme) {
  /*
  var gradioURL = window.location.href;
  if (!gradioURL.includes('?__theme=')) {
      window.location.replace(gradioURL + '?__theme=' + theme);
  }
  */
}

var selectedTabItemId = "tab_txt2img";

function all_gallery_buttons() {
  var allGalleryButtons = gradioApp().querySelectorAll('[style="display: block;"].tabitem div[id$=_gallery].gradio-gallery .thumbnails > .thumbnail-item.thumbnail-small');
  var visibleGalleryButtons = [];
  allGalleryButtons.forEach(function(elem) {
      if (elem.parentElement.offsetParent) {
          visibleGalleryButtons.push(elem);
      }
  });
  return visibleGalleryButtons;
}

function selected_gallery_button() {
  var allCurrentButtons = gradioApp().querySelectorAll('[style="display: block;"].tabitem div[id$=_gallery].gradio-gallery .thumbnail-item.thumbnail-small.selected');
  var visibleCurrentButton = null;
  allCurrentButtons.forEach(function(elem) {
      if (elem.parentElement.offsetParent) {
          visibleCurrentButton = elem;
      }
  });
  return visibleCurrentButton;
}

function selected_gallery_index() {
  var buttons = all_gallery_buttons();
  var button = selected_gallery_button();

  var result = -1;
  buttons.forEach(function(v, i) {
      if (v == button) {
          result = i;
      }
  });

  return result;
}

function extract_image_from_gallery(gallery) {
  if (gallery.length == 0) {
      return [null];
  }
  if (gallery.length == 1) {
      return [gallery[0]];
  }

  var index = selected_gallery_index();

  if (index < 0 || index >= gallery.length) {
      // Use the first image in the gallery as the default
      index = 0;
  }

  return [gallery[index]];
}

window.args_to_array = Array.from; // Compatibility with e.g. extensions that may expect this to be around

function switch_to_txt2img() {
  gradioApp().querySelector('#tabs').querySelectorAll('button')[0].click();

  return Array.from(arguments);
}

function switch_to_img2img_tab(no) {
  gradioApp().querySelector('#tabs').querySelectorAll('button')[1].click();
  gradioApp().getElementById('mode_img2img').querySelectorAll('button')[no].click();
}
function switch_to_img2img() {
  switch_to_img2img_tab(0);
  return Array.from(arguments);
}

function switch_to_sketch() {
  switch_to_img2img_tab(1);
  return Array.from(arguments);
}

function switch_to_inpaint() {
  switch_to_img2img_tab(2);
  return Array.from(arguments);
}

function switch_to_inpaint_sketch() {
  switch_to_img2img_tab(3);
  return Array.from(arguments);
}

function switch_to_extras() {
  gradioApp().querySelector('#tabs').querySelectorAll('button')[2].click();

  return Array.from(arguments);
}

function get_tab_index(tabId) {
  let buttons = gradioApp().getElementById(tabId).querySelector('div').querySelectorAll('button');
  for (let i = 0; i < buttons.length; i++) {
      if (buttons[i].classList.contains('selected')) {
          return i;
      }
  }
  return 0;
}

function create_tab_index_args(tabId, args) {
  var res = Array.from(args);
  res[0] = get_tab_index(tabId);
  return res;
}

function get_img2img_tab_index() {
  let res = Array.from(arguments);
  res.splice(-2);
  res[0] = get_tab_index('mode_img2img');
  return res;
}

function create_submit_args(args) {
  var res = Array.from(args);

  // As it is currently, txt2img and img2img send back the previous output args (txt2img_gallery, generation_info, html_info) whenever you generate a new image.
  // This can lead to uploading a huge gallery of previously generated images, which leads to an unnecessary delay between submitting and beginning to generate.
  // I don't know why gradio is sending outputs along with inputs, but we can prevent sending the image gallery here, which seems to be an issue for some.
  // If gradio at some point stops sending outputs, this may break something
  if (Array.isArray(res[res.length - 3])) {
      res[res.length - 3] = null;
  }

  return res;
}

function showSubmitButtons(tabname, show) {
  gradioApp().getElementById(tabname + "_interrupt").style.display = show ? "none" : "flex";
  gradioApp().getElementById(tabname + "_skip").style.display = show ? "none" : "flex";
  gradioApp().getElementById(tabname + "_generate").style.display = !show ? "none" : "flex";
}

function showRestoreProgressButton(tabname, show) {
  var button = gradioApp().getElementById(tabname + "_restore_progress");
  if (!button) return;

  button.style.display = show ? "flex" : "none";
}


function submit() {
  showSubmitButtons('txt2img', false);

  var id = randomId();
  localStorage.setItem("txt2img_task_id", id);

  requestProgress(id, gradioApp().getElementById('txt2img_gallery_container'), gradioApp().getElementById('txt2img_gallery'), function() {
      showSubmitButtons('txt2img', true);
      localStorage.removeItem("txt2img_task_id");
      showRestoreProgressButton('txt2img', false);
  });

  var res = create_submit_args(arguments);

  res[0] = id;

  return res;
}

function submit_img2img() {
  showSubmitButtons('img2img', false);

  var id = randomId();
  localStorage.setItem("img2img_task_id", id);

  requestProgress(id, gradioApp().getElementById('img2img_gallery_container'), gradioApp().getElementById('img2img_gallery'), function() {
      showSubmitButtons('img2img', true);
      localStorage.removeItem("img2img_task_id");
      showRestoreProgressButton('img2img', false);
  });

  var res = create_submit_args(arguments);

  res[0] = id;
  res[1] = get_tab_index('mode_img2img');

  return res;
}

function restoreProgressTxt2img() {
  showRestoreProgressButton("txt2img", false);
  var id = localStorage.getItem("txt2img_task_id");

  id = localStorage.getItem("txt2img_task_id");

  if (id) {
      requestProgress(id, gradioApp().getElementById('txt2img_gallery_container'), gradioApp().getElementById('txt2img_gallery'), function() {
          showSubmitButtons('txt2img', true);
      }, null, 0);
  }

  return id;
}

function restoreProgressImg2img() {
  showRestoreProgressButton("img2img", false);

  var id = localStorage.getItem("img2img_task_id");

  if (id) {
      requestProgress(id, gradioApp().getElementById('img2img_gallery_container'), gradioApp().getElementById('img2img_gallery'), function() {
          showSubmitButtons('img2img', true);
      }, null, 0);
  }

  return id;
}

onUiLoaded(function() {
  showRestoreProgressButton('txt2img', localStorage.getItem("txt2img_task_id"));
  showRestoreProgressButton('img2img', localStorage.getItem("img2img_task_id"));
});


function modelmerger() {
  var id = randomId();
  requestProgress(id, gradioApp().getElementById('modelmerger_results_panel'), null, function() {});

  var res = create_submit_args(arguments);
  res[0] = id;
  return res;
}


function ask_for_style_name(_, prompt_text, negative_prompt_text) {
  var name_ = prompt('Style name:');
  return [name_, prompt_text, negative_prompt_text];
}

function confirm_clear_prompt(prompt, negative_prompt) {
  if (confirm("Delete prompt?")) {
      prompt = "";
      negative_prompt = "";
  }

  return [prompt, negative_prompt];
}


var promptTokecountUpdateFuncs = {};

function recalculatePromptTokens(name) {
  if (promptTokecountUpdateFuncs[name]) {
      promptTokecountUpdateFuncs[name]();
  }
}

function recalculate_prompts_txt2img() {
  recalculatePromptTokens('txt2img_prompt');
  recalculatePromptTokens('txt2img_neg_prompt');
  return Array.from(arguments);
}

function recalculate_prompts_img2img() {
  recalculatePromptTokens('img2img_prompt');
  recalculatePromptTokens('img2img_neg_prompt');
  return Array.from(arguments);
}


var opts = {};
onUiUpdate(function() {
  
  if (Object.keys(opts).length != 0) return;

  var json_elem = gradioApp().getElementById("settings_json");
  if (json_elem == null) return;

  var textarea = json_elem.querySelector("textarea");
  var jsdata = textarea.value;
  opts = JSON.parse(jsdata);
  executeCallbacks(optionsChangedCallbacks);

  Object.defineProperty(textarea, "value", {
    set: function (newValue) {
      var valueProp = Object.getOwnPropertyDescriptor(
        HTMLTextAreaElement.prototype,
        "value"
      );
      var oldValue = valueProp.get.call(textarea);
      valueProp.set.call(textarea, newValue);

      if (oldValue != newValue) {
        opts = JSON.parse(textarea.value);
      }

      executeCallbacks(optionsChangedCallbacks);
    },
    get: function () {
      var valueProp = Object.getOwnPropertyDescriptor(
        HTMLTextAreaElement.prototype,
        "value"
      );
      return valueProp.get.call(textarea);
    },
  });

  //console.log(opts);

  json_elem.parentElement.style.display = "none";

  function registerTextarea(id, id_counter, id_button) {
    var prompt = gradioApp().getElementById(id);
    var counter = gradioApp().getElementById(id_counter);
    var textarea = gradioApp().querySelector("#" + id + " > label > textarea");

    if (counter.parentElement == prompt.parentElement) {
      return;
    }

    prompt.parentElement.insertBefore(counter, prompt);
    counter.classList.add("token-counter");
    prompt.parentElement.style.position = "relative";

    promptTokecountUpdateFuncs[id] = function () {
      update_token_counter(id_button);
    };
    textarea.addEventListener("input", promptTokecountUpdateFuncs[id]);
  }

  registerTextarea(
    "txt2img_prompt",
    "txt2img_token_counter",
    "txt2img_token_button"
  );
  registerTextarea(
    "txt2img_neg_prompt",
    "txt2img_negative_token_counter",
    "txt2img_negative_token_button"
  );
  registerTextarea(
    "img2img_prompt",
    "img2img_token_counter",
    "img2img_token_button"
  );
  registerTextarea(
    "img2img_neg_prompt",
    "img2img_negative_token_counter",
    "img2img_negative_token_button"
  );

  var show_all_pages = gradioApp().getElementById("settings_show_all_pages");
  var settings_tabs = gradioApp().querySelector("#settings div");
  if (show_all_pages && settings_tabs) {
    settings_tabs.appendChild(show_all_pages);
    show_all_pages.onclick = function () {
      gradioApp()
        .querySelectorAll("#settings > div")
        .forEach(function (elem) {
          elem.style.display = "block";
        });
      gradioApp()
        .querySelectorAll("#settings > div > div > div")
        .forEach(function (elem) {
          elem.style.maxHeight = "none";
        });
    };
  }
  /* 	
	^ matches the start
	* matches any position
	$ matches the end
	*/
  /* anapnoe ui start	*/

  /* auto grow textarea */
  function autoGrowPromptTextarea() {
    gradioApp()
      .querySelectorAll('[id$="_prompt"] textarea')
      .forEach(function (elem) {
        elem.parentElement.click();
      });
  }

  gradioApp()
    .querySelectorAll(
      '[id$="_prompt"] textarea, [id^="setting_"] textarea, textarea'
    )
    .forEach(function (elem) {
      elem.style.boxSizing = "border-box";
      var offset = elem.offsetHeight - elem.clientHeight;
      elem.addEventListener("input", function (e) {
        e.target.style.minHeight = "auto";
        e.target.style.minHeight = e.target.scrollHeight + offset + 2 + "px";
      });

      elem.parentElement.addEventListener("click", function (e) {
        let textarea = e.currentTarget.querySelector("textarea");
        textarea.style.minHeight = "auto";
        textarea.style.minHeight = textarea.scrollHeight + offset + 2 + "px";
      });
    });

  /* resizable split view */
  const resizeEvent = window.document.createEvent("UIEvents");
  resizeEvent.initUIEvent("resize", true, false, window, 0);

  gradioApp()
    .querySelectorAll('[id $="2img_splitter"]')
    .forEach((elem) => {
      elem.addEventListener("mousedown", function (e) {
        e.preventDefault();

        let resizer = e.currentTarget;
        let container = resizer.parentElement;

        let flexDir = window
          .getComputedStyle(container)
          .getPropertyValue("flex-direction");

        let leftSide = resizer.previousElementSibling;
        let rightSide = resizer.nextElementSibling;

        let dir = flexDir == "row-reverse" ? -1.0 : 1.0;

        let x = e.clientX;
        let y = e.clientY;
        let leftWidth = leftSide.getBoundingClientRect().width;

        function mouseMoveHandler(e) {
          resizer.style.cursor = "col-resize";
          container.style.cursor = "col-resize";

          const dx = (e.clientX - x) * dir;
          const dy = (e.clientY - y) * dir;

          const newLeftWidth =
            ((leftWidth + dx) * 100) / container.getBoundingClientRect().width;
          leftSide.style.flexBasis = `${newLeftWidth}%`;
          leftSide.style.userSelect = "none";
          leftSide.style.pointerEvents = "none";
          rightSide.style.userSelect = "none";
          rightSide.style.pointerEvents = "none";
          //window.dispatchEvent(resizeEvent);
        }

        function mouseUpHandler() {
          resizer.style.removeProperty("cursor");
          container.style.removeProperty("cursor");
          leftSide.style.removeProperty("user-select");
          leftSide.style.removeProperty("pointer-events");
          rightSide.style.removeProperty("user-select");
          rightSide.style.removeProperty("pointer-events");
          container.removeEventListener("mousemove", mouseMoveHandler);
          container.removeEventListener("mouseup", mouseUpHandler);
          //window.dispatchEvent(resizeEvent);
        }

        container.addEventListener("mousemove", mouseMoveHandler);
        container.addEventListener("mouseup", mouseUpHandler);
      });

      let flex_reverse = false;
      elem.addEventListener("dblclick", function (e) {
        flex_reverse = !flex_reverse;
        e.preventDefault();

        let resizer = e.currentTarget;
        let container = resizer.parentElement;
        //let flexDir = window.getComputedStyle(container).getPropertyValue('flex-direction');

        if (flex_reverse) {
          container.style.flexDirection = "row-reverse";
        } else {
          container.style.flexDirection = "row";
        }
      });
    });

  // set this globally
  //let selectedTabItemId = "tab_txt2img";
  /* switch tab item from instance button, this is the only method that works i havent found a workaround yet */
  const Observe = (sel, opt, cb) => {
    const Obs = new MutationObserver((m) => [...m].forEach(cb));
    gradioApp()
      .querySelectorAll(sel)
      .forEach((el) => Obs.observe(el, opt));
  };
  Observe(
    "#tabs > div.tabitem",
    {
      attributesList: ["style"],
      attributeOldValue: true,
    },
    (m) => {
      if (m.target.style.display === "block") {
        let idx = parseInt(m.target.getAttribute("tab-item"));
        selectedTabItemId = m.target.id;
        tabItemChanged(idx);
      }
    }
  );

  function tabItemChanged(idx) {
    gradioApp()
      .querySelectorAll(
        "#tabs > div > button.selected, #nav_menu_header_tabs > button.selected"
      )
      .forEach(function (tab) {
        tab.classList.remove("selected");
      });

    gradioApp()
      .querySelectorAll(
        "#tabs > div > button:nth-child(" +
          (idx + 1) +
          "), #nav_menu_header_tabs > button:nth-child(" +
          (idx + 1) +
          ")"
      )
      .forEach(function (tab) {
        tab.classList.add("selected");
      });
    //gardio removes listeners and attributes from tab buttons we add them again here
    gradioApp()
      .querySelectorAll("#tabs > div > button")
      .forEach(function (tab, index) {
        tab.setAttribute("tab-id", index);
        tab.removeEventListener("mouseup", navTabClicked);
        tab.addEventListener("mouseup", navTabClicked);
        if (tab.innerHTML.indexOf("Theme") != -1) tab.style.display = "none";
      });

    /* 		gradioApp().querySelectorAll('[id^="image_buttons_"] button').forEach(function (elem){
			
			if(elem.id == "txt2img_tab"){
				elem.setAttribute("tab-id", 0);
				elem.removeEventListener('click', navTabClicked);
				elem.addEventListener('click', navTabClicked);
			}else if(elem.id == "img2img_tab" || elem.id == "inpaint_tab"){
				elem.setAttribute("tab-id", 1);
				elem.removeEventListener('click', navTabClicked);
				elem.addEventListener('click', navTabClicked);
			}if(elem.id == "extras_tab"){
				elem.setAttribute("tab-id", 2);
				elem.removeEventListener('click', navTabClicked);
				elem.addEventListener('click', navTabClicked);
			}		
		}) */

    /* 		const pdiv = gradioApp().querySelector("#"+selectedTabItemId+" .progressDiv");
		if(!pdiv && selectedTabItemId == "tab_txt2img"){			
			showSubmitButtons('txt2img', true);
		}else if(!pdiv && selectedTabItemId == "tab_img2img"){
			showSubmitButtons('img2img', true);
		} */

    //window.onUiHeaderTabUpdate();
    // also here the same issue
    /*
		gradioApp().querySelectorAll('[id^="image_buttons"] [id$="_tab"]').forEach(function (button, index){
			if(button.id == ("img2img_tab" || "inpaint_tab") ){
				button.setAttribute("tab-id", 1 );
			}else if(button.id == "extras_tab"){
				button.setAttribute("tab-id", 2 );
			}
			
			button.removeEventListener('mouseup', navTabClicked);
			button.addEventListener('mouseup', navTabClicked);	
			
			
		})
		*/

    netMenuVisibility();
  }

  // menu
  function disableScroll() {
    scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
    window.scrollTo(scrollLeft, scrollTop);

    window.onscroll = function () {
      window.scrollTo(scrollLeft, scrollTop);
    };
  }

  function enableScroll() {
    window.onscroll = function () {};
  }

  function getPos(el) {
    let rect = el.getBoundingClientRect();
    return { x: rect.left, y: rect.top };
  }

  function toggleMenu(isopen, icon, panel, func) {
    if (isopen) {
      panel.classList.add("open");
      icon.classList.add("fixed");
      gradioApp().addEventListener("click", func);
      disableScroll();
    } else {
      panel.classList.remove("open");
      icon.classList.remove("fixed");
      gradioApp().removeEventListener("click", func);
      enableScroll();
    }
  }

  // close aside views
  function closeAsideViews(menu) {
    if (quick_menu != menu && quick_menu_open) quick_menu.click();
    if (net_menu != menu && net_menu_open) net_menu.click();
    if (theme_menu != menu && theme_menu_open) theme_menu.click();
  }

  // if we change to other view other than 2img and if aside mode is selected close extra networks aside and hide the net menu icon
  let net_container = gradioApp().querySelector("#txt2img_extra_networks_row");
  let net_menu_open = false;
  const net_menu = gradioApp().querySelector("#extra_networks_menu");
  function netMenuVisibility() {
    if (selectedTabItemId.indexOf("2img") != -1) {
      net_menu.style.display = "block";
      let nid = selectedTabItemId.split("_")[1];
      net_container = gradioApp().querySelector(
        "#" + nid + "_extra_networks_row"
      );
      if (net_container.classList.contains("aside")) {
        net_menu.style.display = "block";
        toggleMenu(net_menu_open, net_menu, net_container, null);
      } else {
        net_menu.style.display = "none";
      }
    } else {
      net_menu.style.display = "none";
    }
  }

  // mobile nav menu
  const tabs_menu = gradioApp().querySelector("#tabs > div:first-child");
  const nav_menu = gradioApp().querySelector("#nav_menu");
  const header = gradioApp().querySelector("#header-top");
  let menu_open = false;
  const z_menu = nav_menu.cloneNode(true);
  z_menu.id = "clone_nav_menu";
  header.parentElement.append(z_menu);
  function toggleNavMenu(e) {
    e.stopPropagation();
    menu_open = !menu_open;
    toggleMenu(menu_open, nav_menu, tabs_menu, toggleNavMenu);
  }
  z_menu.addEventListener("click", toggleNavMenu);

  // quicksettings nav menu
  let quick_menu_open = false;
  const quicksettings_overflow = gradioApp().querySelector(
    "#quicksettings_overflow"
  );
  const quick_menu = gradioApp().querySelector("#quick_menu");
  function toggleQuickMenu(e) {
    closeAsideViews(quick_menu);
    quick_menu_open = !quick_menu_open;
    const withinBoundaries = e.composedPath().includes(quicksettings_overflow);
    if (!quick_menu_open && withinBoundaries) {
      quick_menu_open = true;
    } else {
      e.preventDefault();
      e.stopPropagation();
      toggleMenu(
        quick_menu_open,
        quick_menu,
        quicksettings_overflow,
        toggleQuickMenu
      );
    }
  }
  quick_menu.addEventListener("click", toggleQuickMenu);

  // extra networks nav menu
  function clickedOutside(e) {
    //console.log(e.target.getAttribute('data-testid'));
    if (
      e.target.getAttribute("data-testid") != "textbox" &&
      e.target.getAttribute("data-testid")
    ) {
      if (net_menu_open && e.target.closest('[id$="2img_settings_scroll"]'))
        net_menu.click();
    }
  }
  function toggleNetMenu(e) {
    closeAsideViews(net_menu);
    net_menu_open = !net_menu_open;
    e.preventDefault();
    e.stopPropagation();
    toggleMenu(net_menu_open, net_menu, net_container, clickedOutside);
  }
  net_menu.addEventListener("click", toggleNetMenu);
  gradioApp()
    .querySelectorAll('button[id*="2img_extra_networks"]')
    .forEach((elem) => {
      elem.addEventListener("click", toggleNetMenu);
    });

  // theme nav menu
  let theme_container = gradioApp().querySelector("#tab_ui_theme");
  let theme_menu_open = false;
  const theme_menu = gradioApp().querySelector("#theme_menu");
  function toggleThemeMenu(e) {
    closeAsideViews(theme_menu);
    theme_menu_open = !theme_menu_open;
    e.preventDefault();
    e.stopPropagation();
    toggleMenu(theme_menu_open, theme_menu, theme_container, null);
  }
  theme_menu.addEventListener("click", toggleThemeMenu);

  const theme_tab = gradioApp().querySelector("#tab_ui_theme");
  function theme_aside(value) {
    if (value) {
      theme_tab.classList.add("aside");
    } else {
      theme_tab.classList.remove("aside");
    }
  }
  if (theme_tab) theme_aside(true);

  function generateOnRepeat(elem, isforever) {
    if (elem.generateOnRepeatInterval != null)
      clearInterval(elem.generateOnRepeatInterval);
    if (isforever) {
      const generate_button = elem.previousElementSibling;
      elem.generateOnRepeatInterval = setInterval(function () {
        if (window.getComputedStyle(generate_button).display !== "none") {
          generate_button.click();
        }
      }, 500);
    }
  }

  function toggleGenerateForever(e) {
    e.target.classList.toggle("active");
    if (e.target.className.indexOf("active") != -1) {
      generateOnRepeat(e.target, true);
    } else {
      generateOnRepeat(e.target, false);
    }
    e.preventDefault();
    e.stopPropagation();
  }

  gradioApp()
    .querySelectorAll('button[id*="2img_generate_forever"]')
    .forEach((elem) => {
      elem.addEventListener("click", toggleGenerateForever);
    });

  /*   let generateOnRepeat = function (genbuttonid, interruptbuttonid) {
    let genbutton = gradioApp().querySelector(genbuttonid);
    let interruptbutton = gradioApp().querySelector(interruptbuttonid);
    if (!interruptbutton.offsetParent) {
      genbutton.click();
    }
    clearInterval(window.generateOnRepeatInterval);
    window.generateOnRepeatInterval = setInterval(function () {
      if (!interruptbutton.offsetParent) {
        genbutton.click();
      }
    }, 500);
  };

  appendContextMenuOption("#txt2img_generate", "Generate forever", function () {
    generateOnRepeat("#txt2img_generate", "#txt2img_interrupt");
  });
  appendContextMenuOption("#img2img_generate", "Generate forever", function () {
    generateOnRepeat("#img2img_generate", "#img2img_interrupt");
  });

  let cancelGenerateForever = function () {
    clearInterval(window.generateOnRepeatInterval);
  }; */

  //
  /*
  function attachAccordionListeners(elem) {
    elem.querySelectorAll(".gradio-accordion > div.wrap").forEach((elem) => {
      elem.addEventListener("click", toggleAccordion);
    });
  }
   function toggleAccordion(e) {
    //e.preventDefault();
    //e.stopPropagation();
    //e.stopImmediatePropagation();
    let accordion_content =
      e.currentTarget.parentElement.querySelector(".gap.svelte-vt1mxs");

    if (accordion_content) {
      e.preventDefault();
      e.stopPropagation();
      let accordion_icon = e.currentTarget.parentElement.querySelector(
        ".label-wrap > .icon"
      );
      if (accordion_content.className.indexOf("hidden") != -1) {
        accordion_content.classList.remove("hidden");
        accordion_icon.style.setProperty("transform", "rotate(0deg)");
        e.currentTarget.classList.add("hide");
      } else {
        accordion_content.classList.add("hidden");
        accordion_icon.style.setProperty("transform", "rotate(90deg)");
        e.currentTarget.classList.remove("hide");
      }
    } else {
      let accordion_btn =
        e.currentTarget.parentElement.querySelector(".label-wrap");
      e.currentTarget.classList.add("hide");
      accordion_btn.click();
      //maybe here we need to setInterval until the content is available
      setTimeout(function () {
        accordion_content = accordion_btn.parentElement;
        //console.log(accordion_content);
        attachAccordionListeners(accordion_content);
      }, 1000);
    }
  }

  attachAccordionListeners(gradioApp());
  */
  // additional ui styles
  let styleobj = {};
  const r = gradioApp();
  const style = document.createElement("style");
  style.id = "ui-styles";
  r.appendChild(style);

  function updateOpStyles() {
    let ops_styles = "";
    for (const key in styleobj) {
      ops_styles += styleobj[key];
    }
    const ui_styles = gradioApp().getElementById("ui-styles");
    ui_styles.innerHTML = ops_styles;
    //console.log(ui_styles);
  }

  // generated image fit contain - scale
  function imageGeneratedFitMethod(value) {
    styleobj.ui_view_fit =
      "[id$='2img_gallery'] div>img {object-fit:" + value + "!important;}";
  }
  gradioApp()
    .querySelector("#setting_ui_output_image_fit")
    .addEventListener("click", function (e) {
      if (e.target && e.target.matches("input[type='radio']")) {
        imageGeneratedFitMethod(e.target.value.toLowerCase());
        updateOpStyles();
      }
    });
  imageGeneratedFitMethod(opts.ui_output_image_fit.toLowerCase());

  // livePreview fit contain - scale
  function imagePreviewFitMethod(value) {
    styleobj.ui_fit = ".livePreview img {object-fit:" + value + "!important;}";
  }
  gradioApp()
    .querySelector("#setting_live_preview_image_fit")
    .addEventListener("click", function (e) {
      if (e.target && e.target.matches("input[type='radio']")) {
        imagePreviewFitMethod(e.target.value.toLowerCase());
        updateOpStyles();
      }
    });
  imagePreviewFitMethod(opts.live_preview_image_fit.toLowerCase());

  // viewports order left - right
  function viewportOrder(value) {
    styleobj.ui_views_order =
      "[id$=_prompt_image] + div {flex-direction:" + value + ";}";
  }
  gradioApp()
    .querySelector("#setting_ui_views_order")
    .addEventListener("click", function (e) {
      if (e.target && e.target.matches("input[type='radio']")) {
        viewportOrder(e.target.value.toLowerCase());
        updateOpStyles();
      }
    });
  viewportOrder(opts.ui_views_order.toLowerCase());

  // sd max resolution output
  function sdMaxOutputResolution(value) {
    gradioApp()
      .querySelectorAll('[id$="2img_width"] input,[id$="2img_height"] input')
      .forEach((elem) => {
        elem.max = value;
      });
  }
  gradioApp()
    .querySelector("#setting_sd_max_resolution")
    .addEventListener("input", function (e) {
      let intvalue = parseInt(e.target.value);
      intvalue = Math.min(Math.max(intvalue, 512), 16384);
      sdMaxOutputResolution(intvalue);
    });
  sdMaxOutputResolution(opts.sd_max_resolution);

  function extra_networks_visibility(value) {
    gradioApp()
      .querySelectorAll('[id$="2img_extra_networks_row"]')
      .forEach((elem) => {
        if (value) {
          elem.classList.remove("!hidden");
        } else {
          elem.classList.add("!hidden");
        }
      });
  }
  gradioApp()
    .querySelector("#setting_extra_networks_default_visibility input")
    .addEventListener("click", function (e) {
      extra_networks_visibility(e.target.checked);
    });
  extra_networks_visibility(opts.extra_networks_default_visibility);

  function extra_networks_card_size(value) {
    styleobj.extra_networks_card_size =
      ":root{--ae-extra-networks-card-size:" + value + ";}";
  }
  gradioApp()
    .querySelectorAll("#setting_extra_networks_cards_size input")
    .forEach(function (elem) {
      elem.addEventListener("input", function (e) {
        extra_networks_card_size(e.target.value);
        updateOpStyles();
      });
    });
  extra_networks_card_size(opts.extra_networks_cards_size);

  function extra_networks_cards_visible_rows(value) {
    styleobj.extra_networks_cards_visible_rows =
      ":root{--ae-extra-networks-visible-rows:" + value + ";}";
  }
  gradioApp()
    .querySelectorAll("#setting_extra_networks_cards_visible_rows input")
    .forEach(function (elem) {
      elem.addEventListener("input", function (e) {
        extra_networks_cards_visible_rows(e.target.value);
        updateOpStyles();
      });
    });
  extra_networks_cards_visible_rows(opts.extra_networks_cards_visible_rows);

  function extra_networks_aside(value) {
    gradioApp()
      .querySelectorAll('[id$="2img_extra_networks_row"]')
      .forEach((elem) => {
        if (value) {
          elem.classList.add("aside");
        } else {
          elem.classList.remove("aside");
        }
        netMenuVisibility();
      });
  }
  gradioApp()
    .querySelector("#setting_extra_networks_aside input")
    .addEventListener("click", function (e) {
      extra_networks_aside(e.target.checked);
    });
  extra_networks_aside(opts.extra_networks_aside);

  // hidden - header ui tabs
  let radio_hidden_html = "";
  let radio_header_html = "";
  let hiddentabs = {};
  let headertabs = {};
  const setting_ui_hidden_tabs = gradioApp().querySelector(
    "#setting_ui_hidden_tabs textarea"
  );
  const setting_ui_header_tabs = gradioApp().querySelector(
    "#setting_ui_header_tabs textarea"
  );
  const parent_header_tabs = gradioApp().querySelector("#nav_menu_header_tabs");
  setting_ui_hidden_tabs.style.display = "none";
  setting_ui_header_tabs.style.display = "none";

  const maintabs = gradioApp().querySelectorAll(
    "#tabs > div:first-child > button"
  );
  const tabitems = gradioApp().querySelectorAll("#tabs > div.tabitem");

  function tabOpsSave(setting) {
    updateInput(setting);
    
  }

  function tabsHiddenChange() {
    const keys = Object.keys(hiddentabs);
    setting_ui_hidden_tabs.value = "";
    keys.forEach((key, index) => {
      //console.log(`${key}: ${hiddentabs[key]} ${index}`);
      if (hiddentabs[key] == true) {
        styleobj[key] =
          "#tabs > div:first-child > button:nth-child(" +
          (index + 1) +
          "){display:none;}";
        setting_ui_hidden_tabs.value += key + ",";
      } else {
        styleobj[key] =
          "#tabs > div:first-child  > button:nth-child(" +
          (index + 1) +
          "){display:block;}";
      }
    });

    tabOpsSave(setting_ui_hidden_tabs);
    tabsHeaderChange();
  }
  function tabsHeaderChange() {
    const keys = Object.keys(headertabs);
    setting_ui_header_tabs.value = "";
    keys.forEach((key, index) => {
      //console.log(`${key}: ${hiddentabs[key]} ${index}`);
      let nkey = key + "_hr";
      if (headertabs[key] == true && hiddentabs[key] == false) {
        styleobj[nkey] =
          "#nav_menu_header_tabs > button:nth-child(" +
          (index + 1) +
          "){display:block;}";
        setting_ui_header_tabs.value += key + ",";
      } else {
        styleobj[nkey] =
          "#nav_menu_header_tabs > button:nth-child(" +
          (index + 1) +
          "){display:none;}";
      }
    });

    tabOpsSave(setting_ui_header_tabs);
  }

  function navigate2TabItem(idx) {
    gradioApp()
      .querySelectorAll("#tabs > div.tabitem")
      .forEach(function (tabitem, index) {
        if (idx == index) {
          tabitem.style.display = "block";
        } else {
          tabitem.style.display = "none";
        }
      });
  }

  function navTabClicked(e) {
    const idx = parseInt(e.currentTarget.getAttribute("tab-id"));
    navigate2TabItem(idx);
  }

  maintabs.forEach(function (elem, index) {
    let tabvalue = elem.innerText.replaceAll(" ", "");
    hiddentabs[tabvalue] = false;
    headertabs[tabvalue] = false;
    let checked_hidden = "";
    let checked_header = "";
    if (setting_ui_hidden_tabs.value.indexOf(tabvalue) != -1) {
      hiddentabs[tabvalue] = true;
      checked_hidden = "checked";
    }
    if (setting_ui_header_tabs.value.indexOf(tabvalue) != -1) {
      headertabs[tabvalue] = true;
      checked_header = "checked";
    }
    radio_hidden_html +=
      '<label class="' +
      tabvalue.toLowerCase() +
      ' svelte-1qxcj04"><input type="checkbox" name="uiha" class="svelte-1qxcj04" ' +
      checked_hidden +
      ' value="' +
      elem.innerText +
      '"><span class="ml-2 svelte-1qxcj04">' +
      elem.innerText +
      "</span></label>";

    radio_header_html +=
      '<label class="' +
      tabvalue.toLowerCase() +
      ' svelte-1qxcj04"><input type="checkbox" name="uiha" class="svelte-1qxcj04" ' +
      checked_header +
      ' value="' +
      elem.innerText +
      '"><span class="ml-2 svelte-1qxcj04">' +
      elem.innerText +
      "</span></label>";

    tabitems[index].setAttribute("tab-item", index);
    elem.setAttribute("tab-id", index);

    let clonetab = elem.cloneNode(true);
    clonetab.id = tabvalue + "_clone";
    parent_header_tabs.append(clonetab);
    clonetab.addEventListener("click", navTabClicked);
  });

  let div = document.createElement("div");
  div.id = "hidden_radio_tabs_container";
  div.classList.add("flex", "flex-wrap", "gap-2", "wrap", "svelte-1qxcj04");
  div.innerHTML = radio_hidden_html;
  setting_ui_hidden_tabs.parentElement.appendChild(div);

  div = document.createElement("div");
  div.id = "header_radio_tabs_container";
  div.classList.add("flex", "flex-wrap", "gap-2", "wrap", "svelte-1qxcj04");
  div.innerHTML = radio_header_html;
  setting_ui_header_tabs.parentElement.appendChild(div);

  // hidden tabs
  gradioApp()
    .querySelector("#hidden_radio_tabs_container")
    .addEventListener("click", function (e) {
      if (e.target && e.target.matches("input[type='checkbox']")) {
        let tabvalue = e.target.value.replaceAll(" ", "");
        hiddentabs[tabvalue] = e.target.checked;
        tabsHiddenChange();
        updateOpStyles();
      }
    });
  // header tabs
  gradioApp()
    .querySelector("#header_radio_tabs_container")
    .addEventListener("click", function (e) {
      if (e.target && e.target.matches("input[type='checkbox']")) {
        let tabvalue = e.target.value.replaceAll(" ", "");
        headertabs[tabvalue] = e.target.checked;
        tabsHeaderChange();
        updateOpStyles();
      }
    });

  tabsHiddenChange();

  gradioApp()
    .querySelectorAll('[id^="image_buttons_"] button, #png_2img_results button')
    .forEach(function (elem) {
      //console.log(opts.send_seed);
      if (elem.id == "txt2img_tab") {
        elem.setAttribute("tab-id", 0);
        elem.addEventListener("click", navTabClicked);
      } else if (elem.id == "img2img_tab" || elem.id == "inpaint_tab") {
        elem.setAttribute("tab-id", 1);
        elem.addEventListener("click", navTabClicked);
      }
      if (elem.id == "extras_tab") {
        elem.setAttribute("tab-id", 2);
        elem.addEventListener("click", navTabClicked);
      }
    });

  gradioApp()
    .querySelectorAll('[id$="2img_extra_tabs"] .search')
    .forEach(function (elem) {
      elem.addEventListener("keyup", function (e) {
        if (e.defaultPrevented) {
          return; // Do nothing if event already handled
        }
        switch (e.code) {
          case "Escape":
            if (e.target.value == "") {
              net_menu.click();
            } else {
              e.target.value = "";
              updateInput(e.target);
            }
            break;
        }
      });
    });

  // add - remove quicksettings
  const settings_submit = gradioApp().querySelector("#settings_submit");
  const quick_parent = gradioApp().querySelector(
    "#quicksettings_overflow_container"
  );
  const setting_quicksettings = gradioApp().querySelector(
    "#setting_quicksettings textarea"
  );
  function saveQuickSettings() {
    updateInput(setting_quicksettings);
    const cEvent = new Event("click"); //submit
    Object.defineProperty(cEvent, "target", { value: settings_submit });
    settings_submit.dispatchEvent(cEvent);
    console.log(setting_quicksettings.value);
  }

  /* 	
	function addModelCheckpoint(){
		if(setting_quicksettings.value.indexOf("sd_model_checkpoint") === -1){
			setting_quicksettings.value += ",sd_model_checkpoint";
		}
		saveQuickSettings();
	} 
	*/

  function add2quickSettings(id, section, checked) {
    let field_settings = setting_quicksettings.value.replace(" ", "");
    if (checked) {
      field_settings += "," + id;
      let setting_row = gradioApp().querySelector("#row_setting_" + id);
      quick_parent.append(setting_row);
      setting_row.classList.add("warning");
    } else {
      field_settings = field_settings.replaceAll(id, ",");
      const setting_parent = gradioApp().querySelector(
        "#" + section + "_settings_2img_settings"
      );
      let quick_row = gradioApp().querySelector("#row_setting_" + id);
      setting_parent.append(quick_row);
      quick_row.classList.remove("warning");
    }
    field_settings = field_settings.replace(/,{2,}/g, ",");
    setting_quicksettings.value = field_settings;
    //addModelCheckpoint();
    saveQuickSettings();
    //console.log(section + " - " + id + " - " + checked);
  }
  gradioApp()
    .querySelectorAll('[id*="add2quick_"]')
    .forEach(function (elem) {
      let trg = elem.id.split("_add2quick_setting_");
      let sid = trg[0];
      let tid = trg[1];
      let elem_input = gradioApp().querySelector("#" + elem.id + " input");
      if (elem_input) {
        elem_input.addEventListener("click", function (e) {
          add2quickSettings(tid, sid, e.target.checked);
        });
      }
    });
  //addModelCheckpoint();

  // input release component dispatcher
  let cached_clone_range;
  let cached_clone_num;
  let active_clone_input = [];
  let focus_input;

  function ui_input_release_component(elem) {
    //console.log("ok");
    if (active_clone_input.length > 0) return;

    //img2img_width
    let parent = elem.parentElement;
    let comp_parent = parent.parentElement.parentElement;

    if (
      comp_parent.id == "img2img_width" ||
      comp_parent.id == "img2img_height" ||
      comp_parent.id == "img2img_scale" ||
      comp_parent.id.indexOf("--ae-") != -1 ||
      comp_parent.id.indexOf("theme") != -1 ||
      comp_parent.className.indexOf("posex") != -1
    )
      return;

    let clone_num = elem.cloneNode();
    active_clone_input.push(clone_num);

    let label = parent.querySelector("label");

    clone_num.id = "num_clone";
    clone_num.value = elem.value;
    parent.append(clone_num);
    elem.classList.add("hidden");

    clone_num.addEventListener("change", function (e) {
      elem.value = clone_num.value;
      updateInput(elem);
    });

    clone_num.addEventListener("focus", function (e) {
      focus_input = clone_num;
    });

    cached_clone_num = clone_num;
    cached_clone_range = false;

    if (label) {
      let comp_range = comp_parent.querySelector("input[type='range']");
      let clone_range = comp_range.cloneNode();
      active_clone_input.push(clone_range);

      clone_range.id = comp_range.id + "_clone";
      clone_range.value = comp_range.value;
      comp_range.parentElement.append(clone_range);
      comp_range.classList.add("hidden");

      clone_range.addEventListener("input", function (e) {
        clone_num.value = e.target.value;
      });
      clone_range.addEventListener("change", function (e) {
        elem.value = clone_range.value;
        updateInput(elem);
      });
      clone_num.addEventListener("input", function (e) {
        clone_range.value = e.target.value;
      });

      cached_clone_range = clone_range;
    }
  }
  /*   function ui_input_focus_handler(e) {
    if (e.target != focus_input) {
      focus_input = false;
      ui_input_release_handler(e);
    }
  } */

  function ui_input_release_handler(e) {
    const len = active_clone_input.length;
    if (focus_input) {
      return;
    }
    if (len > 0) {
      if (e.target.id.indexOf("_clone") == -1) {
        for (var i = len - 1; i >= 0; i--) {
          let relem = active_clone_input[i];
          relem.previousElementSibling.classList.remove("hidden");
          relem.remove();
          active_clone_input.pop();
        }
      }
    }

    let elem_type = e.target.tagName;
    if (elem_type == "INPUT") {
      let elem = e.target;
      if (elem.type == "number") {
        ui_input_release_component(elem);
      } else if (elem.type == "range") {
        elem = e.target.parentElement.querySelector("input[type='number']");
        if (elem) {
          ui_input_release_component(elem);
        }
      }
    }
  }
  let timeoutId;

  function ui_input_touchmove_handler(e) {
    if (cached_clone_range && cached_clone_num) {
      if (e.touches) {
        const rect = cached_clone_range.getBoundingClientRect();
        const xoffset_min = rect.left + window.scrollX;
        //const xoffset_max = (rect.right + window.scrollX);
        //const yoffset_min = (rect.top + window.scrollY);
        //const yoffset_max = (rect.bottom + window.scrollY);
        //if(	e.touches[0].pageY > yoffset_min && e.touches[0].pageY < yoffset_max && e.touches[0].pageX > xoffset_min && e.touches[0].pageX < xoffset_max){
        e.preventDefault();
        const percent =
          parseInt(((e.touches[0].pageX - xoffset_min) / rect.width) * 10000) /
          10000;
        cached_clone_range.value =
          percent * (cached_clone_range.max - cached_clone_range.min) +
          parseFloat(cached_clone_range.min);
        cached_clone_num.value = cached_clone_range.value;
        //}
      }
    }
  }
  function ui_input_touchend_handler(e) {
    if (cached_clone_range && cached_clone_num) {
      const elem = cached_clone_range.previousElementSibling;
      elem.value = cached_clone_range.value;
      updateInput(elem);
    }
  }

  function slider_contextmenu(e) {
    e.preventDefault();
  }
  function slider_touchend(e) {
    if (timeoutId) clearTimeout(timeoutId);
  }
  function slider_touchmove(e) {
    if (timeoutId) clearTimeout(timeoutId);
  }
  function slider_touchstart(e) {
    const gcontainer = e.target;
    //gcontainer.removeEventListener('contextmenu',  slider_contextmenu);
    gcontainer.removeEventListener("touchend", slider_touchend);
    gcontainer.removeEventListener("touchmove", slider_touchmove);
    gcontainer.removeEventListener("touchend", ui_input_touchend_handler);
    gcontainer.removeEventListener("touchmove", ui_input_touchmove_handler);

    timeoutId = setTimeout(function () {
      timeoutId = null;
      focus_input = false;
      e.stopPropagation();
      ui_input_release_handler(e);
      ui_input_touchmove_handler(e);
      gcontainer.addEventListener("touchmove", ui_input_touchmove_handler, {
        passive: false,
      });
      gcontainer.addEventListener("touchend", ui_input_touchend_handler);
    }, 500);

    //gcontainer.addEventListener('contextmenu',  slider_contextmenu);
    gcontainer.addEventListener("touchend", slider_touchend);
    gcontainer.addEventListener("touchmove", slider_touchmove, {
      passive: false,
    });
  }

  function ui_dispatch_input_release(value) {
    const gcontainer = gradioApp().querySelector(".gradio-container");
    if (value) {
      gcontainer.addEventListener("mouseover", ui_input_release_handler);
      gcontainer.addEventListener("touchstart", slider_touchstart, {
        passive: false,
      });
    } else {
      gcontainer.removeEventListener("mouseover", ui_input_release_handler);
      gcontainer.removeEventListener("touchstart", slider_touchstart);
      //gcontainer.removeEventListener('contextmenu',  slider_contextmenu);
      gcontainer.removeEventListener("touchend", slider_touchend);
      gcontainer.removeEventListener("touchmove", slider_touchmove);
      gcontainer.removeEventListener("touchend", ui_input_touchend_handler);
      gcontainer.removeEventListener("touchmove", ui_input_touchmove_handler);
    }
  }
  gradioApp()
    .querySelector("#setting_ui_dispatch_input_release input")
    .addEventListener("click", function (e) {
      ui_dispatch_input_release(e.target.checked);
    });
  ui_dispatch_input_release(opts.ui_dispatch_input_release);

  // step ticks for performant input range
  function ui_show_range_ticks(value, interactive) {
    if (value) {
      const range_selectors = "input[type='range']";
      //const range_selectors = "[id$='_clone']:is(input[type='range'])";
      gradioApp()
        .querySelectorAll(range_selectors)
        .forEach(function (elem) {
          let spacing = (elem.step / (elem.max - elem.min)) * 100.0;
          let tsp = "max(3px, calc(" + spacing + "% - 1px))";
          let fsp = "max(4px, calc(" + spacing + "% + 0px))";
          var style = elem.style;
          style.setProperty(
            "--ae-slider-bg-overlay",
            "repeating-linear-gradient( 90deg, transparent, transparent " +
              tsp +
              ", var(--ae-input-border-color) " +
              tsp +
              ", var(--ae-input-border-color) " +
              fsp +
              " )"
          );
        });
    } else if (interactive) {
      gradioApp()
        .querySelectorAll("input[type='range']")
        .forEach(function (elem) {
          var style = elem.style;
          style.setProperty("--ae-slider-bg-overlay", "transparent");
        });
    }
  }
  gradioApp()
    .querySelector("#setting_ui_show_range_ticks input")
    .addEventListener("click", function (e) {
      ui_show_range_ticks(e.target.checked, true);
    });
  ui_show_range_ticks(opts.ui_show_range_ticks);

  const gradio_main = gradioApp().querySelector(".gradio-container > div.main");
  function ui_no_slider_layout(value) {
    if (value) {
      gradio_main.classList.add("no-slider-layout");
    } else {
      gradio_main.classList.remove("no-slider-layout");
    }
  }
  gradioApp()
    .querySelector("#setting_ui_no_slider_layout input")
    .addEventListener("click", function (e) {
      ui_no_slider_layout(e.target.checked, true);
    });
  ui_no_slider_layout(opts.ui_no_slider_layout);

  // draggable reordable quicksettings
  const container = gradioApp().querySelector(
    "#quicksettings_overflow_container"
  );
  let draggables;
  let lastElemAfter;
  let islastChild;
  let timeout;

  function preventBehavior(e) {
    e.stopPropagation();
    e.preventDefault();
    return false;
  }
  let sdCheckpointModels = [];
  function getSdCheckpointModels() {
    gradioApp()
      .querySelectorAll("#txt2img_checkpoints_cards .card")
      .forEach(function (elem, i) {
        sdCheckpointModels[i] = elem.getAttribute("onclick").split('"')[1];
      });
  }
  getSdCheckpointModels();

  function remove_overrides() {
    let checked_overrides = [];
    gradioApp()
      .querySelectorAll("#setting_ignore_overrides input")
      .forEach(function (elem, i) {
        if (elem.checked) {
          checked_overrides[i] = elem.nextElementSibling.innerHTML;
        }
      });
    //console.log(checked_overrides);
    gradioApp()
      .querySelectorAll("[id$='2img_override_settings'] .token")
      .forEach(function (token) {
        let token_arr = token.querySelector("span").innerHTML.split(":");
        let token_name = token_arr[0];
        let token_value = token_arr[1];
        token_value = token_value.replaceAll(" ", "");

        if (token_name.indexOf("Model hash") != -1) {
          const info_label = gradioApp().querySelector(
            "[id$='2img_override_settings'] label span"
          );
          info_label.innerHTML = "Override settings MDL: unknown";
          for (let m = 0; m < sdCheckpointModels.length; m++) {
            let m_str = sdCheckpointModels[m];
            if (m_str.indexOf(token_value) != -1) {
              info_label.innerHTML =
                "Override settings <i>MDL: " + m_str.split("[")[0] + "</i>";
              break;
            }
          }
        }
        if (checked_overrides.indexOf(token_name) != -1) {
          token.querySelector(".token-remove").click();
          gradioApp()
            .querySelector(
              "#" + selectedTabItemId + " [id$='2img_override_settings']"
            )
            .parentElement.classList.add("show");
        } else {
          // maybe we add them again, for now we can select and add the removed tokens manually from the drop down
        }
      });
  }
  gradioApp()
    .querySelector("#setting_ignore_overrides")
    .addEventListener("click", function (e) {
      setTimeout(function () {
        remove_overrides();
      }, 100);
    });

  function update_input_fields(tab) {
    /* 
		let input_selectors = "#tab_"+ tab + " [id^='num_clone']:is(input[type='number'])";
		gradioApp().querySelectorAll(input_selectors).forEach(function (elem){
			let elem_source = elem.previousElementSibling;		
			elem.value = elem_source.value;
			updateInput(elem);	
		}) 
		*/
    remove_overrides();
    autoGrowPromptTextarea();
  }

  gradioApp()
    .querySelectorAll(
      "#tab_pnginfo #png_2img_results button, [id$='2img_actions_column'] #paste"
    )
    .forEach(function (elem) {
      elem.addEventListener("click", function (e) {
        let button_id;
        if (e.target.id == "paste") {
          button_id = e.target.nextElementSibling.id.split("_")[0];
        } else {
          button_id = e.target.id.split("_")[0];
        }
        setTimeout(function () {
          update_input_fields(button_id);
        }, 500);
      });
    });

  const pnginfo = gradioApp().querySelector("#tab_pnginfo");
  function forwardFromPngInfo() {
    if (selectedTabItemId == "tab_txt2img") {
      pnginfo.querySelector("#txt2img_tab").click();
      //close generation info
      gradioApp()
        .querySelector(
          "#txt2img_results > div:last-child > div.gradio-accordion > div.hide"
        )
        ?.click();

      const img_src = pnginfo.querySelector("img");
      const gallery_parent = gradioApp().querySelector(
        "#txt2img_gallery_container"
      );
      const live_preview = gallery_parent.querySelector(".livePreview");
      if (live_preview) {
        live_preview.innerHTML =
          '<img width="' +
          img_src.width +
          '" height="' +
          img_src.height +
          '" src="' +
          img_src.src +
          '">';
      } else {
        const div = document.createElement("div");
        div.classList.add("livePreview", "dropPreview");
        div.innerHTML =
          '<img width="' +
          img_src.width +
          '" height="' +
          img_src.height +
          '" src="' +
          img_src.src +
          '">';
        gallery_parent.prepend(div);
      }
    } else if (selectedTabItemId == "tab_img2img") {
      pnginfo.querySelector("#img2img_tab").click();
      //close generation info
      gradioApp()
        .querySelector(
          "#img2img_results > div:last-child > div.gradio-accordion > div.hide"
        )
        ?.click();
    }
  }

  function fetchPngInfoData(files) {
    /* const oldFetch = window.fetch;
			
		window.fetch = async (input, options) => {			
			const response = await oldFetch(input, options);
			if( 'run/predict/' === input ) {			
				if(response.ok){									
					window.fetch = oldFetch;										
				}
			}
			return response;
		};  */

    const fileInput = gradioApp().querySelector(
      '#pnginfo_image input[type="file"]'
    );
    if (fileInput.files != files) {
      fileInput.files = files;
      fileInput.dispatchEvent(new Event("change"));
    }

    setTimeout(function () {
      forwardFromPngInfo();
    }, 500);
  }

  function drop2View(e) {
    e.stopPropagation();
    e.preventDefault();
    const files = e.dataTransfer.files;

    if (!isValidImageList(files)) {
      return;
    }
    const data_image = gradioApp().querySelector(
      '#pnginfo_image [data-testid="image"]'
    );
    data_image.querySelector('[aria-label="Clear"]')?.click();
    setTimeout(function () {
      fetchPngInfoData(files);
    }, 1000);
  }

  gradioApp()
    .querySelectorAll('[id$="2img_results"]')
    .forEach((elem) => {
      elem.addEventListener("drop", drop2View);
    });

  // function that gets the element next of cursor/touch
  function getElementAfter(container, y) {
    return draggables.reduce(
      (closest, child) => {
        const box = child.getBoundingClientRect();
        const offset = y - box.top - box.height / 2;
        if (offset < 0 && offset > closest.offset) {
          return { offset: offset, element: child };
        } else {
          return closest;
        }
      },
      { offset: Number.NEGATIVE_INFINITY }
    ).element;
  }

  function dragOrderChange(elementAfter, isComplete, delem) {
    if (lastElemAfter !== elementAfter || islastChild) {
      if (lastElemAfter != null) {
        lastElemAfter.classList.remove("marker-top", "marker-bottom");
      }

      if (elementAfter == null) {
        islastChild = true;
        lastElemAfter.classList.add("marker-bottom");
      } else {
        islastChild = false;
        elementAfter.classList.add("marker-top");
        lastElemAfter = elementAfter;
      }
    }

    if (isComplete) {
      if (elementAfter == null) {
        container.append(delem);
      } else {
        container.insertBefore(delem, elementAfter);
      }

      let order_settings = "";

      gradioApp()
        .querySelectorAll("#quicksettings_overflow_container > div")
        .forEach(function (el) {
          el.classList.remove("marker-top", "marker-bottom", "dragging");
          order_settings += el.id.split("row_setting_")[1] + ",";
        });
      //console.log(order_settings);
      const setting_quicksettings = gradioApp().querySelector(
        "#setting_quicksettings textarea"
      );
      setting_quicksettings.value = order_settings;
      updateInput(setting_quicksettings);

      const cEvent = new Event("click"); //submit
      Object.defineProperty(cEvent, "target", { value: settings_submit });
      settings_submit.dispatchEvent(cEvent);

      container.classList.remove("no-scroll");
    }
  }

  function touchmove(e) {
    let y = e.touches[0].clientY;
    let elementAfter = getElementAfter(container, y);
    dragOrderChange(elementAfter);
  }
  function touchstart(e) {
    e.currentTarget.draggable = "false";
    let target = e.currentTarget;
    // touch should be hold for 1 second
    timeout = setTimeout(function () {
      target.classList.add("dragging");
      container.classList.add("no-scroll");
      target.addEventListener("touchmove", touchmove);
      container.addEventListener("touchmove", preventBehavior, {
        passive: false,
      });
    }, 1000);

    target.addEventListener("touchend", touchend);
    target.addEventListener("touchcancel", touchcancel);
  }
  function touchend(e) {
    e.currentTarget.draggable = "true";
    clearTimeout(timeout);
    e.currentTarget.removeEventListener("touchmove", touchmove);
    container.removeEventListener("touchmove", preventBehavior);
    let y = e.changedTouches[0].clientY;
    let elementAfter = getElementAfter(container, y);
    dragOrderChange(elementAfter, true, e.currentTarget);
  }
  function touchcancel(e) {
    e.currentTarget.draggable = "true";
    clearTimeout(timeout);
    e.currentTarget.classList.remove("dragging");
    e.currentTarget.removeEventListener("touchmove", touchmove);
    container.removeEventListener("touchmove", preventBehavior);
  }

  function dragstart(e) {
    e.currentTarget.draggable = "false";
    e.currentTarget.classList.add("dragging");
  }
  function dragend(e) {
    e.stopPropagation();
    e.preventDefault();
    e.currentTarget.draggable = "true";
    let y = e.clientY;
    let elementAfter = getElementAfter(container, y);
    dragOrderChange(elementAfter, true, e.currentTarget);
  }
  function dragOver(e) {
    e.preventDefault();
    let y = e.clientY;
    let elementAfter = getElementAfter(container, y);
    dragOrderChange(elementAfter);
  }

  function actionQuickSettingsDraggable(checked) {
    if (checked) {
      draggables = Array.from(
        gradioApp().querySelectorAll(
          "#quicksettings_overflow_container > div:not(.dragging)"
        )
      );
      gradioApp().addEventListener("drop", preventBehavior);
    } else {
      gradioApp().removeEventListener("drop", preventBehavior);
    }

    gradioApp()
      .querySelectorAll("#quicksettings_overflow_container > div")
      .forEach(function (elem) {
        elem.draggable = checked;
        if (checked) {
          elem.addEventListener("touchstart", touchstart);
          elem.addEventListener("dragstart", dragstart);
          elem.addEventListener("dragend", dragend);
          elem.addEventListener("dragover", dragOver);
        } else {
          elem.removeEventListener("touchstart", touchstart, false);
          elem.removeEventListener("touchend", touchend, false);
          elem.removeEventListener("touchcancel", touchcancel, false);
          elem.removeEventListener("touchmove", touchmove, false);
          elem.removeEventListener("dragstart", dragstart, false);
          elem.removeEventListener("dragend", dragend, false);
          elem.removeEventListener("dragover", dragOver, false);
        }
      });
  }

  gradioApp()
    .querySelector("#quicksettings_draggable")
    .addEventListener("click", function (e) {
      if (e.target && e.target.matches("input[type='checkbox']")) {
        actionQuickSettingsDraggable(e.target.checked);
      }
    });

  updateOpStyles();

  /* anapnoe ui end */
});

onOptionsChanged(function() {
  var elem = gradioApp().getElementById('sd_checkpoint_hash');
  var sd_checkpoint_hash = opts.sd_checkpoint_hash || "";
  var shorthash = sd_checkpoint_hash.substring(0, 10);

  if (elem && elem.textContent != shorthash) {
      elem.textContent = shorthash;
      elem.title = sd_checkpoint_hash;
      elem.href = "https://google.com/search?q=" + sd_checkpoint_hash;
  }
});

let txt2img_textarea, img2img_textarea = undefined;
let wait_time = 800;
let token_timeouts = {};

function update_txt2img_tokens(...args) {
  update_token_counter("txt2img_token_button");
  if (args.length == 2) {
      return args[0];
  }
  return args;
}

function update_img2img_tokens(...args) {
  update_token_counter(
      "img2img_token_button"
  );
  if (args.length == 2) {
      return args[0];
  }
  return args;
}

function update_token_counter(button_id) {
  if (token_timeouts[button_id]) {
      clearTimeout(token_timeouts[button_id]);
  }
  token_timeouts[button_id] = setTimeout(() => gradioApp().getElementById(button_id)?.click(), wait_time);
}



function restart_reload() {
  let bg_color = window
    .getComputedStyle(gradioApp().querySelector("#header-top"))
    .getPropertyValue("--ae-main-bg-color");
  let primary_color = window
    .getComputedStyle(gradioApp().querySelector(".icon-info"))
    .getPropertyValue("--ae-primary-color");
  let panel_color = window
    .getComputedStyle(gradioApp().querySelector(".gradio-box"))
    .getPropertyValue("--ae-panel-bg-color");

  localStorage.setItem("bg_color", bg_color);
  localStorage.setItem("primary_color", primary_color);
  localStorage.setItem("panel_color", panel_color);

  if (localStorage.hasOwnProperty("bg_color")) {
    bg_color = localStorage.getItem("bg_color");
    primary_color = localStorage.getItem("primary_color");
    panel_color = localStorage.getItem("panel_color");
  }

  document.body.style.backgroundColor = bg_color;

  let style = document.createElement("style");
  style.type = "text/css";
  style.innerHTML =
    ".loader{position:absolute;top:50vh;left:50vw;height:60px;width:160px;margin:0;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%)} .circles{position:absolute;left:-5px;top:0;height:60px;width:180px} .circles span{position:absolute;top:25px;height:12px;width:12px;border-radius:12px;background-color:" +
    panel_color +
    "} .circles span.one{right:80px} .circles span.two{right:40px} .circles span.three{right:0px} .circles{-webkit-animation:animcircles 0.5s infinite linear;animation:animcircles 0.5s infinite linear} @-webkit-keyframes animcircles{0%{-webkit-transform:translate(0px,0px);transform:translate(0px,0px)}100%{-webkit-transform:translate(-40px,0px);transform:translate(-40px,0px)}} @keyframes animcircles{0%{-webkit-transform:translate(0px,0px);transform:translate(0px,0px)}100%{-webkit-transform:translate(-40px,0px);transform:translate(-40px,0px)}} .pacman{position:absolute;left:0;top:0;height:60px;width:60px} .pacman .eye{position:absolute;top:10px;left:30px;height:7px;width:7px;border-radius:7px;background-color:" +
    bg_color +
    '} .pacman span{position:absolute;top:0;left:0;height:60px;width:60px} .pacman span::before{content:"";position:absolute;left:0;height:30px;width:60px;background-color:' +
    primary_color +
    "} .pacman .top::before{top:0;border-radius:60px 60px 0px 0px} .pacman .bottom::before{bottom:0;border-radius:0px 0px 60px 60px} .pacman .left::before{bottom:0;height:60px;width:30px;border-radius:60px 0px 0px 60px} .pacman .top{-webkit-animation:animtop 0.5s infinite;animation:animtop 0.5s infinite} @-webkit-keyframes animtop{0%,100%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}50%{-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}} @keyframes animtop{0%,100%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}50%{-webkit-transform:rotate(-45deg);transform:rotate(-45deg)}} .pacman .bottom{-webkit-animation:animbottom 0.5s infinite;animation:animbottom 0.5s infinite} @-webkit-keyframes animbottom{0%,100%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}50%{-webkit-transform:rotate(45deg);transform:rotate(45deg)}} @keyframes animbottom{0%,100%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}50%{-webkit-transform:rotate(45deg);transform:rotate(45deg)}}";

  document.getElementsByTagName("head")[0].appendChild(style);
  document.body.innerHTML =
    '<div class="loader"><div class="circles"><span class="one"></span><span class="two"></span><span class="three"></span></div><div class="pacman"><span class="top"></span><span class="bottom"></span><span class="left"></span><div class="eye"></div></div></div>';

  var requestPing = function () {
    requestGet(
      "./internal/ping",
      {},
      function (data) {
        location.reload();
      },
      function () {
        setTimeout(requestPing, 500);
      }
    );
  };

  setTimeout(requestPing, 2000);

  return [];
}

// Simulate an `input` DOM event for Gradio Textbox component. Needed after you edit its contents in javascript, otherwise your edits
// will only visible on web page and not sent to python.
function updateInput(target) {
  const e = new Event("input", { bubbles: true });
  Object.defineProperty(e, "target", { value: target });
  target.dispatchEvent(e);
  const eb = new Event("blur");
  Object.defineProperty(eb, "target", { value: target });
  target.dispatchEvent(eb);
}

document.addEventListener("readystatechange", function (e) {
  document.body.style.display = "none";
  if (localStorage.hasOwnProperty("bg_color")) {
    document.getElementsByTagName("html")[0].style.backgroundColor =
      localStorage.getItem("bg_color");
    document.body.style.backgroundColor = localStorage.getItem("bg_color");
  }
});

window.onload = function () {
  document.getElementsByTagName("html")[0].style.backgroundColor =
    localStorage.getItem("bg_color");
  document.body.style.backgroundColor = localStorage.getItem("bg_color");
  document.body.style.display = "none";
  document.body.classList.add("dark");
  setTimeout(function () {
    document.body.style.display = "block";
  }, 1000);
};

var desiredCheckpointName = null;
function selectCheckpoint(name) {
    desiredCheckpointName = name;
    gradioApp().getElementById('change_checkpoint').click();
}

function currentImg2imgSourceResolution(w, h, scaleBy) {
    var img = gradioApp().querySelector('#mode_img2img > div[style="display: block;"] img');
    return img ? [img.naturalWidth, img.naturalHeight, scaleBy] : [0, 0, scaleBy];
}

function updateImg2imgResizeToTextAfterChangingImage() {
    // At the time this is called from gradio, the image has no yet been replaced.
    // There may be a better solution, but this is simple and straightforward so I'm going with it.

    setTimeout(function() {
        gradioApp().getElementById('img2img_update_resize_to').click();
    }, 500);

    return [];

}



function setRandomSeed(elem_id) {
    var input = gradioApp().querySelector("#" + elem_id + " input");
    if (!input) return [];

    input.value = "-1";
    updateInput(input);
    return [];
}

function switchWidthHeight(tabname) {
    var width = gradioApp().querySelector("#" + tabname + "_width input[type=number]");
    var height = gradioApp().querySelector("#" + tabname + "_height input[type=number]");
    if (!width || !height) return [];

    var tmp = width.value;
    width.value = height.value;
    height.value = tmp;

    updateInput(width);
    updateInput(height);
    return [];
}