media-models.js 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666
  1. /******/ (function(modules) { // webpackBootstrap
  2. /******/ // The module cache
  3. /******/ var installedModules = {};
  4. /******/
  5. /******/ // The require function
  6. /******/ function __webpack_require__(moduleId) {
  7. /******/
  8. /******/ // Check if module is in cache
  9. /******/ if(installedModules[moduleId]) {
  10. /******/ return installedModules[moduleId].exports;
  11. /******/ }
  12. /******/ // Create a new module (and put it into the cache)
  13. /******/ var module = installedModules[moduleId] = {
  14. /******/ i: moduleId,
  15. /******/ l: false,
  16. /******/ exports: {}
  17. /******/ };
  18. /******/
  19. /******/ // Execute the module function
  20. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  21. /******/
  22. /******/ // Flag the module as loaded
  23. /******/ module.l = true;
  24. /******/
  25. /******/ // Return the exports of the module
  26. /******/ return module.exports;
  27. /******/ }
  28. /******/
  29. /******/
  30. /******/ // expose the modules object (__webpack_modules__)
  31. /******/ __webpack_require__.m = modules;
  32. /******/
  33. /******/ // expose the module cache
  34. /******/ __webpack_require__.c = installedModules;
  35. /******/
  36. /******/ // define getter function for harmony exports
  37. /******/ __webpack_require__.d = function(exports, name, getter) {
  38. /******/ if(!__webpack_require__.o(exports, name)) {
  39. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  40. /******/ }
  41. /******/ };
  42. /******/
  43. /******/ // define __esModule on exports
  44. /******/ __webpack_require__.r = function(exports) {
  45. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  46. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  47. /******/ }
  48. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  49. /******/ };
  50. /******/
  51. /******/ // create a fake namespace object
  52. /******/ // mode & 1: value is a module id, require it
  53. /******/ // mode & 2: merge all properties of value into the ns
  54. /******/ // mode & 4: return value when already ns object
  55. /******/ // mode & 8|1: behave like require
  56. /******/ __webpack_require__.t = function(value, mode) {
  57. /******/ if(mode & 1) value = __webpack_require__(value);
  58. /******/ if(mode & 8) return value;
  59. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  60. /******/ var ns = Object.create(null);
  61. /******/ __webpack_require__.r(ns);
  62. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  63. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  64. /******/ return ns;
  65. /******/ };
  66. /******/
  67. /******/ // getDefaultExport function for compatibility with non-harmony modules
  68. /******/ __webpack_require__.n = function(module) {
  69. /******/ var getter = module && module.__esModule ?
  70. /******/ function getDefault() { return module['default']; } :
  71. /******/ function getModuleExports() { return module; };
  72. /******/ __webpack_require__.d(getter, 'a', getter);
  73. /******/ return getter;
  74. /******/ };
  75. /******/
  76. /******/ // Object.prototype.hasOwnProperty.call
  77. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  78. /******/
  79. /******/ // __webpack_public_path__
  80. /******/ __webpack_require__.p = "";
  81. /******/
  82. /******/
  83. /******/ // Load entry module and return exports
  84. /******/ return __webpack_require__(__webpack_require__.s = 22);
  85. /******/ })
  86. /************************************************************************/
  87. /******/ ({
  88. /***/ 22:
  89. /***/ (function(module, exports, __webpack_require__) {
  90. module.exports = __webpack_require__(23);
  91. /***/ }),
  92. /***/ 23:
  93. /***/ (function(module, exports, __webpack_require__) {
  94. /**
  95. * @output wp-includes/js/media-models.js
  96. */
  97. var $ = jQuery,
  98. Attachment, Attachments, l10n, media;
  99. /** @namespace wp */
  100. window.wp = window.wp || {};
  101. /**
  102. * Create and return a media frame.
  103. *
  104. * Handles the default media experience.
  105. *
  106. * @alias wp.media
  107. * @memberOf wp
  108. * @namespace
  109. *
  110. * @param {object} attributes The properties passed to the main media controller.
  111. * @return {wp.media.view.MediaFrame} A media workflow.
  112. */
  113. media = wp.media = function( attributes ) {
  114. var MediaFrame = media.view.MediaFrame,
  115. frame;
  116. if ( ! MediaFrame ) {
  117. return;
  118. }
  119. attributes = _.defaults( attributes || {}, {
  120. frame: 'select'
  121. });
  122. if ( 'select' === attributes.frame && MediaFrame.Select ) {
  123. frame = new MediaFrame.Select( attributes );
  124. } else if ( 'post' === attributes.frame && MediaFrame.Post ) {
  125. frame = new MediaFrame.Post( attributes );
  126. } else if ( 'manage' === attributes.frame && MediaFrame.Manage ) {
  127. frame = new MediaFrame.Manage( attributes );
  128. } else if ( 'image' === attributes.frame && MediaFrame.ImageDetails ) {
  129. frame = new MediaFrame.ImageDetails( attributes );
  130. } else if ( 'audio' === attributes.frame && MediaFrame.AudioDetails ) {
  131. frame = new MediaFrame.AudioDetails( attributes );
  132. } else if ( 'video' === attributes.frame && MediaFrame.VideoDetails ) {
  133. frame = new MediaFrame.VideoDetails( attributes );
  134. } else if ( 'edit-attachments' === attributes.frame && MediaFrame.EditAttachments ) {
  135. frame = new MediaFrame.EditAttachments( attributes );
  136. }
  137. delete attributes.frame;
  138. media.frame = frame;
  139. return frame;
  140. };
  141. /** @namespace wp.media.model */
  142. /** @namespace wp.media.view */
  143. /** @namespace wp.media.controller */
  144. /** @namespace wp.media.frames */
  145. _.extend( media, { model: {}, view: {}, controller: {}, frames: {} });
  146. // Link any localized strings.
  147. l10n = media.model.l10n = window._wpMediaModelsL10n || {};
  148. // Link any settings.
  149. media.model.settings = l10n.settings || {};
  150. delete l10n.settings;
  151. Attachment = media.model.Attachment = __webpack_require__( 24 );
  152. Attachments = media.model.Attachments = __webpack_require__( 25 );
  153. media.model.Query = __webpack_require__( 26 );
  154. media.model.PostImage = __webpack_require__( 27 );
  155. media.model.Selection = __webpack_require__( 28 );
  156. /**
  157. * ========================================================================
  158. * UTILITIES
  159. * ========================================================================
  160. */
  161. /**
  162. * A basic equality comparator for Backbone models.
  163. *
  164. * Used to order models within a collection - @see wp.media.model.Attachments.comparator().
  165. *
  166. * @param {mixed} a The primary parameter to compare.
  167. * @param {mixed} b The primary parameter to compare.
  168. * @param {string} ac The fallback parameter to compare, a's cid.
  169. * @param {string} bc The fallback parameter to compare, b's cid.
  170. * @return {number} -1: a should come before b.
  171. * 0: a and b are of the same rank.
  172. * 1: b should come before a.
  173. */
  174. media.compare = function( a, b, ac, bc ) {
  175. if ( _.isEqual( a, b ) ) {
  176. return ac === bc ? 0 : (ac > bc ? -1 : 1);
  177. } else {
  178. return a > b ? -1 : 1;
  179. }
  180. };
  181. _.extend( media, /** @lends wp.media */{
  182. /**
  183. * media.template( id )
  184. *
  185. * Fetch a JavaScript template for an id, and return a templating function for it.
  186. *
  187. * See wp.template() in `wp-includes/js/wp-util.js`.
  188. *
  189. * @borrows wp.template as template
  190. */
  191. template: wp.template,
  192. /**
  193. * media.post( [action], [data] )
  194. *
  195. * Sends a POST request to WordPress.
  196. * See wp.ajax.post() in `wp-includes/js/wp-util.js`.
  197. *
  198. * @borrows wp.ajax.post as post
  199. */
  200. post: wp.ajax.post,
  201. /**
  202. * media.ajax( [action], [options] )
  203. *
  204. * Sends an XHR request to WordPress.
  205. * See wp.ajax.send() in `wp-includes/js/wp-util.js`.
  206. *
  207. * @borrows wp.ajax.send as ajax
  208. */
  209. ajax: wp.ajax.send,
  210. /**
  211. * Scales a set of dimensions to fit within bounding dimensions.
  212. *
  213. * @param {Object} dimensions
  214. * @returns {Object}
  215. */
  216. fit: function( dimensions ) {
  217. var width = dimensions.width,
  218. height = dimensions.height,
  219. maxWidth = dimensions.maxWidth,
  220. maxHeight = dimensions.maxHeight,
  221. constraint;
  222. // Compare ratios between the two values to determine which
  223. // max to constrain by. If a max value doesn't exist, then the
  224. // opposite side is the constraint.
  225. if ( ! _.isUndefined( maxWidth ) && ! _.isUndefined( maxHeight ) ) {
  226. constraint = ( width / height > maxWidth / maxHeight ) ? 'width' : 'height';
  227. } else if ( _.isUndefined( maxHeight ) ) {
  228. constraint = 'width';
  229. } else if ( _.isUndefined( maxWidth ) && height > maxHeight ) {
  230. constraint = 'height';
  231. }
  232. // If the value of the constrained side is larger than the max,
  233. // then scale the values. Otherwise return the originals; they fit.
  234. if ( 'width' === constraint && width > maxWidth ) {
  235. return {
  236. width : maxWidth,
  237. height: Math.round( maxWidth * height / width )
  238. };
  239. } else if ( 'height' === constraint && height > maxHeight ) {
  240. return {
  241. width : Math.round( maxHeight * width / height ),
  242. height: maxHeight
  243. };
  244. } else {
  245. return {
  246. width : width,
  247. height: height
  248. };
  249. }
  250. },
  251. /**
  252. * Truncates a string by injecting an ellipsis into the middle.
  253. * Useful for filenames.
  254. *
  255. * @param {String} string
  256. * @param {Number} [length=30]
  257. * @param {String} [replacement=…]
  258. * @returns {String} The string, unless length is greater than string.length.
  259. */
  260. truncate: function( string, length, replacement ) {
  261. length = length || 30;
  262. replacement = replacement || '…';
  263. if ( string.length <= length ) {
  264. return string;
  265. }
  266. return string.substr( 0, length / 2 ) + replacement + string.substr( -1 * length / 2 );
  267. }
  268. });
  269. /**
  270. * ========================================================================
  271. * MODELS
  272. * ========================================================================
  273. */
  274. /**
  275. * wp.media.attachment
  276. *
  277. * @static
  278. * @param {String} id A string used to identify a model.
  279. * @returns {wp.media.model.Attachment}
  280. */
  281. media.attachment = function( id ) {
  282. return Attachment.get( id );
  283. };
  284. /**
  285. * A collection of all attachments that have been fetched from the server.
  286. *
  287. * @static
  288. * @member {wp.media.model.Attachments}
  289. */
  290. Attachments.all = new Attachments();
  291. /**
  292. * wp.media.query
  293. *
  294. * Shorthand for creating a new Attachments Query.
  295. *
  296. * @param {object} [props]
  297. * @returns {wp.media.model.Attachments}
  298. */
  299. media.query = function( props ) {
  300. return new Attachments( null, {
  301. props: _.extend( _.defaults( props || {}, { orderby: 'date' } ), { query: true } )
  302. });
  303. };
  304. // Clean up. Prevents mobile browsers caching
  305. $(window).on('unload', function(){
  306. window.wp = null;
  307. });
  308. /***/ }),
  309. /***/ 24:
  310. /***/ (function(module, exports) {
  311. var $ = Backbone.$,
  312. Attachment;
  313. /**
  314. * wp.media.model.Attachment
  315. *
  316. * @memberOf wp.media.model
  317. *
  318. * @class
  319. * @augments Backbone.Model
  320. */
  321. Attachment = Backbone.Model.extend(/** @lends wp.media.model.Attachment.prototype */{
  322. /**
  323. * Triggered when attachment details change
  324. * Overrides Backbone.Model.sync
  325. *
  326. * @param {string} method
  327. * @param {wp.media.model.Attachment} model
  328. * @param {Object} [options={}]
  329. *
  330. * @returns {Promise}
  331. */
  332. sync: function( method, model, options ) {
  333. // If the attachment does not yet have an `id`, return an instantly
  334. // rejected promise. Otherwise, all of our requests will fail.
  335. if ( _.isUndefined( this.id ) ) {
  336. return $.Deferred().rejectWith( this ).promise();
  337. }
  338. // Overload the `read` request so Attachment.fetch() functions correctly.
  339. if ( 'read' === method ) {
  340. options = options || {};
  341. options.context = this;
  342. options.data = _.extend( options.data || {}, {
  343. action: 'get-attachment',
  344. id: this.id
  345. });
  346. return wp.media.ajax( options );
  347. // Overload the `update` request so properties can be saved.
  348. } else if ( 'update' === method ) {
  349. // If we do not have the necessary nonce, fail immeditately.
  350. if ( ! this.get('nonces') || ! this.get('nonces').update ) {
  351. return $.Deferred().rejectWith( this ).promise();
  352. }
  353. options = options || {};
  354. options.context = this;
  355. // Set the action and ID.
  356. options.data = _.extend( options.data || {}, {
  357. action: 'save-attachment',
  358. id: this.id,
  359. nonce: this.get('nonces').update,
  360. post_id: wp.media.model.settings.post.id
  361. });
  362. // Record the values of the changed attributes.
  363. if ( model.hasChanged() ) {
  364. options.data.changes = {};
  365. _.each( model.changed, function( value, key ) {
  366. options.data.changes[ key ] = this.get( key );
  367. }, this );
  368. }
  369. return wp.media.ajax( options );
  370. // Overload the `delete` request so attachments can be removed.
  371. // This will permanently delete an attachment.
  372. } else if ( 'delete' === method ) {
  373. options = options || {};
  374. if ( ! options.wait ) {
  375. this.destroyed = true;
  376. }
  377. options.context = this;
  378. options.data = _.extend( options.data || {}, {
  379. action: 'delete-post',
  380. id: this.id,
  381. _wpnonce: this.get('nonces')['delete']
  382. });
  383. return wp.media.ajax( options ).done( function() {
  384. this.destroyed = true;
  385. }).fail( function() {
  386. this.destroyed = false;
  387. });
  388. // Otherwise, fall back to `Backbone.sync()`.
  389. } else {
  390. /**
  391. * Call `sync` directly on Backbone.Model
  392. */
  393. return Backbone.Model.prototype.sync.apply( this, arguments );
  394. }
  395. },
  396. /**
  397. * Convert date strings into Date objects.
  398. *
  399. * @param {Object} resp The raw response object, typically returned by fetch()
  400. * @returns {Object} The modified response object, which is the attributes hash
  401. * to be set on the model.
  402. */
  403. parse: function( resp ) {
  404. if ( ! resp ) {
  405. return resp;
  406. }
  407. resp.date = new Date( resp.date );
  408. resp.modified = new Date( resp.modified );
  409. return resp;
  410. },
  411. /**
  412. * @param {Object} data The properties to be saved.
  413. * @param {Object} options Sync options. e.g. patch, wait, success, error.
  414. *
  415. * @this Backbone.Model
  416. *
  417. * @returns {Promise}
  418. */
  419. saveCompat: function( data, options ) {
  420. var model = this;
  421. // If we do not have the necessary nonce, fail immeditately.
  422. if ( ! this.get('nonces') || ! this.get('nonces').update ) {
  423. return $.Deferred().rejectWith( this ).promise();
  424. }
  425. return wp.media.post( 'save-attachment-compat', _.defaults({
  426. id: this.id,
  427. nonce: this.get('nonces').update,
  428. post_id: wp.media.model.settings.post.id
  429. }, data ) ).done( function( resp, status, xhr ) {
  430. model.set( model.parse( resp, xhr ), options );
  431. });
  432. }
  433. },/** @lends wp.media.model.Attachment */{
  434. /**
  435. * Create a new model on the static 'all' attachments collection and return it.
  436. *
  437. * @static
  438. *
  439. * @param {Object} attrs
  440. * @returns {wp.media.model.Attachment}
  441. */
  442. create: function( attrs ) {
  443. var Attachments = wp.media.model.Attachments;
  444. return Attachments.all.push( attrs );
  445. },
  446. /**
  447. * Create a new model on the static 'all' attachments collection and return it.
  448. *
  449. * If this function has already been called for the id,
  450. * it returns the specified attachment.
  451. *
  452. * @static
  453. * @param {string} id A string used to identify a model.
  454. * @param {Backbone.Model|undefined} attachment
  455. * @returns {wp.media.model.Attachment}
  456. */
  457. get: _.memoize( function( id, attachment ) {
  458. var Attachments = wp.media.model.Attachments;
  459. return Attachments.all.push( attachment || { id: id } );
  460. })
  461. });
  462. module.exports = Attachment;
  463. /***/ }),
  464. /***/ 25:
  465. /***/ (function(module, exports) {
  466. /**
  467. * wp.media.model.Attachments
  468. *
  469. * A collection of attachments.
  470. *
  471. * This collection has no persistence with the server without supplying
  472. * 'options.props.query = true', which will mirror the collection
  473. * to an Attachments Query collection - @see wp.media.model.Attachments.mirror().
  474. *
  475. * @memberOf wp.media.model
  476. *
  477. * @class
  478. * @augments Backbone.Collection
  479. *
  480. * @param {array} [models] Models to initialize with the collection.
  481. * @param {object} [options] Options hash for the collection.
  482. * @param {string} [options.props] Options hash for the initial query properties.
  483. * @param {string} [options.props.order] Initial order (ASC or DESC) for the collection.
  484. * @param {string} [options.props.orderby] Initial attribute key to order the collection by.
  485. * @param {string} [options.props.query] Whether the collection is linked to an attachments query.
  486. * @param {string} [options.observe]
  487. * @param {string} [options.filters]
  488. *
  489. */
  490. var Attachments = Backbone.Collection.extend(/** @lends wp.media.model.Attachments.prototype */{
  491. /**
  492. * @type {wp.media.model.Attachment}
  493. */
  494. model: wp.media.model.Attachment,
  495. /**
  496. * @param {Array} [models=[]] Array of models used to populate the collection.
  497. * @param {Object} [options={}]
  498. */
  499. initialize: function( models, options ) {
  500. options = options || {};
  501. this.props = new Backbone.Model();
  502. this.filters = options.filters || {};
  503. // Bind default `change` events to the `props` model.
  504. this.props.on( 'change', this._changeFilteredProps, this );
  505. this.props.on( 'change:order', this._changeOrder, this );
  506. this.props.on( 'change:orderby', this._changeOrderby, this );
  507. this.props.on( 'change:query', this._changeQuery, this );
  508. this.props.set( _.defaults( options.props || {} ) );
  509. if ( options.observe ) {
  510. this.observe( options.observe );
  511. }
  512. },
  513. /**
  514. * Sort the collection when the order attribute changes.
  515. *
  516. * @access private
  517. */
  518. _changeOrder: function() {
  519. if ( this.comparator ) {
  520. this.sort();
  521. }
  522. },
  523. /**
  524. * Set the default comparator only when the `orderby` property is set.
  525. *
  526. * @access private
  527. *
  528. * @param {Backbone.Model} model
  529. * @param {string} orderby
  530. */
  531. _changeOrderby: function( model, orderby ) {
  532. // If a different comparator is defined, bail.
  533. if ( this.comparator && this.comparator !== Attachments.comparator ) {
  534. return;
  535. }
  536. if ( orderby && 'post__in' !== orderby ) {
  537. this.comparator = Attachments.comparator;
  538. } else {
  539. delete this.comparator;
  540. }
  541. },
  542. /**
  543. * If the `query` property is set to true, query the server using
  544. * the `props` values, and sync the results to this collection.
  545. *
  546. * @access private
  547. *
  548. * @param {Backbone.Model} model
  549. * @param {Boolean} query
  550. */
  551. _changeQuery: function( model, query ) {
  552. if ( query ) {
  553. this.props.on( 'change', this._requery, this );
  554. this._requery();
  555. } else {
  556. this.props.off( 'change', this._requery, this );
  557. }
  558. },
  559. /**
  560. * @access private
  561. *
  562. * @param {Backbone.Model} model
  563. */
  564. _changeFilteredProps: function( model ) {
  565. // If this is a query, updating the collection will be handled by
  566. // `this._requery()`.
  567. if ( this.props.get('query') ) {
  568. return;
  569. }
  570. var changed = _.chain( model.changed ).map( function( t, prop ) {
  571. var filter = Attachments.filters[ prop ],
  572. term = model.get( prop );
  573. if ( ! filter ) {
  574. return;
  575. }
  576. if ( term && ! this.filters[ prop ] ) {
  577. this.filters[ prop ] = filter;
  578. } else if ( ! term && this.filters[ prop ] === filter ) {
  579. delete this.filters[ prop ];
  580. } else {
  581. return;
  582. }
  583. // Record the change.
  584. return true;
  585. }, this ).any().value();
  586. if ( ! changed ) {
  587. return;
  588. }
  589. // If no `Attachments` model is provided to source the searches
  590. // from, then automatically generate a source from the existing
  591. // models.
  592. if ( ! this._source ) {
  593. this._source = new Attachments( this.models );
  594. }
  595. this.reset( this._source.filter( this.validator, this ) );
  596. },
  597. validateDestroyed: false,
  598. /**
  599. * Checks whether an attachment is valid.
  600. *
  601. * @param {wp.media.model.Attachment} attachment
  602. * @returns {Boolean}
  603. */
  604. validator: function( attachment ) {
  605. // Filter out contextually created attachments (e.g. headers, logos, etc.).
  606. if (
  607. ! _.isUndefined( attachment.attributes.context ) &&
  608. '' !== attachment.attributes.context
  609. ) {
  610. return false;
  611. }
  612. if ( ! this.validateDestroyed && attachment.destroyed ) {
  613. return false;
  614. }
  615. return _.all( this.filters, function( filter ) {
  616. return !! filter.call( this, attachment );
  617. }, this );
  618. },
  619. /**
  620. * Add or remove an attachment to the collection depending on its validity.
  621. *
  622. * @param {wp.media.model.Attachment} attachment
  623. * @param {Object} options
  624. * @returns {wp.media.model.Attachments} Returns itself to allow chaining
  625. */
  626. validate: function( attachment, options ) {
  627. var valid = this.validator( attachment ),
  628. hasAttachment = !! this.get( attachment.cid );
  629. if ( ! valid && hasAttachment ) {
  630. this.remove( attachment, options );
  631. } else if ( valid && ! hasAttachment ) {
  632. this.add( attachment, options );
  633. }
  634. return this;
  635. },
  636. /**
  637. * Add or remove all attachments from another collection depending on each one's validity.
  638. *
  639. * @param {wp.media.model.Attachments} attachments
  640. * @param {object} [options={}]
  641. *
  642. * @fires wp.media.model.Attachments#reset
  643. *
  644. * @returns {wp.media.model.Attachments} Returns itself to allow chaining
  645. */
  646. validateAll: function( attachments, options ) {
  647. options = options || {};
  648. _.each( attachments.models, function( attachment ) {
  649. this.validate( attachment, { silent: true });
  650. }, this );
  651. if ( ! options.silent ) {
  652. this.trigger( 'reset', this, options );
  653. }
  654. return this;
  655. },
  656. /**
  657. * Start observing another attachments collection change events
  658. * and replicate them on this collection.
  659. *
  660. * @param {wp.media.model.Attachments} The attachments collection to observe.
  661. * @returns {wp.media.model.Attachments} Returns itself to allow chaining.
  662. */
  663. observe: function( attachments ) {
  664. this.observers = this.observers || [];
  665. this.observers.push( attachments );
  666. attachments.on( 'add change remove', this._validateHandler, this );
  667. attachments.on( 'reset', this._validateAllHandler, this );
  668. this.validateAll( attachments );
  669. return this;
  670. },
  671. /**
  672. * Stop replicating collection change events from another attachments collection.
  673. *
  674. * @param {wp.media.model.Attachments} The attachments collection to stop observing.
  675. * @returns {wp.media.model.Attachments} Returns itself to allow chaining
  676. */
  677. unobserve: function( attachments ) {
  678. if ( attachments ) {
  679. attachments.off( null, null, this );
  680. this.observers = _.without( this.observers, attachments );
  681. } else {
  682. _.each( this.observers, function( attachments ) {
  683. attachments.off( null, null, this );
  684. }, this );
  685. delete this.observers;
  686. }
  687. return this;
  688. },
  689. /**
  690. * @access private
  691. *
  692. * @param {wp.media.model.Attachments} attachment
  693. * @param {wp.media.model.Attachments} attachments
  694. * @param {Object} options
  695. *
  696. * @returns {wp.media.model.Attachments} Returns itself to allow chaining
  697. */
  698. _validateHandler: function( attachment, attachments, options ) {
  699. // If we're not mirroring this `attachments` collection,
  700. // only retain the `silent` option.
  701. options = attachments === this.mirroring ? options : {
  702. silent: options && options.silent
  703. };
  704. return this.validate( attachment, options );
  705. },
  706. /**
  707. * @access private
  708. *
  709. * @param {wp.media.model.Attachments} attachments
  710. * @param {Object} options
  711. * @returns {wp.media.model.Attachments} Returns itself to allow chaining
  712. */
  713. _validateAllHandler: function( attachments, options ) {
  714. return this.validateAll( attachments, options );
  715. },
  716. /**
  717. * Start mirroring another attachments collection, clearing out any models already
  718. * in the collection.
  719. *
  720. * @param {wp.media.model.Attachments} The attachments collection to mirror.
  721. * @returns {wp.media.model.Attachments} Returns itself to allow chaining
  722. */
  723. mirror: function( attachments ) {
  724. if ( this.mirroring && this.mirroring === attachments ) {
  725. return this;
  726. }
  727. this.unmirror();
  728. this.mirroring = attachments;
  729. // Clear the collection silently. A `reset` event will be fired
  730. // when `observe()` calls `validateAll()`.
  731. this.reset( [], { silent: true } );
  732. this.observe( attachments );
  733. // Used for the search results.
  734. this.trigger( 'attachments:received', this );
  735. return this;
  736. },
  737. /**
  738. * Stop mirroring another attachments collection.
  739. */
  740. unmirror: function() {
  741. if ( ! this.mirroring ) {
  742. return;
  743. }
  744. this.unobserve( this.mirroring );
  745. delete this.mirroring;
  746. },
  747. /**
  748. * Retrieve more attachments from the server for the collection.
  749. *
  750. * Only works if the collection is mirroring a Query Attachments collection,
  751. * and forwards to its `more` method. This collection class doesn't have
  752. * server persistence by itself.
  753. *
  754. * @param {object} options
  755. * @returns {Promise}
  756. */
  757. more: function( options ) {
  758. var deferred = jQuery.Deferred(),
  759. mirroring = this.mirroring,
  760. attachments = this;
  761. if ( ! mirroring || ! mirroring.more ) {
  762. return deferred.resolveWith( this ).promise();
  763. }
  764. // If we're mirroring another collection, forward `more` to
  765. // the mirrored collection. Account for a race condition by
  766. // checking if we're still mirroring that collection when
  767. // the request resolves.
  768. mirroring.more( options ).done( function() {
  769. if ( this === attachments.mirroring ) {
  770. deferred.resolveWith( this );
  771. }
  772. // Used for the search results.
  773. attachments.trigger( 'attachments:received', this );
  774. });
  775. return deferred.promise();
  776. },
  777. /**
  778. * Whether there are more attachments that haven't been sync'd from the server
  779. * that match the collection's query.
  780. *
  781. * Only works if the collection is mirroring a Query Attachments collection,
  782. * and forwards to its `hasMore` method. This collection class doesn't have
  783. * server persistence by itself.
  784. *
  785. * @returns {boolean}
  786. */
  787. hasMore: function() {
  788. return this.mirroring ? this.mirroring.hasMore() : false;
  789. },
  790. /**
  791. * A custom AJAX-response parser.
  792. *
  793. * See trac ticket #24753
  794. *
  795. * @param {Object|Array} resp The raw response Object/Array.
  796. * @param {Object} xhr
  797. * @returns {Array} The array of model attributes to be added to the collection
  798. */
  799. parse: function( resp, xhr ) {
  800. if ( ! _.isArray( resp ) ) {
  801. resp = [resp];
  802. }
  803. return _.map( resp, function( attrs ) {
  804. var id, attachment, newAttributes;
  805. if ( attrs instanceof Backbone.Model ) {
  806. id = attrs.get( 'id' );
  807. attrs = attrs.attributes;
  808. } else {
  809. id = attrs.id;
  810. }
  811. attachment = wp.media.model.Attachment.get( id );
  812. newAttributes = attachment.parse( attrs, xhr );
  813. if ( ! _.isEqual( attachment.attributes, newAttributes ) ) {
  814. attachment.set( newAttributes );
  815. }
  816. return attachment;
  817. });
  818. },
  819. /**
  820. * If the collection is a query, create and mirror an Attachments Query collection.
  821. *
  822. * @access private
  823. */
  824. _requery: function( refresh ) {
  825. var props;
  826. if ( this.props.get('query') ) {
  827. props = this.props.toJSON();
  828. props.cache = ( true !== refresh );
  829. this.mirror( wp.media.model.Query.get( props ) );
  830. }
  831. },
  832. /**
  833. * If this collection is sorted by `menuOrder`, recalculates and saves
  834. * the menu order to the database.
  835. *
  836. * @returns {undefined|Promise}
  837. */
  838. saveMenuOrder: function() {
  839. if ( 'menuOrder' !== this.props.get('orderby') ) {
  840. return;
  841. }
  842. // Removes any uploading attachments, updates each attachment's
  843. // menu order, and returns an object with an { id: menuOrder }
  844. // mapping to pass to the request.
  845. var attachments = this.chain().filter( function( attachment ) {
  846. return ! _.isUndefined( attachment.id );
  847. }).map( function( attachment, index ) {
  848. // Indices start at 1.
  849. index = index + 1;
  850. attachment.set( 'menuOrder', index );
  851. return [ attachment.id, index ];
  852. }).object().value();
  853. if ( _.isEmpty( attachments ) ) {
  854. return;
  855. }
  856. return wp.media.post( 'save-attachment-order', {
  857. nonce: wp.media.model.settings.post.nonce,
  858. post_id: wp.media.model.settings.post.id,
  859. attachments: attachments
  860. });
  861. }
  862. },/** @lends wp.media.model.Attachments */{
  863. /**
  864. * A function to compare two attachment models in an attachments collection.
  865. *
  866. * Used as the default comparator for instances of wp.media.model.Attachments
  867. * and its subclasses. @see wp.media.model.Attachments._changeOrderby().
  868. *
  869. * @param {Backbone.Model} a
  870. * @param {Backbone.Model} b
  871. * @param {Object} options
  872. * @returns {Number} -1 if the first model should come before the second,
  873. * 0 if they are of the same rank and
  874. * 1 if the first model should come after.
  875. */
  876. comparator: function( a, b, options ) {
  877. var key = this.props.get('orderby'),
  878. order = this.props.get('order') || 'DESC',
  879. ac = a.cid,
  880. bc = b.cid;
  881. a = a.get( key );
  882. b = b.get( key );
  883. if ( 'date' === key || 'modified' === key ) {
  884. a = a || new Date();
  885. b = b || new Date();
  886. }
  887. // If `options.ties` is set, don't enforce the `cid` tiebreaker.
  888. if ( options && options.ties ) {
  889. ac = bc = null;
  890. }
  891. return ( 'DESC' === order ) ? wp.media.compare( a, b, ac, bc ) : wp.media.compare( b, a, bc, ac );
  892. },
  893. /** @namespace wp.media.model.Attachments.filters */
  894. filters: {
  895. /**
  896. * @static
  897. * Note that this client-side searching is *not* equivalent
  898. * to our server-side searching.
  899. *
  900. * @param {wp.media.model.Attachment} attachment
  901. *
  902. * @this wp.media.model.Attachments
  903. *
  904. * @returns {Boolean}
  905. */
  906. search: function( attachment ) {
  907. if ( ! this.props.get('search') ) {
  908. return true;
  909. }
  910. return _.any(['title','filename','description','caption','name'], function( key ) {
  911. var value = attachment.get( key );
  912. return value && -1 !== value.search( this.props.get('search') );
  913. }, this );
  914. },
  915. /**
  916. * @static
  917. * @param {wp.media.model.Attachment} attachment
  918. *
  919. * @this wp.media.model.Attachments
  920. *
  921. * @returns {Boolean}
  922. */
  923. type: function( attachment ) {
  924. var type = this.props.get('type'), atts = attachment.toJSON(), mime, found;
  925. if ( ! type || ( _.isArray( type ) && ! type.length ) ) {
  926. return true;
  927. }
  928. mime = atts.mime || ( atts.file && atts.file.type ) || '';
  929. if ( _.isArray( type ) ) {
  930. found = _.find( type, function (t) {
  931. return -1 !== mime.indexOf( t );
  932. } );
  933. } else {
  934. found = -1 !== mime.indexOf( type );
  935. }
  936. return found;
  937. },
  938. /**
  939. * @static
  940. * @param {wp.media.model.Attachment} attachment
  941. *
  942. * @this wp.media.model.Attachments
  943. *
  944. * @returns {Boolean}
  945. */
  946. uploadedTo: function( attachment ) {
  947. var uploadedTo = this.props.get('uploadedTo');
  948. if ( _.isUndefined( uploadedTo ) ) {
  949. return true;
  950. }
  951. return uploadedTo === attachment.get('uploadedTo');
  952. },
  953. /**
  954. * @static
  955. * @param {wp.media.model.Attachment} attachment
  956. *
  957. * @this wp.media.model.Attachments
  958. *
  959. * @returns {Boolean}
  960. */
  961. status: function( attachment ) {
  962. var status = this.props.get('status');
  963. if ( _.isUndefined( status ) ) {
  964. return true;
  965. }
  966. return status === attachment.get('status');
  967. }
  968. }
  969. });
  970. module.exports = Attachments;
  971. /***/ }),
  972. /***/ 26:
  973. /***/ (function(module, exports) {
  974. var Attachments = wp.media.model.Attachments,
  975. Query;
  976. /**
  977. * wp.media.model.Query
  978. *
  979. * A collection of attachments that match the supplied query arguments.
  980. *
  981. * Note: Do NOT change this.args after the query has been initialized.
  982. * Things will break.
  983. *
  984. * @memberOf wp.media.model
  985. *
  986. * @class
  987. * @augments wp.media.model.Attachments
  988. * @augments Backbone.Collection
  989. *
  990. * @param {array} [models] Models to initialize with the collection.
  991. * @param {object} [options] Options hash.
  992. * @param {object} [options.args] Attachments query arguments.
  993. * @param {object} [options.args.posts_per_page]
  994. */
  995. Query = Attachments.extend(/** @lends wp.media.model.Query.prototype */{
  996. /**
  997. * @param {array} [models=[]] Array of initial models to populate the collection.
  998. * @param {object} [options={}]
  999. */
  1000. initialize: function( models, options ) {
  1001. var allowed;
  1002. options = options || {};
  1003. Attachments.prototype.initialize.apply( this, arguments );
  1004. this.args = options.args;
  1005. this._hasMore = true;
  1006. this.created = new Date();
  1007. this.filters.order = function( attachment ) {
  1008. var orderby = this.props.get('orderby'),
  1009. order = this.props.get('order');
  1010. if ( ! this.comparator ) {
  1011. return true;
  1012. }
  1013. // We want any items that can be placed before the last
  1014. // item in the set. If we add any items after the last
  1015. // item, then we can't guarantee the set is complete.
  1016. if ( this.length ) {
  1017. return 1 !== this.comparator( attachment, this.last(), { ties: true });
  1018. // Handle the case where there are no items yet and
  1019. // we're sorting for recent items. In that case, we want
  1020. // changes that occurred after we created the query.
  1021. } else if ( 'DESC' === order && ( 'date' === orderby || 'modified' === orderby ) ) {
  1022. return attachment.get( orderby ) >= this.created;
  1023. // If we're sorting by menu order and we have no items,
  1024. // accept any items that have the default menu order (0).
  1025. } else if ( 'ASC' === order && 'menuOrder' === orderby ) {
  1026. return attachment.get( orderby ) === 0;
  1027. }
  1028. // Otherwise, we don't want any items yet.
  1029. return false;
  1030. };
  1031. // Observe the central `wp.Uploader.queue` collection to watch for
  1032. // new matches for the query.
  1033. //
  1034. // Only observe when a limited number of query args are set. There
  1035. // are no filters for other properties, so observing will result in
  1036. // false positives in those queries.
  1037. allowed = [ 's', 'order', 'orderby', 'posts_per_page', 'post_mime_type', 'post_parent', 'author' ];
  1038. if ( wp.Uploader && _( this.args ).chain().keys().difference( allowed ).isEmpty().value() ) {
  1039. this.observe( wp.Uploader.queue );
  1040. }
  1041. },
  1042. /**
  1043. * Whether there are more attachments that haven't been sync'd from the server
  1044. * that match the collection's query.
  1045. *
  1046. * @returns {boolean}
  1047. */
  1048. hasMore: function() {
  1049. return this._hasMore;
  1050. },
  1051. /**
  1052. * Fetch more attachments from the server for the collection.
  1053. *
  1054. * @param {object} [options={}]
  1055. * @returns {Promise}
  1056. */
  1057. more: function( options ) {
  1058. var query = this;
  1059. // If there is already a request pending, return early with the Deferred object.
  1060. if ( this._more && 'pending' === this._more.state() ) {
  1061. return this._more;
  1062. }
  1063. if ( ! this.hasMore() ) {
  1064. return jQuery.Deferred().resolveWith( this ).promise();
  1065. }
  1066. options = options || {};
  1067. options.remove = false;
  1068. return this._more = this.fetch( options ).done( function( resp ) {
  1069. if ( _.isEmpty( resp ) || -1 === this.args.posts_per_page || resp.length < this.args.posts_per_page ) {
  1070. query._hasMore = false;
  1071. }
  1072. });
  1073. },
  1074. /**
  1075. * Overrides Backbone.Collection.sync
  1076. * Overrides wp.media.model.Attachments.sync
  1077. *
  1078. * @param {String} method
  1079. * @param {Backbone.Model} model
  1080. * @param {Object} [options={}]
  1081. * @returns {Promise}
  1082. */
  1083. sync: function( method, model, options ) {
  1084. var args, fallback;
  1085. // Overload the read method so Attachment.fetch() functions correctly.
  1086. if ( 'read' === method ) {
  1087. options = options || {};
  1088. options.context = this;
  1089. options.data = _.extend( options.data || {}, {
  1090. action: 'query-attachments',
  1091. post_id: wp.media.model.settings.post.id
  1092. });
  1093. // Clone the args so manipulation is non-destructive.
  1094. args = _.clone( this.args );
  1095. // Determine which page to query.
  1096. if ( -1 !== args.posts_per_page ) {
  1097. args.paged = Math.round( this.length / args.posts_per_page ) + 1;
  1098. }
  1099. options.data.query = args;
  1100. return wp.media.ajax( options );
  1101. // Otherwise, fall back to Backbone.sync()
  1102. } else {
  1103. /**
  1104. * Call wp.media.model.Attachments.sync or Backbone.sync
  1105. */
  1106. fallback = Attachments.prototype.sync ? Attachments.prototype : Backbone;
  1107. return fallback.sync.apply( this, arguments );
  1108. }
  1109. }
  1110. }, /** @lends wp.media.model.Query */{
  1111. /**
  1112. * @readonly
  1113. */
  1114. defaultProps: {
  1115. orderby: 'date',
  1116. order: 'DESC'
  1117. },
  1118. /**
  1119. * @readonly
  1120. */
  1121. defaultArgs: {
  1122. posts_per_page: 40
  1123. },
  1124. /**
  1125. * @readonly
  1126. */
  1127. orderby: {
  1128. allowed: [ 'name', 'author', 'date', 'title', 'modified', 'uploadedTo', 'id', 'post__in', 'menuOrder' ],
  1129. /**
  1130. * A map of JavaScript orderby values to their WP_Query equivalents.
  1131. * @type {Object}
  1132. */
  1133. valuemap: {
  1134. 'id': 'ID',
  1135. 'uploadedTo': 'parent',
  1136. 'menuOrder': 'menu_order ID'
  1137. }
  1138. },
  1139. /**
  1140. * A map of JavaScript query properties to their WP_Query equivalents.
  1141. *
  1142. * @readonly
  1143. */
  1144. propmap: {
  1145. 'search': 's',
  1146. 'type': 'post_mime_type',
  1147. 'perPage': 'posts_per_page',
  1148. 'menuOrder': 'menu_order',
  1149. 'uploadedTo': 'post_parent',
  1150. 'status': 'post_status',
  1151. 'include': 'post__in',
  1152. 'exclude': 'post__not_in',
  1153. 'author': 'author'
  1154. },
  1155. /**
  1156. * Creates and returns an Attachments Query collection given the properties.
  1157. *
  1158. * Caches query objects and reuses where possible.
  1159. *
  1160. * @static
  1161. * @method
  1162. *
  1163. * @param {object} [props]
  1164. * @param {Object} [props.cache=true] Whether to use the query cache or not.
  1165. * @param {Object} [props.order]
  1166. * @param {Object} [props.orderby]
  1167. * @param {Object} [props.include]
  1168. * @param {Object} [props.exclude]
  1169. * @param {Object} [props.s]
  1170. * @param {Object} [props.post_mime_type]
  1171. * @param {Object} [props.posts_per_page]
  1172. * @param {Object} [props.menu_order]
  1173. * @param {Object} [props.post_parent]
  1174. * @param {Object} [props.post_status]
  1175. * @param {Object} [props.author]
  1176. * @param {Object} [options]
  1177. *
  1178. * @returns {wp.media.model.Query} A new Attachments Query collection.
  1179. */
  1180. get: (function(){
  1181. /**
  1182. * @static
  1183. * @type Array
  1184. */
  1185. var queries = [];
  1186. /**
  1187. * @returns {Query}
  1188. */
  1189. return function( props, options ) {
  1190. var args = {},
  1191. orderby = Query.orderby,
  1192. defaults = Query.defaultProps,
  1193. query,
  1194. cache = !! props.cache || _.isUndefined( props.cache );
  1195. // Remove the `query` property. This isn't linked to a query,
  1196. // this *is* the query.
  1197. delete props.query;
  1198. delete props.cache;
  1199. // Fill default args.
  1200. _.defaults( props, defaults );
  1201. // Normalize the order.
  1202. props.order = props.order.toUpperCase();
  1203. if ( 'DESC' !== props.order && 'ASC' !== props.order ) {
  1204. props.order = defaults.order.toUpperCase();
  1205. }
  1206. // Ensure we have a valid orderby value.
  1207. if ( ! _.contains( orderby.allowed, props.orderby ) ) {
  1208. props.orderby = defaults.orderby;
  1209. }
  1210. _.each( [ 'include', 'exclude' ], function( prop ) {
  1211. if ( props[ prop ] && ! _.isArray( props[ prop ] ) ) {
  1212. props[ prop ] = [ props[ prop ] ];
  1213. }
  1214. } );
  1215. // Generate the query `args` object.
  1216. // Correct any differing property names.
  1217. _.each( props, function( value, prop ) {
  1218. if ( _.isNull( value ) ) {
  1219. return;
  1220. }
  1221. args[ Query.propmap[ prop ] || prop ] = value;
  1222. });
  1223. // Fill any other default query args.
  1224. _.defaults( args, Query.defaultArgs );
  1225. // `props.orderby` does not always map directly to `args.orderby`.
  1226. // Substitute exceptions specified in orderby.keymap.
  1227. args.orderby = orderby.valuemap[ props.orderby ] || props.orderby;
  1228. // Search the query cache for a matching query.
  1229. if ( cache ) {
  1230. query = _.find( queries, function( query ) {
  1231. return _.isEqual( query.args, args );
  1232. });
  1233. } else {
  1234. queries = [];
  1235. }
  1236. // Otherwise, create a new query and add it to the cache.
  1237. if ( ! query ) {
  1238. query = new Query( [], _.extend( options || {}, {
  1239. props: props,
  1240. args: args
  1241. } ) );
  1242. queries.push( query );
  1243. }
  1244. return query;
  1245. };
  1246. }())
  1247. });
  1248. module.exports = Query;
  1249. /***/ }),
  1250. /***/ 27:
  1251. /***/ (function(module, exports) {
  1252. /**
  1253. * wp.media.model.PostImage
  1254. *
  1255. * An instance of an image that's been embedded into a post.
  1256. *
  1257. * Used in the embedded image attachment display settings modal - @see wp.media.view.MediaFrame.ImageDetails.
  1258. *
  1259. * @memberOf wp.media.model
  1260. *
  1261. * @class
  1262. * @augments Backbone.Model
  1263. *
  1264. * @param {int} [attributes] Initial model attributes.
  1265. * @param {int} [attributes.attachment_id] ID of the attachment.
  1266. **/
  1267. var PostImage = Backbone.Model.extend(/** @lends wp.media.model.PostImage.prototype */{
  1268. initialize: function( attributes ) {
  1269. var Attachment = wp.media.model.Attachment;
  1270. this.attachment = false;
  1271. if ( attributes.attachment_id ) {
  1272. this.attachment = Attachment.get( attributes.attachment_id );
  1273. if ( this.attachment.get( 'url' ) ) {
  1274. this.dfd = jQuery.Deferred();
  1275. this.dfd.resolve();
  1276. } else {
  1277. this.dfd = this.attachment.fetch();
  1278. }
  1279. this.bindAttachmentListeners();
  1280. }
  1281. // keep url in sync with changes to the type of link
  1282. this.on( 'change:link', this.updateLinkUrl, this );
  1283. this.on( 'change:size', this.updateSize, this );
  1284. this.setLinkTypeFromUrl();
  1285. this.setAspectRatio();
  1286. this.set( 'originalUrl', attributes.url );
  1287. },
  1288. bindAttachmentListeners: function() {
  1289. this.listenTo( this.attachment, 'sync', this.setLinkTypeFromUrl );
  1290. this.listenTo( this.attachment, 'sync', this.setAspectRatio );
  1291. this.listenTo( this.attachment, 'change', this.updateSize );
  1292. },
  1293. changeAttachment: function( attachment, props ) {
  1294. this.stopListening( this.attachment );
  1295. this.attachment = attachment;
  1296. this.bindAttachmentListeners();
  1297. this.set( 'attachment_id', this.attachment.get( 'id' ) );
  1298. this.set( 'caption', this.attachment.get( 'caption' ) );
  1299. this.set( 'alt', this.attachment.get( 'alt' ) );
  1300. this.set( 'size', props.get( 'size' ) );
  1301. this.set( 'align', props.get( 'align' ) );
  1302. this.set( 'link', props.get( 'link' ) );
  1303. this.updateLinkUrl();
  1304. this.updateSize();
  1305. },
  1306. setLinkTypeFromUrl: function() {
  1307. var linkUrl = this.get( 'linkUrl' ),
  1308. type;
  1309. if ( ! linkUrl ) {
  1310. this.set( 'link', 'none' );
  1311. return;
  1312. }
  1313. // default to custom if there is a linkUrl
  1314. type = 'custom';
  1315. if ( this.attachment ) {
  1316. if ( this.attachment.get( 'url' ) === linkUrl ) {
  1317. type = 'file';
  1318. } else if ( this.attachment.get( 'link' ) === linkUrl ) {
  1319. type = 'post';
  1320. }
  1321. } else {
  1322. if ( this.get( 'url' ) === linkUrl ) {
  1323. type = 'file';
  1324. }
  1325. }
  1326. this.set( 'link', type );
  1327. },
  1328. updateLinkUrl: function() {
  1329. var link = this.get( 'link' ),
  1330. url;
  1331. switch( link ) {
  1332. case 'file':
  1333. if ( this.attachment ) {
  1334. url = this.attachment.get( 'url' );
  1335. } else {
  1336. url = this.get( 'url' );
  1337. }
  1338. this.set( 'linkUrl', url );
  1339. break;
  1340. case 'post':
  1341. this.set( 'linkUrl', this.attachment.get( 'link' ) );
  1342. break;
  1343. case 'none':
  1344. this.set( 'linkUrl', '' );
  1345. break;
  1346. }
  1347. },
  1348. updateSize: function() {
  1349. var size;
  1350. if ( ! this.attachment ) {
  1351. return;
  1352. }
  1353. if ( this.get( 'size' ) === 'custom' ) {
  1354. this.set( 'width', this.get( 'customWidth' ) );
  1355. this.set( 'height', this.get( 'customHeight' ) );
  1356. this.set( 'url', this.get( 'originalUrl' ) );
  1357. return;
  1358. }
  1359. size = this.attachment.get( 'sizes' )[ this.get( 'size' ) ];
  1360. if ( ! size ) {
  1361. return;
  1362. }
  1363. this.set( 'url', size.url );
  1364. this.set( 'width', size.width );
  1365. this.set( 'height', size.height );
  1366. },
  1367. setAspectRatio: function() {
  1368. var full;
  1369. if ( this.attachment && this.attachment.get( 'sizes' ) ) {
  1370. full = this.attachment.get( 'sizes' ).full;
  1371. if ( full ) {
  1372. this.set( 'aspectRatio', full.width / full.height );
  1373. return;
  1374. }
  1375. }
  1376. this.set( 'aspectRatio', this.get( 'customWidth' ) / this.get( 'customHeight' ) );
  1377. }
  1378. });
  1379. module.exports = PostImage;
  1380. /***/ }),
  1381. /***/ 28:
  1382. /***/ (function(module, exports) {
  1383. var Attachments = wp.media.model.Attachments,
  1384. Selection;
  1385. /**
  1386. * wp.media.model.Selection
  1387. *
  1388. * A selection of attachments.
  1389. *
  1390. * @memberOf wp.media.model
  1391. *
  1392. * @class
  1393. * @augments wp.media.model.Attachments
  1394. * @augments Backbone.Collection
  1395. */
  1396. Selection = Attachments.extend(/** @lends wp.media.model.Selection.prototype */{
  1397. /**
  1398. * Refresh the `single` model whenever the selection changes.
  1399. * Binds `single` instead of using the context argument to ensure
  1400. * it receives no parameters.
  1401. *
  1402. * @param {Array} [models=[]] Array of models used to populate the collection.
  1403. * @param {Object} [options={}]
  1404. */
  1405. initialize: function( models, options ) {
  1406. /**
  1407. * call 'initialize' directly on the parent class
  1408. */
  1409. Attachments.prototype.initialize.apply( this, arguments );
  1410. this.multiple = options && options.multiple;
  1411. this.on( 'add remove reset', _.bind( this.single, this, false ) );
  1412. },
  1413. /**
  1414. * If the workflow does not support multi-select, clear out the selection
  1415. * before adding a new attachment to it.
  1416. *
  1417. * @param {Array} models
  1418. * @param {Object} options
  1419. * @returns {wp.media.model.Attachment[]}
  1420. */
  1421. add: function( models, options ) {
  1422. if ( ! this.multiple ) {
  1423. this.remove( this.models );
  1424. }
  1425. /**
  1426. * call 'add' directly on the parent class
  1427. */
  1428. return Attachments.prototype.add.call( this, models, options );
  1429. },
  1430. /**
  1431. * Fired when toggling (clicking on) an attachment in the modal.
  1432. *
  1433. * @param {undefined|boolean|wp.media.model.Attachment} model
  1434. *
  1435. * @fires wp.media.model.Selection#selection:single
  1436. * @fires wp.media.model.Selection#selection:unsingle
  1437. *
  1438. * @returns {Backbone.Model}
  1439. */
  1440. single: function( model ) {
  1441. var previous = this._single;
  1442. // If a `model` is provided, use it as the single model.
  1443. if ( model ) {
  1444. this._single = model;
  1445. }
  1446. // If the single model isn't in the selection, remove it.
  1447. if ( this._single && ! this.get( this._single.cid ) ) {
  1448. delete this._single;
  1449. }
  1450. this._single = this._single || this.last();
  1451. // If single has changed, fire an event.
  1452. if ( this._single !== previous ) {
  1453. if ( previous ) {
  1454. previous.trigger( 'selection:unsingle', previous, this );
  1455. // If the model was already removed, trigger the collection
  1456. // event manually.
  1457. if ( ! this.get( previous.cid ) ) {
  1458. this.trigger( 'selection:unsingle', previous, this );
  1459. }
  1460. }
  1461. if ( this._single ) {
  1462. this._single.trigger( 'selection:single', this._single, this );
  1463. }
  1464. }
  1465. // Return the single model, or the last model as a fallback.
  1466. return this._single;
  1467. }
  1468. });
  1469. module.exports = Selection;
  1470. /***/ })
  1471. /******/ });