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