Jake Vanderwerf
2026-02-10 f9c8317a067139d4b75a94933c156f785780d33b
assets/js/concise/UploadManager.js
@@ -10,6 +10,7 @@
      this.initStores();
      this.initWorker();
      //Maps for DOM references
      this.fields = new Map();
      this.uploads = new Map();
@@ -108,7 +109,7 @@
                  break;
            }
            if (refs.details) {
               if (Object.hasOwn(data.field.config, 'showMeta') && !data.field.config.showMeta) {
               if (Object.hasOwn(data, 'field') && Object.hasOwn(data.field,'config') && Object.hasOwn(data.field.config, 'showMeta') && !data.field.config.showMeta) {
                  refs.details.remove();
               } else {
                  if(Object.hasOwn(data, 'id')) {
@@ -138,7 +139,8 @@
            if (manyRefs.inputs) {
               for (let input of manyRefs.inputs) {
                  window.prefixInput(input, `${data.id??data.uploadId}-`);
                  let wrapper = input.closest('[data-field]')??el;
                  window.prefixInput(input, `${data.id??data.uploadId}-`, wrapper);
               }
            }
         }
@@ -154,7 +156,8 @@
         setup({el, refs, manyRefs, data}) {
            el.dataset.groupId = data.groupId;
            if (refs.selectAll) {
               window.prefixInput(refs.selectAll, `select-all-${data.groupId}`, true);
               let wrapper = refs.selectAll.closest('.field');
               window.prefixInput(refs.selectAll, `select-all-${data.groupId}`, wrapper,true);
            }
            let fields = T.create('groupMetadata', {groupId: data.groupId});
            if (fields) {
@@ -175,7 +178,8 @@
         setup({el, refs, manyRefs, data}) {
            if (refs.inputs) {
               refs.inputs.forEach(input => {
                  window.prefixInput(input, `${data.groupId}-`);
                  let wrapper = input.closest('[data-field]');
                  window.prefixInput(input, `${data.groupId}-`, wrapper);
               });
            }
         }
@@ -294,17 +298,83 @@
      this.queue.subscribe((event, operation) => {
         if ((event === 'operation-status' || event === 'cancel-operation')
            && ['image_upload', 'video_upload', 'document_upload'].includes(operation.type)) {
            const data = operation.data instanceof FormData
               ? this.stores.uploads.formDataToObject(operation.data)
               : operation.data;
            let uploadIds = [];
            let uploads = data['upload_ids'];
            if (!uploads || uploads.length === 0) return;
            if (event === 'cancel-operation') return this.handleOperationCancelled(uploads);
            this.setBulkUpload(uploads, 'status', operation.status).then(()=>{});
            if (operation.data) {
               // Handle FormData
               if (operation.data instanceof FormData) {
                  const dataObj = this.stores.uploads.formDataToObject(operation.data);
                  uploadIds = dataObj['upload_ids'] || [];
               }
               // Handle regular object
               else {
                  uploadIds = operation.data['upload_ids'] || [];
               }
            }
            // If not in data, check result (for completed operations from backend)
            if (uploadIds.length === 0 && operation.result && operation.result.upload_ids) {
               uploadIds = operation.result.upload_ids;
            }
            // Still no upload_ids? Log warning and bail
            if (!uploadIds || uploadIds.length === 0) {
               console.warn('[UploadManager] No upload_ids found for operation:', {
                  id: operation.id,
                  type: operation.type,
                  status: operation.status,
                  hasData: !!operation.data,
                  hasResult: !!operation.result
               });
               return;
            }
            // Handle cancellation
            if (event === 'cancel-operation') {
               return this.handleOperationCancelled(uploadIds);
            }
            // Update upload status based on operation status
            this.setBulkUpload(uploadIds, 'status', operation.status).then(() => {
               // Log for debugging
               console.log(`[UploadManager] Updated ${uploadIds.length} uploads to status: ${operation.status}`);
            });
            // Handle completion
            if (operation.status === 'completed') {
               uploads.forEach(upload => {
                  this.removeUpload(upload).then(()=>{});
               // For group uploads, mark as processed but keep for reference
               if (operation.type === 'process_upload_groups') {
                  uploadIds.forEach(uploadId => {
                     this.setBulkUpload([uploadId], 'serverProcessed', true).then(() => {});
                  });
                  // Log created posts if available
                  if (operation.result && operation.result.created_posts) {
                     console.log('[UploadManager] Created posts:', operation.result.created_posts);
                  }
                  // Remove uploads after a delay to allow UI to update
                  setTimeout(() => {
                     uploadIds.forEach(uploadId => {
                        this.removeUpload(uploadId).then(() => {});
                     });
                  }, 2000);
               }
               // For direct uploads, remove immediately
               else {
                  uploadIds.forEach(uploadId => {
                     this.removeUpload(uploadId).then(() => {});
                  });
               }
            }
            // Handle failures
            if (operation.status === 'failed' || operation.status === 'failed_permanent') {
               console.error('[UploadManager] Operation failed:', {
                  id: operation.id,
                  type: operation.type,
                  uploadIds: uploadIds,
                  error: operation.error_message
               });
            }
         }
@@ -344,7 +414,7 @@
         fields: {
            field: '[data-upload-field]',
            input: 'input[type="file"]',
            dropZone: '.file-upload-container',
            dropZone: '.file-upload-wrapper',
            preview: '.preview-wrap',
            grid: '.item-grid.preview',
            progress: {
@@ -535,6 +605,7 @@
      // Capture values immediately (before debouncer)
      const inputName = input.name;
      if (!inputName) return;
      const inputValue = input.value;
      // Extract the field name from the input name
@@ -656,6 +727,13 @@
         if (details) {
            details.open = false;
         }
         this.notify('groups_uploaded', {
            fieldId: fieldId,
            posts: posts,
            content: field.config.content,
         });
      }
      if (operationId) {
         field.operationId = operationId;
@@ -663,10 +741,15 @@
         await this.setBulkUpload(uploads, 'status', 'uploading');
         await this.setBulkGroup(fieldId, 'operationId', operationId);
         this.fields.set(field.id, field);
         this.notify('sent-to-queue', {
            field: field,
            operation: operationId,
         });
      } else {
         await this.setBulkUpload(uploads, 'status', 'failed');
      }
      this.notify('sent-to-queue', fieldId);
      return operationId;
   }
@@ -683,7 +766,7 @@
         canMerge: mergable,
         sendNow: endpoint === 'uploads/groups',
         headers: {
            'action_nonce': window.auth.getNonce('dash')
            'X-Action-Nonce': window.auth.getNonce('dash')
         },
         append: '_upload'
      }
@@ -707,16 +790,21 @@
      let uploadMap = [];
      let files = [];
      for (const group of groups) {
      const validGroups = groups.filter(group => {
         const groupUploads = this.getGroupUploadsInOrder(group);
         return groupUploads.length > 0 && groupUploads.some(u => this.formatFile(u));
      });
      for (const group of validGroups) {
         const groupElement = this.groups.get(group.id)?.element;
         const fields = this.collectGroupFieldsFromDOM(groupElement, group.id);
         const post = {
            groupId: group.id,
            images: [],
            fields: fields
         };
         // Use helper to get uploads in stored order
         const groupUploads = this.getGroupUploadsInOrder(group);
         for (const upload of groupUploads) {
@@ -738,13 +826,17 @@
               uploadMap.push(upload.id);
            }
         }
         posts.push(post);
         if (post.images.length > 0) {
            posts.push(post);
         }
      }
      // Handle remaining uploads not in any group
      const remaining = uploads.filter(u => !u.group);
      for (const upload of remaining) {
         const post = {
            groupId: window.generateID('group'),
            images: [],
            fields: {}
         };
@@ -759,7 +851,10 @@
            post.images.push(imageData);
            uploadMap.push(upload.id);
         }
         posts.push(post);
         if (post.images.length > 0) {
            posts.push(post);
         }
      }
      return {posts, uploadMap, files};
@@ -989,8 +1084,9 @@
      const processNext = async () => {
         while (queue.length > 0) {
            const file = queue.shift();
            results.push(await this.processImage(file, maxWidth, maxHeight));
            const entry = queue.shift();
            const blob = await this.processImage(entry.file, maxWidth, maxHeight);
            results.push({ uploadId: entry.uploadId, blob: blob });
         }
      };
@@ -1133,19 +1229,21 @@
      const otherEntries = uploadEntries.filter(e => !e.file.type.startsWith('image/'));
      // Process images in batches
      const processedBlobs = await this.processImages(
         imageEntries.map(e => e.file)
      const processedImages = await this.processImages(
         imageEntries.map(e => ({ file: e.file, uploadId: e.uploadId }))
      );
      // Update image uploads with processed blobs
      for (let i = 0; i < imageEntries.length; i++) {
         const { uploadId, upload } = imageEntries[i];
         upload.blob = processedBlobs[i];
         upload.fields.size = processedBlobs[i].size;
         upload.status = 'queued';
         await this.setUpload(uploadId, upload);
         processed++;
         this.updateFieldProgress(fieldId, processed, totalFiles, 'Processing files...');
      for (const { uploadId, blob } of processedImages) {
         const entry = imageEntries.find(e => e.uploadId === uploadId);
         if (entry) {
            entry.upload.blob = blob;
            entry.upload.fields.size = blob.size;
            entry.upload.status = 'queued';
            await this.setUpload(uploadId, entry.upload);
            processed++;
            this.updateFieldProgress(fieldId, processed, totalFiles, 'Processing files...');
         }
      }
      // Handle non-image files (no processing needed)
@@ -1167,6 +1265,13 @@
   *************************************************************/
   async checkRecovery() {
      const pendingUploads = this.stores.uploads.filterByIndex({status: ['local_processing', 'queued', 'uploading']});
      const allGroups = Array.from(this.stores.groups.data.values());
      for (const group of allGroups) {
         const hasUploads = this.stores.uploads.filterByIndex({group: group.id}).length > 0;
         if (!hasUploads) {
            await this.stores.groups.delete(group.id);
         }
      }
      if (pendingUploads.length === 0) return;
      // Group by source page
@@ -1746,6 +1851,7 @@
         avoidImplicitDeselect: true,
         group: { name: fieldId, pull: true, put: true },
         dragClass: 'dragging',
         ignore: '.empty-group',
         onStart: (evt) => {
            // Get the dragged item's ID
@@ -1777,6 +1883,7 @@
      emptyZone.addEventListener('dragover', (e) => {
         e.preventDefault();
         e.stopPropagation();
         e.dataTransfer.dropEffect = 'move';
         emptyZone.classList.add('drag-over');
      });
@@ -1789,6 +1896,7 @@
      emptyZone.addEventListener('drop', async (e) => {
         e.preventDefault();
         e.stopPropagation();
         emptyZone.classList.remove('drag-over');
         // Get selected items from our tracking