Robert Birming

Gallery upload

The Gallery upload window, with a file picker, a 10 MB limit note, and checkboxes for Mark as gallery and Keep original quality

A dashboard plugin for uploading, arranging, and captioning photos as a gallery, straight from the post editor.

Update (17 Nov 2026): Version 1.1 fixes uploads failing after a change on Bear's side. If you added the plugin before, replace it with the script below.

I read Harry's post Bear Community, I need your wisdom and thought to myself, "What an awesome Sunday tinkering challenge". This is what I came up with.

After adding the script to your dashboard, you'll see a new "Create gallery" link when drafting posts and pages. Clicking it opens a window where you can upload, rearrange, and caption your photos. I've tried to make it feel as native to Bear as possible.

Tick "Mark as gallery" and each photo gets a #gallery marker, so it works with the photo gallery styles and lightbox. Captions then become the photo's alt text, which the lightbox shows under each photo. Leave it unticked to insert the photos one by one, with captions underneath.

You can drop photos straight into the window, add them a few at a time, and remove any you change your mind about. If an upload fails, you'll see why, and you can retry just the failed ones. Tick "Keep original quality" to skip Bear's image optimisation.

How to use

  1. Copy the script below.
  2. Go to Customise dashboard.
  3. Paste the script under "Dashboard footer content" and save.

Note: Image uploads are a Bear premium feature, so the plugin needs an upgraded account.

<script>
/*
  Plugin name: Gallery upload
  Version: 1.1
  Description: Adds "Create gallery" next to Insert media in the post editor. Upload several photos at once, reorder them by dragging, add optional captions and mark them as a gallery.
  Author: Robert Birming
  Source: https://robertbirming.com/
*/

(function () {
    'use strict';

    document.addEventListener('DOMContentLoaded', function () {
        const $body = document.getElementById('body_content');
        const $insertMedia = document.getElementById('upload-image');

        if (!$body || !$insertMedia) return;

        const blogSlug = window.location.pathname.split('/').filter(Boolean)[0];
        const uploadUrl = '/' + blogSlug + '/dashboard/upload-image/';

        function csrfToken() {
            const el = document.querySelector('[name=csrfmiddlewaretoken]');
            return el ? el.value : '';
        }

        // Unique ID per placeholder - avoids any collision risk with duplicate filenames
        function generateId() {
            if (typeof crypto !== 'undefined' && crypto.randomUUID) {
                return crypto.randomUUID();
            }
            return Date.now().toString(36) + Math.random().toString(36).slice(2);
        }

        // Escape user-supplied caption text before inserting into HTML
        function escapeHtml(str) {
            return str
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;');
        }

        // Track cursor position on blur, click, and keyup for reliability
        let savedCursorPos = $body.value.length;
        ['blur', 'click', 'keyup', 'input', 'select'].forEach(function (eventName) {
            $body.addEventListener(eventName, function () {
                savedCursorPos = this.selectionStart;
            });
        });

        // --- Inject "Create gallery" into the native link bar ---

        const $bar = $insertMedia.parentElement;
        const $sep = document.createTextNode(' | ');
        const $galleryLink = document.createElement('a');

        $galleryLink.href = '#';
        $galleryLink.textContent = 'Create gallery';
        $galleryLink.addEventListener('click', function (e) {
            e.preventDefault();
            openModal();
        });

        $bar.insertBefore($sep, $insertMedia);
        $bar.insertBefore($galleryLink, $sep);

        // --- Styles ---

        const $style = document.createElement('style');
        $style.textContent = `
            #gu-overlay {
                position: fixed;
                inset: 0;
                background: rgba(0, 0, 0, 0.3);
                z-index: 9999;
                display: none;
                align-items: center;
                justify-content: center;
                padding: 20px;
                box-sizing: border-box;
            }
            #gu-modal {
                width: 100%;
                max-width: 640px;
                max-height: 90vh;
                overflow-y: auto;
                background: var(--background-color, #fff);
                color: var(--text-color, #444);
                border: 1px solid lightgrey;
                box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
            }
            #gu-head {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 12px 16px;
                border-bottom: 1px solid lightgrey;
            }
            #gu-body {
                padding: 16px;
            }
            #gu-file-wrap {
                margin-bottom: 12px;
            }
            #gu-file-wrap input[type="file"] {
                width: auto !important;
                background: none !important;
                padding: 0 !important;
                font-size: inherit;
                line-height: inherit;
            }
            #gu-limit {
                display: block;
                font-size: 0.85em;
                opacity: 0.6;
                margin-top: 6px;
            }
            #gu-hint {
                font-size: 0.9em;
                font-weight: normal;
                opacity: 0.6;
                margin: 0 0 10px;
                display: none;
            }
            #gu-thumbs {
                display: flex;
                flex-wrap: wrap;
                gap: 8px;
                margin-bottom: 12px;
                min-height: 1px;
            }
            #gu-thumbs.gu-uploading {
                pointer-events: none;
            }
            .gu-thumb {
                position: relative;
                width: 96px;
                flex-shrink: 0;
                cursor: grab;
            }
            .gu-thumb img {
                width: 96px;
                height: 96px;
                object-fit: cover;
                display: block;
                pointer-events: none;
            }
            .gu-thumb-name {
                font-size: 9px;
                opacity: 0.55;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                width: 96px;
                margin-top: 3px;
            }
            .gu-thumb-caption {
                width: 96px;
                margin-top: 4px;
                font-size: 12px !important;
                line-height: 1.3 !important;
                padding: 3px 5px !important;
                background: none !important;
                border: 1px solid rgba(128, 128, 128, 0.35) !important;
                border-radius: 2px;
                color: inherit !important;
                box-sizing: border-box;
                cursor: text;
            }
            .gu-thumb-caption::placeholder {
                font-size: 12px;
                opacity: 0.45;
            }
            .gu-thumb.gu-error .gu-thumb-name {
                color: #f44336;
                opacity: 1;
                white-space: normal;
            }
            #gu-modal.gu-dropping {
                outline: 2px dashed currentColor;
                outline-offset: -8px;
            }
            .gu-remove {
                position: absolute;
                top: 3px;
                left: 3px;
                width: 20px;
                height: 20px;
                padding: 0 !important;
                border: 0 !important;
                border-radius: 50%;
                background: rgba(0, 0, 0, 0.6) !important;
                color: #fff !important;
                font-size: 14px;
                line-height: 20px !important;
                cursor: pointer;
                opacity: 0;
            }
            .gu-thumb:hover .gu-remove,
            .gu-remove:focus-visible {
                opacity: 1;
            }
            #gu-thumbs.gu-uploading .gu-remove {
                display: none;
            }
            .gu-badge {
                position: absolute;
                top: 3px;
                right: 3px;
                width: 18px;
                height: 18px;
                border-radius: 50%;
                font-size: 11px;
                font-weight: bold;
                display: none;
                align-items: center;
                justify-content: center;
                color: #fff;
            }
            .gu-opt {
                display: flex;
                align-items: center;
                gap: 8px;
                font-size: 0.9em;
                font-weight: normal;
                margin-bottom: 12px;
                cursor: pointer;
            }
            .gu-opt input {
                width: auto !important;
                background: none !important;
                padding: 0 !important;
                margin: 0;
            }
            #gu-actions {
                display: flex;
                align-items: center;
                gap: 12px;
                flex-wrap: wrap;
            }
            #gu-status {
                font-size: 0.85em;
                opacity: 0.6;
            }
            @media (prefers-color-scheme: dark) {
                #gu-overlay {
                    background: rgba(0, 0, 0, 0.5);
                }
                #gu-modal,
                #gu-head {
                    border-color: rgba(255, 255, 255, 0.12);
                }
            }
        `;
        document.head.appendChild($style);

        // --- Build modal ---

        const $overlay = document.createElement('div');
        $overlay.id = 'gu-overlay';

        const $modal = document.createElement('div');
        $modal.id = 'gu-modal';

        const $head = document.createElement('div');
        $head.id = 'gu-head';

        const $title = document.createElement('strong');
        $title.id = 'gu-title';
        $title.textContent = 'Gallery upload';

        $modal.setAttribute('role', 'dialog');
        $modal.setAttribute('aria-modal', 'true');
        $modal.setAttribute('aria-labelledby', 'gu-title');

        const $closeBtn = document.createElement('button');
        $closeBtn.type = 'button';
        $closeBtn.textContent = 'Close';
        $closeBtn.addEventListener('click', closeModal);

        $head.appendChild($title);
        $head.appendChild($closeBtn);

        const $modalBody = document.createElement('div');
        $modalBody.id = 'gu-body';

        const $fileWrap = document.createElement('div');
        $fileWrap.id = 'gu-file-wrap';

        const $fileInput = document.createElement('input');
        $fileInput.type = 'file';
        $fileInput.multiple = true;
        $fileInput.accept = 'image/*';

        const $limit = document.createElement('span');
        $limit.id = 'gu-limit';
        $limit.textContent = 'Max 10 MB per photo';

        $fileWrap.appendChild($fileInput);
        $fileWrap.appendChild($limit);

        const $hint = document.createElement('p');
        $hint.id = 'gu-hint';
        $hint.textContent = 'Drag to reorder · Captions optional';

        const $thumbs = document.createElement('div');
        $thumbs.id = 'gu-thumbs';

        const $optLabel = document.createElement('label');
        $optLabel.className = 'gu-opt';

        const $wrapCheck = document.createElement('input');
        $wrapCheck.type = 'checkbox';
        $wrapCheck.checked = true;

        $optLabel.appendChild($wrapCheck);
        $optLabel.appendChild(document.createTextNode('Mark as gallery (adds #gallery to each photo)'));

        const $rawLabel = document.createElement('label');
        $rawLabel.className = 'gu-opt';

        const $rawCheck = document.createElement('input');
        $rawCheck.type = 'checkbox';
        $rawCheck.checked = false;

        $rawLabel.appendChild($rawCheck);
        $rawLabel.appendChild(document.createTextNode('Keep original quality (skip Bear\'s optimisation)'));

        const $actions = document.createElement('div');
        $actions.id = 'gu-actions';

        const $btn = document.createElement('button');
        $btn.type = 'button';
        $btn.textContent = 'Upload';
        $btn.disabled = true;

        const $status = document.createElement('span');
        $status.id = 'gu-status';

        $actions.appendChild($btn);
        $actions.appendChild($status);

        $modalBody.appendChild($fileWrap);
        $modalBody.appendChild($hint);
        $modalBody.appendChild($thumbs);
        $modalBody.appendChild($optLabel);
        $modalBody.appendChild($rawLabel);
        $modalBody.appendChild($actions);

        $modal.appendChild($head);
        $modal.appendChild($modalBody);
        $overlay.appendChild($modal);
        document.body.appendChild($overlay);

        $overlay.addEventListener('click', function (e) {
            if (e.target === $overlay && !uploading) closeModal();
        });

        // Keep Tab focus inside the modal while it's open
        $modal.addEventListener('keydown', function (e) {
            if (e.key !== 'Tab') return;
            const focusable = Array.from($modal.querySelectorAll('button, input, [href]'))
                .filter(function (el) { return !el.disabled && el.offsetParent !== null; });
            if (!focusable.length) return;
            const first = focusable[0];
            const last = focusable[focusable.length - 1];
            if (e.shiftKey && document.activeElement === first) {
                e.preventDefault();
                last.focus();
            } else if (!e.shiftKey && document.activeElement === last) {
                e.preventDefault();
                first.focus();
            }
        });

        document.addEventListener('keydown', function (e) {
            if (e.key === 'Escape' && $overlay.style.display === 'flex' && !uploading) closeModal();
        });

        let pendingXhrs = [];
        let uploading = false;

        function openModal() {
            files = [];
            captions = [];
            results = [];
            pendingXhrs = [];
            $thumbs.innerHTML = '';
            $thumbs.classList.remove('gu-uploading');
            $hint.style.display = 'none';
            $status.textContent = '';
            $btn.textContent = 'Upload';
            $btn.disabled = true;
            $fileInput.value = '';
            $fileInput.disabled = false;
            $closeBtn.disabled = false;
            $overlay.style.display = 'flex';
            $fileInput.focus();
        }

        function closeModal() {
            pendingXhrs.forEach(function (xhr) { xhr.abort(); });
            pendingXhrs = [];
            uploading = false;
            $overlay.style.display = 'none';
            $galleryLink.focus();
        }

        // --- State ---

        let files = [];
        let captions = [];
        let results = []; // per file: 'done' | 'error' | undefined
        let dragSrcIdx = null;

        const MAX_SIZE = 10 * 1024 * 1024; // Bear's server limit

        // --- File selection ---

        function fileKey(f) {
            return f.name + '|' + f.size + '|' + f.lastModified;
        }

        // Add to the current selection rather than replacing it, so photos can
        // be picked or dropped in a few at a time. Duplicates are skipped.
        // After a finished upload, a new pick starts a fresh batch.
        function addFiles(list) {
            const finished = results.some(function (r) { return r === 'done'; });
            if (finished) {
                files = [];
                captions = [];
                results = [];
            }
            const seen = files.map(fileKey);
            list.forEach(function (f) {
                if (seen.indexOf(fileKey(f)) === -1) {
                    seen.push(fileKey(f));
                    files.push(f);
                    captions.push('');
                }
            });
            refresh();
        }

        function removeFile(i) {
            files.splice(i, 1);
            captions.splice(i, 1);
            results.splice(i, 1);
            refresh();
        }

        function refresh() {
            $thumbs.classList.remove('gu-uploading');
            renderThumbs();
            results.forEach(function (r, i) { if (r) setThumbState(i, r); });
            $btn.textContent = 'Upload';
            $btn.disabled = files.length === 0;
            $hint.style.display = files.length ? 'block' : 'none';
            $status.textContent = files.length
                ? files.length + ' photo' + (files.length > 1 ? 's' : '') + ' selected'
                : '';
        }

        $fileInput.addEventListener('change', function (e) {
            e.stopImmediatePropagation();
            e.stopPropagation();
            addFiles(Array.from(this.files));
            this.value = '';
        }, true);

        // Drop files straight onto the modal. Stopping propagation also keeps
        // Bear's own window-level drop handler from uploading them behind it.

        function hasFiles(e) {
            return e.dataTransfer && Array.from(e.dataTransfer.types).indexOf('Files') !== -1;
        }

        $overlay.addEventListener('dragover', function (e) {
            if (!hasFiles(e)) return;
            e.preventDefault();
            e.stopPropagation();
            if (!uploading) $modal.classList.add('gu-dropping');
        });

        $overlay.addEventListener('dragleave', function (e) {
            if (e.target === $overlay) $modal.classList.remove('gu-dropping');
        });

        $overlay.addEventListener('drop', function (e) {
            if (!hasFiles(e)) return;
            e.preventDefault();
            e.stopPropagation();
            $modal.classList.remove('gu-dropping');
            if (uploading) return;
            const images = Array.from(e.dataTransfer.files).filter(function (f) {
                return f.type.indexOf('image/') === 0;
            });
            if (images.length) addFiles(images);
        });

        // Rebuild files/captions arrays from current DOM order after a drag,
        // without wiping the DOM - keeps dragend from firing on detached nodes.

        function reindexThumbs() {
            const $all = $thumbs.querySelectorAll('.gu-thumb');
            const newFiles = [];
            const newCaptions = [];
            const newResults = [];
            $all.forEach(function ($wrap, newIdx) {
                const oldIdx = parseInt($wrap.dataset.idx);
                newFiles.push(files[oldIdx]);
                newCaptions.push(captions[oldIdx]);
                newResults.push(results[oldIdx]);
                $wrap.dataset.idx = String(newIdx);
            });
            files = newFiles;
            captions = newCaptions;
            results = newResults;
        }

        // --- Thumbnails with drag-to-reorder and optional captions ---

        function renderThumbs() {
            $thumbs.innerHTML = '';
            files.forEach(function (file, i) {
                const $wrap = document.createElement('div');
                $wrap.className = 'gu-thumb';
                $wrap.dataset.idx = String(i);
                $wrap.draggable = true;

                const $img = document.createElement('img');
                const objectUrl = URL.createObjectURL(file);
                $img.src = objectUrl;
                $img.alt = file.name;
                $img.onload = $img.onerror = function () { URL.revokeObjectURL(objectUrl); };

                const $name = document.createElement('div');
                $name.className = 'gu-thumb-name';
                $name.textContent = file.name;

                const $captionInput = document.createElement('input');
                $captionInput.type = 'text';
                $captionInput.className = 'gu-thumb-caption';
                $captionInput.placeholder = 'Caption';
                $captionInput.value = captions[i] || '';

                // Use dataset.idx rather than closure i - stays correct after reindexing
                $captionInput.addEventListener('input', function () {
                    captions[parseInt($wrap.dataset.idx)] = this.value;
                });
                $captionInput.addEventListener('mousedown', function (e) {
                    e.stopPropagation();
                });
                $captionInput.addEventListener('dragstart', function (e) {
                    e.stopPropagation();
                    e.preventDefault();
                });

                const $remove = document.createElement('button');
                $remove.type = 'button';
                $remove.className = 'gu-remove';
                $remove.textContent = '×';
                $remove.setAttribute('aria-label', 'Remove ' + file.name);
                $remove.addEventListener('click', function () {
                    removeFile(parseInt($wrap.dataset.idx));
                });

                const $badge = document.createElement('div');
                $badge.className = 'gu-badge';

                $wrap.addEventListener('dragstart', function (e) {
                    dragSrcIdx = parseInt(this.dataset.idx);
                    e.dataTransfer.effectAllowed = 'move';
                    const el = this;
                    setTimeout(function () { el.style.opacity = '0.4'; }, 0);
                });

                $wrap.addEventListener('dragend', function () {
                    this.style.opacity = '';
                    clearHighlights();
                });

                $wrap.addEventListener('dragover', function (e) {
                    e.preventDefault();
                    e.dataTransfer.dropEffect = 'move';
                    clearHighlights();
                    this.style.outline = '2px solid currentColor';
                    this.style.outlineOffset = '2px';
                });

                $wrap.addEventListener('dragleave', function () {
                    this.style.outline = '';
                    this.style.outlineOffset = '';
                });

                $wrap.addEventListener('drop', function (e) {
                    e.preventDefault();
                    const dropIdx = parseInt(this.dataset.idx);
                    if (dragSrcIdx !== null && dragSrcIdx !== dropIdx) {
                        const $src = $thumbs.querySelector('[data-idx="' + dragSrcIdx + '"]');
                        if ($src) {
                            if (dropIdx < dragSrcIdx) {
                                $thumbs.insertBefore($src, this);
                            } else {
                                $thumbs.insertBefore($src, this.nextSibling);
                            }
                            reindexThumbs();
                        }
                    }
                    dragSrcIdx = null;
                });

                $wrap.appendChild($img);
                $wrap.appendChild($name);
                $wrap.appendChild($captionInput);
                $wrap.appendChild($badge);
                $wrap.appendChild($remove);
                $thumbs.appendChild($wrap);
            });
        }

        function clearHighlights() {
            $thumbs.querySelectorAll('.gu-thumb').forEach(function (el) {
                el.style.outline = '';
                el.style.outlineOffset = '';
            });
        }

        function setThumbState(i, state, message) {
            const $wrap = $thumbs.querySelector('[data-idx="' + i + '"]');
            if (!$wrap) return;
            const $badge = $wrap.querySelector('.gu-badge');
            const $name = $wrap.querySelector('.gu-thumb-name');
            $wrap.classList.toggle('gu-error', state === 'error');
            if ($name) $name.textContent = state === 'error' && message ? message : files[i].name;
            if (state === 'uploading') {
                $wrap.style.opacity = '0.4';
                if ($badge) $badge.style.display = 'none';
            } else if (state === 'done') {
                $wrap.style.opacity = '1';
                if ($badge) {
                    $badge.style.display = 'flex';
                    $badge.style.background = '#4caf50';
                    $badge.textContent = '✓';
                }
            } else if (state === 'error') {
                $wrap.style.opacity = '1';
                if ($badge) {
                    $badge.style.display = 'flex';
                    $badge.style.background = '#f44336';
                    $badge.textContent = '✕';
                }
            }
        }

        // --- Upload via Bear's own endpoint ---

        function uploadFile(file, raw) {
            return new Promise(function (resolve, reject) {
                const formData = new FormData();
                formData.append('file', file);
                formData.append('csrfmiddlewaretoken', csrfToken());
                if (raw) formData.append('raw', 'true');

                const xhr = new XMLHttpRequest();
                xhr.open('POST', uploadUrl, true);
                xhr.setRequestHeader('X-CSRFToken', csrfToken());

                pendingXhrs.push(xhr);

                xhr.onload = function () {
                    pendingXhrs = pendingXhrs.filter(function (x) { return x !== xhr; });
                    let data = null;
                    try { data = JSON.parse(this.responseText); } catch (e) {}

                    if (this.status === 200 && data) {
                        // Current format: { urls: [...] } - older format: [...]
                        const urls = Array.isArray(data) ? data : data.urls;
                        if (Array.isArray(urls) && urls.length) {
                            resolve(urls);
                            return;
                        }
                    }
                    reject(new Error((data && data.error) || 'HTTP ' + this.status));
                };

                xhr.onerror = function () {
                    pendingXhrs = pendingXhrs.filter(function (x) { return x !== xhr; });
                    reject(new Error('Network error'));
                };

                xhr.onabort = function () {
                    pendingXhrs = pendingXhrs.filter(function (x) { return x !== xhr; });
                    reject(new Error('Aborted'));
                };

                xhr.send(formData);
            });
        }

        // --- Build markdown for one image ---
        // Gallery: the caption becomes the alt text, which the lightbox shows
        // Single photos: a caption wraps the image in figure/figcaption

        // Square brackets in alt text can break the image syntax
        function stripBrackets(str) {
            return str.replace(/[\[\]]/g, '');
        }

        function buildMarkdown(url, imageName, caption, gallery) {
            if (gallery) {
                const alt = stripBrackets(caption || imageName);
                return '![' + alt + '](' + url + '#gallery)';
            }
            if (caption) {
                const safe = escapeHtml(caption);
                return '<figure>\n\n'
                    + '![' + safe + '](' + url + ')\n\n'
                    + '<figcaption>' + safe + '</figcaption>\n'
                    + '</figure>';
            }
            return '![' + stripBrackets(imageName) + '](' + url + ')';
        }

        // --- Upload all (or retry only the failed ones) ---

        $btn.addEventListener('click', async function () {
            if (!files.length || uploading) return;

            const todo = [];
            files.forEach(function (f, i) {
                if (results[i] !== 'done') todo.push(i);
            });
            if (!todo.length) return;

            uploading = true;
            $btn.disabled = true;
            $fileInput.disabled = true;
            $closeBtn.disabled = true;
            $thumbs.classList.add('gu-uploading');

            const pos = Math.min(savedCursorPos, $body.value.length);
            const gallery = $wrapCheck.checked;
            const raw = $rawCheck.checked;
            let done = 0;
            let failed = 0;
            let aborted = false;

            try {
                // UUID-based placeholders guarantee uniqueness regardless of filename
                const placeholders = {};
                todo.forEach(function (i) {
                    placeholders[i] = '![uploading-' + generateId() + ']()\n';
                });

                // Remember the text after the insertion point, so a retry lands
                // after this batch instead of in front of it
                const tailLength = $body.value.length - pos;

                $body.value = $body.value.slice(0, pos)
                    + todo.map(function (i) { return placeholders[i]; }).join('')
                    + $body.value.slice(pos);

                for (let n = 0; n < todo.length; n++) {
                    // Exit cleanly if modal was closed between uploads
                    if (!uploading) { aborted = true; break; }

                    const i = todo[n];
                    const file = files[i];
                    const placeholder = placeholders[i];
                    const imageName = file.name.replace(/\.[^/.]+$/, '');
                    const caption = captions[i] ? captions[i].trim() : '';

                    $status.textContent = 'Uploading ' + (n + 1) + ' of ' + todo.length + '…';
                    setThumbState(i, 'uploading');

                    try {
                        // Skip the round trip for files Bear will reject anyway
                        if (file.size > MAX_SIZE) throw new Error('Over 10 MB');

                        const urls = await uploadFile(file, raw);
                        const replacement = urls.map(function (url) {
                            return buildMarkdown(url, imageName, caption, gallery);
                        }).join('\n');
                        $body.value = $body.value.replace(placeholder, replacement + '\n');
                        results[i] = 'done';
                        done++;
                        setThumbState(i, 'done');
                    } catch (e) {
                        if (e.message === 'Aborted') { aborted = true; break; }
                        // Keep the post clean - the reason shows under the thumbnail
                        $body.value = $body.value.replace(placeholder, '');
                        results[i] = 'error';
                        failed++;
                        setThumbState(i, 'error', e.message);
                    }
                }

                // Remove any placeholders left behind by an abort
                todo.forEach(function (i) {
                    $body.value = $body.value.replace(placeholders[i], '');
                });
                savedCursorPos = $body.value.length - tailLength;
                $body.dispatchEvent(new Event('input', { bubbles: true }));

                if (!aborted) {
                    $status.textContent = failed
                        ? done + ' uploaded, ' + failed + ' failed.'
                        : 'Done. ' + done + ' photo' + (done > 1 ? 's' : '') + ' uploaded.';
                    if (failed === 0) setTimeout(closeModal, 1200);
                }

            } catch (e) {
                $status.textContent = 'Something went wrong. Please try again.';
            } finally {
                uploading = false;
                $fileInput.disabled = false;
                $fileInput.value = '';
                $closeBtn.disabled = false;

                const anyFailed = results.some(function (r) { return r === 'error'; });
                const anyDone = results.some(function (r) { return r === 'done'; });
                $btn.textContent = anyDone && anyFailed ? 'Retry failed' : 'Upload';
                $btn.disabled = anyDone && !anyFailed;

                // Once something is in the post, lock the order so retries stay in sync
                if (!anyDone) $thumbs.classList.remove('gu-uploading');
            }
        });
    });
})();
</script>

Notes

Harry's reaction to the plugin

Harry's reaction when I told him about the plugin. 😍

Happy blogging and shooting!

Want more? Check out the full Bear Blog library.