PageRenderTime 65ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

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

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