Flat
Join

Code

GPL v3 or later · 54 files · 1.2 MB

Read me What changed Versions and downloads

top / src / renderer

src/renderer/app.js · 59.6 KB · raw

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 'use strict'; // --------------------------------------------------------------------------- // Handles // --------------------------------------------------------------------------- const $ = (id) => document.getElementById(id); const els = { blocker: $('blocker'), blockerBody: $('blocker-body'), tabAll: $('tab-all'), viewAll: $('view-all'), viewJob: $('view-job'), eyeAllBody: $('eye-all-body'), filterAll: $('filter-all'), allList: $('all-list'), allEmpty: $('all-empty'), allLoading: $('all-loading'), allTally: $('all-tally'), allHint: $('all-hint'), allSelectAll: $('all-select-all'), allSelectNone: $('all-select-none'), allToMine: $('all-to-mine'), runningWarning: $('running-warning'), runningWarningText: $('running-warning-text'), closeRunning: $('close-running'), recheckRunning: $('recheck-running'), mineBackup: $('mine-backup'), tabMine: $('tab-mine'), viewMine: $('view-mine'), eyeMineBody: $('eye-mine-body'), flathubWarning: $('flathub-warning'), addFlathub: $('add-flathub'), mineSearch: $('mine-search'), mineResults: $('mine-results'), mineFromInstalled: $('mine-from-installed'), mineForget: $('mine-forget'), mineImport: $('mine-import'), mineExport: $('mine-export'), mineList: $('mine-list'), mineEmpty: $('mine-empty'), mineTally: $('mine-tally'), mineHint: $('mine-hint'), mineAll: $('mine-all'), mineAllLabel: $('mine-all-label'), tabRestore: $('tab-restore'), viewRestore: $('view-restore'), restoreOpen: $('restore-open'), restoreSourceText: $('restore-source-text'), restoreNote: $('restore-note'), restoreColhead: $('restore-colhead'), restoreAll: $('restore-all'), restoreAllLabel: $('restore-all-label'), restoreList: $('restore-list'), restoreTally: $('restore-tally'), restoreHint: $('restore-hint'), restoreGo: $('restore-go'), mineFullHelp: $('mine-full-help'), helpOpen: $('help-open'), helpClose: $('help-close'), helpNext: $('help-next'), viewHelp: $('view-help'), helpScroll: $('help-scroll'), jobHead: $('job-head'), jobCount: $('job-count'), jobProgressWrap: $('job-progress-wrap'), jobProgressFill: $('job-progress-fill'), jobLine: $('job-line'), jobList: $('job-list'), jobFootbar: $('job-footbar'), jobSummary: $('job-summary'), jobSummaryHint: $('job-summary-hint'), jobReveal: $('job-reveal'), jobDone: $('job-done'), updateWidgetVersion: $('update-widget-version'), updateDot: $('update-dot'), updateDotRingFill: $('update-dot-ring-fill'), }; const state = { mode: 'all', // Every Flatpak app on this machine, and which of them are ticked on the // All apps tab. apps: [], allTicked: new Set(), running: [], // Set once Back up settings has been pressed and something was open: the // warning shows from then until it is dealt with, and not before. backupBlocked: false, jobRows: new Map(), lastBackupFile: null, mine: [], mineNever: new Set(), // The entries themselves, so a tick follows its row through a re-render. mineTicked: new Set(), // The backup open on the Restore tab, and what is ticked and switched there. restore: null, restoreTicked: new Set(), restoreKeep: new Map(), }; // --------------------------------------------------------------------------- // Small helpers // --------------------------------------------------------------------------- function formatBytes(bytes) { if (!bytes) return '—'; const units = ['B', 'KB', 'MB', 'GB', 'TB']; let value = bytes; let unit = 0; while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit += 1; } const decimals = value >= 100 || unit === 0 ? 0 : 1; return `${value.toFixed(decimals)} ${units[unit]}`; } function plural(count, one, many) { return `${count} ${count === 1 ? one : many}`; } // Saying something happened, in the line under the tally where the screen // already explains itself. Not a coloured pill floating over the buttons: // that one covered a control for as long as it was up, and it took the // answer away again before it could be read twice. const SAID_MS = 5000; const saidTimers = new WeakMap(); function say(el, message) { if (!el) return; clearTimeout(saidTimers.get(el)); if (!el.dataset.resting) el.dataset.resting = el.textContent; el.textContent = message; el.classList.add('is-said'); saidTimers.set(el, setTimeout(() => { el.classList.remove('is-said'); el.textContent = el.dataset.resting || ''; delete el.dataset.resting; }, SAID_MS)); } function setHint(el, text) { if (el.classList.contains('is-said')) el.dataset.resting = text; else el.textContent = text; } // The Morphic Button gesture. The first click arms and shows a tick; a // second click inside three seconds acts; silence stands it back down. No // dialog and no success message — the button is the whole conversation. function arming(button, label, act) { let armed = false; let timer = null; const rest = () => { armed = false; clearTimeout(timer); button.classList.remove('is-armed', 'is-error'); button.textContent = label; }; button.addEventListener('click', async () => { if (button.disabled) return; if (!armed) { armed = true; button.classList.add('is-armed'); button.textContent = '✓'; button.title = 'Click again to go ahead'; timer = setTimeout(rest, 3000); return; } clearTimeout(timer); armed = false; button.classList.remove('is-armed'); button.textContent = label; const result = await act(); if (result === false) { button.classList.add('is-error'); setTimeout(rest, 2500); } }); return { rest }; } // --------------------------------------------------------------------------- // Tooltips // --------------------------------------------------------------------------- // Every `title` in the window becomes the same light bubble, rather than the // system's own, which looks different on every desktop and sits there for as // long as the pointer does. The title is moved to data-tip on first hover so // the system one never appears; anything that sets a title later is picked up // the next time round. const TIP_DELAY_MS = 400; const TIP_SHOWN_MS = 1800; const tip = document.getElementById('tip'); let tipTarget = null; let tipShowTimer = null; let tipHideTimer = null; function tipTextOf(el) { if (typeof el.tipText === 'function') return el.tipText(); return el.dataset.tip || ''; } function hideTip() { clearTimeout(tipShowTimer); clearTimeout(tipHideTimer); tip.hidden = true; tipTarget = null; } function placeTip(el) { const text = tipTextOf(el); if (!text) return; tip.textContent = text; tip.hidden = false; const box = el.getBoundingClientRect(); const size = tip.getBoundingClientRect(); const gap = 8; // Above if it fits, otherwise below: it never runs off the top. const above = box.top - size.height - gap >= 4; const top = above ? box.top - size.height - gap : box.bottom + gap; const centre = box.left + box.width / 2; const left = Math.max(4, Math.min(window.innerWidth - size.width - 4, centre - size.width / 2)); tip.style.top = `${Math.round(top)}px`; tip.style.left = `${Math.round(left)}px`; // The arrow still points at the thing, even when the bubble has had to // shift sideways to stay on screen. tip.style.setProperty('--arrow-x', `${Math.round(Math.max(10, Math.min(size.width - 10, centre - left)))}px`); tip.dataset.side = above ? 'above' : 'below'; tipHideTimer = setTimeout(hideTip, TIP_SHOWN_MS); } document.addEventListener('mouseover', (event) => { const el = event.target.closest('[title], [data-tip], .has-tip'); if (!el || el === tipTarget) return; if (el.hasAttribute('title')) { el.dataset.tip = el.getAttribute('title'); el.removeAttribute('title'); } hideTip(); tipTarget = el; tipShowTimer = setTimeout(() => { if (tipTarget === el) placeTip(el); }, TIP_DELAY_MS); }); document.addEventListener('mouseout', (event) => { if (tipTarget && !tipTarget.contains(event.relatedTarget)) hideTip(); }); document.addEventListener('mousedown', hideTip); document.addEventListener('scroll', hideTip, true); window.addEventListener('blur', hideTip); // For a tooltip whose words change with the state of the thing, like the // update dot's: read at the moment it shows. function brief(el, text) { if (typeof text === 'function') { el.tipText = text; el.classList.add('has-tip'); } else { el.dataset.tip = text; el.setAttribute('aria-label', text); } } // --------------------------------------------------------------------------- // The i // --------------------------------------------------------------------------- // The body sits outside the <details> so it can be a flex child of the panel // rather than trapped in the heading row. The details still owns the state. function wireEye(detailsEl, bodyEl) { detailsEl.addEventListener('toggle', () => { bodyEl.hidden = !detailsEl.open; }); } wireEye(document.querySelector('#view-all .eye'), els.eyeAllBody); wireEye(document.querySelector('#view-mine .eye'), els.eyeMineBody); // --------------------------------------------------------------------------- // Views // --------------------------------------------------------------------------- const TABS = { all: { tab: els.tabAll, view: els.viewAll }, mine: { tab: els.tabMine, view: els.viewMine }, restore: { tab: els.tabRestore, view: els.viewRestore }, }; function showView(name) { for (const [key, pair] of Object.entries(TABS)) { pair.view.hidden = key !== name; } els.viewJob.hidden = name !== 'job'; els.viewHelp.hidden = name !== 'help'; els.helpOpen.classList.toggle('is-on', name === 'help'); if (name === 'help') { for (const pair of Object.values(TABS)) { pair.tab.classList.remove('is-on'); pair.tab.setAttribute('aria-selected', 'false'); } return; } if (!TABS[name]) return; // `mode` is where a finished job sends the user back to. state.mode = name; for (const [key, pair] of Object.entries(TABS)) { pair.tab.classList.toggle('is-on', key === name); pair.tab.setAttribute('aria-selected', String(key === name)); } } for (const [key, pair] of Object.entries(TABS)) { pair.tab.addEventListener('click', () => { // Looked at afresh on arrival, so a tab never shows what was true // before something changed on another one. if (key === 'all' && state.apps.length) { renderAllList(); updateAllTally(); } if (key === 'mine') renderMine(); showView(key); }); } // Help shows one topic at a time. It opens on the first, or on the one a // "Full" heading or similar points to; closing it goes back to whichever tab // it was opened from. const HELP_SECTIONS = [...document.querySelectorAll('.help-section')].map((el) => el.id); let helpAt = HELP_SECTIONS[0]; function showHelp(sectionId) { helpAt = HELP_SECTIONS.includes(sectionId) ? sectionId : HELP_SECTIONS[0]; for (const id of HELP_SECTIONS) document.getElementById(id).hidden = id !== helpAt; for (const link of document.querySelectorAll('.help-jump a')) { link.setAttribute('aria-current', String(link.getAttribute('href') === `#${helpAt}`)); } const next = HELP_SECTIONS[HELP_SECTIONS.indexOf(helpAt) + 1]; els.helpNext.hidden = !next; if (next) { const label = document.querySelector(`.help-jump a[href="#${next}"]`); els.helpNext.textContent = `Next: ${label ? label.textContent : ''}`; } els.helpScroll.scrollTop = 0; showView('help'); } els.helpOpen.addEventListener('click', () => { if (!els.viewHelp.hidden) showView(state.mode); else showHelp(); }); els.helpClose.addEventListener('click', () => showView(state.mode)); els.helpNext.addEventListener('click', () => { showHelp(HELP_SECTIONS[HELP_SECTIONS.indexOf(helpAt) + 1]); }); document.addEventListener('keydown', (event) => { if (event.key === 'Escape' && !els.viewHelp.hidden) showView(state.mode); }); els.mineFullHelp.addEventListener('click', () => showHelp('help-full')); // The contents links jump within the page rather than navigating anywhere. for (const link of document.querySelectorAll('.help-jump a')) { link.addEventListener('click', (event) => { event.preventDefault(); showHelp(link.getAttribute('href').slice(1)); }); } // The tray menu names a destination. A job on screen is not interrupted for // it: it finishes and lands the user back where they asked to be. window.flat.onGoToTab((tab) => { if (tab === 'help') { if (els.viewJob.hidden) showHelp(); return; } if (!TABS[tab]) return; state.mode = tab; if (els.viewJob.hidden) showView(tab); }); // --------------------------------------------------------------------------- // Rows // --------------------------------------------------------------------------- // A small, quiet tick beside a name, standing for one plain fact ("installed // here", "on My apps"). It replaces the coloured pills this used to carry: // the fact is worth knowing, not worth shouting. The words are in its // tooltip and its accessible name, so it never relies on the shape alone. function quietTick(label) { const mark = document.createElement('span'); mark.className = 'quiet-tick'; if (!label) { mark.setAttribute('aria-hidden', 'true'); return mark; } mark.title = label; mark.setAttribute('role', 'img'); mark.setAttribute('aria-label', label); mark.innerHTML = '<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">' + '<path d="M3.5 8.5 6.5 11.5 12.5 4.5" fill="none" stroke="currentColor" stroke-width="1.6" ' + 'stroke-linecap="round" stroke-linejoin="round"/></svg>'; return mark; } function makeRow({ id, name, icon, sizeText, tick, title, checked, onToggle }) { const li = document.createElement('li'); li.className = 'row'; li.dataset.id = id; li.dataset.search = `${name} ${id}`.toLowerCase(); const box = document.createElement('input'); box.type = 'checkbox'; box.checked = checked; box.setAttribute('aria-label', `Include ${name}`); box.addEventListener('change', () => onToggle(box.checked)); li.appendChild(box); if (icon) { const img = document.createElement('img'); img.className = 'row-icon'; img.src = icon; img.alt = ''; li.appendChild(img); } else { const blank = document.createElement('span'); blank.className = 'row-icon row-icon--blank'; blank.textContent = (name[0] || '?').toUpperCase(); blank.setAttribute('aria-hidden', 'true'); li.appendChild(blank); } li.appendChild(quietTick(tick)); const text = document.createElement('div'); text.className = 'row-text'; const nameEl = document.createElement('div'); nameEl.className = 'row-name'; nameEl.textContent = name; const idEl = document.createElement('div'); idEl.className = 'row-id'; idEl.textContent = id; text.append(nameEl, idEl); li.appendChild(text); const size = document.createElement('div'); size.className = 'row-size'; size.textContent = sizeText; li.appendChild(size); // The whole row is the hit target, not just the 18px box. li.addEventListener('click', (event) => { if (event.target === box) return; box.checked = !box.checked; onToggle(box.checked); }); if (title) li.title = title; return li; } function applyFilter(listEl, query) { const needle = query.trim().toLowerCase(); for (const li of listEl.children) { li.hidden = needle ? !li.dataset.search.includes(needle) : false; } } // --------------------------------------------------------------------------- // All apps: everything installed on this machine // --------------------------------------------------------------------------- // An app installed on this machine that has saved nothing outside its // cache. Only knowable for apps that are here: for an app on the list but // not on this machine, nobody can say, so it keeps its switch. function noSettingsHere(id) { const app = state.apps.find((a) => a.id === (id || '').trim()); return Boolean(app) && !app.hasSettings; } // Keep settings as it actually works out. An app with nothing to keep is // Fresh whatever its switch last said. An app with settings on this machine // keeps them unless someone has switched that off. An app that is not on // this machine keeps whatever it was last set to. function keeps(entry) { if (noSettingsHere(entry.id)) return false; if (entry.keepChosen) return Boolean(entry.keep); const app = state.apps.find((a) => a.id === (entry.id || '').trim()); if (app && app.hasSettings) return true; return Boolean(entry.keep); } // Settings bigger than this are shown in amber: not wrong, just worth a // second look before carrying them to another machine. const HEAVY_BYTES = 250 * 1024 * 1024; function sizeCell(bytes, known) { const cell = document.createElement('span'); cell.className = 'cell--size'; if (!known) { cell.textContent = '—'; cell.title = 'Not on this machine, so there is nothing here to measure'; return cell; } cell.textContent = bytes ? formatBytes(bytes) : '—'; cell.title = 'Size of its settings and data, not counting its cache'; if (bytes >= HEAVY_BYTES) { cell.classList.add('is-heavy'); cell.title += '. Large enough to think about whether it needs to come along'; } return cell; } // What an app's settings come to, as it is set to be backed up. function chosenBytes(entry, app) { if (!app || !app.hasSettings) return 0; return entry.full ? app.fullBytes : app.dataBytes; } function onMineIds() { return new Set(state.mine.map((e) => (e.id || '').trim()).filter(Boolean)); } function renderAllList() { els.allList.textContent = ''; const onMine = onMineIds(); for (const app of state.apps) { const row = makeRow({ id: app.id, name: app.name, icon: app.icon, sizeText: app.hasSettings ? formatBytes(app.dataBytes) : 'No settings', tick: onMine.has(app.id) ? 'On My apps' : null, title: app.hasSettings ? 'Size of the settings and data it keeps' : 'Has saved nothing yet, so it would only ever install fresh', checked: state.allTicked.has(app.id), onToggle: (on) => { if (on) state.allTicked.add(app.id); else state.allTicked.delete(app.id); updateAllTally(); }, }); els.allList.appendChild(row); } els.allEmpty.hidden = state.apps.length > 0; applyFilter(els.allList, els.filterAll.value); } function updateAllTally() { const ticked = state.apps.filter((a) => state.allTicked.has(a.id)); const already = ticked.filter((a) => onMineIds().has(a.id)).length; els.allTally.textContent = ticked.length ? `${plural(ticked.length, 'app', 'apps')} ticked` : `${plural(state.apps.length, 'app', 'apps')} on this machine`; // What the button is about to do, on the page rather than behind the i. let hint = 'Tick the apps you want on My apps.'; if (ticked.length && already === ticked.length) { hint = ticked.length === 1 ? 'That one is on My apps already.' : 'All of those are on My apps already.'; } else if (already) { hint = `${already} of them ${already === 1 ? 'is' : 'are'} on My apps already. The rest arrive there as Fresh installs.`; } else if (ticked.length) { hint = 'They arrive on My apps as Fresh installs. Choose which keep their settings there.'; } setHint(els.allHint, hint); els.allToMine.disabled = ticked.length === 0; } async function scanApps() { els.allLoading.hidden = false; els.allLoading.textContent = 'Looking at what is installed…'; els.allList.textContent = ''; // Sizes here are without caches: they are what the app keeps, and the // cache switch only matters to the backup, on My apps. const result = await window.flat.scanApps(); els.allLoading.hidden = true; if (!result.ok) { els.allEmpty.hidden = false; els.allEmpty.textContent = result.error || 'Flatpak could not list what is installed.'; return; } state.apps = result.apps; state.running = result.running || []; state.allTicked = new Set([...state.allTicked].filter((id) => result.apps.some((a) => a.id === id))); renderAllList(); updateAllTally(); if (state.mine.length) renderMine(); updateMineTally(); } window.flat.onScanProgress(({ done, total }) => { if (!els.allLoading.hidden) { els.allLoading.textContent = `Measuring what each app is holding… ${done} of ${total}`; } }); els.filterAll.addEventListener('input', () => applyFilter(els.allList, els.filterAll.value)); // All means all: every app on the machine, data or not. With a filter typed // in, it means every app the filter is showing, because ticking rows you // cannot see is a surprise waiting to happen. els.allSelectAll.addEventListener('click', () => { const visible = [...els.allList.children].filter((li) => !li.hidden).map((li) => li.dataset.id); for (const id of visible) state.allTicked.add(id); renderAllList(); updateAllTally(); }); els.allSelectNone.addEventListener('click', () => { state.allTicked = new Set(); renderAllList(); updateAllTally(); }); els.allToMine.addEventListener('click', async () => { const chosen = state.apps.filter((a) => state.allTicked.has(a.id)); if (!chosen.length) return; // Ticking an app and pressing Add is naming it on purpose, so it comes // across even if it was once removed from the list. const { added } = await addBatchToMine( chosen.map((a) => ({ id: a.id, name: a.name, remote: a.origin || 'flathub', installed: true })), 'All apps', { explicit: true }, ); state.allTicked = new Set(); renderAllList(); updateAllTally(); say(els.allHint, added ? `${plural(added, 'app', 'apps')} added to My apps as Fresh installs.` : 'Those are all on My apps already.'); }); // --------------------------------------------------------------------------- // Backing up the Keep settings apps, from My apps // --------------------------------------------------------------------------- // The Keep settings apps that can actually be backed up here: on this // machine, and holding something to back up. function tickedWanted() { return uniqueWanted().filter((e) => state.mineTicked.has(e)); } function keepAppsHere() { const keep = new Set(tickedWanted().filter(keeps).map((e) => e.id)); return state.apps.filter((a) => keep.has(a.id) && a.hasSettings); } function openKeepApps() { const ids = new Set(keepAppsHere().map((a) => a.id)); return state.running.filter((id) => ids.has(id)); } function nameOf(id) { return (state.apps.find((a) => a.id === id) || {}).name || id; } // Shown only once a backup has been asked for and something was open, and // then until it is dealt with. Before that it would be nagging about apps // nobody is trying to back up yet. function updateRunningWarning() { const clash = state.backupBlocked ? openKeepApps() : []; if (!clash.length) { if (state.backupBlocked && !els.runningWarning.hidden) { say(els.mineHint, 'Everything is closed now. Press Back up settings again.'); } state.backupBlocked = false; els.runningWarning.hidden = true; return; } const names = clash.map(nameOf); els.runningWarningText.textContent = names.length === 1 ? `Please close ${names[0]} before backing up.` : `Please close ${names.slice(0, -1).join(', ')} and ${names[names.length - 1]} before backing up.`; els.runningWarning.hidden = false; } // Looks again at what is running: when asked, when the window comes back // into focus after you have been off closing something, and every few // seconds while the warning is up. async function recheckRunning({ quiet = false } = {}) { const before = openKeepApps(); state.running = await window.flat.runningApps(); const still = openKeepApps(); updateRunningWarning(); if (quiet) return; const closed = before.filter((id) => !still.includes(id)).map(nameOf); if (still.length) { say(els.mineHint, `Still open: ${still.map(nameOf).join(', ')}. Some apps keep running in the background after their window closes.`); } else if (closed.length) { say(els.mineHint, `${closed.join(', ')} ${closed.length === 1 ? 'is' : 'are'} closed now. Press Back up settings again.`); } } els.recheckRunning.addEventListener('click', () => recheckRunning()); window.addEventListener('focus', () => { if (!els.runningWarning.hidden) recheckRunning({ quiet: true }); }); setInterval(() => { if (!els.runningWarning.hidden) recheckRunning({ quiet: true }); }, 4000); arming(els.closeRunning, 'Close them for me', async () => { const result = await window.flat.closeApps(openKeepApps()); state.running = await window.flat.runningApps(); updateRunningWarning(); return result.ok; }); els.mineBackup.addEventListener('click', async () => { const list = tickedWanted(); if (!list.length) { say(els.mineHint, 'Tick the apps you want to take with you.'); return; } const keeping = list.filter(keeps); const here = keepAppsHere(); // Not a step further while any app whose settings are going is open. state.running = await window.flat.runningApps(); state.backupBlocked = true; updateRunningWarning(); if (!els.runningWarning.hidden) return; const target = await window.flat.chooseBackupFile(); if (target.canceled) return; // The rows are the apps whose settings are being packed; the rest of the // list goes into the file as names, which takes no time worth showing. startJob('Backing up', here.map((a) => ({ id: a.id, name: a.name }))); const result = await window.flat.runBackup({ apps: here.map((a) => { const entry = list.find((e) => e.id === a.id) || {}; return { id: a.id, name: a.name, branch: a.branch, arch: a.arch, origin: a.origin, scope: a.scope, full: Boolean(entry.full), dataBytes: chosenBytes(entry, a), }; }), list: list.map(({ id, name, remote }) => ({ id, name, remote })), outFile: target.file, }); if (!result.ok) { finishJob({ head: 'Backup failed', summary: result.error, bad: true }); return; } state.lastBackupFile = result.file; for (const entry of result.log || []) noteOnJobRow(entry.message, entry.level); // Keep settings apps that could not be packed are named, not dropped // silently: on the new machine they would come back fresh. const left = keeping.length - here.length; finishJob({ head: 'Backup finished', summary: `${plural(list.length, 'app', 'apps')} saved · ${plural(result.apps, 'with settings', 'with settings')} · ${formatBytes(result.bytes)}`, hint: left ? `${plural(left, 'Keep settings app is', 'Keep settings apps are')} not on this machine, so ${left === 1 ? 'it goes' : 'they go'} in as a fresh install. ${result.file}` : result.file, reveal: true, }); }); // --------------------------------------------------------------------------- // The job view // --------------------------------------------------------------------------- function startJob(head, apps) { els.jobHead.textContent = head; els.jobCount.textContent = ''; els.jobList.textContent = ''; els.jobFootbar.hidden = true; els.jobReveal.hidden = true; els.jobProgressWrap.hidden = false; els.jobProgressFill.style.width = '0%'; els.jobLine.textContent = 'Starting…'; state.jobRows = new Map(); for (const app of apps) { const li = document.createElement('li'); li.className = 'jobrow'; li.dataset.state = 'waiting'; const mark = document.createElement('span'); mark.className = 'jobrow-mark'; mark.textContent = '·'; const text = document.createElement('div'); text.className = 'jobrow-text'; const name = document.createElement('div'); name.className = 'jobrow-name'; name.textContent = app.name; text.appendChild(name); li.append(mark, text); els.jobList.appendChild(li); state.jobRows.set(app.id, { li, mark, text }); } showView('job'); } function markJobRow(id, kind, message) { const row = state.jobRows.get(id); if (!row) return; row.li.dataset.state = kind; row.mark.textContent = kind === 'ok' ? '✓' : kind === 'failed' ? '!' : '·'; if (message) { const note = document.createElement('div'); note.className = kind === 'failed' ? 'jobrow-note jobrow-note--bad' : 'jobrow-note'; note.textContent = message; row.text.appendChild(note); } } function addJobNote(id, text, bad) { const row = state.jobRows.get(id); if (!row) return; const note = document.createElement('div'); note.className = bad ? 'jobrow-note jobrow-note--bad' : 'jobrow-note'; note.textContent = text; row.text.appendChild(note); } // A row that has already been given a note must not collect a second one // saying the same thing when the final results arrive. function noteOnce(id, kind, message) { const row = state.jobRows.get(id); if (!row || row.noted) return; row.noted = true; markJobRow(id, kind, message); } // A note with no id belongs to whichever row is on screen last — used for // the backup log, which is a flat list of warnings rather than per app. function noteOnJobRow(message, level, id) { if (id) { const row = state.jobRows.get(id); if (row) { const note = document.createElement('div'); note.className = 'jobrow-note'; note.textContent = message; row.text.appendChild(note); return; } } const li = document.createElement('li'); li.className = 'jobrow'; li.dataset.state = level === 'error' ? 'failed' : 'waiting'; const mark = document.createElement('span'); mark.className = 'jobrow-mark'; mark.textContent = level === 'error' ? '!' : 'i'; const text = document.createElement('div'); text.className = 'jobrow-text'; const note = document.createElement('div'); note.className = level === 'error' ? 'jobrow-note jobrow-note--bad' : 'jobrow-note'; note.textContent = message; text.appendChild(note); li.append(mark, text); els.jobList.appendChild(li); } window.flat.onJobProgress(({ index, total, appId, step, message }) => { if (total) { const settled = step === 'done' || step === 'failed' || step === 'skipped'; const fraction = Math.min(1, (index + (settled ? 1 : 0.5)) / total); els.jobProgressFill.style.width = `${Math.round(fraction * 100)}%`; els.jobCount.textContent = `${Math.min(index + 1, total)} of ${total}`; } els.jobLine.textContent = message || ''; if (!appId) return; const row = state.jobRows.get(appId); if (!row) return; if (step === 'done') markJobRow(appId, 'ok'); else if (step === 'failed') noteOnce(appId, 'failed', message); else if (step === 'skipped') noteOnce(appId, 'skipped', 'Already here, so it was left alone'); // The settings pass runs on apps already installed and ticked green. It // shows as working while it runs and goes back to its tick after; the // outcome is added as a note once the run has finished. else if (step === 'settings') row.li.dataset.state = 'working'; else if (step === 'settings-done' || step === 'settings-failed') row.li.dataset.state = 'ok'; else row.li.dataset.state = 'working'; }); function finishJob({ head, summary, hint, reveal, bad }) { els.jobHead.textContent = head; els.jobProgressFill.style.width = '100%'; els.jobProgressWrap.hidden = true; els.jobSummary.textContent = summary || ''; els.jobSummaryHint.textContent = hint || ''; els.jobReveal.hidden = !reveal; els.jobFootbar.hidden = false; if (bad) els.jobCount.textContent = ''; } els.jobReveal.addEventListener('click', () => { if (state.lastBackupFile) window.flat.revealFile(state.lastBackupFile); }); els.jobDone.addEventListener('click', async () => { // Back to where the button was pressed from, with what has changed since // looked at again. showView(state.mode); await loadMine(); await scanApps(); const found = await window.flat.settingsBackupFind(); if (found && found.ok) openBackup(found); if (state.restore) { const again = await window.flat.settingsBackupDescribe(state.restore.file); if (again && again.ok) openBackup(again); } }); // --------------------------------------------------------------------------- // My apps: the standing list, and installing it onto a bare machine // --------------------------------------------------------------------------- // Same shape the main process validates against. Checked here too so a typo // shows itself in the field being typed into rather than as a failure three // screens later. const APP_ID = /^[A-Za-z][A-Za-z0-9-_]*(\.[A-Za-z0-9-_]+){2,}$/; // The same app twice is a list that says one thing and installs another, so // the second copy is marked rather than quietly ignored. function duplicateIds() { const seen = new Set(); const twice = new Set(); for (const entry of state.mine) { const id = (entry.id || '').trim(); if (!id) continue; if (seen.has(id)) twice.add(id); seen.add(id); } return twice; } function renderMine() { els.mineList.textContent = ''; const dupes = duplicateIds(); for (const entry of state.mine) { const li = document.createElement('li'); li.className = 'editrow'; li.dataset.id = entry.id; li.classList.toggle('is-ticked', state.mineTicked.has(entry)); const tickWrap = document.createElement('label'); tickWrap.className = 'tick'; const tick = document.createElement('input'); tick.type = 'checkbox'; tick.checked = state.mineTicked.has(entry); tick.setAttribute('aria-label', `Tick ${entry.name || entry.id || 'this row'}`); tick.addEventListener('change', () => { if (tick.checked) state.mineTicked.add(entry); else state.mineTicked.delete(entry); li.classList.toggle('is-ticked', tick.checked); updateTicks(); }); tickWrap.appendChild(tick); const keepCell = document.createElement('div'); keepCell.className = 'keepcell'; // Nothing saved here means nothing to keep, so there is no switch to // flick on in the belief that it was forgotten — just the plain fact. const empty = noSettingsHere(entry.id); if (empty) { const none = document.createElement('span'); none.className = 'no-settings'; none.textContent = 'No settings'; none.title = 'This app has saved nothing on this machine, so it installs fresh'; keepCell.appendChild(none); } const keepLabel = document.createElement('label'); keepLabel.className = 'switch'; const keepBox = document.createElement('input'); keepBox.type = 'checkbox'; keepBox.setAttribute('role', 'switch'); keepBox.checked = keeps(entry); keepBox.setAttribute('aria-label', `Keep the settings of ${entry.name || entry.id || 'this app'}`); const keepTrack = document.createElement('span'); keepTrack.className = 'track'; keepLabel.append(keepBox, keepTrack); if (!empty) keepCell.appendChild(keepLabel); // A switch applies immediately; nothing waits for a Save button. keepBox.addEventListener('change', () => { entry.keep = keepBox.checked; entry.keepChosen = true; renderMine(); saveMineNow(true); }); const name = document.createElement('input'); name.className = 'cell cell--name'; name.value = entry.name || ''; name.placeholder = 'What you call it'; name.setAttribute('aria-label', 'App name'); // The ID and remote are shown, not edited. Every app on the list came // from a search that found it, from this machine, or from a saved list; // a box to type an ID into is only a way to mistype one. const id = document.createElement('span'); id.className = 'cell cell--id cell--fixed'; id.textContent = entry.id || ''; id.title = entry.id || ''; const remote = document.createElement('span'); remote.className = 'cell cell--remote cell--fixed'; remote.textContent = entry.remote || 'flathub'; const tag = quietTick(entry.installed ? 'Installed on this machine' : null); const drop = document.createElement('button'); drop.type = 'button'; drop.className = 'drop'; drop.textContent = '\u00d7'; brief(drop, `Remove ${entry.name || entry.id}`); // A row carried over from an older list with a bad or repeated ID is // still flagged, so it can be seen and removed. const value = (entry.id || '').trim(); if (!APP_ID.test(value) || dupes.has(value)) id.classList.add('is-bad'); // The name is only a label, so it stays editable, and saves itself. name.addEventListener('input', () => { entry.name = name.value; saveMineSoon(); }); // Two-click removal, per the Morphic Button standard: the first click // shows a tick and asks, and stands back down on its own. let armed = false; let timer = null; drop.addEventListener('click', () => { if (!armed) { armed = true; drop.classList.add('is-armed'); drop.textContent = '\u2713'; timer = setTimeout(() => { armed = false; drop.classList.remove('is-armed'); drop.textContent = '\u00d7'; }, 3000); return; } clearTimeout(timer); const gone = (entry.id || '').trim(); if (gone) state.mineNever.add(gone); state.mine = state.mine.filter((e) => e !== entry); state.mineTicked.delete(entry); renderMine(); updateMineTally(); saveMineNow(); }); const here = state.apps.find((a) => a.id === (entry.id || '').trim()); const size = sizeCell(chosenBytes(entry, here), Boolean(here)); if (here && here.trimmable) { size.title = `Settings only: ${formatBytes(here.dataBytes)} · Full: ${formatBytes(here.fullBytes)}`; } // Full: only where it changes something — an app with settings here, // being kept, that has things a trimmed backup would leave out. const fullCell = document.createElement('div'); fullCell.className = 'fullcell'; if (here && here.trimmable && keeps(entry)) { const box = document.createElement('input'); box.type = 'checkbox'; box.checked = Boolean(entry.full); box.title = 'Back up the whole folder, cache and all'; box.setAttribute('aria-label', `Back up all of ${entry.name || entry.id}, cache and all`); box.addEventListener('change', () => { entry.full = box.checked; size.textContent = formatBytes(chosenBytes(entry, here)) || '—'; size.classList.toggle('is-heavy', chosenBytes(entry, here) >= HEAVY_BYTES); updateMineTally(); saveMineNow(true); }); fullCell.appendChild(box); } li.append(tickWrap, tag, name, id, remote, size, keepCell, fullCell, drop); els.mineList.appendChild(li); } els.mineEmpty.hidden = state.mine.length > 0; els.mineAll.closest('.colhead').hidden = state.mine.length === 0; updateTicks(); // All apps marks which apps are on this list, so it follows every change // here at once, rather than showing yesterday's list until Flat restarts. if (state.apps.length) { renderAllList(); updateAllTally(); } } // ---- ticking: what goes into the backup ---------------------------------------- // Ticks choose what the backup carries. Everything starts ticked, so pressing // Back up takes the whole list unless something is deliberately left out. function updateTicks() { for (const entry of [...state.mineTicked]) { if (!state.mine.includes(entry)) state.mineTicked.delete(entry); } const ticked = state.mineTicked.size; const total = state.mine.length; els.mineAll.checked = total > 0 && ticked === total; els.mineAll.indeterminate = ticked > 0 && ticked < total; els.mineAllLabel.textContent = ticked ? `${ticked}` : 'All'; updateMineTally(); } els.mineAll.addEventListener('change', () => { state.mineTicked = els.mineAll.checked ? new Set(state.mine) : new Set(); renderMine(); }); function updateMineTally() { const valid = uniqueWanted(); const broken = state.mine.length - valid.length; const ticked = valid.filter((e) => state.mineTicked.has(e)); const keeping = ticked.filter(keeps).length; const bytes = ticked.filter(keeps).reduce((sum, e) => { const app = state.apps.find((a) => a.id === e.id); return sum + chosenBytes(e, app); }, 0); els.mineTally.textContent = state.mine.length ? `${plural(state.mine.length, 'app', 'apps')} on the list · ${keeping} keep settings${bytes ? ` · about ${formatBytes(bytes)} of settings` : ''}` : 'Nothing on the list'; // What the button is about to do, on the page rather than behind the i. if (broken) { setHint(els.mineHint, `${plural(broken, 'row is', 'rows are')} a repeat or not a valid app ID, and will be left out.`); } else if (!state.mine.length) { setHint(els.mineHint, 'Add apps from All apps, or search for them above.'); } else if (!ticked.length) { setHint(els.mineHint, 'Tick the apps you want to take with you.'); } else { setHint(els.mineHint, `Back up saves ${plural(ticked.length, 'ticked app', 'ticked apps')}${keeping ? `, and the settings of ${keeping}` : ''}.`); } els.mineBackup.disabled = ticked.length === 0; } // Saving is debounced because these are auto-save fields and every keystroke // would otherwise be a write and a toast. let saveTimer = null; function saveMineSoon() { clearTimeout(saveTimer); saveTimer = setTimeout(saveMineNow, 800); } async function saveMineNow(quiet) { clearTimeout(saveTimer); const result = await window.flat.listWrite({ apps: state.mine.map(({ id, name, remote, keep, keepChosen, full }) => ({ id, name, remote, keep: Boolean(keep), keepChosen: Boolean(keepChosen), full: Boolean(full) })), never: [...state.mineNever], }); if (result && result.ok) { state.mineNever = new Set(result.never || []); els.mineForget.hidden = state.mineNever.size === 0; if (!quiet) say(els.mineHint, 'Saved'); } } // One entry per id, valid ids only — the same set the install uses, so the // count on the button is the count that happens. function uniqueWanted() { const seen = new Set(); const out = []; for (const entry of state.mine) { const id = (entry.id || '').trim(); if (!APP_ID.test(id) || seen.has(id)) continue; seen.add(id); out.push(entry); } return out; } // `explicit` is a person naming this one app. That always wins, and it // cancels an earlier removal. A bulk add is not explicit, so it respects // what has been taken off before. function addToMine(entry, { explicit = false } = {}) { const id = (entry.id || '').trim(); if (!id || state.mine.some((e) => e.id === id)) return false; if (!explicit && state.mineNever.has(id)) return false; state.mineNever.delete(id); const row = { id, name: entry.name || id, remote: entry.remote || 'flathub', installed: Boolean(entry.installed), keep: Boolean(entry.keep), }; state.mine.push(row); state.mineTicked.add(row); return true; } // Adds a batch from somewhere else in the app and says what happened, in // words rather than a silent count that does not add up. // `keep`: the batch comes from somewhere about settings — the Back up or // Restore tab — so every app in it is marked Keep settings, including ones // that were already on the list as Fresh. Ticking an app on those tabs and // sending it here is saying "this one's settings matter". async function addBatchToMine(entries, where, { explicit = false } = {}) { let added = 0; let held = 0; const marked = 0; for (const entry of entries) { const id = (entry.id || '').trim(); if (state.mine.some((e) => e.id === id)) continue; if (addToMine({ ...entry, keep: false }, { explicit })) added += 1; else if (state.mineNever.has(id)) held += 1; } renderMine(); updateMineTally(); // `quiet`: the sentence below is the notification, so the save does not // need one of its own on top of it. if (added || marked) await saveMineNow(true); let done = added ? `${plural(added, 'app', 'apps')} added to My apps` : 'Nothing new to add'; if (marked) done += `, ${marked} more marked Keep settings`; const heldNote = held ? ` ${plural(held, 'app you had removed was', 'apps you had removed were')} left out.` : ''; say(els.mineHint, `${done} from ${where}.${heldNote}`); return { added, held, marked, done, heldNote }; } async function loadMine() { const loaded = await window.flat.listRead(); state.mine = loaded.apps; state.mineNever = new Set(loaded.never || []); els.mineForget.hidden = state.mineNever.size === 0; els.flathubWarning.hidden = loaded.hasFlathub; state.mineTicked = new Set(state.mine); renderMine(); updateMineTally(); } // --- searching for something to add ----------------------------------------- let searchTimer = null; els.mineSearch.addEventListener('input', () => { clearTimeout(searchTimer); const term = els.mineSearch.value.trim(); if (term.length < 2) { els.mineResults.hidden = true; return; } searchTimer = setTimeout(async () => { const found = await window.flat.listSearch(term); renderResults(found); }, 350); }); function renderResults(found) { els.mineResults.textContent = ''; if (!found.length) { els.mineResults.hidden = true; return; } for (const hit of found) { const li = document.createElement('li'); li.className = 'result'; const already = state.mine.some((e) => e.id === hit.id); li.dataset.on = String(already); const text = document.createElement('div'); text.className = 'result-text'; const name = document.createElement('div'); name.className = 'result-name'; name.textContent = hit.name; const sub = document.createElement('div'); sub.className = 'result-sub'; sub.textContent = hit.description ? `${hit.id} — ${hit.description}` : hit.id; text.append(name, sub); const add = document.createElement('span'); add.className = 'result-add'; add.textContent = already ? 'on the list' : 'Add'; li.append(text, add); li.addEventListener('click', () => { if (li.dataset.on === 'true') return; addToMine(hit, { explicit: true }); li.dataset.on = 'true'; add.textContent = 'on the list'; renderMine(); updateMineTally(); saveMineNow(); }); els.mineResults.appendChild(li); } els.mineResults.hidden = false; } // --- filling and moving the list -------------------------------------------- els.mineFromInstalled.addEventListener('click', async () => { const installed = await window.flat.listFromInstalled(); await addBatchToMine(installed.map((e) => ({ ...e, installed: true })), 'this machine'); }); // A Reset, and it hides itself when there is nothing to reset: a button that // does nothing when pressed is one you stop trusting. arming(els.mineForget, 'Forget removals', async () => { state.mineNever = new Set(); await saveMineNow(); say(els.mineHint, 'Removals forgotten. A batch add will bring those apps back.'); return true; }); els.mineExport.addEventListener('click', async () => { const result = await window.flat.listExport({ apps: state.mine.map(({ id, name, remote, keep, keepChosen, full }) => ({ id, name, remote, keep: Boolean(keep), keepChosen: Boolean(keepChosen), full: Boolean(full) })), never: [...state.mineNever], }); if (result.canceled) return; if (result.error) { setHint(els.mineHint, result.error); return; } say(els.mineHint, `List saved to ${result.file}`); }); els.mineImport.addEventListener('click', async () => { const result = await window.flat.listImport(); if (result.canceled) return; if (!result.ok) { setHint(els.mineHint, result.error); return; } for (const id of result.never || []) state.mineNever.add(id); for (const entry of result.apps) addToMine(entry, { explicit: true }); await saveMineNow(); await loadMine(); }); // --- installing -------------------------------------------------------------- // --------------------------------------------------------------------------- // Restore: open a backup, choose, press Restore // --------------------------------------------------------------------------- function restoreEntries() { return state.restore ? state.restore.entries : []; } function renderRestore() { els.restoreList.textContent = ''; const entries = restoreEntries(); els.restoreColhead.hidden = entries.length === 0; for (const entry of entries) { const li = document.createElement('li'); li.className = 'editrow'; const ticked = state.restoreTicked.has(entry.id); li.classList.toggle('is-ticked', ticked); const tickWrap = document.createElement('label'); tickWrap.className = 'tick'; const tick = document.createElement('input'); tick.type = 'checkbox'; tick.checked = ticked; tick.setAttribute('aria-label', `Restore ${entry.name}`); tick.addEventListener('change', () => { if (tick.checked) state.restoreTicked.add(entry.id); else state.restoreTicked.delete(entry.id); li.classList.toggle('is-ticked', tick.checked); updateRestoreTally(); }); tickWrap.appendChild(tick); const here = quietTick(entry.installed ? 'Already on this machine' : null); const name = document.createElement('span'); name.className = 'cell cell--name cell--fixed'; name.textContent = entry.name; const id = document.createElement('span'); id.className = 'cell cell--id cell--fixed'; id.textContent = entry.id; id.title = entry.id; // On for every app whose settings are in the backup; the plain words // where there are none, so there is nothing to switch on in vain. const keepCell = document.createElement('div'); keepCell.className = 'keepcell'; if (entry.keep) { const label = document.createElement('label'); label.className = 'switch'; const box = document.createElement('input'); box.type = 'checkbox'; box.setAttribute('role', 'switch'); box.checked = state.restoreKeep.get(entry.id) !== false; box.setAttribute('aria-label', `Bring back the settings of ${entry.name}`); box.addEventListener('change', () => { state.restoreKeep.set(entry.id, box.checked); updateRestoreTally(); }); const track = document.createElement('span'); track.className = 'track'; label.append(box, track); keepCell.appendChild(label); } else { const none = document.createElement('span'); none.className = 'no-settings'; none.textContent = 'No settings'; none.title = 'The backup holds no settings for this app, so it installs fresh'; keepCell.appendChild(none); } const size = sizeCell(entry.keep ? entry.bytes : 0, true); li.append(tickWrap, here, name, id, size, keepCell); els.restoreList.appendChild(li); } updateRestoreTally(); } function updateRestoreTally() { const entries = restoreEntries(); const ticked = entries.filter((e) => state.restoreTicked.has(e.id)); const withSettings = ticked.filter((e) => e.keep && state.restoreKeep.get(e.id) !== false).length; const already = ticked.filter((e) => e.installed).length; els.restoreAll.checked = entries.length > 0 && ticked.length === entries.length; els.restoreAll.indeterminate = ticked.length > 0 && ticked.length < entries.length; els.restoreAllLabel.textContent = ticked.length ? `${ticked.length}` : 'All'; if (!state.restore) { els.restoreTally.textContent = 'No backup open'; setHint(els.restoreHint, ''); } else { const bytes = ticked.filter((e) => e.keep && state.restoreKeep.get(e.id) !== false) .reduce((sum, e) => sum + (e.bytes || 0), 0); els.restoreTally.textContent = `${plural(ticked.length, 'app', 'apps')} ticked · ${withSettings} with settings${bytes ? ` · about ${formatBytes(bytes)}` : ''}`; setHint(els.restoreHint, already ? `${already} ${already === 1 ? 'is' : 'are'} already on this machine and will be left alone, settings and all.` : 'Untick anything you do not want here.'); } els.restoreGo.disabled = ticked.filter((e) => !e.installed).length === 0; } function showBackupSource() { const b = state.restore; els.restoreNote.hidden = !b; els.restoreSourceText.textContent = ''; if (!b) { els.restoreSourceText.textContent = 'Open the backup you made on your old machine.'; return; } const strong = document.createElement('strong'); strong.textContent = b.name; const when = b.created ? new Date(b.created).toLocaleDateString() : ''; els.restoreSourceText.append(strong, `${b.host ? `, made on ${b.host}` : ''}${when ? ` on ${when}` : ''}.`); } function openBackup(described) { state.restore = described; state.restoreTicked = new Set(described.entries.map((e) => e.id)); state.restoreKeep = new Map(); showBackupSource(); renderRestore(); } els.restoreAll.addEventListener('change', () => { state.restoreTicked = els.restoreAll.checked ? new Set(restoreEntries().map((e) => e.id)) : new Set(); renderRestore(); }); els.restoreOpen.addEventListener('click', async () => { const chosen = await window.flat.settingsBackupChoose(); if (chosen.canceled) return; if (!chosen.ok) { say(els.restoreHint, chosen.error); return; } openBackup(chosen); }); els.restoreGo.addEventListener('click', async () => { if (!state.restore) return; const wanted = restoreEntries().filter((e) => state.restoreTicked.has(e.id)); if (!wanted.length) return; startJob('Restoring', wanted.map((e) => ({ id: e.id, name: e.name }))); const result = await window.flat.installApps({ apps: wanted.map((e) => ({ id: e.id, name: e.name, remote: e.remote, keep: Boolean(e.keep) && state.restoreKeep.get(e.id) !== false, })), packFile: state.restore.file, }); if (!result.ok) { finishJob({ head: 'Restore failed', summary: result.error, bad: true }); return; } for (const entry of result.results) { if (entry.skipped) noteOnce(entry.id, 'skipped', 'Already here, so it was left alone'); else if (!entry.ok) noteOnce(entry.id, 'failed', entry.error); } for (const [id, note] of Object.entries(result.settingsNotes || {})) addJobNote(id, note.text, note.bad); const parts = [`${plural(result.succeeded, 'app', 'apps')} installed`]; if (result.settingsRestored) parts.push(`${result.settingsRestored} with settings back`); if (result.skipped) parts.push(`${result.skipped} already here`); if (result.failed) parts.push(`${result.failed} failed`); const problems = result.failed || result.settingsMissed; finishJob({ head: problems ? 'Finished, with problems' : 'Finished', summary: parts.join(' \u00b7 '), hint: result.failed ? 'A failure is usually an app the remote no longer carries.' : 'Sign in again anywhere an app kept its login in the system keyring.', bad: Boolean(problems), }); }); arming(els.addFlathub, 'Add Flathub', async () => { const result = await window.flat.addFlathub(); if (!result.ok) return false; els.flathubWarning.hidden = true; return true; }); // --------------------------------------------------------------------------- // Update widget, to the update-widget spec: one 16px dot, five colours, and // a one-per-second pulse whenever it is working. // --------------------------------------------------------------------------- const RING_RADIUS = 7; const RING_CIRCUMFERENCE = 2 * Math.PI * RING_RADIUS; els.updateDotRingFill.style.strokeDasharray = String(RING_CIRCUMFERENCE); // The spec's own words, where it gives them. const UPDATE_DOT_LABELS = { current: 'up to date', checking: 'checking for an update', available: 'update available — click to download', downloading: 'downloading', downloaded: 'click to restart', installing: 'restarting', error: "can't reach the update server — click to try again", }; // The dot is working, not waiting for you, in these. const INERT_STATES = ['checking', 'downloading', 'installing']; const PULSING_STATES = ['checking', 'installing']; let updateState = null; let updateLabel = ''; function setUpdateDot(nextState, overrideLabel) { updateState = nextState; els.updateDot.dataset.state = nextState; els.updateDot.classList.toggle('is-pulsing', PULSING_STATES.includes(nextState)); els.updateDot.setAttribute('aria-disabled', String(INERT_STATES.includes(nextState))); updateLabel = overrideLabel || UPDATE_DOT_LABELS[nextState] || ''; els.updateDot.setAttribute('aria-label', updateLabel); } function setRingProgress(fraction) { const offset = RING_CIRCUMFERENCE * (1 - Math.max(0, Math.min(1, fraction))); els.updateDotRingFill.style.strokeDashoffset = String(offset); } // Every state has a hover tooltip naming it. It reads the label at the // moment of hovering, so it is never the state from a minute ago, and it // clears itself inside two seconds like every other tooltip in the app. brief(els.updateDot, () => updateLabel); function applyUpdateState(next) { if (next.status === 'none') setUpdateDot('current'); else if (next.status === 'available') setUpdateDot('available'); else if (next.status === 'downloading') { setUpdateDot('downloading'); setRingProgress(next.percent / 100); } else if (next.status === 'downloaded') { setRingProgress(1); setUpdateDot('downloaded'); } else if (next.status === 'error') setUpdateDot('error'); } // A manual check pulses at least three times — three seconds at one a // second — and keeps pulsing if the check takes longer. The minimum is there // so a fast answer still reads as "it looked", not as a flicker. const MIN_CHECK_MS = 3000; const NO_UPDATE_NOTE_MS = 3000; let checking = false; let queuedState = null; async function runManualCheck() { checking = true; queuedState = null; setUpdateDot('checking'); const minimum = new Promise((resolve) => setTimeout(resolve, MIN_CHECK_MS)); const result = await window.flat.updateCheck(); await minimum; checking = false; if (queuedState) { const answer = queuedState; queuedState = null; if (answer.status === 'none') { noUpdateFound(); } else { applyUpdateState(answer); } } else if (result && result.error) { setUpdateDot('error'); } else { noUpdateFound(); } } // "no update available", briefly, then back to plain "up to date". function noUpdateFound() { setUpdateDot('current', 'no update available'); setTimeout(() => { if (updateState === 'current') setUpdateDot('current'); }, NO_UPDATE_NOTE_MS); } window.flat.onUpdateState((next) => { if (checking) queuedState = next; else if (updateState !== 'installing') applyUpdateState(next); }); // The dot is on screen from the first moment, never popping in later. Until // the startup check answers it is checking, so it pulses — a still dot while // it looks would say nothing is happening. If the answer came in before the // page was listening, it is picked up here rather than lost. async function startUpdateDot() { setUpdateDot('checking'); const known = await window.flat.updateStateGet(); if (known && updateState === 'checking') applyUpdateState(known); } els.updateDot.addEventListener('click', async () => { if (checking || INERT_STATES.includes(updateState)) return; if (updateState === 'current' || updateState === 'error') { await runManualCheck(); } else if (updateState === 'available') { setRingProgress(0); setUpdateDot('downloading'); await window.flat.updateDownload(); } else if (updateState === 'downloaded') { // Pulses from here until the app goes down to restart. No fixed count. setUpdateDot('installing'); const result = await window.flat.updateInstall(); if (result && result.error) { // Could not restart right now (a job is running). Say why in the // dot's own label, then drop back to the plain "ready" wording. setUpdateDot('downloaded', result.error); setTimeout(() => { if (updateState === 'downloaded') setUpdateDot('downloaded'); }, 6000); } } }); // --------------------------------------------------------------------------- // Start // --------------------------------------------------------------------------- (async function start() { const info = await window.flat.appInfo(); els.updateWidgetVersion.textContent = `v${info.version}`; startUpdateDot(); const probe = await window.flat.probe(); if (!probe.present) { els.viewAll.hidden = true; els.viewMine.hidden = true; els.blocker.hidden = false; els.blockerBody.textContent = 'Flat works by driving the flatpak command, and it is not on this machine. ' + 'Nothing can be listed, backed up or installed until it is there.'; els.tabAll.disabled = true; els.tabMine.disabled = true; return; } await loadMine(); await scanApps(); }());