/ldg/ Collage Script

Updated version of the collage script created by anon. This enhanced version fixes several issues and adds video collage functionality. Now when you favorite/star either a .webm or .mp4 post, the script will automatically switch to outputting a .webm collage. It takes a few seconds to spool up once you click "Create collages", so don't spam the button, and don't alt-tab or switch browser tabs or it'll cancel it.

Fixes/additions:

  • added the ability to create 5 second long video or mixed video/image collages
  • video collages will automatically scale dimensions to keep the video under 2048 in either aspect (4chan's limit)
  • video collages will automatically search for a bitrate that will keep the collage video under 4MB (4chan's limit)
  • no longer need to refresh to see favorite/star button on new image/video posts
  • remembers highlights after refresh or browser restart
  • adds "clear all selections" button to remove currently selected highlights
  • adds .jpg option when exporting image collages so you don't have to convert the .png by hand, given the .png's are usally above 4MB. The .jpg will also be optimized to keep it under 4MB.
  • fixed bug where thread page would stop scrolling after exporting an image collage, which used to require a page refresh to fix
   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
// ==UserScript==
// @name         4chan Thumbnail Viewer & Collage Creator
// @namespace    http://tampermonkey.net/
// @version      1.0.0
// @description  Mark posts as highlights on the thread or in a thumbnail grid, review your selection, and make collages out of them.
// @match        https://boards.4channel.org/*/thread/*
// @match        https://boards.4chan.org/*/thread/*
// @grant        GM_xmlhttpRequest
// @connect      i.4cdn.org
// ==/UserScript==

(function() {
    'use strict';

    // =========================
    // 1. CSS Styles
    // =========================
    const style = document.createElement('style');
    style.innerHTML = `
        /* Base highlight button */
        .highlight-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            background: rgba(255,255,0,0.7);
            border: 1px solid #000;
            padding: 2px 5px;
            cursor: pointer;
            z-index: 10;
            font-weight: bold;
        }
        .highlighted {
            border: 3px solid red !important;
        }
        /* Generic overlay for views */
        .overlay {
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(0,0,0,0.8);
            z-index: 1000;
            overflow: auto;
            padding: 10px;
            display: flex;
            flex-direction: column;
        }
        .overlay-content {
            flex: 1;
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            position: relative;
        }
        /* Info button and content */
        .overlay-info-button {
            position: absolute;
            top: 10px;
            left: 10px;
            background: #008;
            color: #fff;
            border: none;
            padding: 4px 8px;
            cursor: pointer;
            z-index: 1100;
            border-radius: 3px;
            font-size: 14px;
        }
        .overlay-info-content {
            position: absolute;
            top: 45px;
            left: 10px;
            background: rgba(0,0,0,0.7);
            color: #fff;
            font-size: 12px;
            padding: 5px;
            border-radius: 3px;
            z-index: 1100;
            display: none;
            max-width: 300px;
        }
        .overlay-close-button {
            position: absolute;
            top: 10px;
            left: 70px;  /* Adjust this value to position it right next to the '?' button */
            background: red;
            color: #fff;
            border: none;
            padding: 4px 8px;
            cursor: pointer;
            z-index: 1100;
            border-radius: 3px;
            font-size: 14px;
}
        /* Thumbnail item */
        .thumb-item {
            margin: 5px;
            position: relative;
            cursor: pointer;
        }
        .thumb-item img {
            transition: all 0.3s;
            /* Default unexpanded size */
            max-width: 150px;
            max-height: 150px;
        }
        /* Selected thumbnails get a green border */
        .thumb-item.selected {
            outline: 4px solid #0f0;
        }
        /* Options (Highlights) menu in bottom right */
        .chan-hv-options-menu {
            position: fixed;
            bottom: 10px;
            right: 10px;
            background: rgba(0,0,0,0.8);
            padding: 5px;
            border-radius: 3px;
            z-index: 1001;
        }
        .chan-hv-menu-header {
            cursor: pointer;
            color: #fff;
            font-size: 16px;
            user-select: none;
        }
        .chan-hv-menu-content {
            display: none;
            margin-top: 5px;
        }
        .chan-hv-menu-content button {
            display: block;
            margin: 3px 0;
            background: #008;
            color: #fff;
            border: none;
            padding: 5px 10px;
            cursor: pointer;
            font-size: 14px;
        }
        /* Collage button */
        .collage-btn {
            position: fixed;
            top: 10px;
            right: 10px;
            z-index: 1100;
            padding: 8px 12px;
            background: #080;
            color: #fff;
            border: none;
            cursor: pointer;
            font-size: 14px;
        }
        /* Zoom slider styling */
        .zoom-slider {
            width: 200px;
        }
        /* Thread Thumbnails view */
        .thumbnails-grid img {
            margin: 5px;
        }
        /* Remove preset image size limits for thread view */
        .thumbnails-grid .thumb-item img {
            max-width: none;
            max-height: none;
        }
        /* Header image input container in review view */
        .header-input-container {
            margin-bottom: 10px;
            color: #fff;
            font-size: 16px;
            background-color: rgba(0, 0, 0, 0.5);
            padding: 8px;
            border-radius: 5px;
            width: 100%;
            text-align: center;
        }
        /* Review highlights view layout */
        .review-highlights-container {
            display: block !important;
        }
        .thumbs-container {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
        }
        /* Counter style */
        #selected-counter {
            margin: 10px;
            color: #fff;
            font-size: 16px;
        }
        /* Lightbox overlay for expanded images */
        .lightbox-overlay {
            position: fixed;
            top: 0; left: 0;
            width: 100vw;
            height: 100vh;
            background: rgba(0,0,0,0.9);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1200;
        }
        .lightbox-overlay img {
            max-width: 90vw;
            max-height: 90vh;
        }
    `;
    document.head.appendChild(style);

    // =========================
    // 2. Global Variables
    // =========================
    let selectedHeaderImage = null; // Object: { src, width, height }
    function getThreadKey() {
    const threadMatch = window.location.href.match(/thread\/(\d+)/);
    return threadMatch ? `highlightedImages_${threadMatch[1]}` : 'highlightedImages';
}

    let highlightedImages = [];

    function loadHighlights() {
        const saved = localStorage.getItem(getThreadKey());
        if (saved) {
            try {
                highlightedImages = JSON.parse(saved);
            } catch (e) {
                console.error("Failed to parse saved highlights:", e);
            }
        }
    }

function saveHighlights() {
    localStorage.setItem(getThreadKey(), JSON.stringify(highlightedImages));
}


    // =========================
    // Global: Update review counter
    // =========================
    function updateReviewCounter() {
      const counterDiv = document.getElementById('selected-counter');
      if (counterDiv) {
        const count = document.querySelectorAll('.review-highlights-container .thumb-item.selected').length;
        counterDiv.textContent = 'Selected: ' + count;
      }
    }

    // =========================
    // Show video status message
    // =========================
    let statusInterval = null;

    function showStatusMessage(text, options = {}) {
        let container = document.querySelector('.header-input-container');

        if (!container) {
            console.warn("Couldn't find header input container to insert status message.");
            return;
        }

        let msgBox = document.getElementById('bitrate-status-msg');
        if (!msgBox) {
            msgBox = document.createElement('div');
            msgBox.id = 'bitrate-status-msg';
            msgBox.style.marginTop = '10px';
            msgBox.style.fontSize = '16px';
            msgBox.style.color = '#fff';
            msgBox.style.textAlign = 'center';
            msgBox.style.whiteSpace = 'pre-line';
            container.appendChild(msgBox);
        }

        // Clear animation if needed
        clearInterval(statusInterval);

        if (options.blinking) {
            const baseText = text.replace(/\.*$/, '');
            let dotCount = 0;

            statusInterval = setInterval(() => {
                dotCount = (dotCount + 1) % 4;
                msgBox.querySelector('.status-line').textContent = baseText + '.'.repeat(dotCount);
            }, 500);
        } else {
            clearInterval(statusInterval);
        }

        // Initial render
        msgBox.innerHTML = `
        <div class="status-line">${text}</div>
        <div class="warn-line" style="margin-top: 6px; font-size: 14px; color: #faa;">(Don't alt-tab or change tabs or this will cancel early!)</div>
        <div class="bitrate-line"> </div>
    `;
    }


    // =========================
    // 3. Add Highlight Buttons to Posts
    // =========================
    function addHighlightButtons() {
    const posts = document.querySelectorAll('.post');
    const savedFullSrcs = highlightedImages.map(h => h.fullSrc);

    posts.forEach(post => {
        if (post.querySelector('.highlight-btn')) return; // Skip if already added
        const thumbLink = post.querySelector('a.fileThumb');
        if (!thumbLink) return;
        const img = thumbLink.querySelector('img');
        if (!img) return;

        const fullSrc = thumbLink.href;
        const btn = document.createElement('div');
        btn.textContent = '★';
        btn.className = 'highlight-btn';
        post.style.position = 'relative';

        // Restore highlight state from saved data
        if (savedFullSrcs.includes(fullSrc)) {
            post.classList.add('highlighted');
            btn.style.background = 'rgba(0,255,0,0.7)';
        }

        btn.addEventListener('click', e => {
            e.stopPropagation();
            const index = highlightedImages.findIndex(item => item.fullSrc === fullSrc);
            if (post.classList.contains('highlighted')) {
                post.classList.remove('highlighted');
                btn.style.background = 'rgba(255,255,0,0.7)';
                if (index > -1) highlightedImages.splice(index, 1);
            } else {
                post.classList.add('highlighted');
                btn.style.background = 'rgba(0,255,0,0.7)';
                highlightedImages.push({ post: null, thumbSrc: img.src, fullSrc });
            }
            saveHighlights(); // <--- This is what persists it
        });

        post.appendChild(btn);
    });
}

    // =========================
    // 4. Unified Thumbnail Behavior
    // =========================
    function setupUnifiedThumbnailBehavior(container) {
        const thumbItems = container.querySelectorAll('.thumb-item');
        thumbItems.forEach(item => {
            const img = item.querySelector('img');
            if (!img.dataset.thumb) {
                img.dataset.thumb = img.src;
            }
            item.addEventListener('click', e => {
                if (e.ctrlKey) {
                    if (item.classList.contains('selected')) {
                        item.classList.remove('selected');
                        removeFromHighlights(img.dataset.full);
                        if (container.classList.contains('review-highlights-container')) {
                            item.remove();
                        }
                    } else {
                        item.classList.add('selected');
                        addToHighlights(img.dataset.full, img.dataset.thumb);
                    }
                    // Update counter when selection toggles.
                    updateReviewCounter();
                } else {
                    const parentContainer = item.parentElement;
                    const imageNodes = parentContainer.querySelectorAll("img");
                    const imageList = Array.from(imageNodes).map(i => i.dataset.full);
                    const currentIndex = imageList.indexOf(img.dataset.full);
                    showLightbox(imageList, currentIndex);
                }
                e.stopPropagation();
            });
        });
        container.tabIndex = 0;
        container.focus();
    }
    function addToHighlights(fullSrc, thumbSrc) {
        if (!highlightedImages.find(item => item.fullSrc === fullSrc)) {
            highlightedImages.push({ post: null, thumbSrc, fullSrc });
        }
    }
    function removeFromHighlights(fullSrc) {
        const idx = highlightedImages.findIndex(item => item.fullSrc === fullSrc);
        if (idx > -1) highlightedImages.splice(idx, 1);
    }

    // =========================
    // Lightbox Overlay with Navigation
    // =========================
    function showLightbox(imageList, currentIndex) {
        const overlay = document.createElement('div');
        overlay.className = 'lightbox-overlay';
        const fullImg = document.createElement('img');
        fullImg.src = imageList[currentIndex];
        overlay.appendChild(fullImg);

        function keyHandler(e) {
            if (e.key === 'ArrowLeft') {
                currentIndex = (currentIndex - 1 + imageList.length) % imageList.length;
                fullImg.src = imageList[currentIndex];
                e.preventDefault();
            } else if (e.key === 'ArrowRight') {
                currentIndex = (currentIndex + 1) % imageList.length;
                fullImg.src = imageList[currentIndex];
                e.preventDefault();
            } else if (e.key === 'Escape') {
                document.body.removeChild(overlay);
                window.removeEventListener('keydown', keyHandler);
                e.preventDefault();
            }
        }
        window.addEventListener('keydown', keyHandler);
        overlay.addEventListener('click', () => {
            document.body.removeChild(overlay);
            window.removeEventListener('keydown', keyHandler);
        });
        document.body.appendChild(overlay);
    }

    // =========================
    // 5. Create a Generic Overlay View
    // =========================
    function createOverlayView(contentGenerator, closeCallback) {
        const originalBodyOverflow = document.body.style.overflow;
        document.body.style.overflow = 'hidden';

        const existing = document.querySelector('.overlay');
        if (existing) {
            existing.parentNode.removeChild(existing);
        }
        const overlay = document.createElement('div');
        overlay.className = 'overlay';
        overlay.tabIndex = 0;
        overlay.addEventListener('keydown', e => {
            if (e.key === 'Escape' && !document.querySelector('.lightbox-overlay')) {
                cleanup();
            }
        });
        const infoButton = document.createElement('button');
        infoButton.className = 'overlay-info-button';
        infoButton.textContent = '?';
        const infoContent = document.createElement('div');
        infoContent.className = 'overlay-info-content';
        infoContent.textContent = '(click to expand/contract, ctrl+click to select/deselect, esc to close view)';
        infoButton.addEventListener('click', () => {
            infoContent.style.display = (infoContent.style.display === 'none' || infoContent.style.display === '')
                ? 'block'
                : 'none';
        });
        const closeButton = document.createElement('button');
        closeButton.className = 'overlay-close-button';
        closeButton.textContent = 'X';
        closeButton.addEventListener('click', cleanup);

        overlay.appendChild(infoButton);
        overlay.appendChild(infoContent);
        overlay.appendChild(closeButton);
        const content = contentGenerator();
        overlay.appendChild(content);
        overlay.focus();
        function cleanup() {
            document.body.style.overflow = originalBodyOverflow;
            document.body.removeChild(overlay);
            if (closeCallback) closeCallback();
        }
        overlay.addEventListener('click', e => {
            if (e.target === overlay) cleanup();
        });
        document.body.appendChild(overlay);
    }

    // =========================
    // 6. Review Highlights View
    // =========================
    function showReviewHighlightsView() {
        const contentGenerator = () => {
            const container = document.createElement('div');
            container.className = 'overlay-content review-highlights-container';
            const headerContainer = document.createElement('div');
            headerContainer.className = 'header-input-container';
            headerContainer.innerHTML = `<label style="margin-right:5px;">Header image (optional):</label>`;
            const headerInput = document.createElement('input');
            headerInput.type = 'file';
            headerInput.accept = 'image/*';
            headerInput.addEventListener('change', e => {
                const file = e.target.files[0];
                if (!file) return;
                const reader = new FileReader();
                reader.onload = function(evt) {
                    const tempImg = new Image();
                    tempImg.onload = function() {
                        selectedHeaderImage = {
                            src: evt.target.result,
                            width: tempImg.naturalWidth,
                            height: tempImg.naturalHeight
                        };
                    };
                    tempImg.src = evt.target.result;
                };
                reader.readAsDataURL(file);
            });
            headerContainer.appendChild(headerInput);
            container.appendChild(headerContainer);

            // Add counter element
            const counterDiv = document.createElement('div');
            counterDiv.id = 'selected-counter';
            counterDiv.textContent = 'Selected: 0';
            container.appendChild(counterDiv);

            const thumbsContainer = document.createElement('div');
            thumbsContainer.className = 'thumbs-container';
            highlightedImages.forEach(item => {
                const thumbDiv = document.createElement('div');
                thumbDiv.className = 'thumb-item';
                thumbDiv.classList.add('selected');
                const img = document.createElement('img');
                img.src = item.thumbSrc;
                img.dataset.thumb = item.thumbSrc;
                img.dataset.full = item.fullSrc;
                thumbDiv.appendChild(img);
                thumbsContainer.appendChild(thumbDiv);
            });
            container.appendChild(thumbsContainer);
            const collageBtn = document.createElement('button');
            collageBtn.textContent = "Create Collages";
            collageBtn.className = "collage-btn";
            collageBtn.addEventListener("click", createCollage);
            container.appendChild(collageBtn);
            setTimeout(() => { setupUnifiedThumbnailBehavior(thumbsContainer); updateReviewCounter(); }, 0);
            return container;
        };
        createOverlayView(contentGenerator);
    }

    // =========================
    // 7. Thread Thumbnails View
    // =========================
    function showThreadThumbnailsView() {
        const contentGenerator = () => {
            const container = document.createElement('div');
            container.className = 'overlay-content thumbnails-grid';
            const sliderContainer = document.createElement('div');
            sliderContainer.style.textAlign = 'center';
            sliderContainer.style.width = '100%';
            sliderContainer.style.marginBottom = '10px';
            const zoomLabel = document.createElement('label');
            zoomLabel.textContent = 'Zoom: ';
            const zoomSlider = document.createElement('input');
            zoomSlider.type = 'range';
            zoomSlider.className = 'zoom-slider';
            zoomSlider.min = 50;
            zoomSlider.max = 400;
            zoomSlider.value = 100;
            zoomSlider.style.margin = '10px';
            sliderContainer.appendChild(zoomLabel);
            sliderContainer.appendChild(zoomSlider);
            container.appendChild(sliderContainer);
            const thumbsContainer = document.createElement('div');
            thumbsContainer.className = 'thumbs-container';
            const thumbs = document.querySelectorAll('a.fileThumb img');
            thumbs.forEach(imgEl => {
                const thumbDiv = document.createElement('div');
                thumbDiv.className = 'thumb-item';
                const clone = document.createElement('img');
                clone.src = imgEl.src;
                clone.dataset.thumb = imgEl.src;
                const parentLink = imgEl.closest('a.fileThumb');
                clone.dataset.full = parentLink ? parentLink.href : imgEl.src;
                // When the image loads, store its base width (capped at 200px)
                clone.onload = function() {
                    const naturalW = clone.naturalWidth;
                    const baseW = naturalW > 200 ? 200 : naturalW;
                    clone.dataset.baseWidth = baseW;
                    const scale = zoomSlider.value / 100;
                    clone.style.width = (baseW * scale) + 'px';
                };
                if (highlightedImages.some(item => item.fullSrc === clone.dataset.full)) {
                    thumbDiv.classList.add('selected');
                }
                thumbDiv.appendChild(clone);
                thumbsContainer.appendChild(thumbDiv);
            });
            container.appendChild(thumbsContainer);
            setTimeout(() => { setupUnifiedThumbnailBehavior(thumbsContainer); }, 0);
            zoomSlider.addEventListener('input', () => {
                const scale = zoomSlider.value / 100;
                const images = thumbsContainer.querySelectorAll('img');
                images.forEach(img => {
                    if (!img.closest('.thumb-item').classList.contains('expanded')) {
                        const base = img.dataset.baseWidth ? parseFloat(img.dataset.baseWidth) : 150;
                        img.style.width = (base * scale) + 'px';
                        img.style.height = 'auto';
                    }
                });
            });
            return container;
        };
        createOverlayView(contentGenerator);
    }

    // =========================
    // 8. Create Collage (and trigger PNG download)
    // =========================
    async function createCollage() {
        const hasVideo = highlightedImages.some(item => item.fullSrc.endsWith('.webm') || item.fullSrc.endsWith('.mp4'));
        if (hasVideo) {
            console.log("[Collage Debug] Detected video, switching to video collage mode.");
            createVideoCollage();
            return;
        }

    const numCollages = parseInt(prompt("Enter number of collages:", "1"), 10);
    const targetMP = parseFloat(prompt("Enter target megapixels per image (e.g., 1 for 1MP):", "0.3"));
    const targetAspect = parseFloat(prompt("Enter target aspect ratio (e.g., 1 for square, 1.33 for 4:3):", "1"));
    if (!numCollages || !targetMP || !targetAspect) {
        alert("Invalid input.");
        return;
    }

    const targetArea = targetMP * 1e6;
    let L = [];
    for (let i = 0; i < highlightedImages.length; i++) {
        const imgData = highlightedImages[i];
        try {
            const dims = await getImageDimensions(imgData.fullSrc);
            L.push({
                src: imgData.fullSrc,
                width: dims.width,
                height: dims.height
            });
        } catch (err) {
            console.error("Failed to load image dimensions for", imgData.fullSrc, err);
        }
    }

    if (L.length === 0) {
        alert("No images available for collage.");
        return;
    }

    const collages = roundRobinCollageLayout(L, numCollages, targetArea, selectedHeaderImage, targetAspect);
    if (!collages || collages.length === 0) {
        alert("Collage layout failed.");
        return;
    }

    let collagePromises = collages.map((collage, collageIndex) => {
        return new Promise(resolve => {
            const canvas = document.createElement("canvas");
            canvas.width = collage.width;
            canvas.height = collage.height;
            const ctx = canvas.getContext("2d");
            ctx.fillStyle = "#fff";
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            let placementPromises = collage.placements.map(placement => {
                return new Promise(r => {
                    fetchImageAsBlob(placement.image.src)
                        .then(blob => {
                            const blobUrl = URL.createObjectURL(blob);
                            const imageEl = new Image();
                            imageEl.onload = function() {
                                ctx.drawImage(imageEl,
                                    placement.x,
                                    placement.y,
                                    placement.width,
                                    placement.height
                                );
                                URL.revokeObjectURL(blobUrl);
                                r();
                            };
                            imageEl.onerror = function(e) {
                                console.error("Error loading image:", placement.image.src, e);
                                r();
                            };
                            imageEl.src = blobUrl;
                        })
                        .catch(err => {
                            console.error("GM_xmlhttpRequest error:", err);
                            r();
                        });
                });
            });

            Promise.all(placementPromises).then(() => {
                const dataUrl = canvas.toDataURL('image/png');
                const url = window.location.href;
                const boardMatch = url.match(/boards\.4chan(?:nel)?\.org\/([^\/]+)\//);
                const board = boardMatch ? boardMatch[1] : "unknown";
                const threadMatch = url.match(/thread\/(\d+)/);
                const thread = threadMatch ? threadMatch[1] : "unknown";
                const currentUnixTime = Math.floor(Date.now() / 1000);
                const filename = `highlights_${board}_${thread}_${currentUnixTime}_${collageIndex+1}.png`;

                // Show PNG and JPG download options
                const downloadContainer = document.createElement('div');
                downloadContainer.style.position = 'fixed';
                downloadContainer.style.top = '20px';
                downloadContainer.style.left = '50%';
                downloadContainer.style.transform = 'translateX(-50%)';
                downloadContainer.style.background = 'rgba(0, 0, 0, 0.9)';
                downloadContainer.style.padding = '20px';
                downloadContainer.style.zIndex = '2000';
                downloadContainer.style.borderRadius = '10px';
                downloadContainer.style.color = '#fff';
                downloadContainer.style.textAlign = 'center';

                const pngBtn = document.createElement('button');
                pngBtn.textContent = 'Download Raw .png';
                pngBtn.style.margin = '10px';
                pngBtn.style.padding = '10px';
                pngBtn.style.background = '#008';
                pngBtn.style.color = '#fff';
                pngBtn.style.border = 'none';
                pngBtn.style.cursor = 'pointer';
                pngBtn.style.fontSize = '16px';

                pngBtn.addEventListener('click', () => {
                    const a = document.createElement('a');
                    a.href = dataUrl;
                    a.download = filename;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    document.body.removeChild(downloadContainer);
                    document.body.style.overflow = ''; // ✅ Restore scroll here too
                });

                const jpgBtn = document.createElement('button');
                jpgBtn.textContent = 'Download Compressed .jpg';
                jpgBtn.style.margin = '10px';
                jpgBtn.style.padding = '10px';
                jpgBtn.style.background = '#080';
                jpgBtn.style.color = '#fff';
                jpgBtn.style.border = 'none';
                jpgBtn.style.cursor = 'pointer';
                jpgBtn.style.fontSize = '16px';

                jpgBtn.addEventListener('click', async () => {
                    let quality = 0.92;
                    let blob;
                    do {
                        const jpegDataUrl = canvas.toDataURL('image/jpeg', quality);
                        blob = dataURLToBlob(jpegDataUrl);
                        if (blob.size <= 3.99 * 1024 * 1024) {
                            const a = document.createElement('a');
                            a.href = URL.createObjectURL(blob);
                            a.download = filename.replace('.png', '.jpg');
                            document.body.appendChild(a);
                            a.click();
                            document.body.removeChild(a);
                            document.body.removeChild(downloadContainer);
                            document.body.style.overflow = ''; // ✅ Restore scroll
                            return;
                        }
                        quality -= 0.05;
                    } while (quality > 0.1);

                    alert("Couldn't compress JPG under 3.99MB. You shouldn't see this!");
                });

                downloadContainer.appendChild(pngBtn);
                downloadContainer.appendChild(jpgBtn);
                document.body.appendChild(downloadContainer);

                resolve();
            });
        });
    });

    Promise.all(collagePromises).then(() => {
        const existing = document.querySelector('.overlay');
        if (existing) existing.parentNode.removeChild(existing);
    });
}

    // =========================
    // 8b. Create Video Collage if any videos are selected
    // =========================
    async function createVideoCollage() {
        const duration = 5; // seconds
        const fps = 30;
        const maxSize = 3.99 * 1024 * 1024;
        const maxDim = 2048;
        const targetArea = 0.3 * 1e6;
        const targetAspect = 1;

        // Load media
        let mediaItems = [];
        for (let item of highlightedImages) {
            try {
                if (item.fullSrc.endsWith('.webm') || item.fullSrc.endsWith('.mp4')) {
                    const video = document.createElement('video');
                    video.src = item.fullSrc;
                    video.crossOrigin = 'anonymous';
                    video.muted = true;
                    video.playsInline = true;
                    video.loop = true;
                    await new Promise(res => video.addEventListener('loadeddata', res, { once: true }));
                    mediaItems.push({ type: 'video', element: video, width: video.videoWidth, height: video.videoHeight });
                } else {
                    const img = new Image();
                    img.crossOrigin = 'anonymous';
                    img.src = item.fullSrc;
                    await img.decode();
                    mediaItems.push({ type: 'image', element: img, width: img.naturalWidth, height: img.naturalHeight });
                }
            } catch (e) {
                console.warn("Skipping invalid media:", item.fullSrc, e);
            }
        }

        if (mediaItems.length === 0) {
            alert("No valid media to create collage.");
            return;
        }

        // Initial layout
        let adjustedTargetArea = targetArea;
        let collage = null;

        // Attempt to fit collage layout under 2048x2048 by adjusting targetArea
        for (let attempts = 0; attempts < 10; attempts++) {
            const testCollages = roundRobinCollageLayout(mediaItems, 1, adjustedTargetArea, null, targetAspect);
            collage = testCollages[0];
            if (collage.width <= maxDim && collage.height <= maxDim) {
                break;
            }
            adjustedTargetArea *= 0.9;
        }

        // If it STILL exceeds limits, apply a final canvas scale down, because fuck it, I'm done
        if (collage.width > maxDim || collage.height > maxDim) {
            const scale = Math.min(maxDim / collage.width, maxDim / collage.height);
            collage.placements.forEach(p => {
                p.x *= scale;
                p.y *= scale;
                p.width *= scale;
                p.height *= scale;
            });
            collage.width *= scale;
            collage.height *= scale;
        }

        const canvas = document.createElement('canvas');
        canvas.width = Math.floor(collage.width);
        canvas.height = Math.floor(collage.height);
        const ctx = canvas.getContext('2d');

        async function renderVideoWithBitrate(bitrate) {
            return new Promise((resolve) => {
                const stream = canvas.captureStream(fps);
                const recorder = new MediaRecorder(stream, {
                    mimeType: 'video/webm; codecs=vp8', // vp9 is a little better but encoding it doesn't work on some browsers, so meh
                    videoBitsPerSecond: bitrate
                });
                const chunks = [];
                recorder.ondataavailable = e => chunks.push(e.data);
                recorder.onstop = () => {
                    resolve(new Blob(chunks, { type: 'video/webm' }));
                };

                // Ensure videos are reset and playing
                mediaItems.forEach(m => {
                    if (m.type === 'video') {
                        m.element.currentTime = 0;
                        m.element.play().catch(() => {});
                    }
                });

                // Warmup workaround to fix first few frames glitching out due to browser buffering issues
                const warmupFrames = 5;
                for (let i = 0; i < warmupFrames; i++) {
                    ctx.fillStyle = "#fff";
                    ctx.fillRect(0, 0, canvas.width, canvas.height);
                    collage.placements.forEach(p => {
                        try {
                            ctx.drawImage(p.image.element, p.x, p.y, p.width, p.height);
                        } catch {}
                    });
                }
                setTimeout(() => {
                    recorder.start();

                    const start = performance.now();
                    const end = start + duration * 1000;

                    function draw() {
                        const now = performance.now();
                        ctx.fillStyle = "#fff";
                        ctx.fillRect(0, 0, canvas.width, canvas.height);
                        collage.placements.forEach(p => {
                            try {
                                ctx.drawImage(p.image.element, p.x, p.y, p.width, p.height);
                            } catch {}
                        });
                        if (now < end) {
                            requestAnimationFrame(draw);
                        } else {
                            recorder.stop();
                        }
                    }

                    draw();
                }, 200); // 🕒 200ms delay before recording starts
            });
        }

        // Try to find the best bitrate for the video. Testing indicates its usually between 5-6 to produce 3.8MB files

        async function findBestBitrate() {
            showStatusMessage("Searching for optimal bitrate to keep filesize under 4MB", { blinking: true });

            let bestBlob = null;
            let bitrate = 5000000;
            const maxBitrate = 10000000;
            const step = 500000;

            while (bitrate <= maxBitrate) {
                const blob = await renderVideoWithBitrate(bitrate);

                // Update bitrate + size live
                const msgBox = document.getElementById('bitrate-status-msg');
                if (msgBox) {
                    const sizeMB = (blob.size / (1024 * 1024)).toFixed(2);
                    msgBox.querySelector('.bitrate-line').textContent =
                        `Tried: ${(bitrate / 1e6).toFixed(1)} Mbps | Size = ${sizeMB}MB`;
                }

                console.log(`Bitrate: ${bitrate / 1e6} Mbps - Size: ${blob.size}`);
                if (blob.size <= maxSize) {
                    bestBlob = blob;
                    bitrate += step;
                } else break;
            }

            if (bestBlob) {
                const a = document.createElement('a');
                a.href = URL.createObjectURL(bestBlob);
                a.download = `video_collage_${Date.now()}.webm`;
                a.click();

                showStatusMessage("Complete.");
                setTimeout(() => {
                    const msg = document.getElementById('bitrate-status-msg');
                    if (msg) msg.remove();
                }, 3000);
            } else {
                showStatusMessage("Failed to compress under 4.0MB. You shouldn't see this, it means anon fucked up!");
                setTimeout(() => {
                    const msg = document.getElementById('bitrate-status-msg');
                    if (msg) msg.remove();
                }, 4000);
                alert("Couldn't compress under 3.8MB. You shouldn't see this, it means anon fucked up!");
            }
        }

        await findBestBitrate();
    }

    // =========================
    // 9. Round-Robin Collage Layout with Custom Row Grouping, Row Balancing, and Height Adjustment
    // =========================
    function roundRobinCollageLayout(L, numCollages, targetArea, headerImage, targetAspect) {
        // Scale each image so that its area is proportional to targetArea.
        L.forEach(img => {
            let s = Math.sqrt(targetArea / (img.width * img.height));
            img.scaledWidth = img.width * s;
            img.scaledHeight = img.height * s;
        });
        // Sort images by aspect ratio (narrow to wide)
        L.sort((a, b) => (a.width / a.height) - (b.width / b.height));
        // Distribute images round-robin into groups.
        let groups = [];
        for (let i = 0; i < numCollages; i++) {
            groups.push([]);
        }
        for (let i = 0; i < L.length; i++) {
            groups[i % numCollages].push(L[i]);
        }
        let collages = [];
        groups.forEach((group, groupIndex) => {
            if (group.length === 0) return;
            let m = group.length;
            // Custom row grouping: number of images per row = ceil(sqrt(m) * targetAspect)
            let numColumns = Math.ceil(Math.sqrt(m) * targetAspect);
            let rows = [];
            for (let i = 0; i < m; i += numColumns) {
                rows.push(group.slice(i, i + numColumns));
            }
            // Row Balancing: For each row (except the last), swap its first image with the image that is the r-th widest overall.
            let allBoxes = rows.flat();
            let sortedByWidth = [...allBoxes].sort((a, b) => b.scaledWidth - a.scaledWidth);
            for (let r = 0; r < rows.length - 1; r++) {
                let desired = sortedByWidth[r]; // r-th widest overall
                if (rows[r][0] !== desired) {
                    for (let r2 = r; r2 < rows.length; r2++) {
                        let idx = rows[r2].indexOf(desired);
                        if (idx !== -1) {
                            let temp = rows[r][0];
                            rows[r][0] = rows[r2][idx];
                            rows[r2][idx] = temp;
                            break;
                        }
                    }
                }
            }
            // --- New Height Adjustment based on final (justified) row heights ---
            if (rows.length > 1) {
                // First, compute metrics for each row based on the pre-justified layout.
                const rowMetrics = rows.map(row => {
                    // Use the first image's scaledHeight as the base height.
                    const baseHeight = row[0].scaledHeight;
                    let totalWidth = 0;
                    for (const img of row) {
                        // Scale each image to the base height.
                        const factor = baseHeight / img.scaledHeight;
                        totalWidth += img.scaledWidth * factor;
                    }
                    return { baseHeight, totalWidth };
                });

                // Determine the maximum row width among all rows.
                const maxRowWidth = Math.max(...rowMetrics.map(m => m.totalWidth));

                // Now compute the final height of each row after justification.
                // (Justification scales the row so that its total width equals maxRowWidth.)
                const finalHeights = rowMetrics.map(m => m.baseHeight * (maxRowWidth / m.totalWidth));

                // Get the final height of the bottom row.
                const bottomFinalHeight = finalHeights[finalHeights.length - 1];

                // Find the smallest final height among all rows except the bottom.
                let minFinalHeight = Infinity;
                for (let i = 0; i < finalHeights.length - 1; i++) {
                    if (finalHeights[i] < minFinalHeight) {
                        minFinalHeight = finalHeights[i];
                    }
                }

                // Only perform adjustment if the bottom row's final height exceeds 1.8x the smallest.
                if (bottomFinalHeight > 1.8 * minFinalHeight) {
                    const bottomRow = rows[rows.length - 1];

                    if (bottomRow.length === 1) {
                        // If the bottom row has a single image, move it into the tallest row (excluding the bottom).
                        let tallestRowIndex = -1;
                        let maxFinalHeight = -Infinity;
                        for (let i = 0; i < finalHeights.length - 1; i++) {
                            if (finalHeights[i] > maxFinalHeight) {
                                maxFinalHeight = finalHeights[i];
                                tallestRowIndex = i;
                            }
                        }
                        if (tallestRowIndex !== -1) {
                            const imageToMove = bottomRow.pop();
                            rows[tallestRowIndex].push(imageToMove);
                            // Remove the bottom row if it becomes empty.
                            if (bottomRow.length === 0) {
                                rows.pop();
                            }
                        }
                    } else {
                        // Otherwise, take the widest image from the shortest row (by final height) among non-bottom rows
                        let donorRowIndex = -1;
                        let minRowFinalHeight = Infinity;
                        for (let i = 0; i < finalHeights.length - 1; i++) {
                            if (finalHeights[i] < minRowFinalHeight) {
                                minRowFinalHeight = finalHeights[i];
                                donorRowIndex = i;
                            }
                        }
                        if (donorRowIndex !== -1 && rows[donorRowIndex].length > 0) {
                            const donorRow = rows[donorRowIndex];
                            // Find the widest image in the donor row.
                            let widestImageIndex = 0;
                            let maxWidth = donorRow[0].scaledWidth;
                            for (let j = 1; j < donorRow.length; j++) {
                                if (donorRow[j].scaledWidth > maxWidth) {
                                    maxWidth = donorRow[j].scaledWidth;
                                    widestImageIndex = j;
                                }
                            }
                            const donorImage = donorRow.splice(widestImageIndex, 1)[0];
                            bottomRow.push(donorImage);
                        }
                    }
                }
            }
            // Randomize each row.
            rows = rows.map(row => row.sort(() => Math.random() - 0.5));
            // Insert header image (if any) into the beginning of the narrowest row by total width.
            if (headerImage) {
                let narrowestRowIndex = 0;
                let minRowWidth = Infinity;
                rows.forEach((row, idx) => {
                    let width = row.reduce((sum, img) => sum + img.scaledWidth, 0);
                    if (width < minRowWidth) {
                        minRowWidth = width;
                        narrowestRowIndex = idx;
                    }
                });
                const baseHeight = rows[narrowestRowIndex][0].scaledHeight;
                const factor = baseHeight / headerImage.height;
                const headerScaled = {
                    src: headerImage.src,
                    scaledWidth: headerImage.width * factor,
                    scaledHeight: baseHeight
                };
                rows[narrowestRowIndex].unshift(headerScaled);
            }
            // Justify rows: For each row, compute a layout with common height, then scale rows to the maximum width.
            let rowLayouts = rows.map(row => {
                let baseHeight = row[0].scaledHeight;
                let cells = row.map(img => {
                    let factor = baseHeight / img.scaledHeight;
                    return {
                        image: img,
                        width: img.scaledWidth * factor,
                        height: baseHeight
                    };
                });
                let totalWidth = cells.reduce((sum, cell) => sum + cell.width, 0);
                return { cells, width: totalWidth, height: baseHeight };
            });
            let maxRowWidth = Math.max(...rowLayouts.map(r => r.width));
            rowLayouts = rowLayouts.map(r => {
                if (r.width < maxRowWidth) {
                    let factor = maxRowWidth / r.width;
                    return {
                        cells: r.cells.map(cell => ({
                            image: cell.image,
                            width: cell.width * factor,
                            height: cell.height * factor
                        })),
                        width: r.width * factor,
                        height: r.height * factor
                    };
                } else {
                    return r;
                }
            });
            let placements = [];
            let y = 0;
            rowLayouts.forEach(r => {
                let x = 0;
                r.cells.forEach(cell => {
                    placements.push({
                        image: cell.image,
                        x: x,
                        y: y,
                        width: cell.width,
                        height: cell.height
                    });
                    x += cell.width;
                });
                y += r.height;
            });
            collages.push({ width: maxRowWidth, height: y, placements });
        });
        return collages;
    }

    // =========================
    // 10. Utility: Fetch image as blob.
    // =========================
    function fetchImageAsBlob(url) {
        return new Promise((resolve, reject) => {
            GM_xmlhttpRequest({
                method: "GET",
                url: url,
                responseType: "blob",
                onload: function(response) {
                    if (response.status === 200) {
                        resolve(response.response);
                    } else {
                        reject(new Error("Failed to fetch image. Status: " + response.status));
                    }
                },
                onerror: function(err) {
                    reject(err);
                }
            });
        });
    }

    function dataURLToBlob(dataURL) {
    const binary = atob(dataURL.split(',')[1]);
    const array = [];
    for (let i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
    }
    return new Blob([new Uint8Array(array)], { type: 'image/jpeg' });
}


    // =========================
    // 11. Utility: Get image dimensions.
    // =========================
    function getImageDimensions(url) {
        return new Promise((resolve, reject) => {
            fetchImageAsBlob(url)
                .then(blob => {
                    const blobUrl = URL.createObjectURL(blob);
                    const img = new Image();
                    img.onload = function() {
                        resolve({ width: img.naturalWidth, height: img.naturalHeight });
                        URL.revokeObjectURL(blobUrl);
                    };
                    img.onerror = function(e) { reject(e); };
                    img.src = blobUrl;
                })
                .catch(reject);
        });
    }

    // =========================
    // 12. Options Menu (Renamed "Highlights" and positioned bottom right)
    // =========================
    function addOptionsMenu() {
        const menu = document.createElement('div');
        menu.className = 'chan-hv-options-menu';
        const header = document.createElement('div');
        header.className = 'chan-hv-menu-header';
        header.textContent = '► Highlights';
        header.addEventListener('click', () => {
            const content = menu.querySelector('.chan-hv-menu-content');
            if (content.style.display === 'block') {
                content.style.display = 'none';
                header.textContent = '► Highlights';
            } else {
                content.style.display = 'block';
                header.textContent = '▼ Highlights';
            }
        });
        menu.appendChild(header);
        const content = document.createElement('div');
        content.className = 'chan-hv-menu-content';
        content.style.display = 'none';
        const reviewBtn = document.createElement('button');
        reviewBtn.textContent = 'Review Highlights';
        reviewBtn.addEventListener('click', showReviewHighlightsView);
        const clearBtn = document.createElement('button');
        clearBtn.textContent = 'Clear All Selections';
        clearBtn.addEventListener('click', () => {
            if (!confirm("Are you sure you want to clear all highlighted posts?")) return;

            // Remove highlight class from any posts
            document.querySelectorAll('.post.highlighted').forEach(post => {
                post.classList.remove('highlighted');
                const btn = post.querySelector('.highlight-btn');
                if (btn) btn.style.background = 'rgba(255,255,0,0.7)';
            });
            // Clear in-memory and saved data
            highlightedImages = [];
            saveHighlights();
        });
        const threadBtn = document.createElement('button');
        threadBtn.textContent = 'View Thread Thumbnails';
        threadBtn.addEventListener('click', showThreadThumbnailsView);
        content.appendChild(reviewBtn);
        content.appendChild(threadBtn);
        content.appendChild(clearBtn);
        menu.appendChild(content);
        document.body.appendChild(menu);
    }

    // =========================
    // 13. Initialization
    // =========================
    function init() {
    loadHighlights(); // Load saved highlights first
    addHighlightButtons(); // Then apply them
    addOptionsMenu();

        // Automatically add highlight buttons to new posts
        const observer = new MutationObserver(mutations => {
            for (const mutation of mutations) {
                if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
                    addHighlightButtons();
                }
            }
        });

observer.observe(document.body, {
    childList: true,
    subtree: true
});

}

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
Edit Report
Pub: 26 May 2025 23:05 UTC
Edit: 28 May 2025 01:53 UTC
Views: 242