PageRenderTime 58ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

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

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