PageRenderTime 180ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

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

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