PageRenderTime 54ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

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

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