Sin descripción

media-utils.js 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  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. /***/ "GRId":
  90. /***/ (function(module, exports) {
  91. (function() { module.exports = window["wp"]["element"]; }());
  92. /***/ }),
  93. /***/ "Lb+8":
  94. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  95. "use strict";
  96. // ESM COMPAT FLAG
  97. __webpack_require__.r(__webpack_exports__);
  98. // EXPORTS
  99. __webpack_require__.d(__webpack_exports__, "MediaUpload", function() { return /* reexport */ media_upload; });
  100. __webpack_require__.d(__webpack_exports__, "uploadMedia", function() { return /* reexport */ uploadMedia; });
  101. // EXTERNAL MODULE: external "lodash"
  102. var external_lodash_ = __webpack_require__("YLtl");
  103. // EXTERNAL MODULE: external ["wp","element"]
  104. var external_wp_element_ = __webpack_require__("GRId");
  105. // EXTERNAL MODULE: external ["wp","i18n"]
  106. var external_wp_i18n_ = __webpack_require__("l3Sj");
  107. // CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/components/media-upload/index.js
  108. /**
  109. * External dependencies
  110. */
  111. /**
  112. * WordPress dependencies
  113. */
  114. const {
  115. wp
  116. } = window;
  117. const DEFAULT_EMPTY_GALLERY = [];
  118. /**
  119. * Prepares the Featured Image toolbars and frames.
  120. *
  121. * @return {wp.media.view.MediaFrame.Select} The default media workflow.
  122. */
  123. const getFeaturedImageMediaFrame = () => {
  124. return wp.media.view.MediaFrame.Select.extend({
  125. /**
  126. * Enables the Set Featured Image Button.
  127. *
  128. * @param {Object} toolbar toolbar for featured image state
  129. * @return {void}
  130. */
  131. featuredImageToolbar(toolbar) {
  132. this.createSelectToolbar(toolbar, {
  133. text: wp.media.view.l10n.setFeaturedImage,
  134. state: this.options.state
  135. });
  136. },
  137. /**
  138. * Handle the edit state requirements of selected media item.
  139. *
  140. * @return {void}
  141. */
  142. editState() {
  143. const selection = this.state('featured-image').get('selection');
  144. const view = new wp.media.view.EditImage({
  145. model: selection.single(),
  146. controller: this
  147. }).render(); // Set the view to the EditImage frame using the selected image.
  148. this.content.set(view); // After bringing in the frame, load the actual editor via an ajax call.
  149. view.loadEditor();
  150. },
  151. /**
  152. * Create the default states.
  153. *
  154. * @return {void}
  155. */
  156. createStates: function createStates() {
  157. this.on('toolbar:create:featured-image', this.featuredImageToolbar, this);
  158. this.on('content:render:edit-image', this.editState, this);
  159. this.states.add([new wp.media.controller.FeaturedImage(), new wp.media.controller.EditImage({
  160. model: this.options.editImage
  161. })]);
  162. }
  163. });
  164. };
  165. /**
  166. * Prepares the Gallery toolbars and frames.
  167. *
  168. * @return {wp.media.view.MediaFrame.Post} The default media workflow.
  169. */
  170. const getGalleryDetailsMediaFrame = () => {
  171. /**
  172. * Custom gallery details frame.
  173. *
  174. * @see https://github.com/xwp/wp-core-media-widgets/blob/905edbccfc2a623b73a93dac803c5335519d7837/wp-admin/js/widgets/media-gallery-widget.js
  175. * @class GalleryDetailsMediaFrame
  176. * @class
  177. */
  178. return wp.media.view.MediaFrame.Post.extend({
  179. /**
  180. * Set up gallery toolbar.
  181. *
  182. * @return {void}
  183. */
  184. galleryToolbar() {
  185. const editing = this.state().get('editing');
  186. this.toolbar.set(new wp.media.view.Toolbar({
  187. controller: this,
  188. items: {
  189. insert: {
  190. style: 'primary',
  191. text: editing ? wp.media.view.l10n.updateGallery : wp.media.view.l10n.insertGallery,
  192. priority: 80,
  193. requires: {
  194. library: true
  195. },
  196. /**
  197. * @fires wp.media.controller.State#update
  198. */
  199. click() {
  200. const controller = this.controller,
  201. state = controller.state();
  202. controller.close();
  203. state.trigger('update', state.get('library')); // Restore and reset the default state.
  204. controller.setState(controller.options.state);
  205. controller.reset();
  206. }
  207. }
  208. }
  209. }));
  210. },
  211. /**
  212. * Handle the edit state requirements of selected media item.
  213. *
  214. * @return {void}
  215. */
  216. editState() {
  217. const selection = this.state('gallery').get('selection');
  218. const view = new wp.media.view.EditImage({
  219. model: selection.single(),
  220. controller: this
  221. }).render(); // Set the view to the EditImage frame using the selected image.
  222. this.content.set(view); // After bringing in the frame, load the actual editor via an ajax call.
  223. view.loadEditor();
  224. },
  225. /**
  226. * Create the default states.
  227. *
  228. * @return {void}
  229. */
  230. createStates: function createStates() {
  231. this.on('toolbar:create:main-gallery', this.galleryToolbar, this);
  232. this.on('content:render:edit-image', this.editState, this);
  233. this.states.add([new wp.media.controller.Library({
  234. id: 'gallery',
  235. title: wp.media.view.l10n.createGalleryTitle,
  236. priority: 40,
  237. toolbar: 'main-gallery',
  238. filterable: 'uploaded',
  239. multiple: 'add',
  240. editable: false,
  241. library: wp.media.query(Object(external_lodash_["defaults"])({
  242. type: 'image'
  243. }, this.options.library))
  244. }), new wp.media.controller.EditImage({
  245. model: this.options.editImage
  246. }), new wp.media.controller.GalleryEdit({
  247. library: this.options.selection,
  248. editing: this.options.editing,
  249. menu: 'gallery',
  250. displaySettings: false,
  251. multiple: true
  252. }), new wp.media.controller.GalleryAdd()]);
  253. }
  254. });
  255. }; // the media library image object contains numerous attributes
  256. // we only need this set to display the image in the library
  257. const slimImageObject = img => {
  258. const attrSet = ['sizes', 'mime', 'type', 'subtype', 'id', 'url', 'alt', 'link', 'caption'];
  259. return Object(external_lodash_["pick"])(img, attrSet);
  260. };
  261. const getAttachmentsCollection = ids => {
  262. return wp.media.query({
  263. order: 'ASC',
  264. orderby: 'post__in',
  265. post__in: ids,
  266. posts_per_page: -1,
  267. query: true,
  268. type: 'image'
  269. });
  270. };
  271. class media_upload_MediaUpload extends external_wp_element_["Component"] {
  272. constructor({
  273. allowedTypes,
  274. gallery = false,
  275. unstableFeaturedImageFlow = false,
  276. modalClass,
  277. multiple = false,
  278. title = Object(external_wp_i18n_["__"])('Select or Upload Media')
  279. }) {
  280. super(...arguments);
  281. this.openModal = this.openModal.bind(this);
  282. this.onOpen = this.onOpen.bind(this);
  283. this.onSelect = this.onSelect.bind(this);
  284. this.onUpdate = this.onUpdate.bind(this);
  285. this.onClose = this.onClose.bind(this);
  286. if (gallery) {
  287. this.buildAndSetGalleryFrame();
  288. } else {
  289. const frameConfig = {
  290. title,
  291. multiple
  292. };
  293. if (!!allowedTypes) {
  294. frameConfig.library = {
  295. type: allowedTypes
  296. };
  297. }
  298. this.frame = wp.media(frameConfig);
  299. }
  300. if (modalClass) {
  301. this.frame.$el.addClass(modalClass);
  302. }
  303. if (unstableFeaturedImageFlow) {
  304. this.buildAndSetFeatureImageFrame();
  305. }
  306. this.initializeListeners();
  307. }
  308. initializeListeners() {
  309. // When an image is selected in the media frame...
  310. this.frame.on('select', this.onSelect);
  311. this.frame.on('update', this.onUpdate);
  312. this.frame.on('open', this.onOpen);
  313. this.frame.on('close', this.onClose);
  314. }
  315. /**
  316. * Sets the Gallery frame and initializes listeners.
  317. *
  318. * @return {void}
  319. */
  320. buildAndSetGalleryFrame() {
  321. const {
  322. addToGallery = false,
  323. allowedTypes,
  324. multiple = false,
  325. value = DEFAULT_EMPTY_GALLERY
  326. } = this.props; // If the value did not changed there is no need to rebuild the frame,
  327. // we can continue to use the existing one.
  328. if (value === this.lastGalleryValue) {
  329. return;
  330. }
  331. this.lastGalleryValue = value; // If a frame already existed remove it.
  332. if (this.frame) {
  333. this.frame.remove();
  334. }
  335. let currentState;
  336. if (addToGallery) {
  337. currentState = 'gallery-library';
  338. } else {
  339. currentState = value && value.length ? 'gallery-edit' : 'gallery';
  340. }
  341. if (!this.GalleryDetailsMediaFrame) {
  342. this.GalleryDetailsMediaFrame = getGalleryDetailsMediaFrame();
  343. }
  344. const attachments = getAttachmentsCollection(value);
  345. const selection = new wp.media.model.Selection(attachments.models, {
  346. props: attachments.props.toJSON(),
  347. multiple
  348. });
  349. this.frame = new this.GalleryDetailsMediaFrame({
  350. mimeType: allowedTypes,
  351. state: currentState,
  352. multiple,
  353. selection,
  354. editing: value && value.length ? true : false
  355. });
  356. wp.media.frame = this.frame;
  357. this.initializeListeners();
  358. }
  359. /**
  360. * Initializes the Media Library requirements for the featured image flow.
  361. *
  362. * @return {void}
  363. */
  364. buildAndSetFeatureImageFrame() {
  365. const featuredImageFrame = getFeaturedImageMediaFrame();
  366. const attachments = getAttachmentsCollection(this.props.value);
  367. const selection = new wp.media.model.Selection(attachments.models, {
  368. props: attachments.props.toJSON()
  369. });
  370. this.frame = new featuredImageFrame({
  371. mimeType: this.props.allowedTypes,
  372. state: 'featured-image',
  373. multiple: this.props.multiple,
  374. selection,
  375. editing: this.props.value ? true : false
  376. });
  377. wp.media.frame = this.frame;
  378. }
  379. componentWillUnmount() {
  380. this.frame.remove();
  381. }
  382. onUpdate(selections) {
  383. const {
  384. onSelect,
  385. multiple = false
  386. } = this.props;
  387. const state = this.frame.state();
  388. const selectedImages = selections || state.get('selection');
  389. if (!selectedImages || !selectedImages.models.length) {
  390. return;
  391. }
  392. if (multiple) {
  393. onSelect(selectedImages.models.map(model => slimImageObject(model.toJSON())));
  394. } else {
  395. onSelect(slimImageObject(selectedImages.models[0].toJSON()));
  396. }
  397. }
  398. onSelect() {
  399. const {
  400. onSelect,
  401. multiple = false
  402. } = this.props; // Get media attachment details from the frame state
  403. const attachment = this.frame.state().get('selection').toJSON();
  404. onSelect(multiple ? attachment : attachment[0]);
  405. }
  406. onOpen() {
  407. var _this$props$value;
  408. this.updateCollection(); // Handle both this.props.value being either (number[]) multiple ids
  409. // (for galleries) or a (number) singular id (e.g. image block).
  410. 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;
  411. if (!hasMedia) {
  412. return;
  413. }
  414. if (!this.props.gallery) {
  415. const selection = this.frame.state().get('selection');
  416. Object(external_lodash_["castArray"])(this.props.value).forEach(id => {
  417. selection.add(wp.media.attachment(id));
  418. });
  419. } // load the images so they are available in the media modal.
  420. getAttachmentsCollection(Object(external_lodash_["castArray"])(this.props.value)).more();
  421. }
  422. onClose() {
  423. const {
  424. onClose
  425. } = this.props;
  426. if (onClose) {
  427. onClose();
  428. }
  429. }
  430. updateCollection() {
  431. const frameContent = this.frame.content.get();
  432. if (frameContent && frameContent.collection) {
  433. const collection = frameContent.collection; // clean all attachments we have in memory.
  434. 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.
  435. collection.mirroring._hasMore = true; // request items
  436. collection.more();
  437. }
  438. }
  439. openModal() {
  440. if (this.props.gallery) {
  441. this.buildAndSetGalleryFrame();
  442. }
  443. this.frame.open();
  444. }
  445. render() {
  446. return this.props.render({
  447. open: this.openModal
  448. });
  449. }
  450. }
  451. /* harmony default export */ var media_upload = (media_upload_MediaUpload);
  452. // CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/components/index.js
  453. // EXTERNAL MODULE: external ["wp","apiFetch"]
  454. var external_wp_apiFetch_ = __webpack_require__("ywyh");
  455. var external_wp_apiFetch_default = /*#__PURE__*/__webpack_require__.n(external_wp_apiFetch_);
  456. // EXTERNAL MODULE: external ["wp","blob"]
  457. var external_wp_blob_ = __webpack_require__("xTGt");
  458. // CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/utils/upload-media.js
  459. /**
  460. * External dependencies
  461. */
  462. /**
  463. * WordPress dependencies
  464. */
  465. /**
  466. * Browsers may use unexpected mime types, and they differ from browser to browser.
  467. * This function computes a flexible array of mime types from the mime type structured provided by the server.
  468. * Converts { jpg|jpeg|jpe: "image/jpeg" } into [ "image/jpeg", "image/jpg", "image/jpeg", "image/jpe" ]
  469. * The computation of this array instead of directly using the object,
  470. * solves the problem in chrome where mp3 files have audio/mp3 as mime type instead of audio/mpeg.
  471. * https://bugs.chromium.org/p/chromium/issues/detail?id=227004
  472. *
  473. * @param {?Object} wpMimeTypesObject Mime type object received from the server.
  474. * Extensions are keys separated by '|' and values are mime types associated with an extension.
  475. *
  476. * @return {?Array} An array of mime types or the parameter passed if it was "falsy".
  477. */
  478. function getMimeTypesArray(wpMimeTypesObject) {
  479. if (!wpMimeTypesObject) {
  480. return wpMimeTypesObject;
  481. }
  482. return Object(external_lodash_["flatMap"])(wpMimeTypesObject, (mime, extensionsString) => {
  483. const [type] = mime.split('/');
  484. const extensions = extensionsString.split('|');
  485. return [mime, ...Object(external_lodash_["map"])(extensions, extension => `${type}/${extension}`)];
  486. });
  487. }
  488. /**
  489. * Media Upload is used by audio, image, gallery, video, and file blocks to
  490. * handle uploading a media file when a file upload button is activated.
  491. *
  492. * TODO: future enhancement to add an upload indicator.
  493. *
  494. * @param {Object} $0 Parameters object passed to the function.
  495. * @param {?Array} $0.allowedTypes Array with the types of media that can be uploaded, if unset all types are allowed.
  496. * @param {?Object} $0.additionalData Additional data to include in the request.
  497. * @param {Array} $0.filesList List of files.
  498. * @param {?number} $0.maxUploadFileSize Maximum upload size in bytes allowed for the site.
  499. * @param {Function} $0.onError Function called when an error happens.
  500. * @param {Function} $0.onFileChange Function called each time a file or a temporary representation of the file is available.
  501. * @param {?Object} $0.wpAllowedMimeTypes List of allowed mime types and file extensions.
  502. */
  503. async function uploadMedia({
  504. allowedTypes,
  505. additionalData = {},
  506. filesList,
  507. maxUploadFileSize,
  508. onError = external_lodash_["noop"],
  509. onFileChange,
  510. wpAllowedMimeTypes = null
  511. }) {
  512. // Cast filesList to array
  513. const files = [...filesList];
  514. const filesSet = [];
  515. const setAndUpdateFiles = (idx, value) => {
  516. Object(external_wp_blob_["revokeBlobURL"])(Object(external_lodash_["get"])(filesSet, [idx, 'url']));
  517. filesSet[idx] = value;
  518. onFileChange(Object(external_lodash_["compact"])(filesSet));
  519. }; // Allowed type specified by consumer
  520. const isAllowedType = fileType => {
  521. if (!allowedTypes) {
  522. return true;
  523. }
  524. return Object(external_lodash_["some"])(allowedTypes, allowedType => {
  525. // If a complete mimetype is specified verify if it matches exactly the mime type of the file.
  526. if (Object(external_lodash_["includes"])(allowedType, '/')) {
  527. return allowedType === fileType;
  528. } // Otherwise a general mime type is used and we should verify if the file mimetype starts with it.
  529. return Object(external_lodash_["startsWith"])(fileType, `${allowedType}/`);
  530. });
  531. }; // Allowed types for the current WP_User
  532. const allowedMimeTypesForUser = getMimeTypesArray(wpAllowedMimeTypes);
  533. const isAllowedMimeTypeForUser = fileType => {
  534. return Object(external_lodash_["includes"])(allowedMimeTypesForUser, fileType);
  535. }; // Build the error message including the filename
  536. const triggerError = error => {
  537. error.message = [Object(external_wp_element_["createElement"])("strong", {
  538. key: "filename"
  539. }, error.file.name), ': ', error.message];
  540. onError(error);
  541. };
  542. const validFiles = [];
  543. for (const mediaFile of files) {
  544. // Verify if user is allowed to upload this mime type.
  545. // Defer to the server when type not detected.
  546. if (allowedMimeTypesForUser && mediaFile.type && !isAllowedMimeTypeForUser(mediaFile.type)) {
  547. triggerError({
  548. code: 'MIME_TYPE_NOT_ALLOWED_FOR_USER',
  549. message: Object(external_wp_i18n_["__"])('Sorry, this file type is not permitted for security reasons.'),
  550. file: mediaFile
  551. });
  552. continue;
  553. } // Check if the block supports this mime type.
  554. // Defer to the server when type not detected.
  555. if (mediaFile.type && !isAllowedType(mediaFile.type)) {
  556. triggerError({
  557. code: 'MIME_TYPE_NOT_SUPPORTED',
  558. message: Object(external_wp_i18n_["__"])('Sorry, this file type is not supported here.'),
  559. file: mediaFile
  560. });
  561. continue;
  562. } // verify if file is greater than the maximum file upload size allowed for the site.
  563. if (maxUploadFileSize && mediaFile.size > maxUploadFileSize) {
  564. triggerError({
  565. code: 'SIZE_ABOVE_LIMIT',
  566. message: Object(external_wp_i18n_["__"])('This file exceeds the maximum upload size for this site.'),
  567. file: mediaFile
  568. });
  569. continue;
  570. } // Don't allow empty files to be uploaded.
  571. if (mediaFile.size <= 0) {
  572. triggerError({
  573. code: 'EMPTY_FILE',
  574. message: Object(external_wp_i18n_["__"])('This file is empty.'),
  575. file: mediaFile
  576. });
  577. continue;
  578. }
  579. validFiles.push(mediaFile); // Set temporary URL to create placeholder media file, this is replaced
  580. // with final file from media gallery when upload is `done` below
  581. filesSet.push({
  582. url: Object(external_wp_blob_["createBlobURL"])(mediaFile)
  583. });
  584. onFileChange(filesSet);
  585. }
  586. for (let idx = 0; idx < validFiles.length; ++idx) {
  587. const mediaFile = validFiles[idx];
  588. try {
  589. const savedMedia = await createMediaFromFile(mediaFile, additionalData);
  590. const mediaObject = { ...Object(external_lodash_["omit"])(savedMedia, ['alt_text', 'source_url']),
  591. alt: savedMedia.alt_text,
  592. caption: Object(external_lodash_["get"])(savedMedia, ['caption', 'raw'], ''),
  593. title: savedMedia.title.raw,
  594. url: savedMedia.source_url
  595. };
  596. setAndUpdateFiles(idx, mediaObject);
  597. } catch (error) {
  598. // Reset to empty on failure.
  599. setAndUpdateFiles(idx, null);
  600. let message;
  601. if (Object(external_lodash_["has"])(error, ['message'])) {
  602. message = Object(external_lodash_["get"])(error, ['message']);
  603. } else {
  604. message = Object(external_wp_i18n_["sprintf"])( // translators: %s: file name
  605. Object(external_wp_i18n_["__"])('Error while uploading file %s to the media library.'), mediaFile.name);
  606. }
  607. onError({
  608. code: 'GENERAL',
  609. message,
  610. file: mediaFile
  611. });
  612. }
  613. }
  614. }
  615. /**
  616. * @param {File} file Media File to Save.
  617. * @param {?Object} additionalData Additional data to include in the request.
  618. *
  619. * @return {Promise} Media Object Promise.
  620. */
  621. function createMediaFromFile(file, additionalData) {
  622. // Create upload payload
  623. const data = new window.FormData();
  624. data.append('file', file, file.name || file.type.replace('/', '.'));
  625. Object(external_lodash_["forEach"])(additionalData, (value, key) => data.append(key, value));
  626. return external_wp_apiFetch_default()({
  627. path: '/wp/v2/media',
  628. body: data,
  629. method: 'POST'
  630. });
  631. }
  632. // CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/utils/index.js
  633. // CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/index.js
  634. /***/ }),
  635. /***/ "YLtl":
  636. /***/ (function(module, exports) {
  637. (function() { module.exports = window["lodash"]; }());
  638. /***/ }),
  639. /***/ "l3Sj":
  640. /***/ (function(module, exports) {
  641. (function() { module.exports = window["wp"]["i18n"]; }());
  642. /***/ }),
  643. /***/ "xTGt":
  644. /***/ (function(module, exports) {
  645. (function() { module.exports = window["wp"]["blob"]; }());
  646. /***/ }),
  647. /***/ "ywyh":
  648. /***/ (function(module, exports) {
  649. (function() { module.exports = window["wp"]["apiFetch"]; }());
  650. /***/ })
  651. /******/ });