PageRenderTime 69ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/wordpress-dev/wp-includes/js/media-models.js

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