<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[21898] trunk/wp-includes/js: Allow JS Attachments models to be searchable and sortable.</title>
</head>
<body>
<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; }
#msg dl a { font-weight: bold}
#msg dl a:link { color:#fc3; }
#msg dl a:active { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg > ul, #logmsg > ol { margin-left: 0; margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://core.trac.wordpress.org/changeset/21898">21898</a></dd>
<dt>Author</dt> <dd>koopersmith</dd>
<dt>Date</dt> <dd>2012-09-18 21:42:29 +0000 (Tue, 18 Sep 2012)</dd>
</dl>
<h3>Log Message</h3>
<pre>Allow JS Attachments models to be searchable and sortable.
Moves `wp.media.model.Query` sorting and searching to the parent `wp.media.model.Attachments`.
Query parameters are stored in `attachments.props`, which is a `Backbone.Model`, and supports `order` (`'ASC'` or `'DESC'`), `orderby` (any `Attachment` model property name), `search` (a search term), and `query` (a boolean value that ties the `Attachments` collection to the server).
`wp.media.query( args )` now returns an `Attachments` set that is mapped to a `Query` collection instead of the `Query` collection itself. This allows you to change the query arguments by updating `attachments.props` instead of fetching the mirrored arguments, changing them, and passing them to `wp.media.query()` again.
fixes <a href="http://core.trac.wordpress.org/ticket/21921">#21921</a>, see <a href="http://core.trac.wordpress.org/ticket/21390">#21390</a>, <a href="http://core.trac.wordpress.org/ticket/21809">#21809</a>.</pre>
<h3>Modified Paths</h3>
<ul>
<li><a href="#trunkwpincludesjsmediamodelsjs">trunk/wp-includes/js/media-models.js</a></li>
<li><a href="#trunkwpincludesjsmediaviewsjs">trunk/wp-includes/js/media-views.js</a></li>
</ul>
</div>
<div id="patch">
<h3>Diff</h3>
<a id="trunkwpincludesjsmediamodelsjs"></a>
<div class="modfile"><h4>Modified: trunk/wp-includes/js/media-models.js (21897 => 21898)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/wp-includes/js/media-models.js        2012-09-18 21:36:31 UTC (rev 21897)
+++ trunk/wp-includes/js/media-models.js        2012-09-18 21:42:29 UTC (rev 21898)
</span><span class="lines">@@ -2,7 +2,7 @@
</span><span class="cx">         var wp = {};
</span><span class="cx">
</span><span class="cx"> (function($){
</span><del>-        var Attachment, Attachments, Query;
</del><ins>+        var Attachment, Attachments, Query, compare;
</ins><span class="cx">
</span><span class="cx">         /**
</span><span class="cx">          * wp.media( attributes )
</span><span class="lines">@@ -27,6 +27,24 @@
</span><span class="cx">          * ========================================================================
</span><span class="cx">          */
</span><span class="cx">
</span><ins>+        /**
+         * A basic comparator.
+         *
+         * @param {mixed} a The primary parameter to compare.
+         * @param {mixed} b The primary parameter to compare.
+         * @param {string} ac The fallback parameter to compare, a's cid.
+         * @param {string} bc The fallback parameter to compare, b's cid.
+         * @return {number} -1: a should come before b.
+         * 0: a and b are of the same rank.
+         * 1: b should come before a.
+         */
+        compare = function( a, b, ac, bc ) {
+                if ( _.isEqual( a, b ) )
+                        return ac === bc ? 0 : (ac > bc ? -1 : 1);
+                else
+                        return a > b ? -1 : 1;
+        };
+
</ins><span class="cx">         _.extend( media, {
</span><span class="cx">                 /**
</span><span class="cx">                  * media.template( id )
</span><span class="lines">@@ -159,17 +177,75 @@
</span><span class="cx">                 initialize: function( models, options ) {
</span><span class="cx">                         options = options || {};
</span><span class="cx">
</span><ins>+                        this.props = new Backbone.Model();
</ins><span class="cx">                         this.filters = options.filters || {};
</span><span class="cx">
</span><ins>+                        // Bind default `change` events to the `props` model.
+                        this.props.on( 'change:order', this._changeOrder, this );
+                        this.props.on( 'change:orderby', this._changeOrderby, this );
+                        this.props.on( 'change:query', this._changeQuery, this );
+                        this.props.on( 'change:search', this._changeSearch, this );
+
+                        // Set the `props` model and fill the default property values.
+                        this.props.set( _.defaults( options.props || {}, {
+                                order: 'DESC'
+                        }) );
+
+                        // Observe another `Attachments` collection if one is provided.
</ins><span class="cx">                         if ( options.observe )
</span><span class="cx">                                 this.observe( options.observe );
</span><ins>+                },
</ins><span class="cx">
</span><del>-                        if ( options.mirror )
-                                this.mirror( options.mirror );
</del><ins>+                // Automatically sort the collection when the order changes.
+                _changeOrder: function( model, order ) {
+                        if ( this.comparator )
+                                this.sort();
</ins><span class="cx">                 },
</span><span class="cx">
</span><ins>+                // Set the default comparator only when the `orderby` property is set.
+                _changeOrderby: function( model, orderby ) {
+                        // If a different comparator is defined, bail.
+                        if ( this.comparator && this.comparator !== Attachments.comparator )
+                                return;
+
+                        if ( orderby )
+                                this.comparator = Attachments.comparator;
+                        else
+                                delete this.comparator;
+                },
+
+                // If the `query` property is set to true, query the server using
+                // the `props` values, and sync the results to this collection.
+                _changeQuery: function( model, query ) {
+                        if ( query ) {
+                                this.props.on( 'change', this._requery, this );
+                                this._requery();
+                        } else {
+                                this.props.off( 'change', this._requery, this );
+                        }
+                },
+
+                _changeSearch: function( model, term ) {
+                        // Bail if we're currently searching for the same term.
+                        if ( this.props.get('search') === term )
+                                return;
+
+                        if ( term && ! this.filters.search )
+                                this.filters.search = Attachments.filters.search;
+                        else if ( ! term && this.filters.search === Attachments.filters.search )
+                                delete this.filters.search;
+
+                        // If no `Attachments` model is provided to source the searches
+                        // from, then automatically generate a source from the existing
+                        // models.
+                        if ( ! this.props.get('source') )
+                                this.props.set( 'source', new Attachments( this.models ) );
+
+                        this.reset( this.props.get('source').filter( this.validator ) );
+                },
+
</ins><span class="cx">                 validator: function( attachment ) {
</span><del>-                        return _.all( this.filters, function( filter ) {
</del><ins>+                        return _.all( this.filters, function( filter, key ) {
</ins><span class="cx">                                 return !! filter.call( this, attachment );
</span><span class="cx">                         }, this );
</span><span class="cx">                 },
</span><span class="lines">@@ -230,34 +306,57 @@
</span><span class="cx">                                 var attachment = Attachment.get( attrs.id );
</span><span class="cx">                                 return attachment.set( attachment.parse( attrs, xhr ) );
</span><span class="cx">                         });
</span><ins>+                },
+
+                _requery: function() {
+                        if ( this.props.get('query') )
+                                this.mirror( Query.get( this.props.toJSON() ) );
</ins><span class="cx">                 }
</span><del>-        });
</del><ins>+        }, {
+                comparator: function( a, b ) {
+                        var key = this.props.get('orderby'),
+                                order = this.props.get('order'),
+                                ac = a.cid,
+                                bc = b.cid;
</ins><span class="cx">
</span><del>-        Attachments.all = new Attachments();
</del><ins>+                        a = a.get( key );
+                        b = b.get( key );
</ins><span class="cx">
</span><del>-        /**
-         * wp.media.query
-         */
-        media.query = (function(){
-                var queries = [];
</del><ins>+                        if ( 'date' === key || 'modified' === key ) {
+                                a = a || new Date();
+                                b = b || new Date();
+                        }
</ins><span class="cx">
</span><del>-                return function( args, options ) {
-                        args = _.defaults( args || {}, Query.defaultArgs );
</del><ins>+                        return ( 'DESC' === order ) ? compare( a, b, ac, bc ) : compare( b, a, bc, ac );
+                },
</ins><span class="cx">
</span><del>-                        var query = _.find( queries, function( query ) {
-                                return _.isEqual( query.args, args );
-                        });
</del><ins>+                filters: {
+                        // Note that this client-side searching is *not* equivalent
+                        // to our server-side searching.
+                        search: function( attachment ) {
+                                if ( ! this.searching )
+                                        return true;
</ins><span class="cx">
</span><del>-                        if ( ! query ) {
-                                query = new Query( [], _.extend( options || {}, { args: args } ) );
-                                queries.push( query );
</del><ins>+                                return _.any(['title','filename','description','caption','name'], function( key ) {
+                                        var value = attachment.get( key );
+                                        return value && -1 !== value.search( this.searching );
+                                }, this );
</ins><span class="cx">                         }
</span><ins>+                }
+        });
</ins><span class="cx">
</span><del>-                        return query;
-                };
-        }());
</del><ins>+        Attachments.all = new Attachments();
</ins><span class="cx">
</span><span class="cx">         /**
</span><ins>+         * wp.media.query
+         */
+        media.query = function( props ) {
+                return new Attachments( null, {
+                        props: _.extend( _.defaults( props || {}, { orderby: 'date' } ), { query: true } )
+                });
+        };
+
+        /**
</ins><span class="cx">          * wp.media.model.Query
</span><span class="cx">          *
</span><span class="cx">          * A set of attachments that corresponds to a set of consecutively paged
</span><span class="lines">@@ -268,39 +367,17 @@
</span><span class="cx">          */
</span><span class="cx">         Query = media.model.Query = Attachments.extend({
</span><span class="cx">                 initialize: function( models, options ) {
</span><del>-                        var orderby,
-                                defaultArgs = Query.defaultArgs;
-
</del><span class="cx">                         options = options || {};
</span><span class="cx">                         Attachments.prototype.initialize.apply( this, arguments );
</span><span class="cx">
</span><del>-                        // Generate this.args. Don't mess with them.
-                        this.args = _.defaults( options.args || {}, defaultArgs );
-
-                        // Normalize the order.
-                        this.args.order = this.args.order.toUpperCase();
-                        if ( 'DESC' !== this.args.order && 'ASC' !== this.args.order )
-                                this.args.order = defaultArgs.order.toUpperCase();
-
-                        // Set allowed orderby values.
-                        // These map directly to attachment keys in most scenarios.
-                        // Exceptions are specified in orderby.keymap.
-                        orderby = {
-                                allowed: [ 'name', 'author', 'date', 'title', 'modified', 'parent', 'ID' ],
-                                keymap: {
-                                        'ID': 'id',
-                                        'parent': 'uploadedTo'
-                                }
-                        };
-
-                        if ( ! _.contains( orderby.allowed, this.args.orderby ) )
-                                this.args.orderby = defaultArgs.orderby;
-                        this.orderkey = orderby.keymap[ this.args.orderby ] || this.args.orderby;
-
</del><ins>+                        this.args = options.args;
</ins><span class="cx">                         this.hasMore = true;
</span><span class="cx">                         this.created = new Date();
</span><span class="cx">
</span><span class="cx">                         this.filters.order = function( attachment ) {
</span><ins>+                                if ( ! this.comparator )
+                                        return true;
+
</ins><span class="cx">                                 // We want any items that can be placed before the last
</span><span class="cx">                                 // item in the set. If we add any items after the last
</span><span class="cx">                                 // item, then we can't guarantee the set is complete.
</span><span class="lines">@@ -310,25 +387,14 @@
</span><span class="cx">                                 // Handle the case where there are no items yet and
</span><span class="cx">                                 // we're sorting for recent items. In that case, we want
</span><span class="cx">                                 // changes that occurred after we created the query.
</span><del>-                                } else if ( 'DESC' === this.args.order && ( 'date' === this.orderkey || 'modified' === this.orderkey ) ) {
-                                        return attachment.get( this.orderkey ) >= this.created;
</del><ins>+                                } else if ( 'DESC' === this.args.order && ( 'date' === this.args.orderby || 'modified' === this.args.orderby ) ) {
+                                        return attachment.get( this.args.orderby ) >= this.created;
</ins><span class="cx">                                 }
</span><span class="cx">
</span><span class="cx">                                 // Otherwise, we don't want any items yet.
</span><span class="cx">                                 return false;
</span><span class="cx">                         };
</span><span class="cx">
</span><del>-                        if ( this.args.s ) {
-                                // Note that this client-side searching is *not* equivalent
-                                // to our server-side searching.
-                                this.filters.search = function( attachment ) {
-                                        return _.any(['title','filename','description','caption','name'], function( key ) {
-                                                var value = attachment.get( key );
-                                                return value && -1 !== value.search( this.args.s );
-                                        }, this );
-                                };
-                        }
-
</del><span class="cx">                         this.observe( Attachments.all );
</span><span class="cx">                 },
</span><span class="cx">
</span><span class="lines">@@ -372,50 +438,72 @@
</span><span class="cx">                                 fallback = Attachments.prototype.sync ? Attachments.prototype : Backbone;
</span><span class="cx">                                 return fallback.sync.apply( this, arguments );
</span><span class="cx">                         }
</span><ins>+                }
+        }, {
+                defaultArgs: {
+                        posts_per_page: 40,
+                        orderby: 'date',
+                        order: 'DESC'
</ins><span class="cx">                 },
</span><span class="cx">
</span><del>-                comparator: (function(){
-                        /**
-                         * A basic comparator.
-                         *
-                         * @param {mixed} a The primary parameter to compare.
-                         * @param {mixed} b The primary parameter to compare.
-                         * @param {string} ac The fallback parameter to compare, a's cid.
-                         * @param {string} bc The fallback parameter to compare, b's cid.
-                         * @return {number} -1: a should come before b.
-                         * 0: a and b are of the same rank.
-                         * 1: b should come before a.
-                         */
-                        var compare = function( a, b, ac, bc ) {
-                                if ( _.isEqual( a, b ) )
-                                        return ac === bc ? 0 : (ac > bc ? -1 : 1);
-                                else
-                                        return a > b ? -1 : 1;
-                        };
</del><ins>+                orderby: {
+                        allowed: [ 'name', 'author', 'date', 'title', 'modified', 'parent', 'ID' ],
+                        keymap: {
+                                'id': 'ID',
+                                'uploadedTo': 'parent'
+                        }
+                },
</ins><span class="cx">
</span><del>-                        return function( a, b ) {
-                                var key = this.orderkey,
-                                        order = this.args.order,
-                                        ac = a.cid,
-                                        bc = b.cid;
</del><ins>+                propmap: {
+                        'search': 's'
+                },
</ins><span class="cx">
</span><del>-                                a = a.get( key );
-                                b = b.get( key );
</del><ins>+                // Caches query objects so queries can be easily reused.
+                get: (function(){
+                        var queries = [];
</ins><span class="cx">
</span><del>-                                if ( 'date' === key || 'modified' === key ) {
-                                        a = a || new Date();
-                                        b = b || new Date();
</del><ins>+                        return function( props, options ) {
+                                var args = {},
+                                        orderby = Query.orderby,
+                                        defaults = Query.defaultArgs,
+                                        query;
+
+                                // Correct any differing property names.
+                                _.each( props, function( value, prop ) {
+                                        args[ Query.propmap[ prop ] || prop ] = value;
+                                });
+
+                                // Fill default args.
+                                _.defaults( args, defaults );
+
+                                // Normalize the order.
+                                args.order = args.order.toUpperCase();
+                                if ( 'DESC' !== args.order && 'ASC' !== args.order )
+                                        args.order = defaults.order.toUpperCase();
+
+                                // Set allowed orderby values.
+                                // These map directly to attachment keys in most scenarios.
+                                // Substitute exceptions specified in orderby.keymap.
+                                args.orderby = orderby.keymap[ args.orderby ] || args.orderby;
+
+                                // Ensure we have a valid orderby value.
+                                if ( ! _.contains( orderby.allowed, args.orderby ) )
+                                        args.orderby = defaults.orderby;
+
+                                // Search the query cache.
+                                query = _.find( queries, function( query ) {
+                                        return _.isEqual( query.args, args );
+                                });
+
+                                // Otherwise, create a new query and add it to the cache.
+                                if ( ! query ) {
+                                        query = new Query( [], _.extend( options || {}, { args: args } ) );
+                                        queries.push( query );
</ins><span class="cx">                                 }
</span><span class="cx">
</span><del>-                                return ( 'DESC' === order ) ? compare( a, b, ac, bc ) : compare( b, a, bc, ac );
</del><ins>+                                return query;
</ins><span class="cx">                         };
</span><span class="cx">                 }())
</span><del>-        }, {
-                defaultArgs: {
-                        posts_per_page: 40,
-                        orderby: 'date',
-                        order: 'DESC'
-                }
</del><span class="cx">         });
</span><span class="cx">
</span><span class="cx"> }(jQuery));
</span><span class="cx">\ No newline at end of file
</span></span></pre></div>
<a id="trunkwpincludesjsmediaviewsjs"></a>
<div class="modfile"><h4>Modified: trunk/wp-includes/js/media-views.js (21897 => 21898)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/wp-includes/js/media-views.js        2012-09-18 21:36:31 UTC (rev 21897)
+++ trunk/wp-includes/js/media-views.js        2012-09-18 21:42:29 UTC (rev 21898)
</span><span class="lines">@@ -348,9 +348,7 @@
</span><span class="cx">                         this.attachmentsView = new media.view.Attachments({
</span><span class="cx">                                 controller: this.controller,
</span><span class="cx">                                 directions: 'Select stuff.',
</span><del>-                                collection: new Attachments( null, {
-                                        mirror: media.query()
-                                })
</del><ins>+                                collection: media.query()
</ins><span class="cx">                         });
</span><span class="cx">
</span><span class="cx">                         this.$content.append( this.attachmentsView.$el );
</span><span class="lines">@@ -532,18 +530,12 @@
</span><span class="cx">                 },
</span><span class="cx">
</span><span class="cx">                 search: function( event ) {
</span><del>-                        var args = _.clone( this.collection.mirroring.args );
</del><ins>+                        var props = this.collection.props;
</ins><span class="cx">
</span><del>-                        // Bail if we're currently searching for the same string.
-                        if ( args.s === event.target.value )
-                                return;
-
</del><span class="cx">                         if ( event.target.value )
</span><del>-                                args.s = event.target.value;
</del><ins>+                                props.set( 'search', event.target.value );
</ins><span class="cx">                         else
</span><del>-                                delete args.s;
-
-                        this.collection.mirror( media.query( args ) );
</del><ins>+                                props.unset('search');
</ins><span class="cx">                 }
</span><span class="cx">         });
</span><span class="cx">
</span></span></pre>
</div>
</div>
</body>
</html>