[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-admin/js/ -> media-upload-pipeline.js (source)

   1  /**
   2   * Shared glue for routing classic admin uploads through the client-side
   3   * media pipeline.
   4   *
   5   * The media frames (media-frame-upload.js) and the Add New Media
   6   * File screen (media-new-upload.js) both intercept plupload and hand files
   7   * to @wordpress/upload-media instead. Everything that is not specific to
   8   * one screen's UI lives here: feature detection, configuring the
   9   * upload-media store once, the REST sideload/finalize/delete helpers the
  10   * store needs, queueing a file with success, error, and progress
  11   * callbacks, the error text shown for a failed upload, and the guard that
  12   * warns before leaving while uploads are in flight.
  13   *
  14   * Exposed as wp.mediaUploadPipeline.
  15   *
  16   * @output wp-admin/js/media-upload-pipeline.js
  17   */
  18  
  19  /* global plupload */
  20  
  21  window.wp = window.wp || {};
  22  
  23  ( function ( wp ) {
  24      const __ = wp.i18n.__;
  25      const settings = window._wpMediaUploadPipelineSettings || {};
  26      /** @type {any} */
  27      let uploadStore;
  28      let configured = false;
  29  
  30      // Uploads in flight, keyed by the onSuccess callback queueFile() passes
  31      // to addItems(). The store keeps that callback on the queue item, so it
  32      // identifies the item even after HEIC conversion swaps its file.
  33      const entries = new Map();
  34  
  35      // Files handed back to classic plupload after the pipeline gave up on
  36      // them, so the interceptors let plupload's own handler take them.
  37      const classicFiles = new WeakSet();
  38  
  39      const imageSizeCount = Object.keys( settings.allImageSizes || {} ).length;
  40  
  41      /*
  42       * Image subtypes the pipeline processes. Keep in sync with
  43       * CLIENT_SIDE_SUPPORTED_MIME_TYPES and HEIC_MIME_TYPES in the
  44       * upload-media package.
  45       */
  46      const IMAGE_SUBTYPES = [ 'jpeg', 'png', 'gif', 'webp', 'avif', 'heic', 'heif' ];
  47  
  48      /**
  49       * Recursively appends data to a FormData object, supporting nested objects and arrays.
  50       *
  51       * Mirrors flattenFormData() in the media-utils package.
  52       *
  53       * @param {FormData} formData The form data to append to.
  54       * @param {string}   key      The key to append under.
  55       * @param {*}        data     The value to append.
  56       */
  57  	function flattenFormData( formData, key, data ) {
  58          if (
  59              Array.isArray( data ) ||
  60              ( data !== null &&
  61                  typeof data === 'object' &&
  62                  Object.getPrototypeOf( data ) === Object.prototype )
  63          ) {
  64              Object.keys( data ).forEach( function ( name ) {
  65                  flattenFormData( formData, key + '[' + name + ']', data[ name ] );
  66              } );
  67          } else if ( data !== undefined ) {
  68              formData.append( key, String( data ) );
  69          }
  70      }
  71  
  72      /**
  73       * Sideloads a client-generated thumbnail to an existing attachment.
  74       *
  75       * Reimplements the private sideloadMedia() helper from the media-utils
  76       * package as a thin apiFetch wrapper.
  77       *
  78       * @param {Object}                      args                  The sideload arguments.
  79       * @param {File}                        args.file             The sub-size to sideload.
  80       * @param {number}                      args.attachmentId     The attachment to sideload it to.
  81       * @param {Record<string, unknown>}     [args.additionalData] Extra fields to send with it.
  82       * @param {AbortSignal}                 [args.signal]         Signal aborting the request.
  83       * @param {( subSize: Object ) => void} [args.onSuccess]      Called with the sideloaded sub-size.
  84       * @param {( error: Error ) => void}    [args.onError]        Called when the sideload failed.
  85       */
  86  	function mediaSideload( args ) {
  87          const file = args.file;
  88          const additionalData = args.additionalData || {};
  89  
  90          const data = new FormData();
  91          data.append( 'file', file, file.name || file.type.replace( '/', '.' ) );
  92          Object.keys( additionalData ).forEach( function ( key ) {
  93              flattenFormData( data, key, additionalData[ key ] );
  94          } );
  95  
  96          wp.apiFetch( {
  97              path: '/wp/v2/media/' + args.attachmentId + '/sideload',
  98              body: data,
  99              method: 'POST',
 100              signal: args.signal,
 101          } )
 102              .then( function ( /** @type {Object} */ subSize ) {
 103                  if ( args.onSuccess ) {
 104                      args.onSuccess( subSize );
 105                  }
 106              } )
 107              .catch( function ( /** @type {unknown} */ error ) {
 108                  if ( args.onError ) {
 109                      let normalized = error;
 110                      if ( ! ( error instanceof Error ) ) {
 111                          const rest = /** @type {UploadError} */ ( error );
 112                          normalized = new Error(
 113                              rest && rest.message ? rest.message : String( error )
 114                          );
 115                      }
 116                      args.onError( /** @type {Error} */ ( normalized ) );
 117                  }
 118              } );
 119      }
 120  
 121      /**
 122       * Finalizes an upload once all client-side processing is complete.
 123       *
 124       * Reimplements the private mediaFinalize() helper. The returned
 125       * attachment is load-bearing: it carries the post-finalize (scaled)
 126       * URL used for srcset.
 127       *
 128       * @param {number}   id       The parent attachment ID.
 129       * @param {Object[]} subSizes Accumulated sub-size data.
 130       * @return {Promise<PipelineAttachment|undefined>} Resolves with the transformed attachment.
 131       */
 132      async function mediaFinalize( id, subSizes ) {
 133          /** @type {Object|undefined} */
 134          const response = await wp.apiFetch( {
 135              path: '/wp/v2/media/' + id + '/finalize',
 136              method: 'POST',
 137              data: { sub_sizes: subSizes || [] },
 138          } );
 139          if ( ! response ) {
 140              return undefined;
 141          }
 142          return wp.mediaUtils.transformAttachment( response );
 143      }
 144  
 145      /**
 146       * Deletes an attachment whose client-side processing failed outright.
 147       *
 148       * The queue calls this when every sub-size sideload for an upload fails:
 149       * without it the original file is left behind as an attachment with no
 150       * metadata, visible in the Media Library after the next page load. The
 151       * block editor passes the same setting.
 152       *
 153       * @param {number} id The attachment ID to delete.
 154       * @return {Promise<unknown>} Resolves once the attachment is deleted.
 155       */
 156  	function mediaDelete( id ) {
 157          return wp.apiFetch( {
 158              path: '/wp/v2/media/' + id + '?force=true',
 159              method: 'DELETE',
 160          } );
 161      }
 162  
 163      /**
 164       * Whether every script the pipeline relies on is present.
 165       *
 166       * @return {boolean} True when the dependencies loaded.
 167       */
 168  	function hasDependencies() {
 169          return Boolean(
 170              typeof plupload !== 'undefined' &&
 171                  wp.uploadMedia &&
 172                  wp.mediaUtils &&
 173                  wp.data &&
 174                  wp.element &&
 175                  wp.apiFetch
 176          );
 177      }
 178  
 179      /**
 180       * Whether the browser can run the client-side pipeline on this page.
 181       *
 182       * False when the isolation headers did not land (the page is not
 183       * cross-origin isolated) or the browser lacks the required features,
 184       * in which case classic plupload keeps handling uploads.
 185       *
 186       * @return {boolean} True when client-side processing is available.
 187       */
 188  	function isSupported() {
 189          return Boolean(
 190              hasDependencies() &&
 191                  wp.uploadMedia.detectClientSideMediaSupport &&
 192                  wp.uploadMedia.detectClientSideMediaSupport().supported
 193          );
 194      }
 195  
 196      /**
 197       * Estimates the progress (0-100) of a queue item.
 198       *
 199       * The pipeline never reports a numeric `progress` on its queue items
 200       * (nothing dispatches updateItemProgress), so estimate one from the
 201       * item's operation queue instead: each finished operation (prepare,
 202       * transcode, upload, thumbnails, finalize) advances the bar, and the
 203       * sub-sizes sideloaded so far advance it within thumbnail generation.
 204       * `item.progress` is preferred whenever it is present.
 205       *
 206       * @param {QueueItem}   item  The upload-media queue item.
 207       * @param {UploadEntry} entry The pipeline's bookkeeping for the upload.
 208       * @return {number} Estimated progress.
 209       */
 210  	function estimateProgress( item, entry ) {
 211          if ( typeof item.progress === 'number' ) {
 212              return item.progress;
 213          }
 214  
 215          const remaining = item.operations ? item.operations.length : 0;
 216          let totals = entry.totals;
 217          if ( ! totals ) {
 218              totals = { total: remaining, remaining: remaining };
 219              entry.totals = totals;
 220          }
 221          // Operations are appended after preparation, so grow the total.
 222          if ( remaining > totals.remaining ) {
 223              totals.total += remaining - totals.remaining;
 224          }
 225          totals.remaining = remaining;
 226  
 227          if ( totals.total === 0 ) {
 228              return 0;
 229          }
 230  
 231          const completed = totals.total - remaining;
 232          let fraction = 0;
 233          if (
 234              'THUMBNAIL_GENERATION' === item.currentOperation &&
 235              imageSizeCount > 0
 236          ) {
 237              fraction = Math.min(
 238                  1,
 239                  ( item.subSizes || [] ).length / imageSizeCount
 240              );
 241          }
 242  
 243          return ( ( completed + fraction ) / totals.total ) * 100;
 244      }
 245  
 246      /**
 247       * Tracks queued uploads on every change to the upload-media store.
 248       *
 249       * Reports progress, which holds at 99 until the upload's success
 250       * callback has run so nothing looks finished before the screen has
 251       * synced the result, and notes the attachment once the original is
 252       * uploaded. Sub-size children are skipped; only top-level items matter.
 253       *
 254       * The store can also remove an item without calling either of its
 255       * callbacks (it only calls onSuccess when the item has an attachment),
 256       * so an upload that was seen in the store and is gone fails here
 257       * instead of staying in flight, and holding the unload guard, for good.
 258       */
 259  	function onStoreChange() {
 260          if ( entries.size === 0 ) {
 261              return;
 262          }
 263  
 264          const present = new Set();
 265          const items = wp.data.select( uploadStore ).getItems();
 266          items.forEach( function ( /** @type {QueueItem} */ item ) {
 267              if ( item.parentId ) {
 268                  return;
 269              }
 270  
 271              const entry = entries.get( item.onSuccess );
 272              if ( ! entry ) {
 273                  return;
 274              }
 275  
 276              present.add( item.onSuccess );
 277              entry.seen = true;
 278              if ( item.attachment && item.attachment.id ) {
 279                  entry.attachmentId = item.attachment.id;
 280              }
 281  
 282              if ( ! entry.onProgress ) {
 283                  return;
 284              }
 285  
 286              const percent = Math.min(
 287                  99,
 288                  Math.round( estimateProgress( item, entry ) )
 289              );
 290              if ( percent !== entry.lastPercent ) {
 291                  entry.lastPercent = percent;
 292                  entry.onProgress( percent );
 293              }
 294          } );
 295  
 296          entries.forEach( function ( entry, key ) {
 297              if ( entry.seen && ! present.has( key ) ) {
 298                  entry.fail( {
 299                      message: __( 'An error occurred while uploading the file.' ),
 300                  } );
 301              }
 302          } );
 303      }
 304  
 305      /**
 306       * Whether something else already configured the store on this page.
 307       *
 308       * The block editor renders its own MediaUploadProvider into the same
 309       * store. Neither `mediaSideload` nor `mediaFinalize` has a default, so
 310       * their presence proves a provider's settings landed, whichever one
 311       * rendered them.
 312       *
 313       * @return {boolean} True when the store carries a provider's settings.
 314       */
 315  	function isStoreConfigured() {
 316          const storeSettings = wp.data.select( uploadStore ).getSettings();
 317          return Boolean(
 318              storeSettings &&
 319                  storeSettings.mediaSideload &&
 320                  storeSettings.mediaFinalize
 321          );
 322      }
 323  
 324      /**
 325       * Configures the upload-media store for this page, once.
 326       *
 327       * Rendering the provider with useSubRegistry: false wires the settings
 328       * into the store that wp.data.dispatch/select address. The block editor
 329       * does the same for its own uploads, so on its screens no second
 330       * provider is rendered: whichever committed last would win, and this
 331       * one could replace the editor's mediaUpload. Uploads wait for the
 332       * editor's settings instead (see isReady()).
 333       *
 334       * @return {boolean} True when the pipeline is configured and usable.
 335       */
 336  	function configure() {
 337          if ( configured ) {
 338              return true;
 339          }
 340  
 341          if ( ! isSupported() ) {
 342              return false;
 343          }
 344  
 345          configured = true;
 346          uploadStore = wp.uploadMedia.store;
 347  
 348          if ( settings.isBlockEditor || isStoreConfigured() ) {
 349              wp.data.subscribe( onStoreChange, uploadStore );
 350              addUnloadGuard();
 351              return true;
 352          }
 353  
 354          /*
 355           * The media-utils package branches on this flag: without it
 356           * uploadMedia() creates and revokes a throwaway blob URL per file
 357           * and emits an extra onFileChange carrying it. The block editor
 358           * sets the same flag before configuring the same pipeline.
 359           */
 360          window.__clientSideMediaProcessing = true;
 361  
 362          wp.element
 363              .createRoot( document.createElement( 'div' ) )
 364              .render(
 365                  wp.element.createElement( wp.uploadMedia.MediaUploadProvider, {
 366                      settings: {
 367                          mediaUpload: wp.mediaUtils.uploadMedia,
 368                          mediaSideload: mediaSideload,
 369                          mediaFinalize: mediaFinalize,
 370                          mediaDelete: mediaDelete,
 371                          maxUploadFileSize: settings.maxUploadFileSize,
 372                          allowedMimeTypes: settings.allowedMimeTypes,
 373                          allImageSizes: settings.allImageSizes,
 374                          bigImageSizeThreshold: settings.bigImageSizeThreshold,
 375                          imageStripMeta: settings.imageStripMeta,
 376                          imageMaxBitDepth: settings.imageMaxBitDepth,
 377                          generateAnimatedImageSubsizes:
 378                              settings.generateAnimatedImageSubsizes,
 379                      },
 380                      useSubRegistry: false,
 381                  } )
 382              );
 383  
 384          // Only the upload-media store can change what this listener reads.
 385          wp.data.subscribe( onStoreChange, uploadStore );
 386          addUnloadGuard();
 387  
 388          return true;
 389      }
 390  
 391      /**
 392       * Warns before leaving while uploads are in flight.
 393       *
 394       * Thumbnails that have not been sideloaded yet are lost and the
 395       * attachment is left unfinalized, unlike classic uploads that complete
 396       * server-side once the bytes arrive.
 397       */
 398  	function addUnloadGuard() {
 399          window.addEventListener( 'beforeunload', function ( event ) {
 400              if ( entries.size > 0 ) {
 401                  event.preventDefault();
 402              }
 403          } );
 404      }
 405  
 406      /**
 407       * Whether the store has received a provider's settings.
 408       *
 409       * A provider renders asynchronously, so a file added before its
 410       * settings land must be left to classic plupload - a degradation,
 411       * never data loss. The store's default state already carries a no-op
 412       * `mediaUpload`, so only settings a provider alone supplies prove the
 413       * real ones have landed: a file queued before that would be handed to
 414       * the no-op and never upload. On block editor screens only the
 415       * editor's provider supplies them.
 416       *
 417       * @return {boolean} True when the store is ready to accept files.
 418       */
 419  	function isReady() {
 420          return configured && isStoreConfigured();
 421      }
 422  
 423      /**
 424       * Gets the image subtype of a file name the pipeline can process.
 425       *
 426       * @param {string} fileName A file name.
 427       * @return {string|null} The subtype, eg. `jpeg` for `photo.jpg`, or
 428       *                       null when the pipeline does not process it.
 429       */
 430  	function getImageSubtype( fileName ) {
 431          const match = /\.([a-z0-9]+)$/i.exec( fileName || '' );
 432          if ( ! match ) {
 433              return null;
 434          }
 435          // `jpg` is not a valid subtype, so map it to `jpeg`.
 436          const extension = match[ 1 ].toLowerCase();
 437          const subtype = 'jpg' === extension ? 'jpeg' : extension;
 438          return IMAGE_SUBTYPES.includes( subtype ) ? subtype : null;
 439      }
 440  
 441      /**
 442       * Whether a file is an image the client-side pipeline can process.
 443       *
 444       * A file whose type is missing from the allowed types the page was
 445       * rendered with is left to the server, which can allow it for a single
 446       * request (see partitionBatch()). A HEIC file is also matched by its
 447       * extension, since browsers on platforms without a HEIC codec may give
 448       * it no type at all.
 449       *
 450       * @param {plupload.File} file A file added to the plupload queue.
 451       * @return {boolean} True when the pipeline should take the file.
 452       */
 453  	function isPipelineFile( file ) {
 454          const type = ( file.type || '' ).toLowerCase();
 455          const allowedTypes = settings.allowedMimeTypes;
 456          if (
 457              type &&
 458              allowedTypes &&
 459              ! Object.values( allowedTypes ).includes( type )
 460          ) {
 461              return false;
 462          }
 463          if (
 464              type.startsWith( 'image/' ) &&
 465              IMAGE_SUBTYPES.includes( type.slice( 6 ) )
 466          ) {
 467              return true;
 468          }
 469          const subtype = getImageSubtype( file.name );
 470          return 'heic' === subtype || 'heif' === subtype;
 471      }
 472  
 473      /**
 474       * Splits a batch of plupload files between the pipeline and classic
 475       * plupload.
 476       *
 477       * Only images the pipeline can process are taken (see isPipelineFile()).
 478       * Everything else, such as audio, video, PDF, SVG or JSON, stays
 479       * classic: the pipeline would do nothing for it but upload it, and
 480       * would check its type against the allowed types the page was rendered
 481       * with instead of the uploader's own filters, which a plugin can extend
 482       * for a single frame. For the same reason an image of a type the page
 483       * was not rendered with stays classic, so the server decides. Audio
 484       * also keeps the title and description that media_handle_upload()
 485       * derives from its ID3 tags, which the REST endpoint does not. JPEG
 486       * and PNG images stay classic too while plupload's own client-side
 487       * resize is enabled (the "Scale images" setting, or a `resize` passed
 488       * through `plupload_init`): plupload scales those down before
 489       * uploading them, the pipeline would not.
 490       *
 491       * The whole batch stays classic when a file cannot be re-queued on
 492       * plupload or is already plupload's: plupload returns no native File
 493       * for sources it cannot expose as one (the html4 runtime, say), and a
 494       * file the pipeline handed back (see handOffToClassic()) is plupload's
 495       * to upload.
 496       *
 497       * @param {plupload.Uploader} up    The plupload uploader the files were added to.
 498       * @param {plupload.File[]}   files Files added to the plupload queue.
 499       * @return {{ pipeline: plupload.File[], classic: plupload.File[] }|null} The split,
 500       *         or null when the whole batch stays on the classic path.
 501       */
 502  	function partitionBatch( up, files ) {
 503          const resize = up.settings && up.settings.resize;
 504          const isResizing = Boolean( resize && resize.enabled );
 505          /** @type {{ pipeline: plupload.File[], classic: plupload.File[] }} */
 506          const batch = { pipeline: [], classic: [] };
 507  
 508          for ( const file of files ) {
 509              if ( plupload.FAILED === file.status ) {
 510                  continue;
 511              }
 512              const nativeFile = file.getNative && file.getNative();
 513              if ( ! nativeFile || classicFiles.has( nativeFile ) ) {
 514                  return null;
 515              }
 516              const type = file.type || '';
 517              if (
 518                  ! isPipelineFile( file ) ||
 519                  ( isResizing && /^image\/(?:jpeg|png)$/i.test( type ) )
 520              ) {
 521                  batch.classic.push( file );
 522              } else {
 523                  batch.pipeline.push( file );
 524              }
 525          }
 526  
 527          return batch.pipeline.length ? batch : null;
 528      }
 529  
 530      /**
 531       * Hands a file to classic plupload, whose own FilesAdded handler queues
 532       * and starts the upload.
 533       *
 534       * @param {plupload.Uploader} up         The plupload uploader.
 535       * @param {File}              nativeFile The file to upload.
 536       */
 537  	function addClassicFile( up, nativeFile ) {
 538          classicFiles.add( nativeFile );
 539          up.addFile( nativeFile );
 540      }
 541  
 542      /**
 543       * Re-queues the classic share of a batch on plupload.
 544       *
 545       * Suppressing plupload's built-in FilesAdded handler covers the whole
 546       * batch, so the files partitionBatch() left to plupload are removed and
 547       * added back on their own.
 548       *
 549       * @param {plupload.Uploader} up    The plupload uploader.
 550       * @param {plupload.File[]}   files The files to upload classically.
 551       */
 552  	function handOffBatchToClassic( up, files ) {
 553          files.forEach( function ( file ) {
 554              // partitionBatch() already established that every file has one.
 555              const nativeFile = /** @type {File} */ ( file.getNative() );
 556              up.removeFile( file );
 557              addClassicFile( up, nativeFile );
 558          } );
 559      }
 560  
 561      /**
 562       * Re-queues a file on classic plupload when the server can do what the
 563       * browser could not.
 564       *
 565       * The pipeline converts HEIC in the browser and fails outright when the
 566       * platform has no HEIC decoder (Linux, and Windows without the HEVC
 567       * extension), whereas the classic upload lets the server convert it.
 568       * When the server's image editor supports HEIC - plupload carries no
 569       * `heic_upload_error` setting then - the file goes back to plupload,
 570       * whose own FilesAdded handler queues and starts the classic upload.
 571       * Nothing else can convert it, so any other failure stands.
 572       *
 573       * @param {plupload.Uploader} up         The plupload uploader the file came from.
 574       * @param {UploadError}       error      Why the pipeline gave up on it.
 575       * @param {File}              nativeFile The file the pipeline was given.
 576       * @return {boolean} True when the file was handed to classic plupload.
 577       */
 578  	function handOffToClassic( up, error, nativeFile ) {
 579          const errorCodes = wp.uploadMedia.ErrorCode || {};
 580          if (
 581              ! error ||
 582              ! errorCodes.HEIC_DECODE_ERROR ||
 583              error.code !== errorCodes.HEIC_DECODE_ERROR ||
 584              ! up ||
 585              typeof up.addFile !== 'function' ||
 586              ( up.settings && up.settings.heic_upload_error )
 587          ) {
 588              return false;
 589          }
 590  
 591          addClassicFile( up, nativeFile );
 592          return true;
 593      }
 594  
 595      /**
 596       * Builds the extra fields to send with an upload from plupload's
 597       * multipart params.
 598       *
 599       * Anything a plugin added through the `plupload_default_params` filter
 600       * or wp.Uploader.param() reached the classic upload as $_POST fields,
 601       * so it is forwarded to the REST request the same way. The classic
 602       * transport's own fields are dropped: `action` and `_wpnonce` belong to
 603       * async-upload.php, and `post_id` is spelled `post` by the REST API and
 604       * passed separately after the screen has validated it.
 605       *
 606       * @param {Record<string, string>} params Plupload's multipart_params.
 607       * @param {number}                 postId The validated post to attach the upload to, or 0.
 608       * @return {Record<string, unknown>} Additional data for the upload.
 609       */
 610  	function additionalDataFromParams( params, postId ) {
 611          /** @type {Record<string, unknown>} */
 612          const additionalData = {};
 613          Object.keys( params || {} ).forEach( function ( key ) {
 614              if ( 'action' === key || '_wpnonce' === key || 'post_id' === key ) {
 615                  return;
 616              }
 617              additionalData[ key ] = params[ key ];
 618          } );
 619          if ( postId ) {
 620              additionalData.post = postId;
 621          }
 622          return additionalData;
 623      }
 624  
 625      /**
 626       * Queues a file for client-side processing and upload.
 627       *
 628       * @param {File}                    nativeFile     The file to upload.
 629       * @param {Record<string, unknown>} additionalData Extra fields to send with the attachment.
 630       * @param {QueueFileCallbacks}      [callbacks]    Lifecycle callbacks.
 631       */
 632  	function queueFile( nativeFile, additionalData, callbacks = {} ) {
 633          /**
 634           * Handles successful upload.
 635           *
 636           * @param {PipelineAttachment[]} attachments The uploaded attachments.
 637           */
 638  		function onSuccess( attachments ) {
 639              entries.delete( onSuccess );
 640              if ( callbacks.onSuccess ) {
 641                  callbacks.onSuccess( attachments[ 0 ] );
 642              }
 643          }
 644  
 645          /** @type {UploadEntry} */
 646          const entry = {
 647              onProgress: callbacks.onProgress,
 648              lastPercent: -1,
 649              totals: null,
 650              seen: false,
 651              attachmentId: 0,
 652              fail: function ( error ) {
 653                  if ( ! entries.delete( onSuccess ) ) {
 654                      return;
 655                  }
 656                  // The original already reached the server (finalize failed,
 657                  // say), so delete it: otherwise a retry leaves a duplicate
 658                  // next to an attachment whose metadata was never finalized.
 659                  // The store only deletes it itself when every sub-size failed.
 660                  if ( entry.attachmentId ) {
 661                      mediaDelete( entry.attachmentId ).catch( function () {} );
 662                  }
 663                  if ( callbacks.onError ) {
 664                      callbacks.onError( error );
 665                  }
 666              },
 667          };
 668          entries.set( onSuccess, entry );
 669  
 670          wp.data.dispatch( uploadStore ).addItems( {
 671              files: [ nativeFile ],
 672              additionalData: additionalData || {},
 673              onSuccess: onSuccess,
 674              onError: function ( /** @type {UploadError|string} */ error ) {
 675                  // Also reached for files addItems() rejects before queueing.
 676                  // The block editor's mediaUpload() setting, which the store
 677                  // uses once the editor has configured it, reports transport
 678                  // failures as a bare message string.
 679                  entry.fail(
 680                      typeof error === 'string' ? { message: error } : error
 681                  );
 682              },
 683          } );
 684      }
 685  
 686      /**
 687       * Routes a batch of files added to a plupload uploader through the
 688       * pipeline.
 689       *
 690       * Returns undefined (not false) when the pipeline cannot take the batch
 691       * so plupload's built-in FilesAdded handler runs and uploads it
 692       * server-side - a degradation, never data loss. Otherwise queues the
 693       * files the pipeline can take, re-queues the rest on plupload, and
 694       * returns false to suppress the built-in handler, which would otherwise
 695       * start a classic upload of every file.
 696       *
 697       * The classic flow posts plupload's multipart params to
 698       * async-upload.php, so they are forwarded to the REST request for
 699       * plugins reading $_POST, with `post_id` replaced by `options.postId`.
 700       *
 701       * @param {plupload.Uploader} up      The plupload uploader the files were added to.
 702       * @param {plupload.File[]}   files   Files added to the queue.
 703       * @param {RouteBatchOptions} options The screen's hooks.
 704       * @return {boolean|undefined} False to suppress the built-in handler.
 705       */
 706  	function routeBatch( up, files, options ) {
 707          if ( ! isReady() ) {
 708              return;
 709          }
 710  
 711          const batch = partitionBatch( up, files );
 712          if ( ! batch ) {
 713              return;
 714          }
 715  
 716          const params = ( up.settings && up.settings.multipart_params ) || {};
 717          const additionalData = additionalDataFromParams(
 718              params,
 719              options.postId
 720          );
 721  
 722          if ( options.onStart ) {
 723              options.onStart( batch.pipeline );
 724          }
 725  
 726          batch.pipeline.forEach( function ( /** @type {plupload.File} */ file ) {
 727              // partitionBatch() already established that every file has one.
 728              const nativeFile = /** @type {File} */ ( file.getNative() );
 729              const callbacks = options.onQueue( file, nativeFile );
 730  
 731              // Remove the file from plupload so it is not uploaded twice.
 732              up.removeFile( file );
 733  
 734              queueFile( nativeFile, additionalData, {
 735                  onSuccess: callbacks.onSuccess,
 736                  onProgress: callbacks.onProgress,
 737                  onError: function ( /** @type {UploadError} */ error ) {
 738                      // When the server can convert what the browser could
 739                      // not, plupload takes the file from here and shows its
 740                      // own progress.
 741                      if ( handOffToClassic( up, error, nativeFile ) ) {
 742                          callbacks.onHandOff();
 743                          return;
 744                      }
 745                      callbacks.onError( error );
 746                  },
 747              } );
 748          } );
 749  
 750          handOffBatchToClassic( up, batch.classic );
 751  
 752          up.refresh();
 753  
 754          return false;
 755      }
 756  
 757      /**
 758       * Builds the display text for a failed upload.
 759       *
 760       * wp.uploadMedia.getErrorMessage() maps an error *code* and a file name
 761       * to a { title, description, action } object, so it can neither be handed
 762       * the Error itself nor used as a string. Only codes it actually maps are
 763       * worth using: its fallback (and the GENERAL code) says nothing the
 764       * error's own message does not, and preferring the message there keeps a
 765       * server-supplied reason instead of replacing it with "Please try again."
 766       *
 767       * @param {UploadError} error    The upload error.
 768       * @param {string}      fileName Name of the file that failed to upload.
 769       * @return {string} A human-readable message.
 770       */
 771  	function getErrorText( error, fileName ) {
 772          const errorCodes = wp.uploadMedia.ErrorCode || {};
 773          const code = error && error.code;
 774          let details;
 775  
 776          if (
 777              code &&
 778              code !== errorCodes.GENERAL &&
 779              Object.prototype.hasOwnProperty.call( errorCodes, code ) &&
 780              wp.uploadMedia.getErrorMessage
 781          ) {
 782              details = wp.uploadMedia.getErrorMessage( code, fileName );
 783  
 784              if ( details && details.description ) {
 785                  return details.action ?
 786                      details.description + ' ' + details.action :
 787                      details.description;
 788              }
 789          }
 790  
 791          return (
 792              ( error && error.message ) ||
 793              __( 'An error occurred while uploading the file.' )
 794          );
 795      }
 796  
 797      wp.mediaUploadPipeline = {
 798          isSupported: isSupported,
 799          configure: configure,
 800          isReady: isReady,
 801          routeBatch: routeBatch,
 802          getErrorText: getErrorText,
 803          getImageSubtype: getImageSubtype,
 804      };
 805  } )( window.wp );


Generated : Sun Nov 29 08:20:01 2026 Cross-referenced by PHPXref