@wordpress/media-utils 4.30.0 → 4.31.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,23 +1,20 @@
1
1
  "use strict";
2
2
 
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
-
5
4
  Object.defineProperty(exports, "__esModule", {
6
5
  value: true
7
6
  });
8
7
  exports.getMimeTypesArray = getMimeTypesArray;
9
8
  exports.uploadMedia = uploadMedia;
10
-
11
9
  var _apiFetch = _interopRequireDefault(require("@wordpress/api-fetch"));
12
-
13
10
  var _blob = require("@wordpress/blob");
14
-
15
11
  var _i18n = require("@wordpress/i18n");
16
-
17
12
  /**
18
13
  * WordPress dependencies
19
14
  */
15
+
20
16
  const noop = () => {};
17
+
21
18
  /**
22
19
  * Browsers may use unexpected mime types, and they differ from browser to browser.
23
20
  * This function computes a flexible array of mime types from the mime type structured provided by the server.
@@ -31,19 +28,17 @@ const noop = () => {};
31
28
  *
32
29
  * @return {?Array} An array of mime types or the parameter passed if it was "falsy".
33
30
  */
34
-
35
-
36
31
  function getMimeTypesArray(wpMimeTypesObject) {
37
32
  if (!wpMimeTypesObject) {
38
33
  return wpMimeTypesObject;
39
34
  }
40
-
41
35
  return Object.entries(wpMimeTypesObject).map(([extensionsString, mime]) => {
42
36
  const [type] = mime.split('/');
43
37
  const extensions = extensionsString.split('|');
44
38
  return [mime, ...extensions.map(extension => `${type}/${extension}`)];
45
39
  }).flat();
46
40
  }
41
+
47
42
  /**
48
43
  * Media Upload is used by audio, image, gallery, video, and file blocks to
49
44
  * handle uploading a media file when a file upload button is activated.
@@ -59,8 +54,6 @@ function getMimeTypesArray(wpMimeTypesObject) {
59
54
  * @param {Function} $0.onFileChange Function called each time a file or a temporary representation of the file is available.
60
55
  * @param {?Object} $0.wpAllowedMimeTypes List of allowed mime types and file extensions.
61
56
  */
62
-
63
-
64
57
  async function uploadMedia({
65
58
  allowedTypes,
66
59
  additionalData = {},
@@ -73,109 +66,105 @@ async function uploadMedia({
73
66
  // Cast filesList to array.
74
67
  const files = [...filesList];
75
68
  const filesSet = [];
76
-
77
69
  const setAndUpdateFiles = (idx, value) => {
78
70
  (0, _blob.revokeBlobURL)(filesSet[idx]?.url);
79
71
  filesSet[idx] = value;
80
72
  onFileChange(filesSet.filter(Boolean));
81
- }; // Allowed type specified by consumer.
82
-
73
+ };
83
74
 
75
+ // Allowed type specified by consumer.
84
76
  const isAllowedType = fileType => {
85
77
  if (!allowedTypes) {
86
78
  return true;
87
79
  }
88
-
89
80
  return allowedTypes.some(allowedType => {
90
81
  // If a complete mimetype is specified verify if it matches exactly the mime type of the file.
91
82
  if (allowedType.includes('/')) {
92
83
  return allowedType === fileType;
93
- } // Otherwise a general mime type is used and we should verify if the file mimetype starts with it.
94
-
95
-
84
+ }
85
+ // Otherwise a general mime type is used and we should verify if the file mimetype starts with it.
96
86
  return fileType.startsWith(`${allowedType}/`);
97
87
  });
98
- }; // Allowed types for the current WP_User.
99
-
88
+ };
100
89
 
90
+ // Allowed types for the current WP_User.
101
91
  const allowedMimeTypesForUser = getMimeTypesArray(wpAllowedMimeTypes);
102
-
103
92
  const isAllowedMimeTypeForUser = fileType => {
104
93
  return allowedMimeTypesForUser.includes(fileType);
105
94
  };
106
-
107
95
  const validFiles = [];
108
-
109
96
  for (const mediaFile of files) {
110
97
  // Verify if user is allowed to upload this mime type.
111
98
  // Defer to the server when type not detected.
112
99
  if (allowedMimeTypesForUser && mediaFile.type && !isAllowedMimeTypeForUser(mediaFile.type)) {
113
100
  onError({
114
101
  code: 'MIME_TYPE_NOT_ALLOWED_FOR_USER',
115
- message: (0, _i18n.sprintf)( // translators: %s: file name.
102
+ message: (0, _i18n.sprintf)(
103
+ // translators: %s: file name.
116
104
  (0, _i18n.__)('%s: Sorry, you are not allowed to upload this file type.'), mediaFile.name),
117
105
  file: mediaFile
118
106
  });
119
107
  continue;
120
- } // Check if the block supports this mime type.
121
- // Defer to the server when type not detected.
122
-
108
+ }
123
109
 
110
+ // Check if the block supports this mime type.
111
+ // Defer to the server when type not detected.
124
112
  if (mediaFile.type && !isAllowedType(mediaFile.type)) {
125
113
  onError({
126
114
  code: 'MIME_TYPE_NOT_SUPPORTED',
127
- message: (0, _i18n.sprintf)( // translators: %s: file name.
115
+ message: (0, _i18n.sprintf)(
116
+ // translators: %s: file name.
128
117
  (0, _i18n.__)('%s: Sorry, this file type is not supported here.'), mediaFile.name),
129
118
  file: mediaFile
130
119
  });
131
120
  continue;
132
- } // Verify if file is greater than the maximum file upload size allowed for the site.
133
-
121
+ }
134
122
 
123
+ // Verify if file is greater than the maximum file upload size allowed for the site.
135
124
  if (maxUploadFileSize && mediaFile.size > maxUploadFileSize) {
136
125
  onError({
137
126
  code: 'SIZE_ABOVE_LIMIT',
138
- message: (0, _i18n.sprintf)( // translators: %s: file name.
127
+ message: (0, _i18n.sprintf)(
128
+ // translators: %s: file name.
139
129
  (0, _i18n.__)('%s: This file exceeds the maximum upload size for this site.'), mediaFile.name),
140
130
  file: mediaFile
141
131
  });
142
132
  continue;
143
- } // Don't allow empty files to be uploaded.
144
-
133
+ }
145
134
 
135
+ // Don't allow empty files to be uploaded.
146
136
  if (mediaFile.size <= 0) {
147
137
  onError({
148
138
  code: 'EMPTY_FILE',
149
- message: (0, _i18n.sprintf)( // translators: %s: file name.
139
+ message: (0, _i18n.sprintf)(
140
+ // translators: %s: file name.
150
141
  (0, _i18n.__)('%s: This file is empty.'), mediaFile.name),
151
142
  file: mediaFile
152
143
  });
153
144
  continue;
154
145
  }
146
+ validFiles.push(mediaFile);
155
147
 
156
- validFiles.push(mediaFile); // Set temporary URL to create placeholder media file, this is replaced
148
+ // Set temporary URL to create placeholder media file, this is replaced
157
149
  // with final file from media gallery when upload is `done` below.
158
-
159
150
  filesSet.push({
160
151
  url: (0, _blob.createBlobURL)(mediaFile)
161
152
  });
162
153
  onFileChange(filesSet);
163
154
  }
164
-
165
155
  for (let idx = 0; idx < validFiles.length; ++idx) {
166
156
  const mediaFile = validFiles[idx];
167
-
168
157
  try {
169
158
  var _savedMedia$caption$r;
170
-
171
- const savedMedia = await createMediaFromFile(mediaFile, additionalData); // eslint-disable-next-line camelcase
172
-
159
+ const savedMedia = await createMediaFromFile(mediaFile, additionalData);
160
+ // eslint-disable-next-line camelcase
173
161
  const {
174
162
  alt_text,
175
163
  source_url,
176
164
  ...savedMediaProps
177
165
  } = savedMedia;
178
- const mediaObject = { ...savedMediaProps,
166
+ const mediaObject = {
167
+ ...savedMediaProps,
179
168
  alt: savedMedia.alt_text,
180
169
  caption: (_savedMedia$caption$r = savedMedia.caption?.raw) !== null && _savedMedia$caption$r !== void 0 ? _savedMedia$caption$r : '',
181
170
  title: savedMedia.title.raw,
@@ -186,14 +175,13 @@ async function uploadMedia({
186
175
  // Reset to empty on failure.
187
176
  setAndUpdateFiles(idx, null);
188
177
  let message;
189
-
190
178
  if (error.message) {
191
179
  message = error.message;
192
180
  } else {
193
- message = (0, _i18n.sprintf)( // translators: %s: file name
181
+ message = (0, _i18n.sprintf)(
182
+ // translators: %s: file name
194
183
  (0, _i18n.__)('Error while uploading file %s to the media library.'), mediaFile.name);
195
184
  }
196
-
197
185
  onError({
198
186
  code: 'GENERAL',
199
187
  message,
@@ -202,23 +190,20 @@ async function uploadMedia({
202
190
  }
203
191
  }
204
192
  }
193
+
205
194
  /**
206
195
  * @param {File} file Media File to Save.
207
196
  * @param {?Object} additionalData Additional data to include in the request.
208
197
  *
209
198
  * @return {Promise} Media Object Promise.
210
199
  */
211
-
212
-
213
200
  function createMediaFromFile(file, additionalData) {
214
201
  // Create upload payload.
215
202
  const data = new window.FormData();
216
203
  data.append('file', file, file.name || file.type.replace('/', '.'));
217
-
218
204
  if (additionalData) {
219
205
  Object.entries(additionalData).forEach(([key, value]) => data.append(key, value));
220
206
  }
221
-
222
207
  return (0, _apiFetch.default)({
223
208
  path: '/wp/v2/media',
224
209
  body: data,
@@ -1 +1 @@
1
- {"version":3,"sources":["@wordpress/media-utils/src/utils/upload-media.js"],"names":["noop","getMimeTypesArray","wpMimeTypesObject","Object","entries","map","extensionsString","mime","type","split","extensions","extension","flat","uploadMedia","allowedTypes","additionalData","filesList","maxUploadFileSize","onError","onFileChange","wpAllowedMimeTypes","files","filesSet","setAndUpdateFiles","idx","value","url","filter","Boolean","isAllowedType","fileType","some","allowedType","includes","startsWith","allowedMimeTypesForUser","isAllowedMimeTypeForUser","validFiles","mediaFile","code","message","name","file","size","push","length","savedMedia","createMediaFromFile","alt_text","source_url","savedMediaProps","mediaObject","alt","caption","raw","title","error","data","window","FormData","append","replace","forEach","key","path","body","method"],"mappings":";;;;;;;;;;AAGA;;AACA;;AACA;;AALA;AACA;AACA;AAKA,MAAMA,IAAI,GAAG,MAAM,CAAE,CAArB;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AACO,SAASC,iBAAT,CAA4BC,iBAA5B,EAAgD;AACtD,MAAK,CAAEA,iBAAP,EAA2B;AAC1B,WAAOA,iBAAP;AACA;;AACD,SAAOC,MAAM,CAACC,OAAP,CAAgBF,iBAAhB,EACLG,GADK,CACA,CAAE,CAAEC,gBAAF,EAAoBC,IAApB,CAAF,KAAkC;AACvC,UAAM,CAAEC,IAAF,IAAWD,IAAI,CAACE,KAAL,CAAY,GAAZ,CAAjB;AACA,UAAMC,UAAU,GAAGJ,gBAAgB,CAACG,KAAjB,CAAwB,GAAxB,CAAnB;AACA,WAAO,CACNF,IADM,EAEN,GAAGG,UAAU,CAACL,GAAX,CACAM,SAAF,IAAkB,GAAGH,IAAM,IAAIG,SAAW,EADxC,CAFG,CAAP;AAMA,GAVK,EAWLC,IAXK,EAAP;AAYA;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;AACO,eAAeC,WAAf,CAA4B;AAClCC,EAAAA,YADkC;AAElCC,EAAAA,cAAc,GAAG,EAFiB;AAGlCC,EAAAA,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EJ;AAHE,OAAF,CAAP;AAKA;AACD;AACD;AAED;AACA;AACA;AACA;AACA;AACA;;;AACA,SAASS,mBAAT,CAA8BL,IAA9B,EAAoC3B,cAApC,EAAqD;AACpD;AACA,QAAM0C,IAAI,GAAG,IAAIC,MAAM,CAACC,QAAX,EAAb;AACAF,EAAAA,IAAI,CAACG,MAAL,CAAa,MAAb,EAAqBlB,IAArB,EAA2BA,IAAI,CAACD,IAAL,IAAaC,IAAI,CAAClC,IAAL,CAAUqD,OAAV,CAAmB,GAAnB,EAAwB,GAAxB,CAAxC;;AACA,MAAK9C,cAAL,EAAsB;AACrBZ,IAAAA,MAAM,CAACC,OAAP,CAAgBW,cAAhB,EAAiC+C,OAAjC,CAA0C,CAAE,CAAEC,GAAF,EAAOtC,KAAP,CAAF,KACzCgC,IAAI,CAACG,MAAL,CAAaG,GAAb,EAAkBtC,KAAlB,CADD;AAGA;;AACD,SAAO,uBAAU;AAChBuC,IAAAA,IAAI,EAAE,cADU;AAEhBC,IAAAA,IAAI,EAAER,IAFU;AAGhBS,IAAAA,MAAM,EAAE;AAHQ,GAAV,CAAP;AAKA","sourcesContent":["/**\n * WordPress dependencies\n */\nimport apiFetch from '@wordpress/api-fetch';\nimport { createBlobURL, revokeBlobURL } from '@wordpress/blob';\nimport { __, sprintf } from '@wordpress/i18n';\n\nconst noop = () => {};\n\n/**\n * Browsers may use unexpected mime types, and they differ from browser to browser.\n * This function computes a flexible array of mime types from the mime type structured provided by the server.\n * Converts { jpg|jpeg|jpe: \"image/jpeg\" } into [ \"image/jpeg\", \"image/jpg\", \"image/jpeg\", \"image/jpe\" ]\n * The computation of this array instead of directly using the object,\n * solves the problem in chrome where mp3 files have audio/mp3 as mime type instead of audio/mpeg.\n * https://bugs.chromium.org/p/chromium/issues/detail?id=227004\n *\n * @param {?Object} wpMimeTypesObject Mime type object received from the server.\n * Extensions are keys separated by '|' and values are mime types associated with an extension.\n *\n * @return {?Array} An array of mime types or the parameter passed if it was \"falsy\".\n */\nexport function getMimeTypesArray( wpMimeTypesObject ) {\n\tif ( ! wpMimeTypesObject ) {\n\t\treturn wpMimeTypesObject;\n\t}\n\treturn Object.entries( wpMimeTypesObject )\n\t\t.map( ( [ extensionsString, mime ] ) => {\n\t\t\tconst [ type ] = mime.split( '/' );\n\t\t\tconst extensions = extensionsString.split( '|' );\n\t\t\treturn [\n\t\t\t\tmime,\n\t\t\t\t...extensions.map(\n\t\t\t\t\t( extension ) => `${ type }/${ extension }`\n\t\t\t\t),\n\t\t\t];\n\t\t} )\n\t\t.flat();\n}\n\n/**\n *\tMedia Upload is used by audio, image, gallery, video, and file blocks to\n *\thandle uploading a media file when a file upload button is activated.\n *\n *\tTODO: future enhancement to add an upload indicator.\n *\n * @param {Object} $0 Parameters object passed to the function.\n * @param {?Array} $0.allowedTypes Array with the types of media that can be uploaded, if unset all types are allowed.\n * @param {?Object} $0.additionalData Additional data to include in the request.\n * @param {Array} $0.filesList List of files.\n * @param {?number} $0.maxUploadFileSize Maximum upload size in bytes allowed for the site.\n * @param {Function} $0.onError Function called when an error happens.\n * @param {Function} $0.onFileChange Function called each time a file or a temporary representation of the file is available.\n * @param {?Object} $0.wpAllowedMimeTypes List of allowed mime types and file extensions.\n */\nexport async function uploadMedia( {\n\tallowedTypes,\n\tadditionalData = {},\n\tfilesList,\n\tmaxUploadFileSize,\n\tonError = noop,\n\tonFileChange,\n\twpAllowedMimeTypes = null,\n} ) {\n\t// Cast filesList to array.\n\tconst files = [ ...filesList ];\n\n\tconst filesSet = [];\n\tconst setAndUpdateFiles = ( idx, value ) => {\n\t\trevokeBlobURL( filesSet[ idx ]?.url );\n\t\tfilesSet[ idx ] = value;\n\t\tonFileChange( filesSet.filter( Boolean ) );\n\t};\n\n\t// Allowed type specified by consumer.\n\tconst isAllowedType = ( fileType ) => {\n\t\tif ( ! allowedTypes ) {\n\t\t\treturn true;\n\t\t}\n\t\treturn allowedTypes.some( ( allowedType ) => {\n\t\t\t// If a complete mimetype is specified verify if it matches exactly the mime type of the file.\n\t\t\tif ( allowedType.includes( '/' ) ) {\n\t\t\t\treturn allowedType === fileType;\n\t\t\t}\n\t\t\t// Otherwise a general mime type is used and we should verify if the file mimetype starts with it.\n\t\t\treturn fileType.startsWith( `${ allowedType }/` );\n\t\t} );\n\t};\n\n\t// Allowed types for the current WP_User.\n\tconst allowedMimeTypesForUser = getMimeTypesArray( wpAllowedMimeTypes );\n\tconst isAllowedMimeTypeForUser = ( fileType ) => {\n\t\treturn allowedMimeTypesForUser.includes( fileType );\n\t};\n\n\tconst validFiles = [];\n\n\tfor ( const mediaFile of files ) {\n\t\t// Verify if user is allowed to upload this mime type.\n\t\t// Defer to the server when type not detected.\n\t\tif (\n\t\t\tallowedMimeTypesForUser &&\n\t\t\tmediaFile.type &&\n\t\t\t! isAllowedMimeTypeForUser( mediaFile.type )\n\t\t) {\n\t\t\tonError( {\n\t\t\t\tcode: 'MIME_TYPE_NOT_ALLOWED_FOR_USER',\n\t\t\t\tmessage: sprintf(\n\t\t\t\t\t// translators: %s: file name.\n\t\t\t\t\t__(\n\t\t\t\t\t\t'%s: Sorry, you are not allowed to upload this file type.'\n\t\t\t\t\t),\n\t\t\t\t\tmediaFile.name\n\t\t\t\t),\n\t\t\t\tfile: mediaFile,\n\t\t\t} );\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Check if the block supports this mime type.\n\t\t// Defer to the server when type not detected.\n\t\tif ( mediaFile.type && ! isAllowedType( mediaFile.type ) ) {\n\t\t\tonError( {\n\t\t\t\tcode: 'MIME_TYPE_NOT_SUPPORTED',\n\t\t\t\tmessage: sprintf(\n\t\t\t\t\t// translators: %s: file name.\n\t\t\t\t\t__( '%s: Sorry, this file type is not supported here.' ),\n\t\t\t\t\tmediaFile.name\n\t\t\t\t),\n\t\t\t\tfile: mediaFile,\n\t\t\t} );\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Verify if file is greater than the maximum file upload size allowed for the site.\n\t\tif ( maxUploadFileSize && mediaFile.size > maxUploadFileSize ) {\n\t\t\tonError( {\n\t\t\t\tcode: 'SIZE_ABOVE_LIMIT',\n\t\t\t\tmessage: sprintf(\n\t\t\t\t\t// translators: %s: file name.\n\t\t\t\t\t__(\n\t\t\t\t\t\t'%s: This file exceeds the maximum upload size for this site.'\n\t\t\t\t\t),\n\t\t\t\t\tmediaFile.name\n\t\t\t\t),\n\t\t\t\tfile: mediaFile,\n\t\t\t} );\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Don't allow empty files to be uploaded.\n\t\tif ( mediaFile.size <= 0 ) {\n\t\t\tonError( {\n\t\t\t\tcode: 'EMPTY_FILE',\n\t\t\t\tmessage: sprintf(\n\t\t\t\t\t// translators: %s: file name.\n\t\t\t\t\t__( '%s: This file is empty.' ),\n\t\t\t\t\tmediaFile.name\n\t\t\t\t),\n\t\t\t\tfile: mediaFile,\n\t\t\t} );\n\t\t\tcontinue;\n\t\t}\n\n\t\tvalidFiles.push( mediaFile );\n\n\t\t// Set temporary URL to create placeholder media file, this is replaced\n\t\t// with final file from media gallery when upload is `done` below.\n\t\tfilesSet.push( { url: createBlobURL( mediaFile ) } );\n\t\tonFileChange( filesSet );\n\t}\n\n\tfor ( let idx = 0; idx < validFiles.length; ++idx ) {\n\t\tconst mediaFile = validFiles[ idx ];\n\t\ttry {\n\t\t\tconst savedMedia = await createMediaFromFile(\n\t\t\t\tmediaFile,\n\t\t\t\tadditionalData\n\t\t\t);\n\t\t\t// eslint-disable-next-line camelcase\n\t\t\tconst { alt_text, source_url, ...savedMediaProps } = savedMedia;\n\t\t\tconst mediaObject = {\n\t\t\t\t...savedMediaProps,\n\t\t\t\talt: savedMedia.alt_text,\n\t\t\t\tcaption: savedMedia.caption?.raw ?? '',\n\t\t\t\ttitle: savedMedia.title.raw,\n\t\t\t\turl: savedMedia.source_url,\n\t\t\t};\n\t\t\tsetAndUpdateFiles( idx, mediaObject );\n\t\t} catch ( error ) {\n\t\t\t// Reset to empty on failure.\n\t\t\tsetAndUpdateFiles( idx, null );\n\t\t\tlet message;\n\t\t\tif ( error.message ) {\n\t\t\t\tmessage = error.message;\n\t\t\t} else {\n\t\t\t\tmessage = sprintf(\n\t\t\t\t\t// translators: %s: file name\n\t\t\t\t\t__( 'Error while uploading file %s to the media library.' ),\n\t\t\t\t\tmediaFile.name\n\t\t\t\t);\n\t\t\t}\n\t\t\tonError( {\n\t\t\t\tcode: 'GENERAL',\n\t\t\t\tmessage,\n\t\t\t\tfile: mediaFile,\n\t\t\t} );\n\t\t}\n\t}\n}\n\n/**\n * @param {File} file Media File to Save.\n * @param {?Object} additionalData Additional data to include in the request.\n *\n * @return {Promise} Media Object Promise.\n */\nfunction createMediaFromFile( file, additionalData ) {\n\t// Create upload payload.\n\tconst data = new window.FormData();\n\tdata.append( 'file', file, file.name || file.type.replace( '/', '.' ) );\n\tif ( additionalData ) {\n\t\tObject.entries( additionalData ).forEach( ( [ key, value ] ) =>\n\t\t\tdata.append( key, value )\n\t\t);\n\t}\n\treturn apiFetch( {\n\t\tpath: '/wp/v2/media',\n\t\tbody: data,\n\t\tmethod: 'POST',\n\t} );\n}\n"]}
1
+ {"version":3,"names":["_apiFetch","_interopRequireDefault","require","_blob","_i18n","noop","getMimeTypesArray","wpMimeTypesObject","Object","entries","map","extensionsString","mime","type","split","extensions","extension","flat","uploadMedia","allowedTypes","additionalData","filesList","maxUploadFileSize","onError","onFileChange","wpAllowedMimeTypes","files","filesSet","setAndUpdateFiles","idx","value","revokeBlobURL","url","filter","Boolean","isAllowedType","fileType","some","allowedType","includes","startsWith","allowedMimeTypesForUser","isAllowedMimeTypeForUser","validFiles","mediaFile","code","message","sprintf","__","name","file","size","push","createBlobURL","length","_savedMedia$caption$r","savedMedia","createMediaFromFile","alt_text","source_url","savedMediaProps","mediaObject","alt","caption","raw","title","error","data","window","FormData","append","replace","forEach","key","apiFetch","path","body","method"],"sources":["@wordpress/media-utils/src/utils/upload-media.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport apiFetch from '@wordpress/api-fetch';\nimport { createBlobURL, revokeBlobURL } from '@wordpress/blob';\nimport { __, sprintf } from '@wordpress/i18n';\n\nconst noop = () => {};\n\n/**\n * Browsers may use unexpected mime types, and they differ from browser to browser.\n * This function computes a flexible array of mime types from the mime type structured provided by the server.\n * Converts { jpg|jpeg|jpe: \"image/jpeg\" } into [ \"image/jpeg\", \"image/jpg\", \"image/jpeg\", \"image/jpe\" ]\n * The computation of this array instead of directly using the object,\n * solves the problem in chrome where mp3 files have audio/mp3 as mime type instead of audio/mpeg.\n * https://bugs.chromium.org/p/chromium/issues/detail?id=227004\n *\n * @param {?Object} wpMimeTypesObject Mime type object received from the server.\n * Extensions are keys separated by '|' and values are mime types associated with an extension.\n *\n * @return {?Array} An array of mime types or the parameter passed if it was \"falsy\".\n */\nexport function getMimeTypesArray( wpMimeTypesObject ) {\n\tif ( ! wpMimeTypesObject ) {\n\t\treturn wpMimeTypesObject;\n\t}\n\treturn Object.entries( wpMimeTypesObject )\n\t\t.map( ( [ extensionsString, mime ] ) => {\n\t\t\tconst [ type ] = mime.split( '/' );\n\t\t\tconst extensions = extensionsString.split( '|' );\n\t\t\treturn [\n\t\t\t\tmime,\n\t\t\t\t...extensions.map(\n\t\t\t\t\t( extension ) => `${ type }/${ extension }`\n\t\t\t\t),\n\t\t\t];\n\t\t} )\n\t\t.flat();\n}\n\n/**\n *\tMedia Upload is used by audio, image, gallery, video, and file blocks to\n *\thandle uploading a media file when a file upload button is activated.\n *\n *\tTODO: future enhancement to add an upload indicator.\n *\n * @param {Object} $0 Parameters object passed to the function.\n * @param {?Array} $0.allowedTypes Array with the types of media that can be uploaded, if unset all types are allowed.\n * @param {?Object} $0.additionalData Additional data to include in the request.\n * @param {Array} $0.filesList List of files.\n * @param {?number} $0.maxUploadFileSize Maximum upload size in bytes allowed for the site.\n * @param {Function} $0.onError Function called when an error happens.\n * @param {Function} $0.onFileChange Function called each time a file or a temporary representation of the file is available.\n * @param {?Object} $0.wpAllowedMimeTypes List of allowed mime types and file extensions.\n */\nexport async function uploadMedia( {\n\tallowedTypes,\n\tadditionalData = {},\n\tfilesList,\n\tmaxUploadFileSize,\n\tonError = noop,\n\tonFileChange,\n\twpAllowedMimeTypes = null,\n} ) {\n\t// Cast filesList to array.\n\tconst files = [ ...filesList ];\n\n\tconst filesSet = [];\n\tconst setAndUpdateFiles = ( idx, value ) => {\n\t\trevokeBlobURL( filesSet[ idx ]?.url );\n\t\tfilesSet[ idx ] = value;\n\t\tonFileChange( filesSet.filter( Boolean ) );\n\t};\n\n\t// Allowed type specified by consumer.\n\tconst isAllowedType = ( fileType ) => {\n\t\tif ( ! allowedTypes ) {\n\t\t\treturn true;\n\t\t}\n\t\treturn allowedTypes.some( ( allowedType ) => {\n\t\t\t// If a complete mimetype is specified verify if it matches exactly the mime type of the file.\n\t\t\tif ( allowedType.includes( '/' ) ) {\n\t\t\t\treturn allowedType === fileType;\n\t\t\t}\n\t\t\t// Otherwise a general mime type is used and we should verify if the file mimetype starts with it.\n\t\t\treturn fileType.startsWith( `${ allowedType }/` );\n\t\t} );\n\t};\n\n\t// Allowed types for the current WP_User.\n\tconst allowedMimeTypesForUser = getMimeTypesArray( wpAllowedMimeTypes );\n\tconst isAllowedMimeTypeForUser = ( fileType ) => {\n\t\treturn allowedMimeTypesForUser.includes( fileType );\n\t};\n\n\tconst validFiles = [];\n\n\tfor ( const mediaFile of files ) {\n\t\t// Verify if user is allowed to upload this mime type.\n\t\t// Defer to the server when type not detected.\n\t\tif (\n\t\t\tallowedMimeTypesForUser &&\n\t\t\tmediaFile.type &&\n\t\t\t! isAllowedMimeTypeForUser( mediaFile.type )\n\t\t) {\n\t\t\tonError( {\n\t\t\t\tcode: 'MIME_TYPE_NOT_ALLOWED_FOR_USER',\n\t\t\t\tmessage: sprintf(\n\t\t\t\t\t// translators: %s: file name.\n\t\t\t\t\t__(\n\t\t\t\t\t\t'%s: Sorry, you are not allowed to upload this file type.'\n\t\t\t\t\t),\n\t\t\t\t\tmediaFile.name\n\t\t\t\t),\n\t\t\t\tfile: mediaFile,\n\t\t\t} );\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Check if the block supports this mime type.\n\t\t// Defer to the server when type not detected.\n\t\tif ( mediaFile.type && ! isAllowedType( mediaFile.type ) ) {\n\t\t\tonError( {\n\t\t\t\tcode: 'MIME_TYPE_NOT_SUPPORTED',\n\t\t\t\tmessage: sprintf(\n\t\t\t\t\t// translators: %s: file name.\n\t\t\t\t\t__( '%s: Sorry, this file type is not supported here.' ),\n\t\t\t\t\tmediaFile.name\n\t\t\t\t),\n\t\t\t\tfile: mediaFile,\n\t\t\t} );\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Verify if file is greater than the maximum file upload size allowed for the site.\n\t\tif ( maxUploadFileSize && mediaFile.size > maxUploadFileSize ) {\n\t\t\tonError( {\n\t\t\t\tcode: 'SIZE_ABOVE_LIMIT',\n\t\t\t\tmessage: sprintf(\n\t\t\t\t\t// translators: %s: file name.\n\t\t\t\t\t__(\n\t\t\t\t\t\t'%s: This file exceeds the maximum upload size for this site.'\n\t\t\t\t\t),\n\t\t\t\t\tmediaFile.name\n\t\t\t\t),\n\t\t\t\tfile: mediaFile,\n\t\t\t} );\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Don't allow empty files to be uploaded.\n\t\tif ( mediaFile.size <= 0 ) {\n\t\t\tonError( {\n\t\t\t\tcode: 'EMPTY_FILE',\n\t\t\t\tmessage: sprintf(\n\t\t\t\t\t// translators: %s: file name.\n\t\t\t\t\t__( '%s: This file is empty.' ),\n\t\t\t\t\tmediaFile.name\n\t\t\t\t),\n\t\t\t\tfile: mediaFile,\n\t\t\t} );\n\t\t\tcontinue;\n\t\t}\n\n\t\tvalidFiles.push( mediaFile );\n\n\t\t// Set temporary URL to create placeholder media file, this is replaced\n\t\t// with final file from media gallery when upload is `done` below.\n\t\tfilesSet.push( { url: createBlobURL( mediaFile ) } );\n\t\tonFileChange( filesSet );\n\t}\n\n\tfor ( let idx = 0; idx < validFiles.length; ++idx ) {\n\t\tconst mediaFile = validFiles[ idx ];\n\t\ttry {\n\t\t\tconst savedMedia = await createMediaFromFile(\n\t\t\t\tmediaFile,\n\t\t\t\tadditionalData\n\t\t\t);\n\t\t\t// eslint-disable-next-line camelcase\n\t\t\tconst { alt_text, source_url, ...savedMediaProps } = savedMedia;\n\t\t\tconst mediaObject = {\n\t\t\t\t...savedMediaProps,\n\t\t\t\talt: savedMedia.alt_text,\n\t\t\t\tcaption: savedMedia.caption?.raw ?? '',\n\t\t\t\ttitle: savedMedia.title.raw,\n\t\t\t\turl: savedMedia.source_url,\n\t\t\t};\n\t\t\tsetAndUpdateFiles( idx, mediaObject );\n\t\t} catch ( error ) {\n\t\t\t// Reset to empty on failure.\n\t\t\tsetAndUpdateFiles( idx, null );\n\t\t\tlet message;\n\t\t\tif ( error.message ) {\n\t\t\t\tmessage = error.message;\n\t\t\t} else {\n\t\t\t\tmessage = sprintf(\n\t\t\t\t\t// translators: %s: file name\n\t\t\t\t\t__( 'Error while uploading file %s to the media library.' ),\n\t\t\t\t\tmediaFile.name\n\t\t\t\t);\n\t\t\t}\n\t\t\tonError( {\n\t\t\t\tcode: 'GENERAL',\n\t\t\t\tmessage,\n\t\t\t\tfile: mediaFile,\n\t\t\t} );\n\t\t}\n\t}\n}\n\n/**\n * @param {File} file Media File to Save.\n * @param {?Object} additionalData Additional data to include in the request.\n *\n * @return {Promise} Media Object Promise.\n */\nfunction createMediaFromFile( file, additionalData ) {\n\t// Create upload payload.\n\tconst data = new window.FormData();\n\tdata.append( 'file', file, file.name || file.type.replace( '/', '.' ) );\n\tif ( additionalData ) {\n\t\tObject.entries( additionalData ).forEach( ( [ key, value ] ) =>\n\t\t\tdata.append( key, value )\n\t\t);\n\t}\n\treturn apiFetch( {\n\t\tpath: '/wp/v2/media',\n\t\tbody: data,\n\t\tmethod: 'POST',\n\t} );\n}\n"],"mappings":";;;;;;;;AAGA,IAAAA,SAAA,GAAAC,sBAAA,CAAAC,OAAA;AACA,IAAAC,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IAAI,EAAE,cAAc;IACpBC,IAAI,EAAET,IAAI;IACVU,MAAM,EAAE;EACT,CAAE,CAAC;AACJ"}
@@ -1 +1 @@
1
- {"version":3,"sources":["@wordpress/media-utils/src/components/index.js"],"names":["default","MediaUpload"],"mappings":"AAAA,SAASA,OAAO,IAAIC,WAApB,QAAuC,gBAAvC","sourcesContent":["export { default as MediaUpload } from './media-upload';\n"]}
1
+ {"version":3,"names":["default","MediaUpload"],"sources":["@wordpress/media-utils/src/components/index.js"],"sourcesContent":["export { default as MediaUpload } from './media-upload';\n"],"mappings":"AAAA,SAASA,OAAO,IAAIC,WAAW,QAAQ,gBAAgB"}
@@ -4,12 +4,12 @@
4
4
  import { Component } from '@wordpress/element';
5
5
  import { __ } from '@wordpress/i18n';
6
6
  const DEFAULT_EMPTY_GALLERY = [];
7
+
7
8
  /**
8
9
  * Prepares the Featured Image toolbars and frames.
9
10
  *
10
11
  * @return {window.wp.media.view.MediaFrame.Select} The default media workflow.
11
12
  */
12
-
13
13
  const getFeaturedImageMediaFrame = () => {
14
14
  const {
15
15
  wp
@@ -27,7 +27,6 @@ const getFeaturedImageMediaFrame = () => {
27
27
  state: this.options.state
28
28
  });
29
29
  },
30
-
31
30
  /**
32
31
  * Handle the edit state requirements of selected media item.
33
32
  *
@@ -38,13 +37,14 @@ const getFeaturedImageMediaFrame = () => {
38
37
  const view = new wp.media.view.EditImage({
39
38
  model: selection.single(),
40
39
  controller: this
41
- }).render(); // Set the view to the EditImage frame using the selected image.
40
+ }).render();
42
41
 
43
- this.content.set(view); // After bringing in the frame, load the actual editor via an ajax call.
42
+ // Set the view to the EditImage frame using the selected image.
43
+ this.content.set(view);
44
44
 
45
+ // After bringing in the frame, load the actual editor via an ajax call.
45
46
  view.loadEditor();
46
47
  },
47
-
48
48
  /**
49
49
  * Create the default states.
50
50
  *
@@ -59,13 +59,12 @@ const getFeaturedImageMediaFrame = () => {
59
59
  }
60
60
  });
61
61
  };
62
+
62
63
  /**
63
64
  * Prepares the Gallery toolbars and frames.
64
65
  *
65
66
  * @return {window.wp.media.view.MediaFrame.Post} The default media workflow.
66
67
  */
67
-
68
-
69
68
  const getGalleryDetailsMediaFrame = () => {
70
69
  const {
71
70
  wp
@@ -77,7 +76,6 @@ const getGalleryDetailsMediaFrame = () => {
77
76
  * @class GalleryDetailsMediaFrame
78
77
  * @class
79
78
  */
80
-
81
79
  return wp.media.view.MediaFrame.Post.extend({
82
80
  /**
83
81
  * Set up gallery toolbar.
@@ -96,25 +94,23 @@ const getGalleryDetailsMediaFrame = () => {
96
94
  requires: {
97
95
  library: true
98
96
  },
99
-
100
97
  /**
101
98
  * @fires wp.media.controller.State#update
102
99
  */
103
100
  click() {
104
101
  const controller = this.controller,
105
- state = controller.state();
102
+ state = controller.state();
106
103
  controller.close();
107
- state.trigger('update', state.get('library')); // Restore and reset the default state.
104
+ state.trigger('update', state.get('library'));
108
105
 
106
+ // Restore and reset the default state.
109
107
  controller.setState(controller.options.state);
110
108
  controller.reset();
111
109
  }
112
-
113
110
  }
114
111
  }
115
112
  }));
116
113
  },
117
-
118
114
  /**
119
115
  * Handle the edit state requirements of selected media item.
120
116
  *
@@ -125,13 +121,14 @@ const getGalleryDetailsMediaFrame = () => {
125
121
  const view = new wp.media.view.EditImage({
126
122
  model: selection.single(),
127
123
  controller: this
128
- }).render(); // Set the view to the EditImage frame using the selected image.
124
+ }).render();
129
125
 
130
- this.content.set(view); // After bringing in the frame, load the actual editor via an ajax call.
126
+ // Set the view to the EditImage frame using the selected image.
127
+ this.content.set(view);
131
128
 
129
+ // After bringing in the frame, load the actual editor via an ajax call.
132
130
  view.loadEditor();
133
131
  },
134
-
135
132
  /**
136
133
  * Create the default states.
137
134
  *
@@ -163,21 +160,19 @@ const getGalleryDetailsMediaFrame = () => {
163
160
  }), new wp.media.controller.GalleryAdd()]);
164
161
  }
165
162
  });
166
- }; // The media library image object contains numerous attributes
167
- // we only need this set to display the image in the library.
168
-
163
+ };
169
164
 
165
+ // The media library image object contains numerous attributes
166
+ // we only need this set to display the image in the library.
170
167
  const slimImageObject = img => {
171
168
  const attrSet = ['sizes', 'mime', 'type', 'subtype', 'id', 'url', 'alt', 'link', 'caption'];
172
169
  return attrSet.reduce((result, key) => {
173
170
  if (img?.hasOwnProperty(key)) {
174
171
  result[key] = img[key];
175
172
  }
176
-
177
173
  return result;
178
174
  }, {});
179
175
  };
180
-
181
176
  const getAttachmentsCollection = ids => {
182
177
  const {
183
178
  wp
@@ -191,7 +186,6 @@ const getAttachmentsCollection = ids => {
191
186
  type: 'image'
192
187
  });
193
188
  };
194
-
195
189
  class MediaUpload extends Component {
196
190
  constructor({
197
191
  allowedTypes,
@@ -210,7 +204,6 @@ class MediaUpload extends Component {
210
204
  const {
211
205
  wp
212
206
  } = window;
213
-
214
207
  if (gallery) {
215
208
  this.buildAndSetGalleryFrame();
216
209
  } else {
@@ -218,27 +211,21 @@ class MediaUpload extends Component {
218
211
  title,
219
212
  multiple
220
213
  };
221
-
222
214
  if (!!allowedTypes) {
223
215
  frameConfig.library = {
224
216
  type: allowedTypes
225
217
  };
226
218
  }
227
-
228
219
  this.frame = wp.media(frameConfig);
229
220
  }
230
-
231
221
  if (modalClass) {
232
222
  this.frame.$el.addClass(modalClass);
233
223
  }
234
-
235
224
  if (unstableFeaturedImageFlow) {
236
225
  this.buildAndSetFeatureImageFrame();
237
226
  }
238
-
239
227
  this.initializeListeners();
240
228
  }
241
-
242
229
  initializeListeners() {
243
230
  // When an image is selected in the media frame...
244
231
  this.frame.on('select', this.onSelect);
@@ -246,47 +233,43 @@ class MediaUpload extends Component {
246
233
  this.frame.on('open', this.onOpen);
247
234
  this.frame.on('close', this.onClose);
248
235
  }
236
+
249
237
  /**
250
238
  * Sets the Gallery frame and initializes listeners.
251
239
  *
252
240
  * @return {void}
253
241
  */
254
-
255
-
256
242
  buildAndSetGalleryFrame() {
257
243
  const {
258
244
  addToGallery = false,
259
245
  allowedTypes,
260
246
  multiple = false,
261
247
  value = DEFAULT_EMPTY_GALLERY
262
- } = this.props; // If the value did not changed there is no need to rebuild the frame,
263
- // we can continue to use the existing one.
248
+ } = this.props;
264
249
 
250
+ // If the value did not changed there is no need to rebuild the frame,
251
+ // we can continue to use the existing one.
265
252
  if (value === this.lastGalleryValue) {
266
253
  return;
267
254
  }
268
-
269
255
  const {
270
256
  wp
271
257
  } = window;
272
- this.lastGalleryValue = value; // If a frame already existed remove it.
258
+ this.lastGalleryValue = value;
273
259
 
260
+ // If a frame already existed remove it.
274
261
  if (this.frame) {
275
262
  this.frame.remove();
276
263
  }
277
-
278
264
  let currentState;
279
-
280
265
  if (addToGallery) {
281
266
  currentState = 'gallery-library';
282
267
  } else {
283
268
  currentState = value && value.length ? 'gallery-edit' : 'gallery';
284
269
  }
285
-
286
270
  if (!this.GalleryDetailsMediaFrame) {
287
271
  this.GalleryDetailsMediaFrame = getGalleryDetailsMediaFrame();
288
272
  }
289
-
290
273
  const attachments = getAttachmentsCollection(value);
291
274
  const selection = new wp.media.model.Selection(attachments.models, {
292
275
  props: attachments.props.toJSON(),
@@ -302,13 +285,12 @@ class MediaUpload extends Component {
302
285
  wp.media.frame = this.frame;
303
286
  this.initializeListeners();
304
287
  }
288
+
305
289
  /**
306
290
  * Initializes the Media Library requirements for the featured image flow.
307
291
  *
308
292
  * @return {void}
309
293
  */
310
-
311
-
312
294
  buildAndSetFeatureImageFrame() {
313
295
  const {
314
296
  wp
@@ -327,11 +309,9 @@ class MediaUpload extends Component {
327
309
  });
328
310
  wp.media.frame = this.frame;
329
311
  }
330
-
331
312
  componentWillUnmount() {
332
313
  this.frame.remove();
333
314
  }
334
-
335
315
  onUpdate(selections) {
336
316
  const {
337
317
  onSelect,
@@ -339,28 +319,24 @@ class MediaUpload extends Component {
339
319
  } = this.props;
340
320
  const state = this.frame.state();
341
321
  const selectedImages = selections || state.get('selection');
342
-
343
322
  if (!selectedImages || !selectedImages.models.length) {
344
323
  return;
345
324
  }
346
-
347
325
  if (multiple) {
348
326
  onSelect(selectedImages.models.map(model => slimImageObject(model.toJSON())));
349
327
  } else {
350
328
  onSelect(slimImageObject(selectedImages.models[0].toJSON()));
351
329
  }
352
330
  }
353
-
354
331
  onSelect() {
355
332
  const {
356
333
  onSelect,
357
334
  multiple = false
358
- } = this.props; // Get media attachment details from the frame state.
359
-
335
+ } = this.props;
336
+ // Get media attachment details from the frame state.
360
337
  const attachment = this.frame.state().get('selection').toJSON();
361
338
  onSelect(multiple ? attachment : attachment[0]);
362
339
  }
363
-
364
340
  onOpen() {
365
341
  const {
366
342
  wp
@@ -368,79 +344,72 @@ class MediaUpload extends Component {
368
344
  const {
369
345
  value
370
346
  } = this.props;
371
- this.updateCollection(); //Handle active tab in media model on model open.
347
+ this.updateCollection();
372
348
 
349
+ //Handle active tab in media model on model open.
373
350
  if (this.props.mode) {
374
351
  this.frame.content.mode(this.props.mode);
375
- } // Handle both this.props.value being either (number[]) multiple ids
376
- // (for galleries) or a (number) singular id (e.g. image block).
377
-
352
+ }
378
353
 
354
+ // Handle both this.props.value being either (number[]) multiple ids
355
+ // (for galleries) or a (number) singular id (e.g. image block).
379
356
  const hasMedia = Array.isArray(value) ? !!value?.length : !!value;
380
-
381
357
  if (!hasMedia) {
382
358
  return;
383
359
  }
384
-
385
360
  const isGallery = this.props.gallery;
386
361
  const selection = this.frame.state().get('selection');
387
362
  const valueArray = Array.isArray(value) ? value : [value];
388
-
389
363
  if (!isGallery) {
390
364
  valueArray.forEach(id => {
391
365
  selection.add(wp.media.attachment(id));
392
366
  });
393
- } // Load the images so they are available in the media modal.
394
-
367
+ }
395
368
 
396
- const attachments = getAttachmentsCollection(valueArray); // Once attachments are loaded, set the current selection.
369
+ // Load the images so they are available in the media modal.
370
+ const attachments = getAttachmentsCollection(valueArray);
397
371
 
372
+ // Once attachments are loaded, set the current selection.
398
373
  attachments.more().done(function () {
399
374
  if (isGallery && attachments?.models?.length) {
400
375
  selection.add(attachments.models);
401
376
  }
402
377
  });
403
378
  }
404
-
405
379
  onClose() {
406
380
  const {
407
381
  onClose
408
382
  } = this.props;
409
-
410
383
  if (onClose) {
411
384
  onClose();
412
385
  }
413
386
  }
414
-
415
387
  updateCollection() {
416
388
  const frameContent = this.frame.content.get();
417
-
418
389
  if (frameContent && frameContent.collection) {
419
- const collection = frameContent.collection; // Clean all attachments we have in memory.
390
+ const collection = frameContent.collection;
420
391
 
421
- 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.
392
+ // Clean all attachments we have in memory.
393
+ collection.toArray().forEach(model => model.trigger('destroy', model));
422
394
 
423
- collection.mirroring._hasMore = true; // Request items.
395
+ // Reset has more flag, if library had small amount of items all items may have been loaded before.
396
+ collection.mirroring._hasMore = true;
424
397
 
398
+ // Request items.
425
399
  collection.more();
426
400
  }
427
401
  }
428
-
429
402
  openModal() {
430
403
  if (this.props.gallery) {
431
404
  this.buildAndSetGalleryFrame();
432
405
  }
433
-
434
406
  this.frame.open();
435
407
  }
436
-
437
408
  render() {
438
409
  return this.props.render({
439
410
  open: this.openModal
440
411
  });
441
412
  }
442
-
443
413
  }
444
-
445
414
  export default MediaUpload;
446
415
  //# sourceMappingURL=index.js.map