1 /* global _wpThemeSettings, confirm */
2 window.wp = window.wp || {};
6 // Set up our namespace...
8 themes = wp.themes = wp.themes || {};
10 // Store the theme data and settings for organized and quick access
11 // themes.data.settings, themes.data.themes, themes.data.l10n
12 themes.data = _wpThemeSettings;
13 l10n = themes.data.l10n;
15 // Shortcut for isInstall check
16 themes.isInstall = !! themes.data.settings.isInstall;
18 // Setup app structure
19 _.extend( themes, { model: {}, view: {}, routes: {}, router: {}, template: wp.template });
21 themes.Model = Backbone.Model.extend({
22 // Adds attributes to the default data coming through the .org themes api
23 // Map `id` to `slug` for shared code
24 initialize: function() {
27 // If theme is already installed, set an attribute.
28 if ( _.indexOf( themes.data.installedThemes, this.get( 'slug' ) ) !== -1 ) {
29 this.set({ installed: true });
34 // slug is for installation, id is for existing.
35 id: this.get( 'slug' ) || this.get( 'id' )
38 // Map `section.description` to `description`
39 // as the API sometimes returns it differently
40 if ( this.has( 'sections' ) ) {
41 description = this.get( 'sections' ).description;
42 this.set({ description: description });
47 // Main view controller for themes.php
48 // Unifies and renders all available views
49 themes.view.Appearance = wp.Backbone.View.extend({
51 el: '#wpbody-content .wrap .theme-browser',
54 // Pagination instance
57 // Sets up a throttler for binding to 'scroll'
58 initialize: function( options ) {
59 // Scroller checks how far the scroll position is
60 _.bindAll( this, 'scroller' );
62 this.SearchView = options.SearchView ? options.SearchView : themes.view.Search;
63 // Bind to the scroll event and throttle
64 // the results from this.scroller
65 this.window.bind( 'scroll', _.throttle( this.scroller, 300 ) );
68 // Main render control
70 // Setup the main theme view
71 // with the current theme collection
72 this.view = new themes.view.Themes({
73 collection: this.collection,
77 // Render search form.
82 this.$el.empty().append( this.view.el ).addClass('rendered');
83 this.$el.append( '<br class="clear"/>' );
86 // Defines search element container
87 searchContainer: $( '#wpbody h2:first' ),
89 // Search input and view
90 // for current theme collection
95 // Don't render the search if there is only one theme
96 if ( themes.data.themes.length === 1 ) {
100 view = new this.SearchView({
101 collection: self.collection,
105 // Render and append after screen title
108 .append( $.parseHTML( '<label class="screen-reader-text" for="theme-search-input">' + l10n.search + '</label>' ) )
112 // Checks when the user gets close to the bottom
113 // of the mage and triggers a theme:scroll event
114 scroller: function() {
118 bottom = this.window.scrollTop() + self.window.height();
119 threshold = self.$el.offset().top + self.$el.outerHeight( false ) - self.window.height();
120 threshold = Math.round( threshold * 0.9 );
122 if ( bottom > threshold ) {
123 this.trigger( 'theme:scroll' );
128 // Set up the Collection for our theme data
129 // @has 'id' 'name' 'screenshot' 'author' 'authorURI' 'version' 'active' ...
130 themes.Collection = Backbone.Collection.extend({
137 // Controls searching on the current theme collection
138 // and triggers an update event
139 doSearch: function( value ) {
141 // Don't do anything if we've already done this search
142 // Useful because the Search handler fires multiple times per keystroke
143 if ( this.terms === value ) {
147 // Updates terms with the value passed
150 // If we have terms, run a search...
151 if ( this.terms.length > 0 ) {
152 this.search( this.terms );
155 // If search is blank, show all themes
156 // Useful for resetting the views when you clean the input
157 if ( this.terms === '' ) {
158 this.reset( themes.data.themes );
161 // Trigger an 'update' event
162 this.trigger( 'update' );
165 // Performs a search within the collection
167 search: function( term ) {
168 var match, results, haystack;
170 // Start with a full collection
171 this.reset( themes.data.themes, { silent: true } );
173 // Escape the term string for RegExp meta characters
174 term = term.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' );
176 // Consider spaces as word delimiters and match the whole string
177 // so matching terms can be combined
178 term = term.replace( / /g, ')(?=.*' );
179 match = new RegExp( '^(?=.*' + term + ').+', 'i' );
182 // _.filter and .test
183 results = this.filter( function( data ) {
184 haystack = _.union( data.get( 'name' ), data.get( 'id' ), data.get( 'description' ), data.get( 'author' ), data.get( 'tags' ) );
186 if ( match.test( data.get( 'author' ) ) && term.length > 2 ) {
187 data.set( 'displayAuthor', true );
190 return match.test( haystack );
193 this.reset( results );
196 // Paginates the collection with a helper method
197 // that slices the collection
198 paginate: function( instance ) {
199 var collection = this;
200 instance = instance || 0;
202 // Themes per instance are set at 20
203 collection = _( collection.rest( 20 * instance ) );
204 collection = _( collection.first( 20 ) );
211 // Handles requests for more themes
212 // and caches results
214 // When we are missing a cache object we fire an apiCall()
215 // which triggers events of `query:success` or `query:fail`
216 query: function( request ) {
221 var queries = this.queries,
223 query, isPaginated, count;
225 // Store current query request args
226 // for later use with the event `theme:end`
227 this.currentQuery.request = request;
229 // Search the query cache for matches.
230 query = _.find( queries, function( query ) {
231 return _.isEqual( query.request, request );
234 // If the request matches the stored currentQuery.request
235 // it means we have a paginated request.
236 isPaginated = _.has( request, 'page' );
238 // Reset the internal api page counter for non paginated queries.
239 if ( ! isPaginated ) {
240 this.currentQuery.page = 1;
243 // Otherwise, send a new API call and add it to the cache.
244 if ( ! query && ! isPaginated ) {
245 query = this.apiCall( request ).done( function( data ) {
247 // Update the collection with the queried data.
249 self.reset( data.themes );
250 count = data.info.results;
251 // Store the results and the query request
252 queries.push( { themes: data.themes, request: request, total: count } );
255 // Trigger a collection refresh event
256 // and a `query:success` event with a `count` argument.
257 self.trigger( 'update' );
258 self.trigger( 'query:success', count );
260 if ( data.themes && data.themes.length === 0 ) {
261 self.trigger( 'query:empty' );
264 }).fail( function() {
265 self.trigger( 'query:fail' );
268 // If it's a paginated request we need to fetch more themes...
270 return this.apiCall( request, isPaginated ).done( function( data ) {
271 // Add the new themes to the current collection
272 // @todo update counter
273 self.add( data.themes );
274 self.trigger( 'query:success' );
276 // We are done loading themes for now.
277 self.loadingThemes = false;
279 }).fail( function() {
280 self.trigger( 'query:fail' );
284 if ( query.themes.length === 0 ) {
285 self.trigger( 'query:empty' );
287 $( 'body' ).removeClass( 'no-results' );
290 // Only trigger an update event since we already have the themes
291 // on our cached object
292 if ( _.isNumber( query.total ) ) {
293 this.count = query.total;
296 this.reset( query.themes );
297 if ( ! query.total ) {
298 this.count = this.length;
301 this.trigger( 'update' );
302 this.trigger( 'query:success', this.count );
306 // Local cache array for API queries
309 // Keep track of current query so we can handle pagination
315 // Send request to api.wordpress.org/themes
316 apiCall: function( request, paginated ) {
317 return wp.ajax.send( 'query-themes', {
336 beforeSend: function() {
339 $( 'body' ).addClass( 'loading-themes' ).removeClass( 'no-results' );
345 // Static status controller for when we are loading themes.
349 // This is the view that controls each theme item
350 // that will be displayed on the screen
351 themes.view.Theme = wp.Backbone.View.extend({
353 // Wrap theme data on a div.theme element
356 // Reflects which theme view we have
357 // 'grid' (default) or 'detail'
360 // The HTML template for each element to be rendered
361 html: themes.template( 'theme' ),
364 'click': themes.isInstall ? 'preview': 'expand',
365 'click .preview': 'preview',
366 'keydown': themes.isInstall ? 'preview': 'expand',
367 'touchend': themes.isInstall ? 'preview': 'expand',
369 'touchmove': 'preventExpand'
375 var data = this.model.toJSON();
376 // Render themes using the html template
377 this.$el.html( this.html( data ) ).attr({
379 'aria-describedby' : data.id + '-action ' + data.id + '-name'
382 // Renders active theme styles
385 if ( this.model.get( 'displayAuthor' ) ) {
386 this.$el.addClass( 'display-author' );
389 if ( this.model.get( 'installed' ) ) {
390 this.$el.addClass( 'is-installed' );
394 // Adds a class to the currently active theme
395 // and to the overlay in detailed view mode
396 activeTheme: function() {
397 if ( this.model.get( 'active' ) ) {
398 this.$el.addClass( 'active' );
402 // Add class of focus to the theme we are focused on.
403 addFocus: function() {
404 var $themeToFocus = ( $( ':focus' ).hasClass( 'theme' ) ) ? $( ':focus' ) : $(':focus').parents('.theme');
406 $('.theme.focus').removeClass('focus');
407 $themeToFocus.addClass('focus');
410 // Single theme overlay screen
411 // It's shown when clicking a theme
412 expand: function( event ) {
415 event = event || window.event;
417 // 'enter' and 'space' keys expand the details view when a theme is :focused
418 if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
422 // Bail if the user scrolled on a touch device
423 if ( this.touchDrag === true ) {
424 return this.touchDrag = false;
427 // Prevent the modal from showing when the user clicks
428 // one of the direct action buttons
429 if ( $( event.target ).is( '.theme-actions a' ) ) {
433 // Set focused theme to current element
434 themes.focusedTheme = this.$el;
436 this.trigger( 'theme:expand', self.model.cid );
439 preventExpand: function() {
440 this.touchDrag = true;
443 preview: function( event ) {
447 // Bail if the user scrolled on a touch device
448 if ( this.touchDrag === true ) {
449 return this.touchDrag = false;
452 // Allow direct link path to installing a theme.
453 if ( $( event.target ).hasClass( 'button-primary' ) ) {
457 // 'enter' and 'space' keys expand the details view when a theme is :focused
458 if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
462 // pressing enter while focused on the buttons shouldn't open the preview
463 if ( event.type === 'keydown' && event.which !== 13 && $( ':focus' ).hasClass( 'button' ) ) {
467 event.preventDefault();
469 event = event || window.event;
471 // Set focus to current theme.
472 themes.focusedTheme = this.$el;
474 // Construct a new Preview view.
475 preview = new themes.view.Preview({
479 // Render the view and append it.
481 this.setNavButtonsState();
483 // Hide previous/next navigation if there is only one theme
484 if ( this.model.collection.length === 1 ) {
485 preview.$el.addClass( 'no-navigation' );
487 preview.$el.removeClass( 'no-navigation' );
491 $( 'div.wrap' ).append( preview.el );
493 // Listen to our preview object
494 // for `theme:next` and `theme:previous` events.
495 this.listenTo( preview, 'theme:next', function() {
497 // Keep local track of current theme model.
498 current = self.model;
500 // If we have ventured away from current model update the current model position.
501 if ( ! _.isUndefined( self.current ) ) {
502 current = self.current;
505 // Get previous theme model.
506 self.current = self.model.collection.at( self.model.collection.indexOf( current ) + 1 );
508 // If we have no more themes, bail.
509 if ( _.isUndefined( self.current ) ) {
510 self.options.parent.parent.trigger( 'theme:end' );
511 return self.current = current;
514 // Construct a new Preview view.
515 preview = new themes.view.Preview({
519 // Render and append.
521 this.setNavButtonsState();
522 $( 'div.wrap' ).append( preview.el );
523 $( '.next-theme' ).focus();
525 .listenTo( preview, 'theme:previous', function() {
527 // Keep track of current theme model.
528 current = self.model;
530 // Bail early if we are at the beginning of the collection
531 if ( self.model.collection.indexOf( self.current ) === 0 ) {
535 // If we have ventured away from current model update the current model position.
536 if ( ! _.isUndefined( self.current ) ) {
537 current = self.current;
540 // Get previous theme model.
541 self.current = self.model.collection.at( self.model.collection.indexOf( current ) - 1 );
543 // If we have no more themes, bail.
544 if ( _.isUndefined( self.current ) ) {
548 // Construct a new Preview view.
549 preview = new themes.view.Preview({
553 // Render and append.
555 this.setNavButtonsState();
556 $( 'div.wrap' ).append( preview.el );
557 $( '.previous-theme' ).focus();
560 this.listenTo( preview, 'preview:close', function() {
561 self.current = self.model;
565 // Handles .disabled classes for previous/next buttons in theme installer preview
566 setNavButtonsState: function() {
567 var $themeInstaller = $( '.theme-install-overlay' ),
568 current = _.isUndefined( this.current ) ? this.model : this.current;
570 // Disable previous at the zero position
571 if ( 0 === this.model.collection.indexOf( current ) ) {
572 $themeInstaller.find( '.previous-theme' ).addClass( 'disabled' );
575 // Disable next if the next model is undefined
576 if ( _.isUndefined( this.model.collection.at( this.model.collection.indexOf( current ) + 1 ) ) ) {
577 $themeInstaller.find( '.next-theme' ).addClass( 'disabled' );
582 // Theme Details view
583 // Set ups a modal overlay with the expanded theme data
584 themes.view.Details = wp.Backbone.View.extend({
586 // Wrap theme data on a div.theme element
587 className: 'theme-overlay',
591 'click .delete-theme': 'deleteTheme',
592 'click .left': 'previousTheme',
593 'click .right': 'nextTheme'
596 // The HTML template for the theme overlay
597 html: themes.template( 'theme-single' ),
600 var data = this.model.toJSON();
601 this.$el.html( this.html( data ) );
602 // Renders active theme styles
604 // Set up navigation events
606 // Checks screenshot size
607 this.screenshotCheck( this.$el );
608 // Contain "tabbing" inside the overlay
609 this.containFocus( this.$el );
612 // Adds a class to the currently active theme
613 // and to the overlay in detailed view mode
614 activeTheme: function() {
615 // Check the model has the active property
616 this.$el.toggleClass( 'active', this.model.get( 'active' ) );
619 // Keeps :focus within the theme details elements
620 containFocus: function( $el ) {
623 // Move focus to the primary action
624 _.delay( function() {
625 $( '.theme-wrap a.button-primary:visible' ).focus();
628 $el.on( 'keydown.wp-themes', function( event ) {
631 if ( event.which === 9 ) {
632 $target = $( event.target );
634 // Keep focus within the overlay by making the last link on theme actions
635 // switch focus to button.left on tabbing and vice versa
636 if ( $target.is( 'button.left' ) && event.shiftKey ) {
637 $el.find( '.theme-actions a:last-child' ).focus();
638 event.preventDefault();
639 } else if ( $target.is( '.theme-actions a:last-child' ) ) {
640 $el.find( 'button.left' ).focus();
641 event.preventDefault();
647 // Single theme overlay screen
648 // It's shown when clicking a theme
649 collapse: function( event ) {
653 event = event || window.event;
655 // Prevent collapsing detailed view when there is only one theme available
656 if ( themes.data.themes.length === 1 ) {
660 // Detect if the click is inside the overlay
661 // and don't close it unless the target was
662 // the div.back button
663 if ( $( event.target ).is( '.theme-backdrop' ) || $( event.target ).is( '.close' ) || event.keyCode === 27 ) {
665 // Add a temporary closing class while overlay fades out
666 $( 'body' ).addClass( 'closing-overlay' );
668 // With a quick fade out animation
669 this.$el.fadeOut( 130, function() {
670 // Clicking outside the modal box closes the overlay
671 $( 'body' ).removeClass( 'closing-overlay' );
672 // Handle event cleanup
675 // Get scroll position to avoid jumping to the top
676 scroll = document.body.scrollTop;
678 // Clean the url structure
679 themes.router.navigate( themes.router.baseUrl( '' ) );
681 // Restore scroll position
682 document.body.scrollTop = scroll;
684 // Return focus to the theme div
685 if ( themes.focusedTheme ) {
686 themes.focusedTheme.focus();
692 // Handles .disabled classes for next/previous buttons
693 navigation: function() {
695 // Disable Left/Right when at the start or end of the collection
696 if ( this.model.cid === this.model.collection.at(0).cid ) {
697 this.$el.find( '.left' ).addClass( 'disabled' );
699 if ( this.model.cid === this.model.collection.at( this.model.collection.length - 1 ).cid ) {
700 this.$el.find( '.right' ).addClass( 'disabled' );
704 // Performs the actions to effectively close
705 // the theme details overlay
706 closeOverlay: function() {
707 $( 'body' ).removeClass( 'theme-overlay-open' );
710 this.trigger( 'theme:collapse' );
713 // Confirmation dialog for deleting a theme
714 deleteTheme: function() {
715 return confirm( themes.data.settings.confirmDelete );
718 nextTheme: function() {
720 self.trigger( 'theme:next', self.model.cid );
724 previousTheme: function() {
726 self.trigger( 'theme:previous', self.model.cid );
730 // Checks if the theme screenshot is the old 300px width version
731 // and adds a corresponding class if it's true
732 screenshotCheck: function( el ) {
733 var screenshot, image;
735 screenshot = el.find( '.screenshot img' );
737 image.src = screenshot.attr( 'src' );
740 if ( image.width && image.width <= 300 ) {
741 el.addClass( 'small-screenshot' );
746 // Theme Preview view
747 // Set ups a modal overlay with the expanded theme data
748 themes.view.Preview = themes.view.Details.extend({
750 className: 'wp-full-overlay expanded',
751 el: '.theme-install-overlay',
754 'click .close-full-overlay': 'close',
755 'click .collapse-sidebar': 'collapse',
756 'click .previous-theme': 'previousTheme',
757 'click .next-theme': 'nextTheme',
761 // The HTML template for the theme preview
762 html: themes.template( 'theme-preview' ),
765 var data = this.model.toJSON();
767 this.$el.html( this.html( data ) );
769 themes.router.navigate( themes.router.baseUrl( '?theme=' + this.model.get( 'id' ) ), { replace: true } );
771 this.$el.fadeIn( 200, function() {
772 $( 'body' ).addClass( 'theme-installer-active full-overlay-active' );
773 $( '.close-full-overlay' ).focus();
778 this.$el.fadeOut( 200, function() {
779 $( 'body' ).removeClass( 'theme-installer-active full-overlay-active' );
781 // Return focus to the theme div
782 if ( themes.focusedTheme ) {
783 themes.focusedTheme.focus();
787 themes.router.navigate( themes.router.baseUrl( '' ) );
788 this.trigger( 'preview:close' );
793 collapse: function() {
795 this.$el.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
799 keyEvent: function( event ) {
800 // The escape key closes the preview
801 if ( event.keyCode === 27 ) {
802 this.undelegateEvents();
805 // The right arrow key, next theme
806 if ( event.keyCode === 39 ) {
807 _.once( this.nextTheme() );
810 // The left arrow key, previous theme
811 if ( event.keyCode === 37 ) {
812 this.previousTheme();
817 // Controls the rendering of div.themes,
818 // a wrapper that will hold all the theme elements
819 themes.view.Themes = wp.Backbone.View.extend({
822 $overlay: $( 'div.theme-overlay' ),
824 // Number to keep track of scroll position
825 // while in theme-overlay mode
828 // The theme count element
829 count: $( '.theme-count' ),
831 initialize: function( options ) {
835 this.parent = options.parent;
837 // Set current view to [grid]
838 this.setView( 'grid' );
840 // Move the active theme to the beginning of the collection
843 // When the collection is updated by user input...
844 this.listenTo( self.collection, 'update', function() {
845 self.parent.page = 0;
850 // Update theme count to full result set when available.
851 this.listenTo( self.collection, 'query:success', function( count ) {
852 if ( _.isNumber( count ) ) {
853 self.count.text( count );
855 self.count.text( self.collection.length );
859 this.listenTo( self.collection, 'query:empty', function() {
860 $( 'body' ).addClass( 'no-results' );
863 this.listenTo( this.parent, 'theme:scroll', function() {
864 self.renderThemes( self.parent.page );
867 this.listenTo( this.parent, 'theme:close', function() {
868 if ( self.overlay ) {
869 self.overlay.closeOverlay();
873 // Bind keyboard events.
874 $( 'body' ).on( 'keyup', function( event ) {
875 if ( ! self.overlay ) {
879 // Pressing the right arrow key fires a theme:next event
880 if ( event.keyCode === 39 ) {
881 self.overlay.nextTheme();
884 // Pressing the left arrow key fires a theme:previous event
885 if ( event.keyCode === 37 ) {
886 self.overlay.previousTheme();
889 // Pressing the escape key fires a theme:collapse event
890 if ( event.keyCode === 27 ) {
891 self.overlay.collapse( event );
896 // Manages rendering of theme pages
897 // and keeping theme count in sync
899 // Clear the DOM, please
902 // If the user doesn't have switch capabilities
903 // or there is only one theme in the collection
904 // render the detailed view of the active theme
905 if ( themes.data.themes.length === 1 ) {
907 // Constructs the view
908 this.singleTheme = new themes.view.Details({
909 model: this.collection.models[0]
912 // Render and apply a 'single-theme' class to our container
913 this.singleTheme.render();
914 this.$el.addClass( 'single-theme' );
915 this.$el.append( this.singleTheme.el );
918 // Generate the themes
919 // Using page instance
920 // While checking the collection has items
921 if ( this.options.collection.size() > 0 ) {
922 this.renderThemes( this.parent.page );
925 // Display a live theme count for the collection
926 this.count.text( this.collection.count ? this.collection.count : this.collection.length );
929 // Iterates through each instance of the collection
930 // and renders each theme module
931 renderThemes: function( page ) {
934 self.instance = self.collection.paginate( page );
936 // If we have no more themes bail
937 if ( self.instance.size() === 0 ) {
938 // Fire a no-more-themes event.
939 this.parent.trigger( 'theme:end' );
943 // Make sure the add-new stays at the end
945 $( '.add-new-theme' ).remove();
948 // Loop through the themes and setup each theme view
949 self.instance.each( function( theme ) {
950 self.theme = new themes.view.Theme({
955 // Render the views...
957 // and append them to div.themes
958 self.$el.append( self.theme.el );
960 // Binds to theme:expand to show the modal box
961 // with the theme details
962 self.listenTo( self.theme, 'theme:expand', self.expand, self );
965 // 'Add new theme' element shown at the end of the grid
966 if ( themes.data.settings.canInstall ) {
967 this.$el.append( '<div class="theme add-new-theme"><a href="' + themes.data.settings.installURI + '"><div class="theme-screenshot"><span></span></div><h3 class="theme-name">' + l10n.addNew + '</h3></a></div>' );
973 // Grabs current theme and puts it at the beginning of the collection
974 currentTheme: function() {
978 current = self.collection.findWhere({ active: true });
980 // Move the active theme to the beginning of the collection
982 self.collection.remove( current );
983 self.collection.add( current, { at:0 } );
988 setView: function( view ) {
992 // Renders the overlay with the ThemeDetails view
993 // Uses the current model data
994 expand: function( id ) {
997 // Set the current theme model
998 this.model = self.collection.get( id );
1000 // Trigger a route update for the current model
1001 themes.router.navigate( themes.router.baseUrl( '?theme=' + this.model.id ) );
1003 // Sets this.view to 'detail'
1004 this.setView( 'detail' );
1005 $( 'body' ).addClass( 'theme-overlay-open' );
1007 // Set up the theme details view
1008 this.overlay = new themes.view.Details({
1012 this.overlay.render();
1013 this.$overlay.html( this.overlay.el );
1015 // Bind to theme:next and theme:previous
1016 // triggered by the arrow keys
1018 // Keep track of the current model so we
1019 // can infer an index position
1020 this.listenTo( this.overlay, 'theme:next', function() {
1021 // Renders the next theme on the overlay
1022 self.next( [ self.model.cid ] );
1025 .listenTo( this.overlay, 'theme:previous', function() {
1026 // Renders the previous theme on the overlay
1027 self.previous( [ self.model.cid ] );
1031 // This method renders the next theme on the overlay modal
1032 // based on the current position in the collection
1033 // @params [model cid]
1034 next: function( args ) {
1038 // Get the current theme
1039 model = self.collection.get( args[0] );
1040 // Find the next model within the collection
1041 nextModel = self.collection.at( self.collection.indexOf( model ) + 1 );
1043 // Sanity check which also serves as a boundary test
1044 if ( nextModel !== undefined ) {
1046 // We have a new theme...
1047 // Close the overlay
1048 this.overlay.closeOverlay();
1050 // Trigger a route update for the current model
1051 self.theme.trigger( 'theme:expand', nextModel.cid );
1056 // This method renders the previous theme on the overlay modal
1057 // based on the current position in the collection
1058 // @params [model cid]
1059 previous: function( args ) {
1061 model, previousModel;
1063 // Get the current theme
1064 model = self.collection.get( args[0] );
1065 // Find the previous model within the collection
1066 previousModel = self.collection.at( self.collection.indexOf( model ) - 1 );
1068 if ( previousModel !== undefined ) {
1070 // We have a new theme...
1071 // Close the overlay
1072 this.overlay.closeOverlay();
1074 // Trigger a route update for the current model
1075 self.theme.trigger( 'theme:expand', previousModel.cid );
1081 // Search input view controller.
1082 themes.view.Search = wp.Backbone.View.extend({
1085 className: 'theme-search',
1086 id: 'theme-search-input',
1090 placeholder: l10n.searchPlaceholder,
1102 initialize: function( options ) {
1104 this.parent = options.parent;
1106 this.listenTo( this.parent, 'theme:close', function() {
1107 this.searching = false;
1112 // Runs a search on the theme collection.
1113 search: function( event ) {
1117 if ( event.type === 'keyup' && event.which === 27 ) {
1118 event.target.value = '';
1121 // Lose input focus when pressing enter
1122 if ( event.which === 13 ) {
1123 this.$el.trigger( 'blur' );
1126 this.collection.doSearch( event.target.value );
1128 // if search is initiated and key is not return
1129 if ( this.searching && event.which !== 13 ) {
1130 options.replace = true;
1132 this.searching = true;
1135 // Update the URL hash
1136 if ( event.target.value ) {
1137 themes.router.navigate( themes.router.baseUrl( '?search=' + event.target.value ), options );
1139 themes.router.navigate( themes.router.baseUrl( '' ) );
1143 pushState: function( event ) {
1144 var url = themes.router.baseUrl( '' );
1146 if ( event.target.value ) {
1147 url = themes.router.baseUrl( '?search=' + event.target.value );
1150 this.searching = false;
1151 themes.router.navigate( url );
1156 // Sets up the routes events for relevant url queries
1157 // Listens to [theme] and [search] params
1158 themes.Router = Backbone.Router.extend({
1161 'themes.php?theme=:slug': 'theme',
1162 'themes.php?search=:query': 'search',
1163 'themes.php?s=:query': 'search',
1164 'themes.php': 'themes',
1168 baseUrl: function( url ) {
1169 return 'themes.php' + url;
1172 search: function( query ) {
1173 $( '.theme-search' ).val( query );
1176 themes: function() {
1177 $( '.theme-search' ).val( '' );
1180 navigate: function() {
1181 if ( Backbone.history._hasPushState ) {
1182 Backbone.Router.prototype.navigate.apply( this, arguments );
1188 // Execute and setup the application
1191 // Initializes the blog's theme library view
1192 // Create a new collection with data
1193 this.themes = new themes.Collection( themes.data.themes );
1196 this.view = new themes.view.Appearance({
1197 collection: this.themes
1203 render: function() {
1209 Backbone.history.start({
1210 root: themes.data.settings.adminUrl,
1216 routes: function() {
1218 // Bind to our global thx object
1219 // so that the object is available to sub-views
1220 themes.router = new themes.Router();
1222 // Handles theme details route event
1223 themes.router.on( 'route:theme', function( slug ) {
1224 self.view.view.expand( slug );
1227 themes.router.on( 'route:themes', function() {
1228 self.themes.doSearch( '' );
1229 self.view.trigger( 'theme:close' );
1232 // Handles search route event
1233 themes.router.on( 'route:search', function() {
1234 $( '.theme-search' ).trigger( 'keyup' );
1240 extraRoutes: function() {
1245 // Extend the main Search view
1246 themes.view.InstallerSearch = themes.view.Search.extend({
1252 // Handles Ajax request for searching through themes in public repo
1253 search: function( event ) {
1255 // Tabbing or reverse tabbing into the search input shouldn't trigger a search
1256 if ( event.type === 'keyup' && ( event.which === 9 || event.which === 16 ) ) {
1260 this.collection = this.options.parent.view.collection;
1263 if ( event.type === 'keyup' && event.which === 27 ) {
1264 event.target.value = '';
1267 _.debounce( _.bind( this.doSearch, this ), 300 )( event.target.value );
1270 doSearch: _.debounce( function( value ) {
1273 request.search = value;
1275 // Intercept an [author] search.
1277 // If input value starts with `author:` send a request
1278 // for `author` instead of a regular `search`
1279 if ( value.substring( 0, 7 ) === 'author:' ) {
1280 request.search = '';
1281 request.author = value.slice( 7 );
1284 // Intercept a [tag] search.
1286 // If input value starts with `tag:` send a request
1287 // for `tag` instead of a regular `search`
1288 if ( value.substring( 0, 4 ) === 'tag:' ) {
1289 request.search = '';
1290 request.tag = [ value.slice( 4 ) ];
1293 $( '.theme-section.current' ).removeClass( 'current' );
1294 $( 'body' ).removeClass( 'more-filters-opened filters-applied' );
1296 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1297 // or searching the local cache
1298 this.collection.query( request );
1301 themes.router.navigate( themes.router.baseUrl( '?search=' + value ), { replace: true } );
1305 themes.view.Installer = themes.view.Appearance.extend({
1307 el: '#wpbody-content .wrap',
1309 // Register events for sorting and filters in theme-navigation
1311 'click .theme-section': 'onSort',
1312 'click .theme-filter': 'onFilter',
1313 'click .more-filters': 'moreFilters',
1314 'click .apply-filters': 'applyFilters',
1315 'click [type="checkbox"]': 'addFilter',
1316 'click .clear-filters': 'clearFilters',
1317 'click .feature-name': 'filterSection',
1318 'click .filtering-by a': 'backToFilters'
1321 // Initial render method
1322 render: function() {
1328 this.collection = new themes.Collection();
1330 // Bump `collection.currentQuery.page` and request more themes if we hit the end of the page.
1331 this.listenTo( this, 'theme:end', function() {
1333 // Make sure we are not already loading
1334 if ( self.collection.loadingThemes ) {
1338 // Set loadingThemes to true and bump page instance of currentQuery.
1339 self.collection.loadingThemes = true;
1340 self.collection.currentQuery.page++;
1342 // Use currentQuery.page to build the themes request.
1343 _.extend( self.collection.currentQuery.request, { page: self.collection.currentQuery.page } );
1344 self.collection.query( self.collection.currentQuery.request );
1347 this.listenTo( this.collection, 'query:success', function() {
1348 $( 'body' ).removeClass( 'loading-themes' );
1349 $( '.theme-browser' ).find( 'div.error' ).remove();
1352 this.listenTo( this.collection, 'query:fail', function() {
1353 $( 'body' ).removeClass( 'loading-themes' );
1354 $( '.theme-browser' ).find( 'div.error' ).remove();
1355 $( '.theme-browser' ).find( 'div.themes' ).before( '<div class="error"><p>' + l10n.error + '</p></div>' );
1362 // Set ups the view and passes the section argument
1363 this.view = new themes.view.Themes({
1364 collection: this.collection,
1368 // Reset pagination every time the install view handler is run
1371 // Render and append
1372 this.$el.find( '.themes' ).remove();
1374 this.$el.find( '.theme-browser' ).append( this.view.el ).addClass( 'rendered' );
1377 // Handles all the rendering of the public theme directory
1378 browse: function( section ) {
1379 // Create a new collection with the proper theme data
1381 this.collection.query( { browse: section } );
1384 // Sorting navigation
1385 onSort: function( event ) {
1386 var $el = $( event.target ),
1387 sort = $el.data( 'sort' );
1389 event.preventDefault();
1391 $( 'body' ).removeClass( 'filters-applied more-filters-opened' );
1393 // Bail if this is already active
1394 if ( $el.hasClass( this.activeClass ) ) {
1400 // Trigger a router.naviagte update
1401 themes.router.navigate( themes.router.baseUrl( '?browse=' + sort ) );
1404 sort: function( sort ) {
1407 $( '.theme-section, .theme-filter' ).removeClass( this.activeClass );
1408 $( '[data-sort="' + sort + '"]' ).addClass( this.activeClass );
1410 this.browse( sort );
1414 onFilter: function( event ) {
1416 $el = $( event.target ),
1417 filter = $el.data( 'filter' );
1419 // Bail if this is already active
1420 if ( $el.hasClass( this.activeClass ) ) {
1424 $( '.theme-filter, .theme-section' ).removeClass( this.activeClass );
1425 $el.addClass( this.activeClass );
1431 // Construct the filter request
1432 // using the default values
1433 filter = _.union( filter, this.filtersChecked() );
1434 request = { tag: [ filter ] };
1436 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1437 // or searching the local cache
1438 this.collection.query( request );
1441 // Clicking on a checkbox to add another filter to the request
1442 addFilter: function() {
1443 this.filtersChecked();
1446 // Applying filters triggers a tag request
1447 applyFilters: function( event ) {
1449 tags = this.filtersChecked(),
1450 request = { tag: tags },
1451 filteringBy = $( '.filtering-by .tags' );
1454 event.preventDefault();
1457 $( 'body' ).addClass( 'filters-applied' );
1458 $( '.theme-section.current' ).removeClass( 'current' );
1459 filteringBy.empty();
1461 _.each( tags, function( tag ) {
1462 name = $( 'label[for="feature-id-' + tag + '"]' ).text();
1463 filteringBy.append( '<span class="tag">' + name + '</span>' );
1466 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1467 // or searching the local cache
1468 this.collection.query( request );
1471 // Get the checked filters
1472 // @return {array} of tags or false
1473 filtersChecked: function() {
1474 var items = $( '.feature-group' ).find( ':checkbox' ),
1477 _.each( items.filter( ':checked' ), function( item ) {
1478 tags.push( $( item ).prop( 'value' ) );
1481 // When no filters are checked, restore initial state and return
1482 if ( tags.length === 0 ) {
1483 $( '.apply-filters' ).find( 'span' ).text( '' );
1484 $( '.clear-filters' ).hide();
1485 $( 'body' ).removeClass( 'filters-applied' );
1489 $( '.apply-filters' ).find( 'span' ).text( tags.length );
1490 $( '.clear-filters' ).css( 'display', 'inline-block' );
1495 activeClass: 'current',
1497 // Overwrite search container class to append search
1499 searchContainer: $( '.theme-navigation' ),
1501 uploader: function() {
1502 $( 'a.upload' ).on( 'click', function( event ) {
1503 event.preventDefault();
1504 $( 'body' ).addClass( 'show-upload-theme' );
1505 themes.router.navigate( themes.router.baseUrl( '?upload' ), { replace: true } );
1507 $( 'a.browse-themes' ).on( 'click', function( event ) {
1508 event.preventDefault();
1509 $( 'body' ).removeClass( 'show-upload-theme' );
1510 themes.router.navigate( themes.router.baseUrl( '' ), { replace: true } );
1514 // Toggle the full filters navigation
1515 moreFilters: function( event ) {
1516 event.preventDefault();
1518 if ( $( 'body' ).hasClass( 'filters-applied' ) ) {
1519 return this.backToFilters();
1522 // If the filters section is opened and filters are checked
1523 // run the relevant query collapsing to filtered-by state
1524 if ( $( 'body' ).hasClass( 'more-filters-opened' ) && this.filtersChecked() ) {
1525 return this.addFilter();
1530 themes.router.navigate( themes.router.baseUrl( '' ) );
1531 $( 'body' ).toggleClass( 'more-filters-opened' );
1534 // Expand/collapse each individual filter section
1535 filterSection: function() {
1536 $( event.target ).parent().toggleClass( 'open' );
1539 // Clears all the checked filters
1540 // @uses filtersChecked()
1541 clearFilters: function( event ) {
1542 var items = $( '.feature-group' ).find( ':checkbox' ),
1545 event.preventDefault();
1547 _.each( items.filter( ':checked' ), function( item ) {
1548 $( item ).prop( 'checked', false );
1549 return self.filtersChecked();
1553 backToFilters: function( event ) {
1555 event.preventDefault();
1558 $( 'body' ).removeClass( 'filters-applied' );
1561 clearSearch: function() {
1562 $( '#theme-search-input').val( '' );
1566 themes.InstallerRouter = Backbone.Router.extend({
1568 'theme-install.php?theme=:slug': 'preview',
1569 'theme-install.php?browse=:sort': 'sort',
1570 'theme-install.php?upload': 'upload',
1571 'theme-install.php?search=:query': 'search',
1572 'theme-install.php': 'sort'
1575 baseUrl: function( url ) {
1576 return 'theme-install.php' + url;
1579 search: function( query ) {
1580 $( '.theme-search' ).val( query );
1583 navigate: function() {
1584 if ( Backbone.history._hasPushState ) {
1585 Backbone.Router.prototype.navigate.apply( this, arguments );
1591 themes.RunInstaller = {
1595 // Passes the default 'section' as an option
1596 this.view = new themes.view.Installer({
1597 section: 'featured',
1598 SearchView: themes.view.InstallerSearch
1606 render: function() {
1612 Backbone.history.start({
1613 root: themes.data.settings.adminUrl,
1619 routes: function() {
1623 // Bind to our global `wp.themes` object
1624 // so that the router is available to sub-views
1625 themes.router = new themes.InstallerRouter();
1627 // Handles `theme` route event
1628 // Queries the API for the passed theme slug
1629 themes.router.on( 'route:preview', function( slug ) {
1630 request.theme = slug;
1631 self.view.collection.query( request );
1634 // Handles sorting / browsing routes
1635 // Also handles the root URL triggering a sort request
1636 // for `featured`, the default view
1637 themes.router.on( 'route:sort', function( sort ) {
1641 self.view.sort( sort );
1642 self.view.trigger( 'theme:close' );
1645 // Support the `upload` route by going straight to upload section
1646 themes.router.on( 'route:upload', function() {
1647 $( 'a.upload' ).trigger( 'click' );
1650 // The `search` route event. The router populates the input field.
1651 themes.router.on( 'route:search', function() {
1652 $( '.theme-search' ).focus().trigger( 'keyup' );
1658 extraRoutes: function() {
1664 $( document ).ready(function() {
1665 if ( themes.isInstall ) {
1666 themes.RunInstaller.init();
1674 // Align theme browser thickbox
1676 jQuery(document).ready( function($) {
1677 tb_position = function() {
1678 var tbWindow = $('#TB_window'),
1679 width = $(window).width(),
1680 H = $(window).height(),
1681 W = ( 1040 < width ) ? 1040 : width,
1682 adminbar_height = 0;
1684 if ( $('#wpadminbar').length ) {
1685 adminbar_height = parseInt( $('#wpadminbar').css('height'), 10 );
1688 if ( tbWindow.size() ) {
1689 tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
1690 $('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
1691 tbWindow.css({'margin-left': '-' + parseInt( ( ( W - 50 ) / 2 ), 10 ) + 'px'});
1692 if ( typeof document.body.style.maxWidth !== 'undefined' ) {
1693 tbWindow.css({'top': 20 + adminbar_height + 'px', 'margin-top': '0'});
1698 $(window).resize(function(){ tb_position(); });