media-utils.js 22 KB

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