[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-includes/js/dist/ -> media-utils.js (source)

   1  this["wp"] = this["wp"] || {}; this["wp"]["mediaUtils"] =
   2  /******/ (function(modules) { // webpackBootstrap
   3  /******/     // The module cache
   4  /******/     var installedModules = {};
   5  /******/
   6  /******/     // The require function
   7  /******/ 	function __webpack_require__(moduleId) {
   8  /******/
   9  /******/         // Check if module is in cache
  10  /******/         if(installedModules[moduleId]) {
  11  /******/             return installedModules[moduleId].exports;
  12  /******/         }
  13  /******/         // Create a new module (and put it into the cache)
  14  /******/         var module = installedModules[moduleId] = {
  15  /******/             i: moduleId,
  16  /******/             l: false,
  17  /******/             exports: {}
  18  /******/         };
  19  /******/
  20  /******/         // Execute the module function
  21  /******/         modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  22  /******/
  23  /******/         // Flag the module as loaded
  24  /******/         module.l = true;
  25  /******/
  26  /******/         // Return the exports of the module
  27  /******/         return module.exports;
  28  /******/     }
  29  /******/
  30  /******/
  31  /******/     // expose the modules object (__webpack_modules__)
  32  /******/     __webpack_require__.m = modules;
  33  /******/
  34  /******/     // expose the module cache
  35  /******/     __webpack_require__.c = installedModules;
  36  /******/
  37  /******/     // define getter function for harmony exports
  38  /******/     __webpack_require__.d = function(exports, name, getter) {
  39  /******/         if(!__webpack_require__.o(exports, name)) {
  40  /******/             Object.defineProperty(exports, name, { enumerable: true, get: getter });
  41  /******/         }
  42  /******/     };
  43  /******/
  44  /******/     // define __esModule on exports
  45  /******/     __webpack_require__.r = function(exports) {
  46  /******/         if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  47  /******/             Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  48  /******/         }
  49  /******/         Object.defineProperty(exports, '__esModule', { value: true });
  50  /******/     };
  51  /******/
  52  /******/     // create a fake namespace object
  53  /******/     // mode & 1: value is a module id, require it
  54  /******/     // mode & 2: merge all properties of value into the ns
  55  /******/     // mode & 4: return value when already ns object
  56  /******/     // mode & 8|1: behave like require
  57  /******/     __webpack_require__.t = function(value, mode) {
  58  /******/         if(mode & 1) value = __webpack_require__(value);
  59  /******/         if(mode & 8) return value;
  60  /******/         if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  61  /******/         var ns = Object.create(null);
  62  /******/         __webpack_require__.r(ns);
  63  /******/         Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  64  /******/         if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  65  /******/         return ns;
  66  /******/     };
  67  /******/
  68  /******/     // getDefaultExport function for compatibility with non-harmony modules
  69  /******/     __webpack_require__.n = function(module) {
  70  /******/         var getter = module && module.__esModule ?
  71  /******/ 			function getDefault() { return module['default']; } :
  72  /******/ 			function getModuleExports() { return module; };
  73  /******/         __webpack_require__.d(getter, 'a', getter);
  74  /******/         return getter;
  75  /******/     };
  76  /******/
  77  /******/     // Object.prototype.hasOwnProperty.call
  78  /******/     __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  79  /******/
  80  /******/     // __webpack_public_path__
  81  /******/     __webpack_require__.p = "";
  82  /******/
  83  /******/
  84  /******/     // Load entry module and return exports
  85  /******/     return __webpack_require__(__webpack_require__.s = "Lb+8");
  86  /******/ })
  87  /************************************************************************/
  88  /******/ ({
  89  
  90  /***/ "GRId":
  91  /***/ (function(module, exports) {
  92  
  93  (function() { module.exports = window["wp"]["element"]; }());
  94  
  95  /***/ }),
  96  
  97  /***/ "Lb+8":
  98  /***/ (function(module, __webpack_exports__, __webpack_require__) {
  99  
 100  "use strict";
 101  // ESM COMPAT FLAG
 102  __webpack_require__.r(__webpack_exports__);
 103  
 104  // EXPORTS
 105  __webpack_require__.d(__webpack_exports__, "MediaUpload", function() { return /* reexport */ media_upload; });
 106  __webpack_require__.d(__webpack_exports__, "uploadMedia", function() { return /* reexport */ uploadMedia; });
 107  
 108  // EXTERNAL MODULE: external "lodash"
 109  var external_lodash_ = __webpack_require__("YLtl");
 110  
 111  // EXTERNAL MODULE: external ["wp","element"]
 112  var external_wp_element_ = __webpack_require__("GRId");
 113  
 114  // EXTERNAL MODULE: external ["wp","i18n"]
 115  var external_wp_i18n_ = __webpack_require__("l3Sj");
 116  
 117  // CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/components/media-upload/index.js
 118  /**
 119   * External dependencies
 120   */
 121  
 122  /**
 123   * WordPress dependencies
 124   */
 125  
 126  
 127  
 128  const {
 129    wp
 130  } = window;
 131  const DEFAULT_EMPTY_GALLERY = [];
 132  /**
 133   * Prepares the Featured Image toolbars and frames.
 134   *
 135   * @return {wp.media.view.MediaFrame.Select} The default media workflow.
 136   */
 137  
 138  const getFeaturedImageMediaFrame = () => {
 139    return wp.media.view.MediaFrame.Select.extend({
 140      /**
 141       * Enables the Set Featured Image Button.
 142       *
 143       * @param {Object} toolbar toolbar for featured image state
 144       * @return {void}
 145       */
 146      featuredImageToolbar(toolbar) {
 147        this.createSelectToolbar(toolbar, {
 148          text: wp.media.view.l10n.setFeaturedImage,
 149          state: this.options.state
 150        });
 151      },
 152  
 153      /**
 154       * Handle the edit state requirements of selected media item.
 155       *
 156       * @return {void}
 157       */
 158      editState() {
 159        const selection = this.state('featured-image').get('selection');
 160        const view = new wp.media.view.EditImage({
 161          model: selection.single(),
 162          controller: this
 163        }).render(); // Set the view to the EditImage frame using the selected image.
 164  
 165        this.content.set(view); // After bringing in the frame, load the actual editor via an ajax call.
 166  
 167        view.loadEditor();
 168      },
 169  
 170      /**
 171       * Create the default states.
 172       *
 173       * @return {void}
 174       */
 175      createStates: function createStates() {
 176        this.on('toolbar:create:featured-image', this.featuredImageToolbar, this);
 177        this.on('content:render:edit-image', this.editState, this);
 178        this.states.add([new wp.media.controller.FeaturedImage(), new wp.media.controller.EditImage({
 179          model: this.options.editImage
 180        })]);
 181      }
 182    });
 183  };
 184  /**
 185   * Prepares the Gallery toolbars and frames.
 186   *
 187   * @return {wp.media.view.MediaFrame.Post} The default media workflow.
 188   */
 189  
 190  
 191  const getGalleryDetailsMediaFrame = () => {
 192    /**
 193     * Custom gallery details frame.
 194     *
 195     * @see https://github.com/xwp/wp-core-media-widgets/blob/905edbccfc2a623b73a93dac803c5335519d7837/wp-admin/js/widgets/media-gallery-widget.js
 196     * @class GalleryDetailsMediaFrame
 197     * @class
 198     */
 199    return wp.media.view.MediaFrame.Post.extend({
 200      /**
 201       * Set up gallery toolbar.
 202       *
 203       * @return {void}
 204       */
 205      galleryToolbar() {
 206        const editing = this.state().get('editing');
 207        this.toolbar.set(new wp.media.view.Toolbar({
 208          controller: this,
 209          items: {
 210            insert: {
 211              style: 'primary',
 212              text: editing ? wp.media.view.l10n.updateGallery : wp.media.view.l10n.insertGallery,
 213              priority: 80,
 214              requires: {
 215                library: true
 216              },
 217  
 218              /**
 219               * @fires wp.media.controller.State#update
 220               */
 221              click() {
 222                const controller = this.controller,
 223                      state = controller.state();
 224                controller.close();
 225                state.trigger('update', state.get('library')); // Restore and reset the default state.
 226  
 227                controller.setState(controller.options.state);
 228                controller.reset();
 229              }
 230  
 231            }
 232          }
 233        }));
 234      },
 235  
 236      /**
 237       * Handle the edit state requirements of selected media item.
 238       *
 239       * @return {void}
 240       */
 241      editState() {
 242        const selection = this.state('gallery').get('selection');
 243        const view = new wp.media.view.EditImage({
 244          model: selection.single(),
 245          controller: this
 246        }).render(); // Set the view to the EditImage frame using the selected image.
 247  
 248        this.content.set(view); // After bringing in the frame, load the actual editor via an ajax call.
 249  
 250        view.loadEditor();
 251      },
 252  
 253      /**
 254       * Create the default states.
 255       *
 256       * @return {void}
 257       */
 258      createStates: function createStates() {
 259        this.on('toolbar:create:main-gallery', this.galleryToolbar, this);
 260        this.on('content:render:edit-image', this.editState, this);
 261        this.states.add([new wp.media.controller.Library({
 262          id: 'gallery',
 263          title: wp.media.view.l10n.createGalleryTitle,
 264          priority: 40,
 265          toolbar: 'main-gallery',
 266          filterable: 'uploaded',
 267          multiple: 'add',
 268          editable: false,
 269          library: wp.media.query(Object(external_lodash_["defaults"])({
 270            type: 'image'
 271          }, this.options.library))
 272        }), new wp.media.controller.EditImage({
 273          model: this.options.editImage
 274        }), new wp.media.controller.GalleryEdit({
 275          library: this.options.selection,
 276          editing: this.options.editing,
 277          menu: 'gallery',
 278          displaySettings: false,
 279          multiple: true
 280        }), new wp.media.controller.GalleryAdd()]);
 281      }
 282    });
 283  }; // the media library image object contains numerous attributes
 284  // we only need this set to display the image in the library
 285  
 286  
 287  const slimImageObject = img => {
 288    const attrSet = ['sizes', 'mime', 'type', 'subtype', 'id', 'url', 'alt', 'link', 'caption'];
 289    return Object(external_lodash_["pick"])(img, attrSet);
 290  };
 291  
 292  const getAttachmentsCollection = ids => {
 293    return wp.media.query({
 294      order: 'ASC',
 295      orderby: 'post__in',
 296      post__in: ids,
 297      posts_per_page: -1,
 298      query: true,
 299      type: 'image'
 300    });
 301  };
 302  
 303  class media_upload_MediaUpload extends external_wp_element_["Component"] {
 304    constructor(_ref) {
 305      let {
 306        allowedTypes,
 307        gallery = false,
 308        unstableFeaturedImageFlow = false,
 309        modalClass,
 310        multiple = false,
 311        title = Object(external_wp_i18n_["__"])('Select or Upload Media')
 312      } = _ref;
 313      super(...arguments);
 314      this.openModal = this.openModal.bind(this);
 315      this.onOpen = this.onOpen.bind(this);
 316      this.onSelect = this.onSelect.bind(this);
 317      this.onUpdate = this.onUpdate.bind(this);
 318      this.onClose = this.onClose.bind(this);
 319  
 320      if (gallery) {
 321        this.buildAndSetGalleryFrame();
 322      } else {
 323        const frameConfig = {
 324          title,
 325          multiple
 326        };
 327  
 328        if (!!allowedTypes) {
 329          frameConfig.library = {
 330            type: allowedTypes
 331          };
 332        }
 333  
 334        this.frame = wp.media(frameConfig);
 335      }
 336  
 337      if (modalClass) {
 338        this.frame.$el.addClass(modalClass);
 339      }
 340  
 341      if (unstableFeaturedImageFlow) {
 342        this.buildAndSetFeatureImageFrame();
 343      }
 344  
 345      this.initializeListeners();
 346    }
 347  
 348    initializeListeners() {
 349      // When an image is selected in the media frame...
 350      this.frame.on('select', this.onSelect);
 351      this.frame.on('update', this.onUpdate);
 352      this.frame.on('open', this.onOpen);
 353      this.frame.on('close', this.onClose);
 354    }
 355    /**
 356     * Sets the Gallery frame and initializes listeners.
 357     *
 358     * @return {void}
 359     */
 360  
 361  
 362    buildAndSetGalleryFrame() {
 363      const {
 364        addToGallery = false,
 365        allowedTypes,
 366        multiple = false,
 367        value = DEFAULT_EMPTY_GALLERY
 368      } = this.props; // If the value did not changed there is no need to rebuild the frame,
 369      // we can continue to use the existing one.
 370  
 371      if (value === this.lastGalleryValue) {
 372        return;
 373      }
 374  
 375      this.lastGalleryValue = value; // If a frame already existed remove it.
 376  
 377      if (this.frame) {
 378        this.frame.remove();
 379      }
 380  
 381      let currentState;
 382  
 383      if (addToGallery) {
 384        currentState = 'gallery-library';
 385      } else {
 386        currentState = value && value.length ? 'gallery-edit' : 'gallery';
 387      }
 388  
 389      if (!this.GalleryDetailsMediaFrame) {
 390        this.GalleryDetailsMediaFrame = getGalleryDetailsMediaFrame();
 391      }
 392  
 393      const attachments = getAttachmentsCollection(value);
 394      const selection = new wp.media.model.Selection(attachments.models, {
 395        props: attachments.props.toJSON(),
 396        multiple
 397      });
 398      this.frame = new this.GalleryDetailsMediaFrame({
 399        mimeType: allowedTypes,
 400        state: currentState,
 401        multiple,
 402        selection,
 403        editing: value && value.length ? true : false
 404      });
 405      wp.media.frame = this.frame;
 406      this.initializeListeners();
 407    }
 408    /**
 409     * Initializes the Media Library requirements for the featured image flow.
 410     *
 411     * @return {void}
 412     */
 413  
 414  
 415    buildAndSetFeatureImageFrame() {
 416      const featuredImageFrame = getFeaturedImageMediaFrame();
 417      const attachments = getAttachmentsCollection(this.props.value);
 418      const selection = new wp.media.model.Selection(attachments.models, {
 419        props: attachments.props.toJSON()
 420      });
 421      this.frame = new featuredImageFrame({
 422        mimeType: this.props.allowedTypes,
 423        state: 'featured-image',
 424        multiple: this.props.multiple,
 425        selection,
 426        editing: this.props.value ? true : false
 427      });
 428      wp.media.frame = this.frame;
 429    }
 430  
 431    componentWillUnmount() {
 432      this.frame.remove();
 433    }
 434  
 435    onUpdate(selections) {
 436      const {
 437        onSelect,
 438        multiple = false
 439      } = this.props;
 440      const state = this.frame.state();
 441      const selectedImages = selections || state.get('selection');
 442  
 443      if (!selectedImages || !selectedImages.models.length) {
 444        return;
 445      }
 446  
 447      if (multiple) {
 448        onSelect(selectedImages.models.map(model => slimImageObject(model.toJSON())));
 449      } else {
 450        onSelect(slimImageObject(selectedImages.models[0].toJSON()));
 451      }
 452    }
 453  
 454    onSelect() {
 455      const {
 456        onSelect,
 457        multiple = false
 458      } = this.props; // Get media attachment details from the frame state
 459  
 460      const attachment = this.frame.state().get('selection').toJSON();
 461      onSelect(multiple ? attachment : attachment[0]);
 462    }
 463  
 464    onOpen() {
 465      var _this$props$value;
 466  
 467      this.updateCollection(); // Handle both this.props.value being either (number[]) multiple ids
 468      // (for galleries) or a (number) singular id (e.g. image block).
 469  
 470      const hasMedia = Array.isArray(this.props.value) ? !!((_this$props$value = this.props.value) !== null && _this$props$value !== void 0 && _this$props$value.length) : !!this.props.value;
 471  
 472      if (!hasMedia) {
 473        return;
 474      }
 475  
 476      const isGallery = this.props.gallery;
 477      const selection = this.frame.state().get('selection');
 478  
 479      if (!isGallery) {
 480        Object(external_lodash_["castArray"])(this.props.value).forEach(id => {
 481          selection.add(wp.media.attachment(id));
 482        });
 483      } // Load the images so they are available in the media modal.
 484  
 485  
 486      const attachments = getAttachmentsCollection(Object(external_lodash_["castArray"])(this.props.value)); // Once attachments are loaded, set the current selection.
 487  
 488      attachments.more().done(function () {
 489        var _attachments$models;
 490  
 491        if (isGallery && attachments !== null && attachments !== void 0 && (_attachments$models = attachments.models) !== null && _attachments$models !== void 0 && _attachments$models.length) {
 492          selection.add(attachments.models);
 493        }
 494      });
 495    }
 496  
 497    onClose() {
 498      const {
 499        onClose
 500      } = this.props;
 501  
 502      if (onClose) {
 503        onClose();
 504      }
 505    }
 506  
 507    updateCollection() {
 508      const frameContent = this.frame.content.get();
 509  
 510      if (frameContent && frameContent.collection) {
 511        const collection = frameContent.collection; // clean all attachments we have in memory.
 512  
 513        collection.toArray().forEach(model => model.trigger('destroy', model)); // reset has more flag, if library had small amount of items all items may have been loaded before.
 514  
 515        collection.mirroring._hasMore = true; // request items
 516  
 517        collection.more();
 518      }
 519    }
 520  
 521    openModal() {
 522      if (this.props.gallery) {
 523        this.buildAndSetGalleryFrame();
 524      }
 525  
 526      this.frame.open();
 527    }
 528  
 529    render() {
 530      return this.props.render({
 531        open: this.openModal
 532      });
 533    }
 534  
 535  }
 536  
 537  /* harmony default export */ var media_upload = (media_upload_MediaUpload);
 538  
 539  // CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/components/index.js
 540  
 541  
 542  // EXTERNAL MODULE: external ["wp","apiFetch"]
 543  var external_wp_apiFetch_ = __webpack_require__("ywyh");
 544  var external_wp_apiFetch_default = /*#__PURE__*/__webpack_require__.n(external_wp_apiFetch_);
 545  
 546  // EXTERNAL MODULE: external ["wp","blob"]
 547  var external_wp_blob_ = __webpack_require__("xTGt");
 548  
 549  // CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/utils/upload-media.js
 550  
 551  
 552  /**
 553   * External dependencies
 554   */
 555  
 556  /**
 557   * WordPress dependencies
 558   */
 559  
 560  
 561  
 562  
 563  /**
 564   * Browsers may use unexpected mime types, and they differ from browser to browser.
 565   * This function computes a flexible array of mime types from the mime type structured provided by the server.
 566   * Converts { jpg|jpeg|jpe: "image/jpeg" } into [ "image/jpeg", "image/jpg", "image/jpeg", "image/jpe" ]
 567   * The computation of this array instead of directly using the object,
 568   * solves the problem in chrome where mp3 files have audio/mp3 as mime type instead of audio/mpeg.
 569   * https://bugs.chromium.org/p/chromium/issues/detail?id=227004
 570   *
 571   * @param {?Object} wpMimeTypesObject Mime type object received from the server.
 572   *                                    Extensions are keys separated by '|' and values are mime types associated with an extension.
 573   *
 574   * @return {?Array} An array of mime types or the parameter passed if it was "falsy".
 575   */
 576  
 577  function getMimeTypesArray(wpMimeTypesObject) {
 578    if (!wpMimeTypesObject) {
 579      return wpMimeTypesObject;
 580    }
 581  
 582    return Object(external_lodash_["flatMap"])(wpMimeTypesObject, (mime, extensionsString) => {
 583      const [type] = mime.split('/');
 584      const extensions = extensionsString.split('|');
 585      return [mime, ...Object(external_lodash_["map"])(extensions, extension => `$type}/$extension}`)];
 586    });
 587  }
 588  /**
 589   *    Media Upload is used by audio, image, gallery, video, and file blocks to
 590   *    handle uploading a media file when a file upload button is activated.
 591   *
 592   *    TODO: future enhancement to add an upload indicator.
 593   *
 594   * @param {Object}   $0                    Parameters object passed to the function.
 595   * @param {?Array}   $0.allowedTypes       Array with the types of media that can be uploaded, if unset all types are allowed.
 596   * @param {?Object}  $0.additionalData     Additional data to include in the request.
 597   * @param {Array}    $0.filesList          List of files.
 598   * @param {?number}  $0.maxUploadFileSize  Maximum upload size in bytes allowed for the site.
 599   * @param {Function} $0.onError            Function called when an error happens.
 600   * @param {Function} $0.onFileChange       Function called each time a file or a temporary representation of the file is available.
 601   * @param {?Object}  $0.wpAllowedMimeTypes List of allowed mime types and file extensions.
 602   */
 603  
 604  async function uploadMedia(_ref) {
 605    let {
 606      allowedTypes,
 607      additionalData = {},
 608      filesList,
 609      maxUploadFileSize,
 610      onError = external_lodash_["noop"],
 611      onFileChange,
 612      wpAllowedMimeTypes = null
 613    } = _ref;
 614    // Cast filesList to array
 615    const files = [...filesList];
 616    const filesSet = [];
 617  
 618    const setAndUpdateFiles = (idx, value) => {
 619      Object(external_wp_blob_["revokeBlobURL"])(Object(external_lodash_["get"])(filesSet, [idx, 'url']));
 620      filesSet[idx] = value;
 621      onFileChange(Object(external_lodash_["compact"])(filesSet));
 622    }; // Allowed type specified by consumer
 623  
 624  
 625    const isAllowedType = fileType => {
 626      if (!allowedTypes) {
 627        return true;
 628      }
 629  
 630      return Object(external_lodash_["some"])(allowedTypes, allowedType => {
 631        // If a complete mimetype is specified verify if it matches exactly the mime type of the file.
 632        if (Object(external_lodash_["includes"])(allowedType, '/')) {
 633          return allowedType === fileType;
 634        } // Otherwise a general mime type is used and we should verify if the file mimetype starts with it.
 635  
 636  
 637        return Object(external_lodash_["startsWith"])(fileType, `$allowedType}/`);
 638      });
 639    }; // Allowed types for the current WP_User
 640  
 641  
 642    const allowedMimeTypesForUser = getMimeTypesArray(wpAllowedMimeTypes);
 643  
 644    const isAllowedMimeTypeForUser = fileType => {
 645      return Object(external_lodash_["includes"])(allowedMimeTypesForUser, fileType);
 646    }; // Build the error message including the filename
 647  
 648  
 649    const triggerError = error => {
 650      error.message = [Object(external_wp_element_["createElement"])("strong", {
 651        key: "filename"
 652      }, error.file.name), ': ', error.message];
 653      onError(error);
 654    };
 655  
 656    const validFiles = [];
 657  
 658    for (const mediaFile of files) {
 659      // Verify if user is allowed to upload this mime type.
 660      // Defer to the server when type not detected.
 661      if (allowedMimeTypesForUser && mediaFile.type && !isAllowedMimeTypeForUser(mediaFile.type)) {
 662        triggerError({
 663          code: 'MIME_TYPE_NOT_ALLOWED_FOR_USER',
 664          message: Object(external_wp_i18n_["__"])('Sorry, you are not allowed to upload this file type.'),
 665          file: mediaFile
 666        });
 667        continue;
 668      } // Check if the block supports this mime type.
 669      // Defer to the server when type not detected.
 670  
 671  
 672      if (mediaFile.type && !isAllowedType(mediaFile.type)) {
 673        triggerError({
 674          code: 'MIME_TYPE_NOT_SUPPORTED',
 675          message: Object(external_wp_i18n_["__"])('Sorry, this file type is not supported here.'),
 676          file: mediaFile
 677        });
 678        continue;
 679      } // verify if file is greater than the maximum file upload size allowed for the site.
 680  
 681  
 682      if (maxUploadFileSize && mediaFile.size > maxUploadFileSize) {
 683        triggerError({
 684          code: 'SIZE_ABOVE_LIMIT',
 685          message: Object(external_wp_i18n_["__"])('This file exceeds the maximum upload size for this site.'),
 686          file: mediaFile
 687        });
 688        continue;
 689      } // Don't allow empty files to be uploaded.
 690  
 691  
 692      if (mediaFile.size <= 0) {
 693        triggerError({
 694          code: 'EMPTY_FILE',
 695          message: Object(external_wp_i18n_["__"])('This file is empty.'),
 696          file: mediaFile
 697        });
 698        continue;
 699      }
 700  
 701      validFiles.push(mediaFile); // Set temporary URL to create placeholder media file, this is replaced
 702      // with final file from media gallery when upload is `done` below
 703  
 704      filesSet.push({
 705        url: Object(external_wp_blob_["createBlobURL"])(mediaFile)
 706      });
 707      onFileChange(filesSet);
 708    }
 709  
 710    for (let idx = 0; idx < validFiles.length; ++idx) {
 711      const mediaFile = validFiles[idx];
 712  
 713      try {
 714        const savedMedia = await createMediaFromFile(mediaFile, additionalData);
 715        const mediaObject = { ...Object(external_lodash_["omit"])(savedMedia, ['alt_text', 'source_url']),
 716          alt: savedMedia.alt_text,
 717          caption: Object(external_lodash_["get"])(savedMedia, ['caption', 'raw'], ''),
 718          title: savedMedia.title.raw,
 719          url: savedMedia.source_url
 720        };
 721        setAndUpdateFiles(idx, mediaObject);
 722      } catch (error) {
 723        // Reset to empty on failure.
 724        setAndUpdateFiles(idx, null);
 725        let message;
 726  
 727        if (Object(external_lodash_["has"])(error, ['message'])) {
 728          message = Object(external_lodash_["get"])(error, ['message']);
 729        } else {
 730          message = Object(external_wp_i18n_["sprintf"])( // translators: %s: file name
 731          Object(external_wp_i18n_["__"])('Error while uploading file %s to the media library.'), mediaFile.name);
 732        }
 733  
 734        onError({
 735          code: 'GENERAL',
 736          message,
 737          file: mediaFile
 738        });
 739      }
 740    }
 741  }
 742  /**
 743   * @param {File}    file           Media File to Save.
 744   * @param {?Object} additionalData Additional data to include in the request.
 745   *
 746   * @return {Promise} Media Object Promise.
 747   */
 748  
 749  function createMediaFromFile(file, additionalData) {
 750    // Create upload payload
 751    const data = new window.FormData();
 752    data.append('file', file, file.name || file.type.replace('/', '.'));
 753    Object(external_lodash_["forEach"])(additionalData, (value, key) => data.append(key, value));
 754    return external_wp_apiFetch_default()({
 755      path: '/wp/v2/media',
 756      body: data,
 757      method: 'POST'
 758    });
 759  }
 760  
 761  // CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/utils/index.js
 762  
 763  
 764  // CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/index.js
 765  
 766  
 767  
 768  
 769  /***/ }),
 770  
 771  /***/ "YLtl":
 772  /***/ (function(module, exports) {
 773  
 774  (function() { module.exports = window["lodash"]; }());
 775  
 776  /***/ }),
 777  
 778  /***/ "l3Sj":
 779  /***/ (function(module, exports) {
 780  
 781  (function() { module.exports = window["wp"]["i18n"]; }());
 782  
 783  /***/ }),
 784  
 785  /***/ "xTGt":
 786  /***/ (function(module, exports) {
 787  
 788  (function() { module.exports = window["wp"]["blob"]; }());
 789  
 790  /***/ }),
 791  
 792  /***/ "ywyh":
 793  /***/ (function(module, exports) {
 794  
 795  (function() { module.exports = window["wp"]["apiFetch"]; }());
 796  
 797  /***/ })
 798  
 799  /******/ });


Generated: Sun Dec 5 01:00:03 2021 Cross-referenced by PHPXref 0.7.1