PageRenderTime 53ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://gitlab.com/SiryjVyiko/qwerty
JavaScript | 1362 lines | 716 code | 154 blank | 492 comment | 189 complexity | 9f1cc3edfd9f471f51f6d5177fe646a8 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. * 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( refresh ) {
  729. var props;
  730. if ( this.props.get('query') ) {
  731. props = this.props.toJSON();
  732. props.cache = ( true !== refresh );
  733. this.mirror( Query.get( props ) );
  734. }
  735. },
  736. /**
  737. * If this collection is sorted by `menuOrder`, recalculates and saves
  738. * the menu order to the database.
  739. *
  740. * @returns {undefined|Promise}
  741. */
  742. saveMenuOrder: function() {
  743. if ( 'menuOrder' !== this.props.get('orderby') ) {
  744. return;
  745. }
  746. // Removes any uploading attachments, updates each attachment's
  747. // menu order, and returns an object with an { id: menuOrder }
  748. // mapping to pass to the request.
  749. var attachments = this.chain().filter( function( attachment ) {
  750. return ! _.isUndefined( attachment.id );
  751. }).map( function( attachment, index ) {
  752. // Indices start at 1.
  753. index = index + 1;
  754. attachment.set( 'menuOrder', index );
  755. return [ attachment.id, index ];
  756. }).object().value();
  757. if ( _.isEmpty( attachments ) ) {
  758. return;
  759. }
  760. return media.post( 'save-attachment-order', {
  761. nonce: media.model.settings.post.nonce,
  762. post_id: media.model.settings.post.id,
  763. attachments: attachments
  764. });
  765. }
  766. }, {
  767. /**
  768. * @static
  769. * Overrides Backbone.Collection.comparator
  770. *
  771. * @param {Backbone.Model} a
  772. * @param {Backbone.Model} b
  773. * @param {Object} options
  774. * @returns {Number} -1 if the first model should come before the second,
  775. * 0 if they are of the same rank and
  776. * 1 if the first model should come after.
  777. */
  778. comparator: function( a, b, options ) {
  779. var key = this.props.get('orderby'),
  780. order = this.props.get('order') || 'DESC',
  781. ac = a.cid,
  782. bc = b.cid;
  783. a = a.get( key );
  784. b = b.get( key );
  785. if ( 'date' === key || 'modified' === key ) {
  786. a = a || new Date();
  787. b = b || new Date();
  788. }
  789. // If `options.ties` is set, don't enforce the `cid` tiebreaker.
  790. if ( options && options.ties ) {
  791. ac = bc = null;
  792. }
  793. return ( 'DESC' === order ) ? compare( a, b, ac, bc ) : compare( b, a, bc, ac );
  794. },
  795. /**
  796. * @namespace
  797. */
  798. filters: {
  799. /**
  800. * @static
  801. * Note that this client-side searching is *not* equivalent
  802. * to our server-side searching.
  803. *
  804. * @param {wp.media.model.Attachment} attachment
  805. *
  806. * @this wp.media.model.Attachments
  807. *
  808. * @returns {Boolean}
  809. */
  810. search: function( attachment ) {
  811. if ( ! this.props.get('search') ) {
  812. return true;
  813. }
  814. return _.any(['title','filename','description','caption','name'], function( key ) {
  815. var value = attachment.get( key );
  816. return value && -1 !== value.search( this.props.get('search') );
  817. }, this );
  818. },
  819. /**
  820. * @static
  821. * @param {wp.media.model.Attachment} attachment
  822. *
  823. * @this wp.media.model.Attachments
  824. *
  825. * @returns {Boolean}
  826. */
  827. type: function( attachment ) {
  828. var type = this.props.get('type');
  829. return ! type || -1 !== type.indexOf( attachment.get('type') );
  830. },
  831. /**
  832. * @static
  833. * @param {wp.media.model.Attachment} attachment
  834. *
  835. * @this wp.media.model.Attachments
  836. *
  837. * @returns {Boolean}
  838. */
  839. uploadedTo: function( attachment ) {
  840. var uploadedTo = this.props.get('uploadedTo');
  841. if ( _.isUndefined( uploadedTo ) ) {
  842. return true;
  843. }
  844. return uploadedTo === attachment.get('uploadedTo');
  845. },
  846. /**
  847. * @static
  848. * @param {wp.media.model.Attachment} attachment
  849. *
  850. * @this wp.media.model.Attachments
  851. *
  852. * @returns {Boolean}
  853. */
  854. status: function( attachment ) {
  855. var status = this.props.get('status');
  856. if ( _.isUndefined( status ) ) {
  857. return true;
  858. }
  859. return status === attachment.get('status');
  860. }
  861. }
  862. });
  863. /**
  864. * @static
  865. * @member {wp.media.model.Attachments}
  866. */
  867. Attachments.all = new Attachments();
  868. /**
  869. * wp.media.query
  870. *
  871. * @static
  872. * @returns {wp.media.model.Attachments}
  873. */
  874. media.query = function( props ) {
  875. return new Attachments( null, {
  876. props: _.extend( _.defaults( props || {}, { orderby: 'date' } ), { query: true } )
  877. });
  878. };
  879. /**
  880. * wp.media.model.Query
  881. *
  882. * A set of attachments that corresponds to a set of consecutively paged
  883. * queries on the server.
  884. *
  885. * Note: Do NOT change this.args after the query has been initialized.
  886. * Things will break.
  887. *
  888. * @constructor
  889. * @augments wp.media.model.Attachments
  890. * @augments Backbone.Collection
  891. */
  892. Query = media.model.Query = Attachments.extend({
  893. /**
  894. * @global wp.Uploader
  895. *
  896. * @param {Array} [models=[]] Array of models used to populate the collection.
  897. * @param {Object} [options={}]
  898. */
  899. initialize: function( models, options ) {
  900. var allowed;
  901. options = options || {};
  902. Attachments.prototype.initialize.apply( this, arguments );
  903. this.args = options.args;
  904. this._hasMore = true;
  905. this.created = new Date();
  906. this.filters.order = function( attachment ) {
  907. var orderby = this.props.get('orderby'),
  908. order = this.props.get('order');
  909. if ( ! this.comparator ) {
  910. return true;
  911. }
  912. // We want any items that can be placed before the last
  913. // item in the set. If we add any items after the last
  914. // item, then we can't guarantee the set is complete.
  915. if ( this.length ) {
  916. return 1 !== this.comparator( attachment, this.last(), { ties: true });
  917. // Handle the case where there are no items yet and
  918. // we're sorting for recent items. In that case, we want
  919. // changes that occurred after we created the query.
  920. } else if ( 'DESC' === order && ( 'date' === orderby || 'modified' === orderby ) ) {
  921. return attachment.get( orderby ) >= this.created;
  922. // If we're sorting by menu order and we have no items,
  923. // accept any items that have the default menu order (0).
  924. } else if ( 'ASC' === order && 'menuOrder' === orderby ) {
  925. return attachment.get( orderby ) === 0;
  926. }
  927. // Otherwise, we don't want any items yet.
  928. return false;
  929. };
  930. // Observe the central `wp.Uploader.queue` collection to watch for
  931. // new matches for the query.
  932. //
  933. // Only observe when a limited number of query args are set. There
  934. // are no filters for other properties, so observing will result in
  935. // false positives in those queries.
  936. allowed = [ 's', 'order', 'orderby', 'posts_per_page', 'post_mime_type', 'post_parent' ];
  937. if ( wp.Uploader && _( this.args ).chain().keys().difference( allowed ).isEmpty().value() ) {
  938. this.observe( wp.Uploader.queue );
  939. }
  940. },
  941. /**
  942. * @returns {Boolean}
  943. */
  944. hasMore: function() {
  945. return this._hasMore;
  946. },
  947. /**
  948. * @param {Object} [options={}]
  949. * @returns {Promise}
  950. */
  951. more: function( options ) {
  952. var query = this;
  953. if ( this._more && 'pending' === this._more.state() ) {
  954. return this._more;
  955. }
  956. if ( ! this.hasMore() ) {
  957. return $.Deferred().resolveWith( this ).promise();
  958. }
  959. options = options || {};
  960. options.remove = false;
  961. return this._more = this.fetch( options ).done( function( resp ) {
  962. if ( _.isEmpty( resp ) || -1 === this.args.posts_per_page || resp.length < this.args.posts_per_page ) {
  963. query._hasMore = false;
  964. }
  965. });
  966. },
  967. /**
  968. * Overrides Backbone.Collection.sync
  969. * Overrides wp.media.model.Attachments.sync
  970. *
  971. * @param {String} method
  972. * @param {Backbone.Model} model
  973. * @param {Object} [options={}]
  974. * @returns {Promise}
  975. */
  976. sync: function( method, model, options ) {
  977. var args, fallback;
  978. // Overload the read method so Attachment.fetch() functions correctly.
  979. if ( 'read' === method ) {
  980. options = options || {};
  981. options.context = this;
  982. options.data = _.extend( options.data || {}, {
  983. action: 'query-attachments',
  984. post_id: media.model.settings.post.id
  985. });
  986. // Clone the args so manipulation is non-destructive.
  987. args = _.clone( this.args );
  988. // Determine which page to query.
  989. if ( -1 !== args.posts_per_page ) {
  990. args.paged = Math.floor( this.length / args.posts_per_page ) + 1;
  991. }
  992. options.data.query = args;
  993. return media.ajax( options );
  994. // Otherwise, fall back to Backbone.sync()
  995. } else {
  996. /**
  997. * Call wp.media.model.Attachments.sync or Backbone.sync
  998. */
  999. fallback = Attachments.prototype.sync ? Attachments.prototype : Backbone;
  1000. return fallback.sync.apply( this, arguments );
  1001. }
  1002. }
  1003. }, {
  1004. /**
  1005. * @readonly
  1006. */
  1007. defaultProps: {
  1008. orderby: 'date',
  1009. order: 'DESC'
  1010. },
  1011. /**
  1012. * @readonly
  1013. */
  1014. defaultArgs: {
  1015. posts_per_page: 40
  1016. },
  1017. /**
  1018. * @readonly
  1019. */
  1020. orderby: {
  1021. allowed: [ 'name', 'author', 'date', 'title', 'modified', 'uploadedTo', 'id', 'post__in', 'menuOrder' ],
  1022. valuemap: {
  1023. 'id': 'ID',
  1024. 'uploadedTo': 'parent',
  1025. 'menuOrder': 'menu_order ID'
  1026. }
  1027. },
  1028. /**
  1029. * @readonly
  1030. */
  1031. propmap: {
  1032. 'search': 's',
  1033. 'type': 'post_mime_type',
  1034. 'perPage': 'posts_per_page',
  1035. 'menuOrder': 'menu_order',
  1036. 'uploadedTo': 'post_parent',
  1037. 'status': 'post_status',
  1038. 'include': 'post__in',
  1039. 'exclude': 'post__not_in'
  1040. },
  1041. /**
  1042. * @static
  1043. * @method
  1044. *
  1045. * @returns {wp.media.model.Query} A new query.
  1046. */
  1047. // Caches query objects so queries can be easily reused.
  1048. get: (function(){
  1049. /**
  1050. * @static
  1051. * @type Array
  1052. */
  1053. var queries = [];
  1054. /**
  1055. * @param {Object} props
  1056. * @param {Object} options
  1057. * @returns {Query}
  1058. */
  1059. return function( props, options ) {
  1060. var args = {},
  1061. orderby = Query.orderby,
  1062. defaults = Query.defaultProps,
  1063. query,
  1064. cache = !! props.cache || _.isUndefined( props.cache );
  1065. // Remove the `query` property. This isn't linked to a query,
  1066. // this *is* the query.
  1067. delete props.query;
  1068. delete props.cache;
  1069. // Fill default args.
  1070. _.defaults( props, defaults );
  1071. // Normalize the order.
  1072. props.order = props.order.toUpperCase();
  1073. if ( 'DESC' !== props.order && 'ASC' !== props.order ) {
  1074. props.order = defaults.order.toUpperCase();
  1075. }
  1076. // Ensure we have a valid orderby value.
  1077. if ( ! _.contains( orderby.allowed, props.orderby ) ) {
  1078. props.orderby = defaults.orderby;
  1079. }
  1080. _.each( [ 'include', 'exclude' ], function( prop ) {
  1081. if ( props[ prop ] && ! _.isArray( props[ prop ] ) ) {
  1082. props[ prop ] = [ props[ prop ] ];
  1083. }
  1084. } );
  1085. // Generate the query `args` object.
  1086. // Correct any differing property names.
  1087. _.each( props, function( value, prop ) {
  1088. if ( _.isNull( value ) ) {
  1089. return;
  1090. }
  1091. args[ Query.propmap[ prop ] || prop ] = value;
  1092. });
  1093. // Fill any other default query args.
  1094. _.defaults( args, Query.defaultArgs );
  1095. // `props.orderby` does not always map directly to `args.orderby`.
  1096. // Substitute exceptions specified in orderby.keymap.
  1097. args.orderby = orderby.valuemap[ props.orderby ] || props.orderby;
  1098. // Search the query cache for matches.
  1099. if ( cache ) {
  1100. query = _.find( queries, function( query ) {
  1101. return _.isEqual( query.args, args );
  1102. });
  1103. } else {
  1104. queries = [];
  1105. }
  1106. // Otherwise, create a new query and add it to the cache.
  1107. if ( ! query ) {
  1108. query = new Query( [], _.extend( options || {}, {
  1109. props: props,
  1110. args: args
  1111. } ) );
  1112. queries.push( query );
  1113. }
  1114. return query;
  1115. };
  1116. }())
  1117. });
  1118. /**
  1119. * wp.media.model.Selection
  1120. *
  1121. * Used to manage a selection of attachments in the views.
  1122. *
  1123. * @constructor
  1124. * @augments wp.media.model.Attachments
  1125. * @augments Backbone.Collection
  1126. */
  1127. media.model.Selection = Attachments.extend({
  1128. /**
  1129. * Refresh the `single` model whenever the selection changes.
  1130. * Binds `single` instead of using the context argument to ensure
  1131. * it receives no parameters.
  1132. *
  1133. * @param {Array} [models=[]] Array of models used to populate the collection.
  1134. * @param {Object} [options={}]
  1135. */
  1136. initialize: function( models, options ) {
  1137. /**
  1138. * call 'initialize' directly on the parent class
  1139. */
  1140. Attachments.prototype.initialize.apply( this, arguments );
  1141. this.multiple = options && options.multiple;
  1142. this.on( 'add remove reset', _.bind( this.single, this, false ) );
  1143. },
  1144. /**
  1145. * Override the selection's add method.
  1146. * If the workflow does not support multiple
  1147. * selected attachments, reset the selection.
  1148. *
  1149. * Overrides Backbone.Collection.add
  1150. * Overrides wp.media.model.Attachments.add
  1151. *
  1152. * @param {Array} models
  1153. * @param {Object} options
  1154. * @returns {wp.media.model.Attachment[]}
  1155. */
  1156. add: function( models, options ) {
  1157. if ( ! this.multiple ) {
  1158. this.remove( this.models );
  1159. }
  1160. /**
  1161. * call 'add' directly on the parent class
  1162. */
  1163. return Attachments.prototype.add.call( this, models, options );
  1164. },
  1165. /**
  1166. * Triggered when toggling (clicking on) an attachment in the modal
  1167. *
  1168. * @param {undefined|boolean|wp.media.model.Attachment} model
  1169. *
  1170. * @fires wp.media.model.Selection#selection:single
  1171. * @fires wp.media.model.Selection#selection:unsingle
  1172. *
  1173. * @returns {Backbone.Model}
  1174. */
  1175. single: function( model ) {
  1176. var previous = this._single;
  1177. // If a `model` is provided, use it as the single model.
  1178. if ( model ) {
  1179. this._single = model;
  1180. }
  1181. // If the single model isn't in the selection, remove it.
  1182. if ( this._single && ! this.get( this._single.cid ) ) {
  1183. delete this._single;
  1184. }
  1185. this._single = this._single || this.last();
  1186. // If single has changed, fire an event.
  1187. if ( this._single !== previous ) {
  1188. if ( previous ) {
  1189. previous.trigger( 'selection:unsingle', previous, this );
  1190. // If the model was already removed, trigger the collection
  1191. // event manually.
  1192. if ( ! this.get( previous.cid ) ) {
  1193. this.trigger( 'selection:unsingle', previous, this );
  1194. }
  1195. }
  1196. if ( this._single ) {
  1197. this._single.trigger( 'selection:single', this._single, this );
  1198. }
  1199. }
  1200. // Return the single model, or the last model as a fallback.
  1201. return this._single;
  1202. }
  1203. });
  1204. // Clean up. Prevents mobile browsers caching
  1205. $(window).on('unload', function(){
  1206. window.wp = null;
  1207. });
  1208. }(jQuery));