PageRenderTime 67ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

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

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