Spaces:
Running
Running
File size: 100,158 Bytes
b82d373 |
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 |
import { POPUP_RESULT, POPUP_TYPE, Popup } from '../../../popup.js';
import { setSlashCommandAutoComplete } from '../../../slash-commands.js';
import { SlashCommandAbortController } from '../../../slash-commands/SlashCommandAbortController.js';
import { SlashCommandBreakPoint } from '../../../slash-commands/SlashCommandBreakPoint.js';
import { SlashCommandClosure } from '../../../slash-commands/SlashCommandClosure.js';
import { SlashCommandClosureResult } from '../../../slash-commands/SlashCommandClosureResult.js';
import { SlashCommandDebugController } from '../../../slash-commands/SlashCommandDebugController.js';
import { SlashCommandExecutor } from '../../../slash-commands/SlashCommandExecutor.js';
import { SlashCommandParser } from '../../../slash-commands/SlashCommandParser.js';
import { SlashCommandParserError } from '../../../slash-commands/SlashCommandParserError.js';
import { SlashCommandScope } from '../../../slash-commands/SlashCommandScope.js';
import { debounce, delay, getSortableDelay, showFontAwesomePicker } from '../../../utils.js';
import { log, quickReplyApi, warn } from '../index.js';
import morphdom from '../lib/morphdom-esm.js';
import { QuickReplyContextLink } from './QuickReplyContextLink.js';
import { QuickReplySet } from './QuickReplySet.js';
import { ContextMenu } from './ui/ctx/ContextMenu.js';
export class QuickReply {
/**
* @param {{ id?: number; contextList?: any; }} props
*/
static from(props) {
props.contextList = (props.contextList ?? []).map((/** @type {any} */ it)=>QuickReplyContextLink.from(it));
return Object.assign(new this(), props);
}
/**@type {number}*/ id;
/**@type {string}*/ icon;
/**@type {string}*/ label = '';
/**@type {boolean}*/ showLabel = false;
/**@type {string}*/ title = '';
/**@type {string}*/ message = '';
/**@type {QuickReplyContextLink[]}*/ contextList;
/**@type {boolean}*/ preventAutoExecute = true;
/**@type {boolean}*/ isHidden = false;
/**@type {boolean}*/ executeOnStartup = false;
/**@type {boolean}*/ executeOnUser = false;
/**@type {boolean}*/ executeOnAi = false;
/**@type {boolean}*/ executeOnChatChange = false;
/**@type {boolean}*/ executeOnGroupMemberDraft = false;
/**@type {boolean}*/ executeOnNewChat = false;
/**@type {string}*/ automationId = '';
/**@type {function}*/ onExecute;
/**@type {(qr:QuickReply)=>AsyncGenerator<SlashCommandClosureResult|{closure:SlashCommandClosure, executor:SlashCommandExecutor|SlashCommandClosureResult}, SlashCommandClosureResult, boolean>}*/ onDebug;
/**@type {function}*/ onDelete;
/**@type {function}*/ onUpdate;
/**@type {function}*/ onInsertBefore;
/**@type {function}*/ onTransfer;
/**@type {HTMLElement}*/ dom;
/**@type {HTMLElement}*/ domIcon;
/**@type {HTMLElement}*/ domLabel;
/**@type {HTMLElement}*/ settingsDom;
/**@type {HTMLElement}*/ settingsDomIcon;
/**@type {HTMLInputElement}*/ settingsDomLabel;
/**@type {HTMLTextAreaElement}*/ settingsDomMessage;
/**@type {Popup}*/ editorPopup;
/**@type {HTMLElement}*/ editorDom;
/**@type {HTMLTextAreaElement}*/ editorMessage;
/**@type {HTMLTextAreaElement}*/ editorMessageLabel;
/**@type {HTMLElement}*/ editorSyntax;
/**@type {HTMLElement}*/ editorExecuteBtn;
/**@type {HTMLElement}*/ editorExecuteBtnPause;
/**@type {HTMLElement}*/ editorExecuteBtnStop;
/**@type {HTMLElement}*/ editorExecuteProgress;
/**@type {HTMLElement}*/ editorExecuteErrors;
/**@type {HTMLElement}*/ editorExecuteResult;
/**@type {HTMLElement}*/ editorDebugState;
/**@type {Promise}*/ editorExecutePromise;
/**@type {boolean}*/ isExecuting;
/**@type {SlashCommandAbortController}*/ abortController;
/**@type {SlashCommandDebugController}*/ debugController;
get hasContext() {
return this.contextList && this.contextList.filter(it => it.set).length > 0;
}
unrender() {
this.dom?.remove();
this.dom = null;
}
updateRender() {
if (!this.dom) return;
this.dom.title = this.title || this.message;
if (this.icon) {
this.domIcon.classList.remove('qr--hidden');
if (this.showLabel) this.domLabel.classList.remove('qr--hidden');
else this.domLabel.classList.add('qr--hidden');
} else {
this.domIcon.classList.add('qr--hidden');
this.domLabel.classList.remove('qr--hidden');
}
this.domLabel.textContent = this.label;
this.dom.classList[this.hasContext ? 'add' : 'remove']('qr--hasCtx');
}
render() {
this.unrender();
if (!this.dom) {
const root = document.createElement('div'); {
this.dom = root;
root.classList.add('qr--button');
root.classList.add('menu_button');
if (this.hasContext) {
root.classList.add('qr--hasCtx');
}
root.title = this.title || this.message;
root.addEventListener('contextmenu', (evt) => {
log('contextmenu', this, this.hasContext);
if (this.hasContext) {
evt.preventDefault();
evt.stopPropagation();
const menu = new ContextMenu(this);
menu.show(evt);
}
});
root.addEventListener('click', (evt)=>{
if (evt.ctrlKey) {
this.showEditor();
return;
}
this.execute();
});
const icon = document.createElement('div'); {
this.domIcon = icon;
icon.classList.add('qr--button-icon');
icon.classList.add('fa-solid');
if (!this.icon) icon.classList.add('qr--hidden');
else icon.classList.add(this.icon);
root.append(icon);
}
const lbl = document.createElement('div'); {
this.domLabel = lbl;
lbl.classList.add('qr--button-label');
if (this.icon && !this.showLabel) lbl.classList.add('qr--hidden');
lbl.textContent = this.label;
root.append(lbl);
}
const expander = document.createElement('div'); {
expander.classList.add('qr--button-expander');
expander.textContent = '⋮';
expander.title = 'Open context menu';
expander.addEventListener('click', (evt) => {
evt.stopPropagation();
evt.preventDefault();
const menu = new ContextMenu(this);
menu.show(evt);
});
root.append(expander);
}
}
}
return this.dom;
}
renderSettings(idx) {
if (!this.settingsDom) {
const item = document.createElement('div'); {
this.settingsDom = item;
item.classList.add('qr--set-item');
item.setAttribute('data-order', String(idx));
item.setAttribute('data-id', String(this.id));
const adder = document.createElement('div'); {
adder.classList.add('qr--set-itemAdder');
const actions = document.createElement('div'); {
actions.classList.add('qr--actions');
const addNew = document.createElement('div'); {
addNew.classList.add('qr--action');
addNew.classList.add('qr--add');
addNew.classList.add('menu_button');
addNew.classList.add('menu_button_icon');
addNew.classList.add('fa-solid');
addNew.classList.add('fa-plus');
addNew.title = 'Add quick reply';
addNew.addEventListener('click', ()=>this.onInsertBefore());
actions.append(addNew);
}
const paste = document.createElement('div'); {
paste.classList.add('qr--action');
paste.classList.add('qr--paste');
paste.classList.add('menu_button');
paste.classList.add('menu_button_icon');
paste.classList.add('fa-solid');
paste.classList.add('fa-paste');
paste.title = 'Add quick reply from clipboard';
paste.addEventListener('click', async()=>{
const text = await navigator.clipboard.readText();
this.onInsertBefore(text);
});
actions.append(paste);
}
const importFile = document.createElement('div'); {
importFile.classList.add('qr--action');
importFile.classList.add('qr--importFile');
importFile.classList.add('menu_button');
importFile.classList.add('menu_button_icon');
importFile.classList.add('fa-solid');
importFile.classList.add('fa-file-import');
importFile.title = 'Add quick reply from JSON file';
importFile.addEventListener('click', async()=>{
const inp = document.createElement('input'); {
inp.type = 'file';
inp.accept = '.json';
inp.addEventListener('change', async()=>{
if (inp.files.length > 0) {
for (const file of inp.files) {
const text = await file.text();
this.onInsertBefore(text);
}
}
});
inp.click();
}
});
actions.append(importFile);
}
adder.append(actions);
}
item.append(adder);
}
const itemContent = document.createElement('div'); {
itemContent.classList.add('qr--content');
const drag = document.createElement('div'); {
drag.classList.add('drag-handle');
drag.classList.add('ui-sortable-handle');
drag.textContent = '☰';
itemContent.append(drag);
}
const lblContainer = document.createElement('div'); {
lblContainer.classList.add('qr--set-itemLabelContainer');
const icon = document.createElement('div'); {
this.settingsDomIcon = icon;
icon.title = 'Click to change icon';
icon.classList.add('qr--set-itemIcon');
icon.classList.add('menu_button');
icon.classList.add('fa-fw');
if (this.icon) {
icon.classList.add('fa-solid');
icon.classList.add(this.icon);
}
icon.addEventListener('click', async()=>{
let value = await showFontAwesomePicker();
this.updateIcon(value);
});
lblContainer.append(icon);
}
const lbl = document.createElement('input'); {
this.settingsDomLabel = lbl;
lbl.classList.add('qr--set-itemLabel');
lbl.classList.add('text_pole');
lbl.value = this.label;
lbl.addEventListener('input', ()=>this.updateLabel(lbl.value));
lblContainer.append(lbl);
}
itemContent.append(lblContainer);
}
item.append(itemContent);
}
const optContainer = document.createElement('div'); {
optContainer.classList.add('qr--set-optionsContainer');
const opt = document.createElement('div'); {
opt.classList.add('qr--action');
opt.classList.add('menu_button');
opt.classList.add('fa-fw');
opt.classList.add('fa-solid');
opt.textContent = '⁝';
opt.title = 'Additional options:\n - large editor\n - context menu\n - auto-execution\n - tooltip';
opt.addEventListener('click', ()=>this.showEditor());
optContainer.append(opt);
}
itemContent.append(optContainer);
}
const mes = document.createElement('textarea'); {
this.settingsDomMessage = mes;
mes.id = `qr--set--item${this.id}`;
mes.classList.add('qr--set-itemMessage');
mes.value = this.message;
//HACK need to use jQuery to catch the triggered event from the expanded editor
$(mes).on('input', ()=>this.updateMessage(mes.value));
itemContent.append(mes);
}
const actions = document.createElement('div'); {
actions.classList.add('qr--actions');
const move = document.createElement('div'); {
move.classList.add('qr--action');
move.classList.add('menu_button');
move.classList.add('fa-fw');
move.classList.add('fa-solid');
move.classList.add('fa-truck-arrow-right');
move.title = 'Move quick reply to other set';
move.addEventListener('click', ()=>this.onTransfer(this));
actions.append(move);
}
const copy = document.createElement('div'); {
copy.classList.add('qr--action');
copy.classList.add('menu_button');
copy.classList.add('fa-fw');
copy.classList.add('fa-solid');
copy.classList.add('fa-copy');
copy.title = 'Copy quick reply to clipboard';
copy.addEventListener('click', async()=>{
await navigator.clipboard.writeText(JSON.stringify(this));
copy.classList.add('qr--success');
await delay(3010);
copy.classList.remove('qr--success');
});
actions.append(copy);
}
const cut = document.createElement('div'); {
cut.classList.add('qr--action');
cut.classList.add('menu_button');
cut.classList.add('fa-fw');
cut.classList.add('fa-solid');
cut.classList.add('fa-cut');
cut.title = 'Cut quick reply to clipboard (copy and remove)';
cut.addEventListener('click', async()=>{
await navigator.clipboard.writeText(JSON.stringify(this));
this.delete();
});
actions.append(cut);
}
const exp = document.createElement('div'); {
exp.classList.add('qr--action');
exp.classList.add('menu_button');
exp.classList.add('fa-fw');
exp.classList.add('fa-solid');
exp.classList.add('fa-file-export');
exp.title = 'Export quick reply as file';
exp.addEventListener('click', ()=>{
const blob = new Blob([JSON.stringify(this)], { type:'text' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a'); {
a.href = url;
a.download = `${this.label}.qr.json`;
a.click();
}
});
actions.append(exp);
}
const del = document.createElement('div'); {
del.classList.add('qr--action');
del.classList.add('menu_button');
del.classList.add('fa-fw');
del.classList.add('fa-solid');
del.classList.add('fa-trash-can');
del.classList.add('redWarningBG');
del.title = 'Remove Quick Reply\n---\nShit+Click to skip confirmation';
del.addEventListener('click', async(evt)=>{
if (!evt.shiftKey) {
const result = await Popup.show.confirm(
'Remove Quick Reply',
'Are you sure you want to remove this Quick Reply?',
);
if (result != POPUP_RESULT.AFFIRMATIVE) {
return;
}
}
this.delete();
});
actions.append(del);
}
itemContent.append(actions);
}
}
}
return this.settingsDom;
}
unrenderSettings() {
this.settingsDom?.remove();
}
async showEditor() {
const response = await fetch('/scripts/extensions/quick-reply/html/qrEditor.html', { cache: 'no-store' });
if (response.ok) {
this.template = document.createRange().createContextualFragment(await response.text()).querySelector('#qr--modalEditor');
/**@type {HTMLElement} */
// @ts-ignore
const dom = this.template.cloneNode(true);
this.editorDom = dom;
this.editorPopup = new Popup(dom, POPUP_TYPE.TEXT, undefined, { okButton: 'OK', wide: true, large: true, rows: 1 });
const popupResult = this.editorPopup.show();
// basics
/**@type {HTMLElement}*/
const icon = dom.querySelector('#qr--modal-icon');
if (this.icon) {
icon.classList.add('fa-solid');
icon.classList.add(this.icon);
}
else {
icon.textContent = '…';
}
icon.addEventListener('click', async()=>{
let value = await showFontAwesomePicker();
if (value === null) return;
if (this.icon) icon.classList.remove(this.icon);
if (value == '') {
icon.classList.remove('fa-solid');
icon.textContent = '…';
} else {
icon.textContent = '';
icon.classList.add('fa-solid');
icon.classList.add(value);
}
this.updateIcon(value);
});
/**@type {HTMLInputElement}*/
const showLabel = dom.querySelector('#qr--modal-showLabel');
showLabel.checked = this.showLabel;
showLabel.addEventListener('click', ()=>{
this.updateShowLabel(showLabel.checked);
});
/**@type {HTMLInputElement}*/
const label = dom.querySelector('#qr--modal-label');
label.value = this.label;
label.addEventListener('input', ()=>{
this.updateLabel(label.value);
});
let switcherList;
dom.querySelector('#qr--modal-switcher').addEventListener('click', (evt)=>{
if (switcherList) {
switcherList.remove();
switcherList = null;
return;
}
const list = document.createElement('ul'); {
switcherList = list;
list.classList.add('qr--modal-switcherList');
const makeList = (qrs)=>{
const setItem = document.createElement('li'); {
setItem.classList.add('qr--modal-switcherItem');
setItem.addEventListener('click', ()=>{
list.innerHTML = '';
for (const qrs of quickReplyApi.listSets()) {
const item = document.createElement('li'); {
item.classList.add('qr--modal-switcherItem');
item.addEventListener('click', ()=>{
list.innerHTML = '';
makeList(quickReplyApi.getSetByName(qrs));
});
const lbl = document.createElement('div'); {
lbl.classList.add('qr--label');
lbl.textContent = qrs;
item.append(lbl);
}
list.append(item);
}
}
});
const lbl = document.createElement('div'); {
lbl.classList.add('qr--label');
const icon = document.createElement('i'); {
icon.classList.add('fa-solid');
icon.classList.add('fa-arrow-alt-circle-right');
icon.classList.add('menu_button');
lbl.append(icon);
}
const text = document.createElement('span'); {
text.textContent = 'Switch QR Sets...';
lbl.append(text);
}
setItem.append(lbl);
}
list.append(setItem);
}
const addItem = document.createElement('li'); {
addItem.classList.add('qr--modal-switcherItem');
addItem.addEventListener('click', ()=>{
const qr = quickReplyApi.getSetByQr(this).addQuickReply();
this.editorPopup.completeAffirmative();
qr.showEditor();
});
const lbl = document.createElement('div'); {
lbl.classList.add('qr--label');
const icon = document.createElement('i'); {
icon.classList.add('fa-solid');
icon.classList.add('fa-plus');
icon.classList.add('menu_button');
lbl.append(icon);
}
const text = document.createElement('span'); {
text.textContent = 'Add QR';
lbl.append(text);
}
addItem.append(lbl);
}
list.append(addItem);
}
for (const qr of qrs.qrList.toSorted((a,b)=>a.label.toLowerCase().localeCompare(b.label.toLowerCase()))) {
const item = document.createElement('li'); {
item.classList.add('qr--modal-switcherItem');
if (qr == this) item.classList.add('qr--current');
else item.addEventListener('click', ()=>{
this.editorPopup.completeAffirmative();
qr.showEditor();
});
const lbl = document.createElement('div'); {
lbl.classList.add('qr--label');
lbl.textContent = qr.label;
item.append(lbl);
}
const id = document.createElement('div'); {
id.classList.add('qr--id');
id.textContent = qr.id.toString();
item.append(id);
}
const mes = document.createElement('div'); {
mes.classList.add('qr--message');
mes.textContent = qr.message;
item.append(mes);
}
list.append(item);
}
}
};
makeList(quickReplyApi.getSetByQr(this));
}
label.parentElement.append(list);
});
/**@type {HTMLInputElement}*/
const title = dom.querySelector('#qr--modal-title');
title.value = this.title;
title.addEventListener('input', () => {
this.updateTitle(title.value);
});
/**@type {HTMLElement}*/
const messageSyntaxInner = dom.querySelector('#qr--modal-messageSyntaxInner');
this.editorSyntax = messageSyntaxInner;
/**@type {HTMLInputElement}*/
const wrap = dom.querySelector('#qr--modal-wrap');
wrap.checked = JSON.parse(localStorage.getItem('qr--wrap') ?? 'false');
wrap.addEventListener('click', () => {
localStorage.setItem('qr--wrap', JSON.stringify(wrap.checked));
updateWrap();
});
const updateWrap = () => {
if (wrap.checked) {
message.style.whiteSpace = 'pre-wrap';
messageSyntaxInner.style.whiteSpace = 'pre-wrap';
if (this.clone) {
this.clone.style.whiteSpace = 'pre-wrap';
}
} else {
message.style.whiteSpace = 'pre';
messageSyntaxInner.style.whiteSpace = 'pre';
if (this.clone) {
this.clone.style.whiteSpace = 'pre';
}
}
updateScrollDebounced();
};
const updateScroll = (evt) => {
let left = message.scrollLeft;
let top = message.scrollTop;
if (evt) {
evt.preventDefault();
left = message.scrollLeft + evt.deltaX;
top = message.scrollTop + evt.deltaY;
message.scrollTo({
behavior: 'instant',
left,
top,
});
}
messageSyntaxInner.scrollTo({
behavior: 'instant',
left,
top,
});
};
const updateScrollDebounced = updateScroll;
const updateSyntaxEnabled = ()=>{
if (syntax.checked) {
dom.querySelector('#qr--modal-messageHolder').classList.remove('qr--noSyntax');
} else {
dom.querySelector('#qr--modal-messageHolder').classList.add('qr--noSyntax');
}
};
/**@type {HTMLInputElement}*/
const tabSize = dom.querySelector('#qr--modal-tabSize');
tabSize.value = JSON.parse(localStorage.getItem('qr--tabSize') ?? '4');
const updateTabSize = () => {
message.style.tabSize = tabSize.value;
messageSyntaxInner.style.tabSize = tabSize.value;
updateScrollDebounced();
};
tabSize.addEventListener('change', () => {
localStorage.setItem('qr--tabSize', JSON.stringify(Number(tabSize.value)));
updateTabSize();
});
/**@type {HTMLInputElement}*/
const executeShortcut = dom.querySelector('#qr--modal-executeShortcut');
executeShortcut.checked = JSON.parse(localStorage.getItem('qr--executeShortcut') ?? 'true');
executeShortcut.addEventListener('click', () => {
localStorage.setItem('qr--executeShortcut', JSON.stringify(executeShortcut.checked));
});
/**@type {HTMLInputElement}*/
const syntax = dom.querySelector('#qr--modal-syntax');
syntax.checked = JSON.parse(localStorage.getItem('qr--syntax') ?? 'true');
syntax.addEventListener('click', () => {
localStorage.setItem('qr--syntax', JSON.stringify(syntax.checked));
updateSyntaxEnabled();
});
if (navigator.keyboard) {
navigator.keyboard.getLayoutMap().then(it=>dom.querySelector('#qr--modal-commentKey').textContent = it.get('Backslash'));
} else {
dom.querySelector('#qr--modal-commentKey').closest('small').remove();
}
this.editorMessageLabel = dom.querySelector('label[for="qr--modal-message"]');
/**@type {HTMLTextAreaElement}*/
const message = dom.querySelector('#qr--modal-message');
this.editorMessage = message;
message.value = this.message;
const updateMessageDebounced = debounce((value)=>this.updateMessage(value), 10);
message.addEventListener('input', () => {
updateMessageDebounced(message.value);
updateScrollDebounced();
}, { passive:true });
const getLineStart = ()=>{
const start = message.selectionStart;
const end = message.selectionEnd;
let lineStart;
if (start == 0 || message.value[start - 1] == '\n') {
// cursor is already at beginning of line
// -> keep start
lineStart = start;
} else {
// cursor is at end of line or somewhere in the line
// -> find last newline before cursor and start after that
lineStart = message.value.lastIndexOf('\n', start - 1) + 1;
}
return lineStart;
};
message.addEventListener('keydown', async(evt) => {
if (this.isExecuting) return;
if (evt.key == 'Tab' && !evt.shiftKey && !evt.ctrlKey && !evt.altKey) {
// increase indent
evt.preventDefault();
const start = message.selectionStart;
const end = message.selectionEnd;
if (end - start > 0 && message.value.substring(start, end).includes('\n')) {
evt.stopImmediatePropagation();
evt.stopPropagation();
const lineStart = getLineStart();
message.selectionStart = lineStart;
const affectedLines = message.value.substring(lineStart, end).split('\n');
// document.execCommand is deprecated (and potentially buggy in some browsers) but the only way to retain undo-history
document.execCommand('insertText', false, `\t${affectedLines.join('\n\t')}`);
message.selectionStart = start + 1;
message.selectionEnd = end + affectedLines.length;
message.dispatchEvent(new Event('input', { bubbles:true }));
} else if (!(ac.isReplaceable && ac.isActive)) {
evt.stopImmediatePropagation();
evt.stopPropagation();
// document.execCommand is deprecated (and potentially buggy in some browsers) but the only way to retain undo-history
document.execCommand('insertText', false, '\t');
message.dispatchEvent(new Event('input', { bubbles:true }));
}
} else if (evt.key == 'Tab' && evt.shiftKey && !evt.ctrlKey && !evt.altKey) {
// decrease indent
evt.preventDefault();
evt.stopImmediatePropagation();
evt.stopPropagation();
const start = message.selectionStart;
const end = message.selectionEnd;
const lineStart = getLineStart();
message.selectionStart = lineStart;
const affectedLines = message.value.substring(lineStart, end).split('\n');
const newText = affectedLines.map(it=>it.replace(/^\t/, '')).join('\n');
const delta = affectedLines.join('\n').length - newText.length;
// document.execCommand is deprecated (and potentially buggy in some browsers) but the only way to retain undo-history
if (delta > 0) {
if (newText == '') {
document.execCommand('delete', false);
} else {
document.execCommand('insertText', false, newText);
}
message.selectionStart = start - (affectedLines[0].startsWith('\t') ? 1 : 0);
message.selectionEnd = end - delta;
message.dispatchEvent(new Event('input', { bubbles:true }));
} else {
message.selectionStart = start;
}
} else if (evt.key == 'Enter' && !evt.ctrlKey && !evt.shiftKey && !evt.altKey && !(ac.isReplaceable && ac.isActive)) {
// new line, keep indent
const start = message.selectionStart;
const end = message.selectionEnd;
let lineStart = getLineStart();
const indent = /^([^\S\n]*)/.exec(message.value.slice(lineStart))[1] ?? '';
if (indent.length) {
evt.stopImmediatePropagation();
evt.stopPropagation();
evt.preventDefault();
// document.execCommand is deprecated (and potentially buggy in some browsers) but the only way to retain undo-history
document.execCommand('insertText', false, `\n${indent}`);
message.selectionStart = start + 1 + indent.length;
message.selectionEnd = message.selectionStart;
message.dispatchEvent(new Event('input', { bubbles:true }));
}
} else if (evt.key == 'Enter' && evt.ctrlKey && !evt.shiftKey && !evt.altKey) {
if (executeShortcut.checked) {
// execute QR
evt.stopImmediatePropagation();
evt.stopPropagation();
evt.preventDefault();
const selectionStart = message.selectionStart;
const selectionEnd = message.selectionEnd;
message.blur();
await this.executeFromEditor();
if (document.activeElement != message) {
message.focus();
message.selectionStart = selectionStart;
message.selectionEnd = selectionEnd;
}
}
} else if (evt.key == 'F9' && !evt.ctrlKey && !evt.shiftKey && !evt.altKey) {
// toggle breakpoint
evt.stopImmediatePropagation();
evt.stopPropagation();
evt.preventDefault();
preBreakPointStart = message.selectionStart;
preBreakPointEnd = message.selectionEnd;
toggleBreakpoint();
} else if (evt.code == 'Backslash' && evt.ctrlKey && !evt.shiftKey && !evt.altKey) {
// toggle block comment
// (evt.code will use the same physical key on the keyboard across different keyboard layouts)
evt.stopImmediatePropagation();
evt.stopPropagation();
evt.preventDefault();
// check if we are inside a comment -> uncomment
const parser = new SlashCommandParser();
parser.parse(message.value, false);
const start = message.selectionStart;
const end = message.selectionEnd;
const comment = parser.commandIndex.findLast(it=>it.name == '*' && (it.start <= start && it.end >= start || it.start <= end && it.end >= end));
if (comment) {
// uncomment
let content = message.value.slice(comment.start + 1, comment.end - 1);
let len = content.length;
content = content.replace(/^ /, '');
const offsetStart = len - content.length;
len = content.length;
content = content.replace(/ $/, '');
const offsetEnd = len - content.length;
message.selectionStart = comment.start - 1;
message.selectionEnd = comment.end + 1;
// document.execCommand is deprecated (and potentially buggy in some browsers) but the only way to retain undo-history
document.execCommand('insertText', false, content);
message.selectionStart = start - (start >= comment.start ? 2 + offsetStart : 0);
message.selectionEnd = end - 2 - offsetStart - (end >= comment.end ? 2 + offsetEnd : 0);
} else {
// comment
const lineStart = getLineStart();
const lineEnd = message.value.indexOf('\n', end);
message.selectionStart = lineStart;
message.selectionEnd = lineEnd;
// document.execCommand is deprecated (and potentially buggy in some browsers) but the only way to retain undo-history
document.execCommand('insertText', false, `/* ${message.value.slice(lineStart, lineEnd)} *|`);
message.selectionStart = start + 3;
message.selectionEnd = end + 3;
}
message.dispatchEvent(new Event('input', { bubbles:true }));
}
});
const ac = await setSlashCommandAutoComplete(message, true);
message.addEventListener('wheel', (evt)=>{
updateScrollDebounced(evt);
});
message.addEventListener('scroll', (evt)=>{
updateScrollDebounced();
});
let preBreakPointStart;
let preBreakPointEnd;
/**
* @param {SlashCommandBreakPoint} bp
*/
const removeBreakpoint = (bp)=>{
// start at -1 because "/" is not included in start-end
let start = bp.start - 1;
// step left until forward slash "/"
while (message.value[start] != '/') start--;
// step left while whitespace (except newline) before start
while (/[^\S\n]/.test(message.value[start - 1])) start--;
// if newline before indent, include the newline for removal
if (message.value[start - 1] == '\n') start--;
let end = bp.end;
// step right while whitespace
while (/\s/.test(message.value[end])) end++;
// if pipe after whitepace, include pipe for removal
if (message.value[end] == '|') end++;
message.selectionStart = start;
message.selectionEnd = end;
// document.execCommand is deprecated (and potentially buggy in some browsers) but the only way to retain undo-history
document.execCommand('insertText', false, '');
message.dispatchEvent(new Event('input', { bubbles:true }));
let postStart = preBreakPointStart;
let postEnd = preBreakPointEnd;
// set caret back to where it was
if (preBreakPointStart <= start) {
// selection start was before breakpoint: do nothing
} else if (preBreakPointStart > start && preBreakPointEnd < end) {
// selection start was inside breakpoint: move to index before breakpoint
postStart = start;
} else if (preBreakPointStart >= end) {
// selection start was behind breakpoint: move back by length of removed string
postStart = preBreakPointStart - (end - start);
}
if (preBreakPointEnd <= start) {
// do nothing
} else if (preBreakPointEnd > start && preBreakPointEnd < end) {
// selection end was inside breakpoint: move to index before breakpoint
postEnd = start;
} else if (preBreakPointEnd >= end) {
// selection end was behind breakpoint: move back by length of removed string
postEnd = preBreakPointEnd - (end - start);
}
return { start:postStart, end:postEnd };
};
/**
* @param {SlashCommandExecutor} cmd
*/
const addBreakpoint = (cmd)=>{
// start at -1 because "/" is not included in start-end
let start = cmd.start - 1;
let indent = '';
// step left until forward slash "/"
while (message.value[start] != '/') start--;
// step left while whitespace (except newline) before start, collect the whitespace to help build indentation
while (/[^\S\n]/.test(message.value[start - 1])) {
start--;
indent += message.value[start];
}
// if newline before indent, include the newline
if (message.value[start - 1] == '\n') {
start--;
indent = `\n${indent}`;
}
const breakpointText = `${indent}/breakpoint |`;
message.selectionStart = start;
message.selectionEnd = start;
// document.execCommand is deprecated (and potentially buggy in some browsers) but the only way to retain undo-history
document.execCommand('insertText', false, breakpointText);
message.dispatchEvent(new Event('input', { bubbles:true }));
return breakpointText.length;
};
const toggleBreakpoint = ()=>{
const idx = message.selectionStart;
let postStart = preBreakPointStart;
let postEnd = preBreakPointEnd;
const parser = new SlashCommandParser();
parser.parse(message.value, false);
const cmdIdx = parser.commandIndex.findLastIndex(it=>it.start <= idx);
if (cmdIdx > -1) {
const cmd = parser.commandIndex[cmdIdx];
if (cmd instanceof SlashCommandBreakPoint) {
const bp = cmd;
const { start, end } = removeBreakpoint(bp);
postStart = start;
postEnd = end;
} else if (parser.commandIndex[cmdIdx - 1] instanceof SlashCommandBreakPoint) {
const bp = parser.commandIndex[cmdIdx - 1];
const { start, end } = removeBreakpoint(bp);
postStart = start;
postEnd = end;
} else {
const len = addBreakpoint(cmd);
postStart += len;
postEnd += len;
}
message.selectionStart = postStart;
message.selectionEnd = postEnd;
}
};
message.addEventListener('pointerdown', (evt)=>{
if (!evt.ctrlKey || !evt.altKey) return;
preBreakPointStart = message.selectionStart;
preBreakPointEnd = message.selectionEnd;
});
message.addEventListener('pointerup', async(evt)=>{
if (!evt.ctrlKey || !evt.altKey || message.selectionStart != message.selectionEnd) return;
toggleBreakpoint();
});
/** @type {any} */
const resizeListener = debounce((evt) => {
updateScrollDebounced(evt);
if (document.activeElement == message) {
message.blur();
message.focus();
}
});
window.addEventListener('resize', resizeListener);
updateSyntaxEnabled();
const updateSyntax = ()=>{
if (messageSyntaxInner && syntax.checked) {
morphdom(
messageSyntaxInner,
`<div>${hljs.highlight(`${message.value}${message.value.slice(-1) == '\n' ? ' ' : ''}`, { language:'stscript', ignoreIllegals:true })?.value}</div>`,
{ childrenOnly: true },
);
updateScrollDebounced();
}
};
let lastSyntaxUpdate = 0;
const fpsTime = 1000 / 30;
let lastMessageValue = null;
let wasSyntax = null;
const updateSyntaxLoop = ()=>{
const now = Date.now();
// fps limit
if (now - lastSyntaxUpdate < fpsTime) return requestAnimationFrame(updateSyntaxLoop);
// elements don't exist (yet?)
if (!messageSyntaxInner || !message) return requestAnimationFrame(updateSyntaxLoop);
// elements no longer part of the document
if (!messageSyntaxInner.closest('body')) return;
// debugger is running
if (this.isExecuting) {
lastMessageValue = null;
return requestAnimationFrame(updateSyntaxLoop);
}
// value hasn't changed
if (wasSyntax == syntax.checked && lastMessageValue == message.value) return requestAnimationFrame(updateSyntaxLoop);
wasSyntax = syntax.checked;
lastSyntaxUpdate = now;
lastMessageValue = message.value;
updateSyntax();
requestAnimationFrame(updateSyntaxLoop);
};
requestAnimationFrame(()=>updateSyntaxLoop());
message.style.setProperty('text-shadow', 'none', 'important');
updateWrap();
updateTabSize();
// context menu
/**@type {HTMLTemplateElement}*/
const tpl = dom.querySelector('#qr--ctxItem');
const linkList = dom.querySelector('#qr--ctxEditor');
const fillQrSetSelect = (/**@type {HTMLSelectElement}*/select, /**@type {QuickReplyContextLink}*/ link) => {
[{ name: 'Select a QR set' }, ...QuickReplySet.list.toSorted((a,b)=>a.name.toLowerCase().localeCompare(b.name.toLowerCase()))].forEach(qrs => {
const opt = document.createElement('option'); {
opt.value = qrs.name;
opt.textContent = qrs.name;
opt.selected = qrs.name == link.set?.name;
select.append(opt);
}
});
};
const addCtxItem = (/**@type {QuickReplyContextLink}*/link, /**@type {number}*/idx) => {
/**@type {HTMLElement} */
// @ts-ignore
const itemDom = tpl.content.querySelector('.qr--ctxItem').cloneNode(true); {
itemDom.setAttribute('data-order', String(idx));
/**@type {HTMLSelectElement} */
const select = itemDom.querySelector('.qr--set');
fillQrSetSelect(select, link);
select.addEventListener('change', () => {
link.set = QuickReplySet.get(select.value);
this.updateContext();
});
/**@type {HTMLInputElement} */
const chain = itemDom.querySelector('.qr--isChained');
chain.checked = link.isChained;
chain.addEventListener('click', () => {
link.isChained = chain.checked;
this.updateContext();
});
itemDom.querySelector('.qr--delete').addEventListener('click', () => {
itemDom.remove();
this.contextList.splice(this.contextList.indexOf(link), 1);
this.updateContext();
});
linkList.append(itemDom);
}
};
[...this.contextList].forEach((link, idx) => addCtxItem(link, idx));
dom.querySelector('#qr--ctxAdd').addEventListener('click', () => {
const link = new QuickReplyContextLink();
this.contextList.push(link);
addCtxItem(link, this.contextList.length - 1);
});
const onContextSort = () => {
this.contextList = Array.from(linkList.querySelectorAll('.qr--ctxItem')).map((it,idx) => {
const link = this.contextList[Number(it.getAttribute('data-order'))];
it.setAttribute('data-order', String(idx));
return link;
});
this.updateContext();
};
// @ts-ignore
$(linkList).sortable({
delay: getSortableDelay(),
stop: () => onContextSort(),
});
// auto-exec
/**@type {HTMLInputElement}*/
const preventAutoExecute = dom.querySelector('#qr--preventAutoExecute');
preventAutoExecute.checked = this.preventAutoExecute;
preventAutoExecute.addEventListener('click', ()=>{
this.preventAutoExecute = preventAutoExecute.checked;
this.updateContext();
});
/**@type {HTMLInputElement}*/
const isHidden = dom.querySelector('#qr--isHidden');
isHidden.checked = this.isHidden;
isHidden.addEventListener('click', ()=>{
this.isHidden = isHidden.checked;
this.updateContext();
});
/**@type {HTMLInputElement}*/
const executeOnStartup = dom.querySelector('#qr--executeOnStartup');
executeOnStartup.checked = this.executeOnStartup;
executeOnStartup.addEventListener('click', ()=>{
this.executeOnStartup = executeOnStartup.checked;
this.updateContext();
});
/**@type {HTMLInputElement}*/
const executeOnUser = dom.querySelector('#qr--executeOnUser');
executeOnUser.checked = this.executeOnUser;
executeOnUser.addEventListener('click', ()=>{
this.executeOnUser = executeOnUser.checked;
this.updateContext();
});
/**@type {HTMLInputElement}*/
const executeOnAi = dom.querySelector('#qr--executeOnAi');
executeOnAi.checked = this.executeOnAi;
executeOnAi.addEventListener('click', ()=>{
this.executeOnAi = executeOnAi.checked;
this.updateContext();
});
/**@type {HTMLInputElement}*/
const executeOnChatChange = dom.querySelector('#qr--executeOnChatChange');
executeOnChatChange.checked = this.executeOnChatChange;
executeOnChatChange.addEventListener('click', ()=>{
this.executeOnChatChange = executeOnChatChange.checked;
this.updateContext();
});
/**@type {HTMLInputElement}*/
const executeOnGroupMemberDraft = dom.querySelector('#qr--executeOnGroupMemberDraft');
executeOnGroupMemberDraft.checked = this.executeOnGroupMemberDraft;
executeOnGroupMemberDraft.addEventListener('click', ()=>{
this.executeOnGroupMemberDraft = executeOnGroupMemberDraft.checked;
this.updateContext();
});
/**@type {HTMLInputElement}*/
const executeOnNewChat = dom.querySelector('#qr--executeOnNewChat');
executeOnNewChat.checked = this.executeOnNewChat;
executeOnNewChat.addEventListener('click', ()=>{
this.executeOnNewChat = executeOnNewChat.checked;
this.updateContext();
});
/**@type {HTMLInputElement}*/
const automationId = dom.querySelector('#qr--automationId');
automationId.value = this.automationId;
automationId.addEventListener('input', () => {
this.automationId = automationId.value;
this.updateContext();
});
/**@type {HTMLElement}*/
const executeProgress = dom.querySelector('#qr--modal-executeProgress');
this.editorExecuteProgress = executeProgress;
/**@type {HTMLElement}*/
const executeErrors = dom.querySelector('#qr--modal-executeErrors');
this.editorExecuteErrors = executeErrors;
/**@type {HTMLElement}*/
const executeResult = dom.querySelector('#qr--modal-executeResult');
this.editorExecuteResult = executeResult;
/**@type {HTMLElement}*/
const debugState = dom.querySelector('#qr--modal-debugState');
this.editorDebugState = debugState;
/**@type {HTMLElement}*/
const executeBtn = dom.querySelector('#qr--modal-execute');
this.editorExecuteBtn = executeBtn;
executeBtn.addEventListener('click', async()=>{
await this.executeFromEditor();
});
/**@type {HTMLElement}*/
const executeBtnPause = dom.querySelector('#qr--modal-pause');
this.editorExecuteBtnPause = executeBtnPause;
executeBtnPause.addEventListener('click', async()=>{
if (this.abortController) {
if (this.abortController.signal.paused) {
this.abortController.continue('Continue button clicked');
this.editorExecuteProgress.classList.remove('qr--paused');
} else {
this.abortController.pause('Pause button clicked');
this.editorExecuteProgress.classList.add('qr--paused');
}
}
});
/**@type {HTMLElement}*/
const executeBtnStop = dom.querySelector('#qr--modal-stop');
this.editorExecuteBtnStop = executeBtnStop;
executeBtnStop.addEventListener('click', async()=>{
this.abortController?.abort('Stop button clicked');
});
/**@type {HTMLTextAreaElement} */
const inputOg = document.querySelector('#send_textarea');
const inputMirror = dom.querySelector('#qr--modal-send_textarea');
inputMirror.value = inputOg.value;
const inputOgMo = new MutationObserver(muts=>{
if (muts.find(it=>[...it.removedNodes].includes(inputMirror) || [...it.removedNodes].find(n=>n.contains(inputMirror)))) {
inputOg.removeEventListener('input', inputOgListener);
}
});
inputOgMo.observe(document.body, { childList:true });
const inputOgListener = ()=>{
inputMirror.value = inputOg.value;
};
inputOg.addEventListener('input', inputOgListener);
inputMirror.addEventListener('input', ()=>{
inputOg.value = inputMirror.value;
});
/**@type {HTMLElement}*/
const resumeBtn = dom.querySelector('#qr--modal-resume');
resumeBtn.addEventListener('click', ()=>{
this.debugController?.resume();
});
/**@type {HTMLElement}*/
const stepBtn = dom.querySelector('#qr--modal-step');
stepBtn.addEventListener('click', ()=>{
this.debugController?.step();
});
/**@type {HTMLElement}*/
const stepIntoBtn = dom.querySelector('#qr--modal-stepInto');
stepIntoBtn.addEventListener('click', ()=>{
this.debugController?.stepInto();
});
/**@type {HTMLElement}*/
const stepOutBtn = dom.querySelector('#qr--modal-stepOut');
stepOutBtn.addEventListener('click', ()=>{
this.debugController?.stepOut();
});
/**@type {HTMLElement}*/
const minimizeBtn = dom.querySelector('#qr--modal-minimize');
minimizeBtn.addEventListener('click', ()=>{
this.editorDom.classList.add('qr--minimized');
});
const maximizeBtn = dom.querySelector('#qr--modal-maximize');
maximizeBtn.addEventListener('click', ()=>{
this.editorDom.classList.remove('qr--minimized');
});
/**@type {boolean}*/
let isResizing = false;
let resizeStart;
let wStart;
/**@type {HTMLElement}*/
const resizeHandle = dom.querySelector('#qr--resizeHandle');
resizeHandle.addEventListener('pointerdown', (evt)=>{
if (isResizing) return;
isResizing = true;
evt.preventDefault();
resizeStart = evt.x;
wStart = dom.querySelector('#qr--qrOptions').offsetWidth;
const dragListener = debounce((evt)=>{
const w = wStart + resizeStart - evt.x;
dom.querySelector('#qr--qrOptions').style.setProperty('--width', `${w}px`);
}, 5);
window.addEventListener('pointerup', ()=>{
window.removeEventListener('pointermove', dragListener);
isResizing = false;
}, { once:true });
window.addEventListener('pointermove', dragListener);
});
await popupResult;
window.removeEventListener('resize', resizeListener);
} else {
warn('failed to fetch qrEditor template');
}
}
getEditorPosition(start, end, message = null) {
const inputRect = this.editorMessage.getBoundingClientRect();
const style = window.getComputedStyle(this.editorMessage);
if (!this.clone) {
this.clone = document.createElement('div');
for (const key of style) {
this.clone.style[key] = style[key];
}
this.clone.style.position = 'fixed';
this.clone.style.visibility = 'hidden';
const mo = new MutationObserver(muts=>{
if (muts.find(it=>[...it.removedNodes].includes(this.editorMessage) || [...it.removedNodes].find(n=>n.contains(this.editorMessage)))) {
this.clone?.remove();
this.clone = null;
}
});
mo.observe(document.body, { childList:true });
}
document.body.append(this.clone);
this.clone.style.width = `${inputRect.width}px`;
this.clone.style.height = `${inputRect.height}px`;
this.clone.style.left = `${inputRect.left}px`;
this.clone.style.top = `${inputRect.top}px`;
this.clone.style.whiteSpace = style.whiteSpace;
this.clone.style.tabSize = style.tabSize;
const text = message ?? this.editorMessage.value;
const before = text.slice(0, start);
this.clone.textContent = before;
const locator = document.createElement('span');
locator.textContent = text.slice(start, end);
this.clone.append(locator);
this.clone.append(text.slice(end));
this.clone.scrollTop = this.editorSyntax.scrollTop;
this.clone.scrollLeft = this.editorSyntax.scrollLeft;
const locatorRect = locator.getBoundingClientRect();
const bodyRect = document.body.getBoundingClientRect();
const location = {
left: locatorRect.left - bodyRect.left,
right: locatorRect.right - bodyRect.left,
top: locatorRect.top - bodyRect.top,
bottom: locatorRect.bottom - bodyRect.top,
};
// this.clone.remove();
return location;
}
async executeFromEditor() {
if (this.isExecuting) return;
this.editorPopup.onClosing = ()=>false;
const uuidCheck = /^[0-9a-z]{8}(-[0-9a-z]{4}){3}-[0-9a-z]{12}$/;
const oText = this.message;
this.isExecuting = true;
this.editorDom.classList.add('qr--isExecuting');
const noSyntax = this.editorDom.querySelector('#qr--modal-messageHolder').classList.contains('qr--noSyntax');
if (noSyntax) {
this.editorDom.querySelector('#qr--modal-messageHolder').classList.remove('qr--noSyntax');
}
this.editorExecuteBtn.classList.add('qr--busy');
this.editorExecuteProgress.style.setProperty('--prog', '0');
this.editorExecuteErrors.classList.remove('qr--hasErrors');
this.editorExecuteResult.classList.remove('qr--hasResult');
this.editorExecuteProgress.classList.remove('qr--error');
this.editorExecuteProgress.classList.remove('qr--success');
this.editorExecuteProgress.classList.remove('qr--paused');
this.editorExecuteProgress.classList.remove('qr--aborted');
this.editorExecuteErrors.innerHTML = '';
this.editorExecuteResult.innerHTML = '';
const syntax = this.editorDom.querySelector('#qr--modal-messageSyntaxInner');
const updateScroll = (evt) => {
let left = syntax.scrollLeft;
let top = syntax.scrollTop;
if (evt) {
evt.preventDefault();
left = syntax.scrollLeft + evt.deltaX;
top = syntax.scrollTop + evt.deltaY;
syntax.scrollTo({
behavior: 'instant',
left,
top,
});
}
this.editorMessage.scrollTo({
behavior: 'instant',
left,
top,
});
};
const updateScrollDebounced = updateScroll;
syntax.addEventListener('wheel', (evt)=>{
updateScrollDebounced(evt);
});
syntax.addEventListener('scroll', (evt)=>{
updateScrollDebounced();
});
try {
this.abortController = new SlashCommandAbortController();
this.debugController = new SlashCommandDebugController();
this.debugController.onBreakPoint = async(closure, executor)=>{
this.editorDom.classList.add('qr--isPaused');
syntax.innerHTML = hljs.highlight(`${closure.fullText}${closure.fullText.slice(-1) == '\n' ? ' ' : ''}`, { language:'stscript', ignoreIllegals:true })?.value;
this.editorMessageLabel.innerHTML = '';
if (uuidCheck.test(closure.source)) {
const p0 = document.createElement('span'); {
p0.textContent = 'anonymous: ';
this.editorMessageLabel.append(p0);
}
const p1 = document.createElement('strong'); {
p1.textContent = executor.source.slice(0,5);
this.editorMessageLabel.append(p1);
}
const p2 = document.createElement('span'); {
p2.textContent = executor.source.slice(5, -5);
this.editorMessageLabel.append(p2);
}
const p3 = document.createElement('strong'); {
p3.textContent = executor.source.slice(-5);
this.editorMessageLabel.append(p3);
}
} else {
this.editorMessageLabel.textContent = executor.source;
}
const source = closure.source;
this.editorDebugState.innerHTML = '';
let ci = -1;
const varNames = [];
const macroNames = [];
/**
* @param {SlashCommandScope} scope
*/
const buildVars = (scope, isCurrent = false)=>{
if (!isCurrent) {
ci--;
}
const c = this.debugController.stack.slice(ci)[0];
const wrap = document.createElement('div'); {
wrap.classList.add('qr--scope');
if (isCurrent) {
const executor = this.debugController.cmdStack.slice(-1)[0];
{ // named args
const namedTitle = document.createElement('div'); {
namedTitle.classList.add('qr--title');
namedTitle.textContent = `Named Args - /${executor.name}`;
if (executor.command.name == 'run') {
namedTitle.textContent += `${(executor.name == ':' ? '' : ' ')}${executor.unnamedArgumentList[0]?.value}`;
}
wrap.append(namedTitle);
}
const keys = new Set([...Object.keys(this.debugController.namedArguments ?? {}), ...(executor.namedArgumentList ?? []).map(it=>it.name)]);
for (const key of keys) {
if (key[0] == '_') continue;
const item = document.createElement('div'); {
item.classList.add('qr--var');
const k = document.createElement('div'); {
k.classList.add('qr--key');
k.textContent = key;
item.append(k);
}
const vUnresolved = document.createElement('div'); {
vUnresolved.classList.add('qr--val');
vUnresolved.classList.add('qr--singleCol');
const val = executor.namedArgumentList.find(it=>it.name == key)?.value;
if (val instanceof SlashCommandClosure) {
vUnresolved.classList.add('qr--closure');
vUnresolved.title = val.rawText;
vUnresolved.textContent = val.toString();
} else if (val === undefined) {
vUnresolved.classList.add('qr--undefined');
vUnresolved.textContent = 'undefined';
} else {
let jsonVal;
try { jsonVal = JSON.parse(val); } catch { /* empty */ }
if (jsonVal && typeof jsonVal == 'object') {
vUnresolved.textContent = JSON.stringify(jsonVal, null, 2);
} else {
vUnresolved.textContent = val;
vUnresolved.classList.add('qr--simple');
}
}
item.append(vUnresolved);
}
const vResolved = document.createElement('div'); {
vResolved.classList.add('qr--val');
vResolved.classList.add('qr--singleCol');
if (this.debugController.namedArguments === undefined) {
vResolved.classList.add('qr--unresolved');
} else {
const val = this.debugController.namedArguments?.[key];
if (val instanceof SlashCommandClosure) {
vResolved.classList.add('qr--closure');
vResolved.title = val.rawText;
vResolved.textContent = val.toString();
} else if (val === undefined) {
vResolved.classList.add('qr--undefined');
vResolved.textContent = 'undefined';
} else {
let jsonVal;
try { jsonVal = JSON.parse(val); } catch { /* empty */ }
if (jsonVal && typeof jsonVal == 'object') {
vResolved.textContent = JSON.stringify(jsonVal, null, 2);
} else {
vResolved.textContent = val;
vResolved.classList.add('qr--simple');
}
}
}
item.append(vResolved);
}
wrap.append(item);
}
}
}
{ // unnamed args
const unnamedTitle = document.createElement('div'); {
unnamedTitle.classList.add('qr--title');
unnamedTitle.textContent = `Unnamed Args - /${executor.name}`;
if (executor.command.name == 'run') {
unnamedTitle.textContent += `${(executor.name == ':' ? '' : ' ')}${executor.unnamedArgumentList[0]?.value}`;
}
wrap.append(unnamedTitle);
}
let i = 0;
let unnamed = this.debugController.unnamedArguments ?? [];
if (!Array.isArray(unnamed)) unnamed = [unnamed];
while (unnamed.length < executor.unnamedArgumentList?.length ?? 0) unnamed.push(undefined);
unnamed = unnamed.map((it,idx)=>[executor.unnamedArgumentList?.[idx], it]);
for (const arg of unnamed) {
i++;
const item = document.createElement('div'); {
item.classList.add('qr--var');
const k = document.createElement('div'); {
k.classList.add('qr--key');
k.textContent = i.toString();
item.append(k);
}
const vUnresolved = document.createElement('div'); {
vUnresolved.classList.add('qr--val');
vUnresolved.classList.add('qr--singleCol');
const val = arg[0]?.value;
if (val instanceof SlashCommandClosure) {
vUnresolved.classList.add('qr--closure');
vUnresolved.title = val.rawText;
vUnresolved.textContent = val.toString();
} else if (val === undefined) {
vUnresolved.classList.add('qr--undefined');
vUnresolved.textContent = 'undefined';
} else {
let jsonVal;
try { jsonVal = JSON.parse(val); } catch { /* empty */ }
if (jsonVal && typeof jsonVal == 'object') {
vUnresolved.textContent = JSON.stringify(jsonVal, null, 2);
} else {
vUnresolved.textContent = val;
vUnresolved.classList.add('qr--simple');
}
}
item.append(vUnresolved);
}
const vResolved = document.createElement('div'); {
vResolved.classList.add('qr--val');
vResolved.classList.add('qr--singleCol');
if (this.debugController.unnamedArguments === undefined) {
vResolved.classList.add('qr--unresolved');
} else if ((Array.isArray(this.debugController.unnamedArguments) ? this.debugController.unnamedArguments : [this.debugController.unnamedArguments]).length < i) {
// do nothing
} else {
const val = arg[1];
if (val instanceof SlashCommandClosure) {
vResolved.classList.add('qr--closure');
vResolved.title = val.rawText;
vResolved.textContent = val.toString();
} else if (val === undefined) {
vResolved.classList.add('qr--undefined');
vResolved.textContent = 'undefined';
} else {
let jsonVal;
try { jsonVal = JSON.parse(val); } catch { /* empty */ }
if (jsonVal && typeof jsonVal == 'object') {
vResolved.textContent = JSON.stringify(jsonVal, null, 2);
} else {
vResolved.textContent = val;
vResolved.classList.add('qr--simple');
}
}
}
item.append(vResolved);
}
wrap.append(item);
}
}
}
}
// current scope
const title = document.createElement('div'); {
title.classList.add('qr--title');
title.textContent = isCurrent ? 'Current Scope' : 'Parent Scope';
if (c.source == source) {
let hi;
title.addEventListener('pointerenter', ()=>{
const loc = this.getEditorPosition(Math.max(0, c.executorList[0].start - 1), c.executorList.slice(-1)[0].end, c.fullText);
const layer = syntax.getBoundingClientRect();
hi = document.createElement('div');
hi.classList.add('qr--highlight-secondary');
hi.style.left = `${loc.left - layer.left}px`;
hi.style.width = `${loc.right - loc.left}px`;
hi.style.top = `${loc.top - layer.top + syntax.scrollTop}px`;
hi.style.height = `${loc.bottom - loc.top}px`;
syntax.append(hi);
});
title.addEventListener('pointerleave', ()=>hi?.remove());
}
wrap.append(title);
}
for (const key of Object.keys(scope.variables)) {
const isHidden = varNames.includes(key);
if (!isHidden) varNames.push(key);
const item = document.createElement('div'); {
item.classList.add('qr--var');
if (isHidden) item.classList.add('qr--isHidden');
const k = document.createElement('div'); {
k.classList.add('qr--key');
k.textContent = key;
item.append(k);
}
const v = document.createElement('div'); {
v.classList.add('qr--val');
const val = scope.variables[key];
if (val instanceof SlashCommandClosure) {
v.classList.add('qr--closure');
v.title = val.rawText;
v.textContent = val.toString();
} else if (val === undefined) {
v.classList.add('qr--undefined');
v.textContent = 'undefined';
} else {
let jsonVal;
try { jsonVal = JSON.parse(val); } catch { /* empty */ }
if (jsonVal && typeof jsonVal == 'object') {
v.textContent = JSON.stringify(jsonVal, null, 2);
} else {
v.textContent = val;
v.classList.add('qr--simple');
}
}
item.append(v);
}
wrap.append(item);
}
}
for (const key of Object.keys(scope.macros)) {
const isHidden = macroNames.includes(key);
if (!isHidden) macroNames.push(key);
const item = document.createElement('div'); {
item.classList.add('qr--macro');
if (isHidden) item.classList.add('qr--isHidden');
const k = document.createElement('div'); {
k.classList.add('qr--key');
k.textContent = key;
item.append(k);
}
const v = document.createElement('div'); {
v.classList.add('qr--val');
const val = scope.macros[key];
if (val instanceof SlashCommandClosure) {
v.classList.add('qr--closure');
v.title = val.rawText;
v.textContent = val.toString();
} else if (val === undefined) {
v.classList.add('qr--undefined');
v.textContent = 'undefined';
} else {
let jsonVal;
try { jsonVal = JSON.parse(val); } catch { /* empty */ }
if (jsonVal && typeof jsonVal == 'object') {
v.textContent = JSON.stringify(jsonVal, null, 2);
} else {
v.textContent = val;
v.classList.add('qr--simple');
}
}
item.append(v);
}
wrap.append(item);
}
}
const pipeItem = document.createElement('div'); {
pipeItem.classList.add('qr--pipe');
const k = document.createElement('div'); {
k.classList.add('qr--key');
k.textContent = 'pipe';
pipeItem.append(k);
}
const v = document.createElement('div'); {
v.classList.add('qr--val');
const val = scope.pipe;
if (val instanceof SlashCommandClosure) {
v.classList.add('qr--closure');
v.title = val.rawText;
v.textContent = val.toString();
} else if (val === undefined) {
v.classList.add('qr--undefined');
v.textContent = 'undefined';
} else {
let jsonVal;
try { jsonVal = JSON.parse(val); } catch { /* empty */ }
if (jsonVal && typeof jsonVal == 'object') {
v.textContent = JSON.stringify(jsonVal, null, 2);
} else {
v.textContent = val;
v.classList.add('qr--simple');
}
}
pipeItem.append(v);
}
wrap.append(pipeItem);
}
if (scope.parent) {
wrap.append(buildVars(scope.parent));
}
}
return wrap;
};
const buildStack = ()=>{
const wrap = document.createElement('div'); {
wrap.classList.add('qr--stack');
const title = document.createElement('div'); {
title.classList.add('qr--title');
title.textContent = 'Call Stack';
wrap.append(title);
}
let ei = -1;
for (const executor of this.debugController.cmdStack.toReversed()) {
ei++;
const c = this.debugController.stack.toReversed()[ei];
const item = document.createElement('div'); {
item.classList.add('qr--item');
if (executor.source == source) {
let hi;
item.addEventListener('pointerenter', ()=>{
const loc = this.getEditorPosition(Math.max(0, executor.start - 1), executor.end, c.fullText);
const layer = syntax.getBoundingClientRect();
hi = document.createElement('div');
hi.classList.add('qr--highlight-secondary');
hi.style.left = `${loc.left - layer.left}px`;
hi.style.width = `${loc.right - loc.left}px`;
hi.style.top = `${loc.top - layer.top + syntax.scrollTop}px`;
hi.style.height = `${loc.bottom - loc.top}px`;
syntax.append(hi);
});
item.addEventListener('pointerleave', ()=>hi?.remove());
}
const cmd = document.createElement('div'); {
cmd.classList.add('qr--cmd');
cmd.textContent = `/${executor.name}`;
if (executor.command.name == 'run') {
cmd.textContent += `${(executor.name == ':' ? '' : ' ')}${executor.unnamedArgumentList[0]?.value}`;
}
item.append(cmd);
}
const src = document.createElement('div'); {
src.classList.add('qr--source');
const line = closure.fullText.slice(0, executor.start).split('\n').length;
if (uuidCheck.test(executor.source)) {
const p1 = document.createElement('span'); {
p1.classList.add('qr--fixed');
p1.textContent = executor.source.slice(0,5);
src.append(p1);
}
const p2 = document.createElement('span'); {
p2.classList.add('qr--truncated');
p2.textContent = '…';
src.append(p2);
}
const p3 = document.createElement('span'); {
p3.classList.add('qr--fixed');
p3.textContent = `${executor.source.slice(-5)}:${line}`;
src.append(p3);
}
src.title = `anonymous: ${executor.source}`;
} else {
src.textContent = `${executor.source}:${line}`;
}
item.append(src);
}
wrap.append(item);
}
}
}
return wrap;
};
this.editorDebugState.append(buildVars(closure.scope, true));
this.editorDebugState.append(buildStack());
this.editorDebugState.classList.add('qr--active');
const loc = this.getEditorPosition(Math.max(0, executor.start - 1), executor.end, closure.fullText);
const layer = syntax.getBoundingClientRect();
const hi = document.createElement('div');
hi.classList.add('qr--highlight');
if (this.debugController.namedArguments === undefined) {
hi.classList.add('qr--unresolved');
}
hi.style.left = `${loc.left - layer.left}px`;
hi.style.width = `${loc.right - loc.left}px`;
hi.style.top = `${loc.top - layer.top + syntax.scrollTop}px`;
hi.style.height = `${loc.bottom - loc.top}px`;
syntax.append(hi);
const isStepping = await this.debugController.awaitContinue();
hi.remove();
this.editorDebugState.textContent = '';
this.editorDebugState.classList.remove('qr--active');
this.editorDom.classList.remove('qr--isPaused');
return isStepping;
};
const result = await this.onDebug(this);
if (this.abortController?.signal?.aborted) {
this.editorExecuteProgress.classList.add('qr--aborted');
} else {
this.editorExecuteResult.textContent = result?.toString();
this.editorExecuteResult.classList.add('qr--hasResult');
this.editorExecuteProgress.classList.add('qr--success');
}
this.editorExecuteProgress.classList.remove('qr--paused');
} catch (ex) {
this.editorExecuteErrors.classList.add('qr--hasErrors');
this.editorExecuteProgress.classList.add('qr--error');
this.editorExecuteProgress.classList.remove('qr--paused');
if (ex instanceof SlashCommandParserError) {
this.editorExecuteErrors.innerHTML = `
<div>${ex.message}</div>
<div>Line: ${ex.line} Column: ${ex.column}</div>
<pre style="text-align:left;">${ex.hint}</pre>
`;
} else {
this.editorExecuteErrors.innerHTML = `
<div>${ex.message}</div>
`;
}
}
if (noSyntax) {
this.editorDom.querySelector('#qr--modal-messageHolder').classList.add('qr--noSyntax');
}
this.editorMessageLabel.innerHTML = '';
this.editorMessageLabel.textContent = 'Message / Command: ';
this.editorMessage.value = oText;
this.editorMessage.dispatchEvent(new Event('input', { bubbles:true }));
this.editorExecutePromise = null;
this.editorExecuteBtn.classList.remove('qr--busy');
this.editorDom.classList.remove('qr--isExecuting');
this.isExecuting = false;
this.editorPopup.onClosing = null;
}
updateEditorProgress(done, total) {
this.editorExecuteProgress.style.setProperty('--prog', `${done / total * 100}`);
}
delete() {
if (this.onDelete) {
this.unrender();
this.unrenderSettings();
this.onDelete(this);
}
}
/**
* @param {string} value
*/
updateMessage(value) {
if (this.onUpdate) {
if (this.settingsDomMessage && this.settingsDomMessage.value != value) {
this.settingsDomMessage.value = value;
}
this.message = value;
this.updateRender();
this.onUpdate(this);
}
}
/**
* @param {string} value
*/
updateIcon(value) {
if (this.onUpdate) {
if (value === null) return;
if (this.settingsDomIcon) {
if (this.icon != value) {
if (value == '') {
if (this.icon) {
this.settingsDomIcon.classList.remove(this.icon);
}
this.settingsDomIcon.textContent = '…';
this.settingsDomIcon.classList.remove('fa-solid');
} else {
if (this.icon) {
this.settingsDomIcon.classList.remove(this.icon);
} else {
this.settingsDomIcon.classList.add('fa-solid');
}
this.settingsDomIcon.classList.add(value);
}
}
}
this.icon = value;
this.updateRender();
this.onUpdate(this);
}
}
/**
* @param {boolean} value
*/
updateShowLabel(value) {
if (this.onUpdate) {
this.showLabel = value;
this.updateRender();
this.onUpdate(this);
}
}
/**
* @param {string} value
*/
updateLabel(value) {
if (this.onUpdate) {
if (this.settingsDomLabel && this.settingsDomLabel.value != value) {
this.settingsDomLabel.value = value;
}
this.label = value;
this.updateRender();
this.onUpdate(this);
}
}
/**
* @param {string} value
*/
updateTitle(value) {
if (this.onUpdate) {
this.title = value;
this.updateRender();
this.onUpdate(this);
}
}
updateContext() {
if (this.onUpdate) {
this.updateRender();
this.onUpdate(this);
}
}
addContextLink(cl) {
this.contextList.push(cl);
this.updateContext();
}
removeContextLink(setName) {
const idx = this.contextList.findIndex(it=>it.set.name == setName);
if (idx > -1) {
this.contextList.splice(idx, 1);
this.updateContext();
}
}
clearContextLinks() {
if (this.contextList.length) {
this.contextList.splice(0, this.contextList.length);
this.updateContext();
}
}
async execute(args = {}, isEditor = false, isRun = false, options = {}) {
if (this.message?.length > 0 && this.onExecute) {
const scope = new SlashCommandScope();
for (const key of Object.keys(args)) {
if (key[0] == '_') continue;
if (key == 'isAutoExecute') continue;
scope.setMacro(`arg::${key}`, args[key]);
}
scope.setMacro('arg::*', '');
if (isEditor) {
this.abortController = new SlashCommandAbortController();
}
return await this.onExecute(this, {
message: this.message,
isAutoExecute: args.isAutoExecute ?? false,
isEditor,
isRun,
scope,
executionOptions: options,
});
}
}
toJSON() {
return {
id: this.id,
icon: this.icon,
showLabel: this.showLabel,
label: this.label,
title: this.title,
message: this.message,
contextList: this.contextList,
preventAutoExecute: this.preventAutoExecute,
isHidden: this.isHidden,
executeOnStartup: this.executeOnStartup,
executeOnUser: this.executeOnUser,
executeOnAi: this.executeOnAi,
executeOnChatChange: this.executeOnChatChange,
executeOnGroupMemberDraft: this.executeOnGroupMemberDraft,
automationId: this.automationId,
};
}
}
|