PageRenderTime 59ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://gitlab.com/Blueprint-Marketing/wordpress-unit-tests
JavaScript | 864 lines | 527 code | 162 blank | 175 comment | 145 complexity | d9e47adf1273751d1c1262ecd3ef666f MD5 | raw file
  1. window.wp = window.wp || {};
  2. (function($){
  3. var Attachment, Attachments, Query, compare, l10n, media, bindSyncEvents;
  4. /**
  5. * wp.media( attributes )
  6. *
  7. * Handles the default media experience. Automatically creates
  8. * and opens a media frame, and returns the result.
  9. * Does nothing if the controllers do not exist.
  10. *
  11. * @param {object} attributes The properties passed to the main media controller.
  12. * @return {object} A media workflow.
  13. */
  14. media = wp.media = function( attributes ) {
  15. var MediaFrame = media.view.MediaFrame,
  16. frame;
  17. if ( ! MediaFrame )
  18. return;
  19. attributes = _.defaults( attributes || {}, {
  20. frame: 'select'
  21. });
  22. if ( 'select' === attributes.frame && MediaFrame.Select )
  23. frame = new MediaFrame.Select( attributes );
  24. else if ( 'post' === attributes.frame && MediaFrame.Post )
  25. frame = new MediaFrame.Post( attributes );
  26. delete attributes.frame;
  27. return frame;
  28. };
  29. _.extend( media, { model: {}, view: {}, controller: {}, frames: {} });
  30. // Link any localized strings.
  31. l10n = media.model.l10n = typeof _wpMediaModelsL10n === 'undefined' ? {} : _wpMediaModelsL10n;
  32. // Link any settings.
  33. media.model.settings = l10n.settings || {};
  34. delete l10n.settings;
  35. /**
  36. * ========================================================================
  37. * UTILITIES
  38. * ========================================================================
  39. */
  40. /**
  41. * A basic comparator.
  42. *
  43. * @param {mixed} a The primary parameter to compare.
  44. * @param {mixed} b The primary parameter to compare.
  45. * @param {string} ac The fallback parameter to compare, a's cid.
  46. * @param {string} bc The fallback parameter to compare, b's cid.
  47. * @return {number} -1: a should come before b.
  48. * 0: a and b are of the same rank.
  49. * 1: b should come before a.
  50. */
  51. compare = function( a, b, ac, bc ) {
  52. if ( _.isEqual( a, b ) )
  53. return ac === bc ? 0 : (ac > bc ? -1 : 1);
  54. else
  55. return a > b ? -1 : 1;
  56. };
  57. // Ensures the 'sync' and 'error' events are always
  58. // correctly triggered when overloading `Backbone.sync`.
  59. bindSyncEvents = function( model, options ) {
  60. var success = options.success,
  61. error = options.error;
  62. options.success = function( resp ) {
  63. if ( success )
  64. success( resp );
  65. model.trigger( 'sync', model, resp, options );
  66. };
  67. options.error = function( xhr ) {
  68. if ( error )
  69. error( xhr );
  70. model.trigger( 'error', model, xhr, options );
  71. };
  72. return options;
  73. };
  74. _.extend( media, {
  75. /**
  76. * media.template( id )
  77. *
  78. * Fetches a template by id.
  79. * See wp.template() in `wp-includes/js/wp-util.js`.
  80. */
  81. template: wp.template,
  82. /**
  83. * media.post( [action], [data] )
  84. *
  85. * Sends a POST request to WordPress.
  86. * See wp.ajax.post() in `wp-includes/js/wp-util.js`.
  87. */
  88. post: wp.ajax.post,
  89. /**
  90. * media.ajax( [action], [options] )
  91. *
  92. * Sends an XHR request to WordPress.
  93. * See wp.ajax.send() in `wp-includes/js/wp-util.js`.
  94. */
  95. ajax: wp.ajax.send,
  96. // Scales a set of dimensions to fit within bounding dimensions.
  97. fit: function( dimensions ) {
  98. var width = dimensions.width,
  99. height = dimensions.height,
  100. maxWidth = dimensions.maxWidth,
  101. maxHeight = dimensions.maxHeight,
  102. constraint;
  103. // Compare ratios between the two values to determine which
  104. // max to constrain by. If a max value doesn't exist, then the
  105. // opposite side is the constraint.
  106. if ( ! _.isUndefined( maxWidth ) && ! _.isUndefined( maxHeight ) ) {
  107. constraint = ( width / height > maxWidth / maxHeight ) ? 'width' : 'height';
  108. } else if ( _.isUndefined( maxHeight ) ) {
  109. constraint = 'width';
  110. } else if ( _.isUndefined( maxWidth ) && height > maxHeight ) {
  111. constraint = 'height';
  112. }
  113. // If the value of the constrained side is larger than the max,
  114. // then scale the values. Otherwise return the originals; they fit.
  115. if ( 'width' === constraint && width > maxWidth ) {
  116. return {
  117. width : maxWidth,
  118. height: Math.round( maxWidth * height / width )
  119. };
  120. } else if ( 'height' === constraint && height > maxHeight ) {
  121. return {
  122. width : Math.round( maxHeight * width / height ),
  123. height: maxHeight
  124. };
  125. } else {
  126. return {
  127. width : width,
  128. height: height
  129. };
  130. }
  131. },
  132. // Truncates a string by injecting an ellipsis into the middle.
  133. // Useful for filenames.
  134. truncate: function( string, length, replacement ) {
  135. length = length || 30;
  136. replacement = replacement || '…';
  137. if ( string.length <= length )
  138. return string;
  139. return string.substr( 0, length / 2 ) + replacement + string.substr( -1 * length / 2 );
  140. }
  141. });
  142. /**
  143. * ========================================================================
  144. * MODELS
  145. * ========================================================================
  146. */
  147. /**
  148. * wp.media.attachment
  149. */
  150. media.attachment = function( id ) {
  151. return Attachment.get( id );
  152. };
  153. /**
  154. * wp.media.model.Attachment
  155. */
  156. Attachment = media.model.Attachment = Backbone.Model.extend({
  157. sync: function( method, model, options ) {
  158. // If the attachment does not yet have an `id`, return an instantly
  159. // rejected promise. Otherwise, all of our requests will fail.
  160. if ( _.isUndefined( this.id ) )
  161. return $.Deferred().rejectWith( this ).promise();
  162. // Overload the `read` request so Attachment.fetch() functions correctly.
  163. if ( 'read' === method ) {
  164. options = options || {};
  165. options.context = this;
  166. options.data = _.extend( options.data || {}, {
  167. action: 'get-attachment',
  168. id: this.id
  169. });
  170. bindSyncEvents( model, options );
  171. return media.ajax( options );
  172. // Overload the `update` request so properties can be saved.
  173. } else if ( 'update' === method ) {
  174. // If we do not have the necessary nonce, fail immeditately.
  175. if ( ! this.get('nonces') || ! this.get('nonces').update )
  176. return $.Deferred().rejectWith( this ).promise();
  177. options = options || {};
  178. options.context = this;
  179. // Set the action and ID.
  180. options.data = _.extend( options.data || {}, {
  181. action: 'save-attachment',
  182. id: this.id,
  183. nonce: this.get('nonces').update,
  184. post_id: media.model.settings.post.id
  185. });
  186. // Record the values of the changed attributes.
  187. if ( model.hasChanged() ) {
  188. options.data.changes = {};
  189. _.each( model.changed, function( value, key ) {
  190. options.data.changes[ key ] = this.get( key );
  191. }, this );
  192. }
  193. bindSyncEvents( model, options );
  194. return media.ajax( options );
  195. // Overload the `delete` request so attachments can be removed.
  196. // This will permanently delete an attachment.
  197. } else if ( 'delete' === method ) {
  198. options = options || {};
  199. if ( ! options.wait )
  200. this.destroyed = true;
  201. options.context = this;
  202. options.data = _.extend( options.data || {}, {
  203. action: 'delete-post',
  204. id: this.id,
  205. _wpnonce: this.get('nonces')['delete']
  206. });
  207. bindSyncEvents( model, options );
  208. return media.ajax( options ).done( function() {
  209. this.destroyed = true;
  210. }).fail( function() {
  211. this.destroyed = false;
  212. });
  213. // Otherwise, fall back to `Backbone.sync()`.
  214. } else {
  215. return Backbone.Model.prototype.sync.apply( this, arguments );
  216. }
  217. },
  218. parse: function( resp, xhr ) {
  219. if ( ! resp )
  220. return resp;
  221. // Convert date strings into Date objects.
  222. resp.date = new Date( resp.date );
  223. resp.modified = new Date( resp.modified );
  224. return resp;
  225. },
  226. saveCompat: function( data, options ) {
  227. var model = this;
  228. // If we do not have the necessary nonce, fail immeditately.
  229. if ( ! this.get('nonces') || ! this.get('nonces').update )
  230. return $.Deferred().rejectWith( this ).promise();
  231. return media.post( 'save-attachment-compat', _.defaults({
  232. id: this.id,
  233. nonce: this.get('nonces').update,
  234. post_id: media.model.settings.post.id
  235. }, data ) ).done( function( resp, status, xhr ) {
  236. model.set( model.parse( resp, xhr ), options );
  237. });
  238. }
  239. }, {
  240. create: function( attrs ) {
  241. return Attachments.all.push( attrs );
  242. },
  243. get: _.memoize( function( id, attachment ) {
  244. return Attachments.all.push( attachment || { id: id } );
  245. })
  246. });
  247. /**
  248. * wp.media.model.Attachments
  249. */
  250. Attachments = media.model.Attachments = Backbone.Collection.extend({
  251. model: Attachment,
  252. initialize: function( models, options ) {
  253. options = options || {};
  254. this.props = new Backbone.Model();
  255. this.filters = options.filters || {};
  256. // Bind default `change` events to the `props` model.
  257. this.props.on( 'change', this._changeFilteredProps, this );
  258. this.props.on( 'change:order', this._changeOrder, this );
  259. this.props.on( 'change:orderby', this._changeOrderby, this );
  260. this.props.on( 'change:query', this._changeQuery, this );
  261. // Set the `props` model and fill the default property values.
  262. this.props.set( _.defaults( options.props || {} ) );
  263. // Observe another `Attachments` collection if one is provided.
  264. if ( options.observe )
  265. this.observe( options.observe );
  266. },
  267. // Automatically sort the collection when the order changes.
  268. _changeOrder: function( model, order ) {
  269. if ( this.comparator )
  270. this.sort();
  271. },
  272. // Set the default comparator only when the `orderby` property is set.
  273. _changeOrderby: function( model, orderby ) {
  274. // If a different comparator is defined, bail.
  275. if ( this.comparator && this.comparator !== Attachments.comparator )
  276. return;
  277. if ( orderby && 'post__in' !== orderby )
  278. this.comparator = Attachments.comparator;
  279. else
  280. delete this.comparator;
  281. },
  282. // If the `query` property is set to true, query the server using
  283. // the `props` values, and sync the results to this collection.
  284. _changeQuery: function( model, query ) {
  285. if ( query ) {
  286. this.props.on( 'change', this._requery, this );
  287. this._requery();
  288. } else {
  289. this.props.off( 'change', this._requery, this );
  290. }
  291. },
  292. _changeFilteredProps: function( model, options ) {
  293. // If this is a query, updating the collection will be handled by
  294. // `this._requery()`.
  295. if ( this.props.get('query') )
  296. return;
  297. var changed = _.chain( model.changed ).map( function( t, prop ) {
  298. var filter = Attachments.filters[ prop ],
  299. term = model.get( prop );
  300. if ( ! filter )
  301. return;
  302. if ( term && ! this.filters[ prop ] )
  303. this.filters[ prop ] = filter;
  304. else if ( ! term && this.filters[ prop ] === filter )
  305. delete this.filters[ prop ];
  306. else
  307. return;
  308. // Record the change.
  309. return true;
  310. }, this ).any().value();
  311. if ( ! changed )
  312. return;
  313. // If no `Attachments` model is provided to source the searches
  314. // from, then automatically generate a source from the existing
  315. // models.
  316. if ( ! this._source )
  317. this._source = new Attachments( this.models );
  318. this.reset( this._source.filter( this.validator, this ) );
  319. },
  320. validateDestroyed: false,
  321. validator: function( attachment ) {
  322. if ( ! this.validateDestroyed && attachment.destroyed )
  323. return false;
  324. return _.all( this.filters, function( filter, key ) {
  325. return !! filter.call( this, attachment );
  326. }, this );
  327. },
  328. validate: function( attachment, options ) {
  329. var valid = this.validator( attachment ),
  330. hasAttachment = !! this.get( attachment.cid );
  331. if ( ! valid && hasAttachment )
  332. this.remove( attachment, options );
  333. else if ( valid && ! hasAttachment )
  334. this.add( attachment, options );
  335. return this;
  336. },
  337. validateAll: function( attachments, options ) {
  338. options = options || {};
  339. _.each( attachments.models, function( attachment ) {
  340. this.validate( attachment, { silent: true });
  341. }, this );
  342. if ( ! options.silent )
  343. this.trigger( 'reset', this, options );
  344. return this;
  345. },
  346. observe: function( attachments ) {
  347. this.observers = this.observers || [];
  348. this.observers.push( attachments );
  349. attachments.on( 'add change remove', this._validateHandler, this );
  350. attachments.on( 'reset', this._validateAllHandler, this );
  351. this.validateAll( attachments );
  352. return this;
  353. },
  354. unobserve: function( attachments ) {
  355. if ( attachments ) {
  356. attachments.off( null, null, this );
  357. this.observers = _.without( this.observers, attachments );
  358. } else {
  359. _.each( this.observers, function( attachments ) {
  360. attachments.off( null, null, this );
  361. }, this );
  362. delete this.observers;
  363. }
  364. return this;
  365. },
  366. _validateHandler: function( attachment, attachments, options ) {
  367. // If we're not mirroring this `attachments` collection,
  368. // only retain the `silent` option.
  369. options = attachments === this.mirroring ? options : {
  370. silent: options && options.silent
  371. };
  372. return this.validate( attachment, options );
  373. },
  374. _validateAllHandler: function( attachments, options ) {
  375. return this.validateAll( attachments, options );
  376. },
  377. mirror: function( attachments ) {
  378. if ( this.mirroring && this.mirroring === attachments )
  379. return this;
  380. this.unmirror();
  381. this.mirroring = attachments;
  382. // Clear the collection silently. A `reset` event will be fired
  383. // when `observe()` calls `validateAll()`.
  384. this.reset( [], { silent: true } );
  385. this.observe( attachments );
  386. return this;
  387. },
  388. unmirror: function() {
  389. if ( ! this.mirroring )
  390. return;
  391. this.unobserve( this.mirroring );
  392. delete this.mirroring;
  393. },
  394. more: function( options ) {
  395. var deferred = $.Deferred(),
  396. mirroring = this.mirroring,
  397. attachments = this;
  398. if ( ! mirroring || ! mirroring.more )
  399. return deferred.resolveWith( this ).promise();
  400. // If we're mirroring another collection, forward `more` to
  401. // the mirrored collection. Account for a race condition by
  402. // checking if we're still mirroring that collection when
  403. // the request resolves.
  404. mirroring.more( options ).done( function() {
  405. if ( this === attachments.mirroring )
  406. deferred.resolveWith( this );
  407. });
  408. return deferred.promise();
  409. },
  410. hasMore: function() {
  411. return this.mirroring ? this.mirroring.hasMore() : false;
  412. },
  413. _requery: function() {
  414. if ( this.props.get('query') )
  415. this.mirror( Query.get( this.props.toJSON() ) );
  416. },
  417. // If this collection is sorted by `menuOrder`, recalculates and saves
  418. // the menu order to the database.
  419. saveMenuOrder: function() {
  420. if ( 'menuOrder' !== this.props.get('orderby') )
  421. return;
  422. // Removes any uploading attachments, updates each attachment's
  423. // menu order, and returns an object with an { id: menuOrder }
  424. // mapping to pass to the request.
  425. var attachments = this.chain().filter( function( attachment ) {
  426. return ! _.isUndefined( attachment.id );
  427. }).map( function( attachment, index ) {
  428. // Indices start at 1.
  429. index = index + 1;
  430. attachment.set( 'menuOrder', index );
  431. return [ attachment.id, index ];
  432. }).object().value();
  433. if ( _.isEmpty( attachments ) )
  434. return;
  435. return media.post( 'save-attachment-order', {
  436. nonce: media.model.settings.post.nonce,
  437. post_id: media.model.settings.post.id,
  438. attachments: attachments
  439. });
  440. }
  441. }, {
  442. comparator: function( a, b, options ) {
  443. var key = this.props.get('orderby'),
  444. order = this.props.get('order') || 'DESC',
  445. ac = a.cid,
  446. bc = b.cid;
  447. a = a.get( key );
  448. b = b.get( key );
  449. if ( 'date' === key || 'modified' === key ) {
  450. a = a || new Date();
  451. b = b || new Date();
  452. }
  453. // If `options.ties` is set, don't enforce the `cid` tiebreaker.
  454. if ( options && options.ties )
  455. ac = bc = null;
  456. return ( 'DESC' === order ) ? compare( a, b, ac, bc ) : compare( b, a, bc, ac );
  457. },
  458. filters: {
  459. // Note that this client-side searching is *not* equivalent
  460. // to our server-side searching.
  461. search: function( attachment ) {
  462. if ( ! this.props.get('search') )
  463. return true;
  464. return _.any(['title','filename','description','caption','name'], function( key ) {
  465. var value = attachment.get( key );
  466. return value && -1 !== value.search( this.props.get('search') );
  467. }, this );
  468. },
  469. type: function( attachment ) {
  470. var type = this.props.get('type');
  471. return ! type || -1 !== type.indexOf( attachment.get('type') );
  472. },
  473. uploadedTo: function( attachment ) {
  474. var uploadedTo = this.props.get('uploadedTo');
  475. if ( _.isUndefined( uploadedTo ) )
  476. return true;
  477. return uploadedTo === attachment.get('uploadedTo');
  478. }
  479. }
  480. });
  481. Attachments.all = new Attachments();
  482. /**
  483. * wp.media.query
  484. */
  485. media.query = function( props ) {
  486. return new Attachments( null, {
  487. props: _.extend( _.defaults( props || {}, { orderby: 'date' } ), { query: true } )
  488. });
  489. };
  490. /**
  491. * wp.media.model.Query
  492. *
  493. * A set of attachments that corresponds to a set of consecutively paged
  494. * queries on the server.
  495. *
  496. * Note: Do NOT change this.args after the query has been initialized.
  497. * Things will break.
  498. */
  499. Query = media.model.Query = Attachments.extend({
  500. initialize: function( models, options ) {
  501. var allowed;
  502. options = options || {};
  503. Attachments.prototype.initialize.apply( this, arguments );
  504. this.args = options.args;
  505. this._hasMore = true;
  506. this.created = new Date();
  507. this.filters.order = function( attachment ) {
  508. var orderby = this.props.get('orderby'),
  509. order = this.props.get('order');
  510. if ( ! this.comparator )
  511. return true;
  512. // We want any items that can be placed before the last
  513. // item in the set. If we add any items after the last
  514. // item, then we can't guarantee the set is complete.
  515. if ( this.length ) {
  516. return 1 !== this.comparator( attachment, this.last(), { ties: true });
  517. // Handle the case where there are no items yet and
  518. // we're sorting for recent items. In that case, we want
  519. // changes that occurred after we created the query.
  520. } else if ( 'DESC' === order && ( 'date' === orderby || 'modified' === orderby ) ) {
  521. return attachment.get( orderby ) >= this.created;
  522. // If we're sorting by menu order and we have no items,
  523. // accept any items that have the default menu order (0).
  524. } else if ( 'ASC' === order && 'menuOrder' === orderby ) {
  525. return attachment.get( orderby ) === 0;
  526. }
  527. // Otherwise, we don't want any items yet.
  528. return false;
  529. };
  530. // Observe the central `wp.Uploader.queue` collection to watch for
  531. // new matches for the query.
  532. //
  533. // Only observe when a limited number of query args are set. There
  534. // are no filters for other properties, so observing will result in
  535. // false positives in those queries.
  536. allowed = [ 's', 'order', 'orderby', 'posts_per_page', 'post_mime_type', 'post_parent' ];
  537. if ( wp.Uploader && _( this.args ).chain().keys().difference( allowed ).isEmpty().value() )
  538. this.observe( wp.Uploader.queue );
  539. },
  540. hasMore: function() {
  541. return this._hasMore;
  542. },
  543. more: function( options ) {
  544. var query = this;
  545. if ( this._more && 'pending' === this._more.state() )
  546. return this._more;
  547. if ( ! this.hasMore() )
  548. return $.Deferred().resolveWith( this ).promise();
  549. options = options || {};
  550. options.remove = false;
  551. return this._more = this.fetch( options ).done( function( resp ) {
  552. if ( _.isEmpty( resp ) || -1 === this.args.posts_per_page || resp.length < this.args.posts_per_page )
  553. query._hasMore = false;
  554. });
  555. },
  556. sync: function( method, model, options ) {
  557. var fallback;
  558. // Overload the read method so Attachment.fetch() functions correctly.
  559. if ( 'read' === method ) {
  560. options = options || {};
  561. options.context = this;
  562. options.data = _.extend( options.data || {}, {
  563. action: 'query-attachments',
  564. post_id: media.model.settings.post.id
  565. });
  566. // Clone the args so manipulation is non-destructive.
  567. args = _.clone( this.args );
  568. // Determine which page to query.
  569. if ( -1 !== args.posts_per_page )
  570. args.paged = Math.floor( this.length / args.posts_per_page ) + 1;
  571. options.data.query = args;
  572. bindSyncEvents( model, options );
  573. return media.ajax( options );
  574. // Otherwise, fall back to Backbone.sync()
  575. } else {
  576. fallback = Attachments.prototype.sync ? Attachments.prototype : Backbone;
  577. return fallback.sync.apply( this, arguments );
  578. }
  579. }
  580. }, {
  581. defaultProps: {
  582. orderby: 'date',
  583. order: 'DESC'
  584. },
  585. defaultArgs: {
  586. posts_per_page: 40
  587. },
  588. orderby: {
  589. allowed: [ 'name', 'author', 'date', 'title', 'modified', 'uploadedTo', 'id', 'post__in', 'menuOrder' ],
  590. valuemap: {
  591. 'id': 'ID',
  592. 'uploadedTo': 'parent',
  593. 'menuOrder': 'menu_order ID'
  594. }
  595. },
  596. propmap: {
  597. 'search': 's',
  598. 'type': 'post_mime_type',
  599. 'perPage': 'posts_per_page',
  600. 'menuOrder': 'menu_order',
  601. 'uploadedTo': 'post_parent'
  602. },
  603. // Caches query objects so queries can be easily reused.
  604. get: (function(){
  605. var queries = [];
  606. return function( props, options ) {
  607. var args = {},
  608. orderby = Query.orderby,
  609. defaults = Query.defaultProps,
  610. query;
  611. // Remove the `query` property. This isn't linked to a query,
  612. // this *is* the query.
  613. delete props.query;
  614. // Fill default args.
  615. _.defaults( props, defaults );
  616. // Normalize the order.
  617. props.order = props.order.toUpperCase();
  618. if ( 'DESC' !== props.order && 'ASC' !== props.order )
  619. props.order = defaults.order.toUpperCase();
  620. // Ensure we have a valid orderby value.
  621. if ( ! _.contains( orderby.allowed, props.orderby ) )
  622. props.orderby = defaults.orderby;
  623. // Generate the query `args` object.
  624. // Correct any differing property names.
  625. _.each( props, function( value, prop ) {
  626. if ( _.isNull( value ) )
  627. return;
  628. args[ Query.propmap[ prop ] || prop ] = value;
  629. });
  630. // Fill any other default query args.
  631. _.defaults( args, Query.defaultArgs );
  632. // `props.orderby` does not always map directly to `args.orderby`.
  633. // Substitute exceptions specified in orderby.keymap.
  634. args.orderby = orderby.valuemap[ props.orderby ] || props.orderby;
  635. // Search the query cache for matches.
  636. query = _.find( queries, function( query ) {
  637. return _.isEqual( query.args, args );
  638. });
  639. // Otherwise, create a new query and add it to the cache.
  640. if ( ! query ) {
  641. query = new Query( [], _.extend( options || {}, {
  642. props: props,
  643. args: args
  644. } ) );
  645. queries.push( query );
  646. }
  647. return query;
  648. };
  649. }())
  650. });
  651. /**
  652. * wp.media.model.Selection
  653. *
  654. * Used to manage a selection of attachments in the views.
  655. */
  656. media.model.Selection = Attachments.extend({
  657. initialize: function( models, options ) {
  658. Attachments.prototype.initialize.apply( this, arguments );
  659. this.multiple = options && options.multiple;
  660. // Refresh the `single` model whenever the selection changes.
  661. // Binds `single` instead of using the context argument to ensure
  662. // it receives no parameters.
  663. this.on( 'add remove reset', _.bind( this.single, this, false ) );
  664. },
  665. // Override the selection's add method.
  666. // If the workflow does not support multiple
  667. // selected attachments, reset the selection.
  668. add: function( models, options ) {
  669. if ( ! this.multiple )
  670. this.remove( this.models );
  671. return Attachments.prototype.add.call( this, models, options );
  672. },
  673. single: function( model ) {
  674. var previous = this._single;
  675. // If a `model` is provided, use it as the single model.
  676. if ( model )
  677. this._single = model;
  678. // If the single model isn't in the selection, remove it.
  679. if ( this._single && ! this.get( this._single.cid ) )
  680. delete this._single;
  681. this._single = this._single || this.last();
  682. // If single has changed, fire an event.
  683. if ( this._single !== previous ) {
  684. if ( previous ) {
  685. previous.trigger( 'selection:unsingle', previous, this );
  686. // If the model was already removed, trigger the collection
  687. // event manually.
  688. if ( ! this.get( previous.cid ) )
  689. this.trigger( 'selection:unsingle', previous, this );
  690. }
  691. if ( this._single )
  692. this._single.trigger( 'selection:single', this._single, this );
  693. }
  694. // Return the single model, or the last model as a fallback.
  695. return this._single;
  696. }
  697. });
  698. // Clean up. Prevents mobile browsers caching
  699. $(window).on('unload', function(){
  700. window.wp = null;
  701. });
  702. }(jQuery));