PageRenderTime 50ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

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

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