PageRenderTime 90ms CodeModel.GetById 28ms RepoModel.GetById 2ms app.codeStats 0ms

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

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