1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
var Attachments = wp.media.model.Attachments,
Query;
/**
* wp.media.model.Query
*
* A collection of attachments that match the supplied query arguments.
*
* Note: Do NOT change this.args after the query has been initialized.
* Things will break.
*
* @memberOf wp.media.model
*
* @class
* @augments wp.media.model.Attachments
* @augments Backbone.Collection
*
* @param {array} [models] Models to initialize with the collection.
* @param {object} [options] Options hash.
* @param {object} [options.args] Attachments query arguments.
* @param {object} [options.args.posts_per_page]
*/
Query = Attachments.extend(/** @lends wp.media.model.Query.prototype */{
/**
* @param {array} [models=[]] Array of initial models to populate the collection.
* @param {object} [options={}]
*/
initialize: function( models, options ) {
var allowed;
options = options || {};
Attachments.prototype.initialize.apply( this, arguments );
this.args = options.args;
this._hasMore = true;
this.created = new Date();
this.filters.order = function( attachment ) {
var orderby = this.props.get('orderby'),
order = this.props.get('order');
if ( ! this.comparator ) {
return true;
}
/*
* We want any items that can be placed before the last
* item in the set. If we add any items after the last
* item, then we can't guarantee the set is complete.
*/
if ( this.length ) {
return 1 !== this.comparator( attachment, this.last(), { ties: true });
/*
* Handle the case where there are no items yet and
* we're sorting for recent items. In that case, we want
* changes that occurred after we created the query.
*/
} else if ( 'DESC' === order && ( 'date' === orderby || 'modified' === orderby ) ) {
return attachment.get( orderby ) >= this.created;
// If we're sorting by menu order and we have no items,
// accept any items that have the default menu order (0).
} else if ( 'ASC' === order && 'menuOrder' === orderby ) {
return attachment.get( orderby ) === 0;
}
// Otherwise, we don't want any items yet.
return false;
};
/*
* Observe the central `wp.Uploader.queue` collection to watch for
* new matches for the query.
*
* Only observe when a limited number of query args are set. There
* are no filters for other properties, so observing will result in
* false positives in those queries.
*/
allowed = [ 's', 'order', 'orderby', 'posts_per_page', 'post_mime_type', 'post_parent', 'author' ];
if ( wp.Uploader && _( this.args ).chain().keys().difference( allowed ).isEmpty().value() ) {
this.observe( wp.Uploader.queue );
}
},
/**
* Whether there are more attachments that haven't been sync'd from the server
* that match the collection's query.
*
* @return {boolean}
*/
hasMore: function() {
return this._hasMore;
},
/**
* Fetch more attachments from the server for the collection.
*
* @param {object} [options={}]
* @return {Promise}
*/
more: function( options ) {
var query = this;
// If there is already a request pending, return early with the Deferred object.
if ( this._more && 'pending' === this._more.state() ) {
return this._more;
}
if ( ! this.hasMore() ) {
return jQuery.Deferred().resolveWith( this ).promise();
}
options = options || {};
options.remove = false;
return this._more = this.fetch( options ).done( function( resp ) {
if ( _.isEmpty( resp ) || -1 === this.args.posts_per_page || resp.length < this.args.posts_per_page ) {
query._hasMore = false;
}
});
},
/**
* Overrides Backbone.Collection.sync
* Overrides wp.media.model.Attachments.sync
*
* @param {String} method
* @param {Backbone.Model} model
* @param {Object} [options={}]
* @return {Promise}
*/
sync: function( method, model, options ) {
var args, fallback;
// Overload the read method so Attachment.fetch() functions correctly.
if ( 'read' === method ) {
options = options || {};
options.context = this;
options.data = _.extend( options.data || {}, {
action: 'query-attachments',
post_id: wp.media.model.settings.post.id
});
// Clone the args so manipulation is non-destructive.
args = _.clone( this.args );
// Determine which page to query.
if ( -1 !== args.posts_per_page ) {
args.paged = Math.round( this.length / args.posts_per_page ) + 1;
}
options.data.query = args;
return wp.media.ajax( options );
// Otherwise, fall back to `Backbone.sync()`.
} else {
/**
* Call wp.media.model.Attachments.sync or Backbone.sync
*/
fallback = Attachments.prototype.sync ? Attachments.prototype : Backbone;
return fallback.sync.apply( this, arguments );
}
}
}, /** @lends wp.media.model.Query */{
/**
* @readonly
*/
defaultProps: {
orderby: 'date',
order: 'DESC'
},
/**
* @readonly
*/
defaultArgs: {
posts_per_page: 40
},
/**
* @readonly
*/
orderby: {
allowed: [ 'name', 'author', 'date', 'title', 'modified', 'uploadedTo', 'id', 'post__in', 'menuOrder' ],
/**
* A map of JavaScript orderby values to their WP_Query equivalents.
* @type {Object}
*/
valuemap: {
'id': 'ID',
'uploadedTo': 'parent',
'menuOrder': 'menu_order ID'
}
},
/**
* A map of JavaScript query properties to their WP_Query equivalents.
*
* @readonly
*/
propmap: {
'search': 's',
'type': 'post_mime_type',
'perPage': 'posts_per_page',
'menuOrder': 'menu_order',
'uploadedTo': 'post_parent',
'status': 'post_status',
'include': 'post__in',
'exclude': 'post__not_in',
'author': 'author'
},
/**
* Creates and returns an Attachments Query collection given the properties.
*
* Caches query objects and reuses where possible.
*
* @static
* @method
*
* @param {object} [props]
* @param {Object} [props.cache=true] Whether to use the query cache or not.
* @param {Object} [props.order]
* @param {Object} [props.orderby]
* @param {Object} [props.include]
* @param {Object} [props.exclude]
* @param {Object} [props.s]
* @param {Object} [props.post_mime_type]
* @param {Object} [props.posts_per_page]
* @param {Object} [props.menu_order]
* @param {Object} [props.post_parent]
* @param {Object} [props.post_status]
* @param {Object} [props.author]
* @param {Object} [options]
*
* @return {wp.media.model.Query} A new Attachments Query collection.
*/
get: (function(){
/**
* @static
* @type Array
*/
var queries = [];
/**
* @return {Query}
*/
return function( props, options ) {
var args = {},
orderby = Query.orderby,
defaults = Query.defaultProps,
query,
cache = !! props.cache || _.isUndefined( props.cache );
// Remove the `query` property. This isn't linked to a query,
// this *is* the query.
delete props.query;
delete props.cache;
// Fill default args.
_.defaults( props, defaults );
// Normalize the order.
props.order = props.order.toUpperCase();
if ( 'DESC' !== props.order && 'ASC' !== props.order ) {
props.order = defaults.order.toUpperCase();
}
// Ensure we have a valid orderby value.
if ( ! _.contains( orderby.allowed, props.orderby ) ) {
props.orderby = defaults.orderby;
}
_.each( [ 'include', 'exclude' ], function( prop ) {
if ( props[ prop ] && ! _.isArray( props[ prop ] ) ) {
props[ prop ] = [ props[ prop ] ];
}
} );
// Generate the query `args` object.
// Correct any differing property names.
_.each( props, function( value, prop ) {
if ( _.isNull( value ) ) {
return;
}
args[ Query.propmap[ prop ] || prop ] = value;
});
// Fill any other default query args.
_.defaults( args, Query.defaultArgs );
// `props.orderby` does not always map directly to `args.orderby`.
// Substitute exceptions specified in orderby.keymap.
args.orderby = orderby.valuemap[ props.orderby ] || props.orderby;
// Search the query cache for a matching query.
if ( cache ) {
query = _.find( queries, function( query ) {
return _.isEqual( query.args, args );
});
} else {
queries = [];
}
// Otherwise, create a new query and add it to the cache.
if ( ! query ) {
query = new Query( [], _.extend( options || {}, {
props: props,
args: args
} ) );
queries.push( query );
}
return query;
};
}())
});
module.exports = Query;