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' );
85 // Defines search element container
86 searchContainer: $( '#wpbody h1:first' ),
88 // Search input and view
89 // for current theme collection
94 // Don't render the search if there is only one theme
95 if ( themes.data.themes.length === 1 ) {
99 view = new this.SearchView({
100 collection: self.collection,
104 // Render and append after screen title
107 .append( $.parseHTML( '<label class="screen-reader-text" for="wp-filter-search-input">' + l10n.search + '</label>' ) )
111 // Checks when the user gets close to the bottom
112 // of the mage and triggers a theme:scroll event
113 scroller: function() {
117 bottom = this.window.scrollTop() + self.window.height();
118 threshold = self.$el.offset().top + self.$el.outerHeight( false ) - self.window.height();
119 threshold = Math.round( threshold * 0.9 );
121 if ( bottom > threshold ) {
122 this.trigger( 'theme:scroll' );
127 // Set up the Collection for our theme data
128 // @has 'id' 'name' 'screenshot' 'author' 'authorURI' 'version' 'active' ...
129 themes.Collection = Backbone.Collection.extend({
136 // Controls searching on the current theme collection
137 // and triggers an update event
138 doSearch: function( value ) {
140 // Don't do anything if we've already done this search
141 // Useful because the Search handler fires multiple times per keystroke
142 if ( this.terms === value ) {
146 // Updates terms with the value passed
149 // If we have terms, run a search...
150 if ( this.terms.length > 0 ) {
151 this.search( this.terms );
154 // If search is blank, show all themes
155 // Useful for resetting the views when you clean the input
156 if ( this.terms === '' ) {
157 this.reset( themes.data.themes );
158 $( 'body' ).removeClass( 'no-results' );
161 // Trigger a 'themes:update' event
162 this.trigger( 'themes:update' );
165 // Performs a search within the collection
167 search: function( term ) {
168 var match, results, haystack, name, description, author;
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 name = data.get( 'name' ).replace( /(<([^>]+)>)/ig, '' );
185 description = data.get( 'description' ).replace( /(<([^>]+)>)/ig, '' );
186 author = data.get( 'author' ).replace( /(<([^>]+)>)/ig, '' );
188 haystack = _.union( [ name, data.get( 'id' ), description, author, data.get( 'tags' ) ] );
190 if ( match.test( data.get( 'author' ) ) && term.length > 2 ) {
191 data.set( 'displayAuthor', true );
194 return match.test( haystack );
197 if ( results.length === 0 ) {
198 this.trigger( 'query:empty' );
200 $( 'body' ).removeClass( 'no-results' );
203 this.reset( results );
206 // Paginates the collection with a helper method
207 // that slices the collection
208 paginate: function( instance ) {
209 var collection = this;
210 instance = instance || 0;
212 // Themes per instance are set at 20
213 collection = _( collection.rest( 20 * instance ) );
214 collection = _( collection.first( 20 ) );
221 // Handles requests for more themes
222 // and caches results
224 // When we are missing a cache object we fire an apiCall()
225 // which triggers events of `query:success` or `query:fail`
226 query: function( request ) {
231 var queries = this.queries,
233 query, isPaginated, count;
235 // Store current query request args
236 // for later use with the event `theme:end`
237 this.currentQuery.request = request;
239 // Search the query cache for matches.
240 query = _.find( queries, function( query ) {
241 return _.isEqual( query.request, request );
244 // If the request matches the stored currentQuery.request
245 // it means we have a paginated request.
246 isPaginated = _.has( request, 'page' );
248 // Reset the internal api page counter for non paginated queries.
249 if ( ! isPaginated ) {
250 this.currentQuery.page = 1;
253 // Otherwise, send a new API call and add it to the cache.
254 if ( ! query && ! isPaginated ) {
255 query = this.apiCall( request ).done( function( data ) {
257 // Update the collection with the queried data.
259 self.reset( data.themes );
260 count = data.info.results;
261 // Store the results and the query request
262 queries.push( { themes: data.themes, request: request, total: count } );
265 // Trigger a collection refresh event
266 // and a `query:success` event with a `count` argument.
267 self.trigger( 'themes:update' );
268 self.trigger( 'query:success', count );
270 if ( data.themes && data.themes.length === 0 ) {
271 self.trigger( 'query:empty' );
274 }).fail( function() {
275 self.trigger( 'query:fail' );
278 // If it's a paginated request we need to fetch more themes...
280 return this.apiCall( request, isPaginated ).done( function( data ) {
281 // Add the new themes to the current collection
282 // @todo update counter
283 self.add( data.themes );
284 self.trigger( 'query:success' );
286 // We are done loading themes for now.
287 self.loadingThemes = false;
289 }).fail( function() {
290 self.trigger( 'query:fail' );
294 if ( query.themes.length === 0 ) {
295 self.trigger( 'query:empty' );
297 $( 'body' ).removeClass( 'no-results' );
300 // Only trigger an update event since we already have the themes
301 // on our cached object
302 if ( _.isNumber( query.total ) ) {
303 this.count = query.total;
306 this.reset( query.themes );
307 if ( ! query.total ) {
308 this.count = this.length;
311 this.trigger( 'themes:update' );
312 this.trigger( 'query:success', this.count );
316 // Local cache array for API queries
319 // Keep track of current query so we can handle pagination
325 // Send request to api.wordpress.org/themes
326 apiCall: function( request, paginated ) {
327 return wp.ajax.send( 'query-themes', {
346 beforeSend: function() {
349 $( 'body' ).addClass( 'loading-content' ).removeClass( 'no-results' );
355 // Static status controller for when we are loading themes.
359 // This is the view that controls each theme item
360 // that will be displayed on the screen
361 themes.view.Theme = wp.Backbone.View.extend({
363 // Wrap theme data on a div.theme element
366 // Reflects which theme view we have
367 // 'grid' (default) or 'detail'
370 // The HTML template for each element to be rendered
371 html: themes.template( 'theme' ),
374 'click': themes.isInstall ? 'preview': 'expand',
375 'keydown': themes.isInstall ? 'preview': 'expand',
376 'touchend': themes.isInstall ? 'preview': 'expand',
378 'touchmove': 'preventExpand',
379 'click .theme-install': 'installTheme',
380 'click .update-message': 'updateTheme'
385 initialize: function() {
386 this.model.on( 'change', this.render, this );
390 var data = this.model.toJSON();
392 // Render themes using the html template
393 this.$el.html( this.html( data ) ).attr({
395 'aria-describedby' : data.id + '-action ' + data.id + '-name',
399 // Renders active theme styles
402 if ( this.model.get( 'displayAuthor' ) ) {
403 this.$el.addClass( 'display-author' );
407 // Adds a class to the currently active theme
408 // and to the overlay in detailed view mode
409 activeTheme: function() {
410 if ( this.model.get( 'active' ) ) {
411 this.$el.addClass( 'active' );
415 // Add class of focus to the theme we are focused on.
416 addFocus: function() {
417 var $themeToFocus = ( $( ':focus' ).hasClass( 'theme' ) ) ? $( ':focus' ) : $(':focus').parents('.theme');
419 $('.theme.focus').removeClass('focus');
420 $themeToFocus.addClass('focus');
423 // Single theme overlay screen
424 // It's shown when clicking a theme
425 expand: function( event ) {
428 event = event || window.event;
430 // 'enter' and 'space' keys expand the details view when a theme is :focused
431 if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
435 // Bail if the user scrolled on a touch device
436 if ( this.touchDrag === true ) {
437 return this.touchDrag = false;
440 // Prevent the modal from showing when the user clicks
441 // one of the direct action buttons
442 if ( $( event.target ).is( '.theme-actions a' ) ) {
446 // Prevent the modal from showing when the user clicks one of the direct action buttons.
447 if ( $( event.target ).is( '.theme-actions a, .update-message, .button-link, .notice-dismiss' ) ) {
451 // Set focused theme to current element
452 themes.focusedTheme = this.$el;
454 this.trigger( 'theme:expand', self.model.cid );
457 preventExpand: function() {
458 this.touchDrag = true;
461 preview: function( event ) {
465 event = event || window.event;
467 // Bail if the user scrolled on a touch device
468 if ( this.touchDrag === true ) {
469 return this.touchDrag = false;
472 // Allow direct link path to installing a theme.
473 if ( $( event.target ).not( '.install-theme-preview' ).parents( '.theme-actions' ).length ) {
477 // 'enter' and 'space' keys expand the details view when a theme is :focused
478 if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
482 // pressing enter while focused on the buttons shouldn't open the preview
483 if ( event.type === 'keydown' && event.which !== 13 && $( ':focus' ).hasClass( 'button' ) ) {
487 event.preventDefault();
489 event = event || window.event;
491 // Set focus to current theme.
492 themes.focusedTheme = this.$el;
494 // Construct a new Preview view.
495 preview = new themes.view.Preview({
499 // Render the view and append it.
501 this.setNavButtonsState();
503 // Hide previous/next navigation if there is only one theme
504 if ( this.model.collection.length === 1 ) {
505 preview.$el.addClass( 'no-navigation' );
507 preview.$el.removeClass( 'no-navigation' );
511 $( 'div.wrap' ).append( preview.el );
513 // Listen to our preview object
514 // for `theme:next` and `theme:previous` events.
515 this.listenTo( preview, 'theme:next', function() {
517 // Keep local track of current theme model.
518 current = self.model;
520 // If we have ventured away from current model update the current model position.
521 if ( ! _.isUndefined( self.current ) ) {
522 current = self.current;
525 // Get next theme model.
526 self.current = self.model.collection.at( self.model.collection.indexOf( current ) + 1 );
528 // If we have no more themes, bail.
529 if ( _.isUndefined( self.current ) ) {
530 self.options.parent.parent.trigger( 'theme:end' );
531 return self.current = current;
534 preview.model = self.current;
536 // Render and append.
538 this.setNavButtonsState();
539 $( '.next-theme' ).focus();
541 .listenTo( preview, 'theme:previous', function() {
543 // Keep track of current theme model.
544 current = self.model;
546 // Bail early if we are at the beginning of the collection
547 if ( self.model.collection.indexOf( self.current ) === 0 ) {
551 // If we have ventured away from current model update the current model position.
552 if ( ! _.isUndefined( self.current ) ) {
553 current = self.current;
556 // Get previous theme model.
557 self.current = self.model.collection.at( self.model.collection.indexOf( current ) - 1 );
559 // If we have no more themes, bail.
560 if ( _.isUndefined( self.current ) ) {
564 preview.model = self.current;
566 // Render and append.
568 this.setNavButtonsState();
569 $( '.previous-theme' ).focus();
572 this.listenTo( preview, 'preview:close', function() {
573 self.current = self.model;
577 // Handles .disabled classes for previous/next buttons in theme installer preview
578 setNavButtonsState: function() {
579 var $themeInstaller = $( '.theme-install-overlay' ),
580 current = _.isUndefined( this.current ) ? this.model : this.current;
582 // Disable previous at the zero position
583 if ( 0 === this.model.collection.indexOf( current ) ) {
584 $themeInstaller.find( '.previous-theme' ).addClass( 'disabled' );
587 // Disable next if the next model is undefined
588 if ( _.isUndefined( this.model.collection.at( this.model.collection.indexOf( current ) + 1 ) ) ) {
589 $themeInstaller.find( '.next-theme' ).addClass( 'disabled' );
593 installTheme: function( event ) {
596 event.preventDefault();
598 wp.updates.maybeRequestFilesystemCredentials( event );
600 $( document ).on( 'wp-theme-install-success', function( event, response ) {
601 if ( _this.model.get( 'id' ) === response.slug ) {
602 _this.model.set( { 'installed': true } );
606 wp.updates.installTheme( {
607 slug: $( event.target ).data( 'slug' )
611 updateTheme: function( event ) {
614 if ( ! this.model.get( 'hasPackage' ) ) {
618 event.preventDefault();
620 wp.updates.maybeRequestFilesystemCredentials( event );
622 $( document ).on( 'wp-theme-update-success', function( event, response ) {
623 _this.model.off( 'change', _this.render, _this );
624 if ( _this.model.get( 'id' ) === response.slug ) {
627 version: response.newVersion
630 _this.model.on( 'change', _this.render, _this );
633 wp.updates.updateTheme( {
634 slug: $( event.target ).parents( 'div.theme' ).first().data( 'slug' )
639 // Theme Details view
640 // Set ups a modal overlay with the expanded theme data
641 themes.view.Details = wp.Backbone.View.extend({
643 // Wrap theme data on a div.theme element
644 className: 'theme-overlay',
648 'click .delete-theme': 'deleteTheme',
649 'click .left': 'previousTheme',
650 'click .right': 'nextTheme',
651 'click #update-theme': 'updateTheme'
654 // The HTML template for the theme overlay
655 html: themes.template( 'theme-single' ),
658 var data = this.model.toJSON();
659 this.$el.html( this.html( data ) );
660 // Renders active theme styles
662 // Set up navigation events
664 // Checks screenshot size
665 this.screenshotCheck( this.$el );
666 // Contain "tabbing" inside the overlay
667 this.containFocus( this.$el );
670 // Adds a class to the currently active theme
671 // and to the overlay in detailed view mode
672 activeTheme: function() {
673 // Check the model has the active property
674 this.$el.toggleClass( 'active', this.model.get( 'active' ) );
677 // Set initial focus and constrain tabbing within the theme browser modal.
678 containFocus: function( $el ) {
680 // Set initial focus on the primary action control.
681 _.delay( function() {
682 $( '.theme-wrap a.button-primary:visible' ).focus();
685 // Constrain tabbing within the modal.
686 $el.on( 'keydown.wp-themes', function( event ) {
687 var $firstFocusable = $el.find( '.theme-header button:not(.disabled)' ).first(),
688 $lastFocusable = $el.find( '.theme-actions a:visible' ).last();
690 // Check for the Tab key.
691 if ( 9 === event.which ) {
692 if ( $firstFocusable[0] === event.target && event.shiftKey ) {
693 $lastFocusable.focus();
694 event.preventDefault();
695 } else if ( $lastFocusable[0] === event.target && ! event.shiftKey ) {
696 $firstFocusable.focus();
697 event.preventDefault();
703 // Single theme overlay screen
704 // It's shown when clicking a theme
705 collapse: function( event ) {
709 event = event || window.event;
711 // Prevent collapsing detailed view when there is only one theme available
712 if ( themes.data.themes.length === 1 ) {
716 // Detect if the click is inside the overlay
717 // and don't close it unless the target was
718 // the div.back button
719 if ( $( event.target ).is( '.theme-backdrop' ) || $( event.target ).is( '.close' ) || event.keyCode === 27 ) {
721 // Add a temporary closing class while overlay fades out
722 $( 'body' ).addClass( 'closing-overlay' );
724 // With a quick fade out animation
725 this.$el.fadeOut( 130, function() {
726 // Clicking outside the modal box closes the overlay
727 $( 'body' ).removeClass( 'closing-overlay' );
728 // Handle event cleanup
731 // Get scroll position to avoid jumping to the top
732 scroll = document.body.scrollTop;
734 // Clean the url structure
735 themes.router.navigate( themes.router.baseUrl( '' ) );
737 // Restore scroll position
738 document.body.scrollTop = scroll;
740 // Return focus to the theme div
741 if ( themes.focusedTheme ) {
742 themes.focusedTheme.focus();
748 // Handles .disabled classes for next/previous buttons
749 navigation: function() {
751 // Disable Left/Right when at the start or end of the collection
752 if ( this.model.cid === this.model.collection.at(0).cid ) {
753 this.$el.find( '.left' )
754 .addClass( 'disabled' )
755 .prop( 'disabled', true );
757 if ( this.model.cid === this.model.collection.at( this.model.collection.length - 1 ).cid ) {
758 this.$el.find( '.right' )
759 .addClass( 'disabled' )
760 .prop( 'disabled', true );
764 // Performs the actions to effectively close
765 // the theme details overlay
766 closeOverlay: function() {
767 $( 'body' ).removeClass( 'modal-open' );
770 this.trigger( 'theme:collapse' );
773 updateTheme: function( event ) {
775 event.preventDefault();
777 wp.updates.maybeRequestFilesystemCredentials( event );
779 $( document ).on( 'wp-theme-update-success', function( event, response ) {
780 if ( _this.model.get( 'id' ) === response.slug ) {
783 version: response.newVersion
789 wp.updates.updateTheme( {
790 slug: $( event.target ).data( 'slug' )
794 deleteTheme: function( event ) {
796 _collection = _this.model.collection,
798 event.preventDefault();
800 // Confirmation dialog for deleting a theme.
801 if ( ! window.confirm( wp.themes.data.settings.confirmDelete ) ) {
805 wp.updates.maybeRequestFilesystemCredentials( event );
807 $( document ).one( 'wp-theme-delete-success', function( event, response ) {
808 _this.$el.find( '.close' ).trigger( 'click' );
809 $( '[data-slug="' + response.slug + '"]' ).css( { backgroundColor:'#faafaa' } ).fadeOut( 350, function() {
811 _themes.data.themes = _.without( _themes.data.themes, _.findWhere( _themes.data.themes, { id: response.slug } ) );
813 $( '.wp-filter-search' ).val( '' );
814 _collection.doSearch( '' );
815 _collection.remove( _this.model );
816 _collection.trigger( 'themes:update' );
820 wp.updates.deleteTheme( {
821 slug: this.model.get( 'id' )
825 nextTheme: function() {
827 self.trigger( 'theme:next', self.model.cid );
831 previousTheme: function() {
833 self.trigger( 'theme:previous', self.model.cid );
837 // Checks if the theme screenshot is the old 300px width version
838 // and adds a corresponding class if it's true
839 screenshotCheck: function( el ) {
840 var screenshot, image;
842 screenshot = el.find( '.screenshot img' );
844 image.src = screenshot.attr( 'src' );
847 if ( image.width && image.width <= 300 ) {
848 el.addClass( 'small-screenshot' );
853 // Theme Preview view
854 // Set ups a modal overlay with the expanded theme data
855 themes.view.Preview = themes.view.Details.extend({
857 className: 'wp-full-overlay expanded',
858 el: '.theme-install-overlay',
861 'click .close-full-overlay': 'close',
862 'click .collapse-sidebar': 'collapse',
863 'click .devices button': 'previewDevice',
864 'click .previous-theme': 'previousTheme',
865 'click .next-theme': 'nextTheme',
867 'click .theme-install': 'installTheme'
870 // The HTML template for the theme preview
871 html: themes.template( 'theme-preview' ),
875 currentPreviewDevice,
876 data = this.model.toJSON(),
877 $body = $( document.body );
879 $body.attr( 'aria-busy', 'true' );
881 this.$el.removeClass( 'iframe-ready' ).html( this.html( data ) );
883 currentPreviewDevice = this.$el.data( 'current-preview-device' );
884 if ( currentPreviewDevice ) {
885 self.tooglePreviewDeviceButtons( currentPreviewDevice );
888 themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.get( 'id' ) ), { replace: true } );
890 this.$el.fadeIn( 200, function() {
891 $body.addClass( 'theme-installer-active full-overlay-active' );
894 this.$el.find( 'iframe' ).one( 'load', function() {
899 iframeLoaded: function() {
900 this.$el.addClass( 'iframe-ready' );
901 $( document.body ).attr( 'aria-busy', 'false' );
905 this.$el.fadeOut( 200, function() {
906 $( 'body' ).removeClass( 'theme-installer-active full-overlay-active' );
908 // Return focus to the theme div
909 if ( themes.focusedTheme ) {
910 themes.focusedTheme.focus();
912 }).removeClass( 'iframe-ready' );
914 themes.router.navigate( themes.router.baseUrl( '' ) );
915 this.trigger( 'preview:close' );
916 this.undelegateEvents();
921 collapse: function( event ) {
922 var $button = $( event.currentTarget );
923 if ( 'true' === $button.attr( 'aria-expanded' ) ) {
924 $button.attr({ 'aria-expanded': 'false', 'aria-label': l10n.expandSidebar });
926 $button.attr({ 'aria-expanded': 'true', 'aria-label': l10n.collapseSidebar });
929 this.$el.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
933 previewDevice: function( event ) {
934 var device = $( event.currentTarget ).data( 'device' );
937 .removeClass( 'preview-desktop preview-tablet preview-mobile' )
938 .addClass( 'preview-' + device )
939 .data( 'current-preview-device', device );
941 this.tooglePreviewDeviceButtons( device );
944 tooglePreviewDeviceButtons: function( newDevice ) {
945 var $devices = $( '.wp-full-overlay-footer .devices' );
947 $devices.find( 'button' )
948 .removeClass( 'active' )
949 .attr( 'aria-pressed', false );
951 $devices.find( 'button.preview-' + newDevice )
952 .addClass( 'active' )
953 .attr( 'aria-pressed', true );
956 keyEvent: function( event ) {
957 // The escape key closes the preview
958 if ( event.keyCode === 27 ) {
959 this.undelegateEvents();
962 // The right arrow key, next theme
963 if ( event.keyCode === 39 ) {
964 _.once( this.nextTheme() );
967 // The left arrow key, previous theme
968 if ( event.keyCode === 37 ) {
969 this.previousTheme();
973 installTheme: function( event ) {
975 $target = $( event.target );
976 event.preventDefault();
978 if ( $target.hasClass( 'disabled' ) ) {
982 wp.updates.maybeRequestFilesystemCredentials( event );
984 $( document ).on( 'wp-theme-install-success', function() {
985 _this.model.set( { 'installed': true } );
988 wp.updates.installTheme( {
989 slug: $target.data( 'slug' )
994 // Controls the rendering of div.themes,
995 // a wrapper that will hold all the theme elements
996 themes.view.Themes = wp.Backbone.View.extend({
998 className: 'themes wp-clearfix',
999 $overlay: $( 'div.theme-overlay' ),
1001 // Number to keep track of scroll position
1002 // while in theme-overlay mode
1005 // The theme count element
1006 count: $( '.wrap .theme-count' ),
1008 // The live themes count
1011 initialize: function( options ) {
1015 this.parent = options.parent;
1017 // Set current view to [grid]
1018 this.setView( 'grid' );
1020 // Move the active theme to the beginning of the collection
1021 self.currentTheme();
1023 // When the collection is updated by user input...
1024 this.listenTo( self.collection, 'themes:update', function() {
1025 self.parent.page = 0;
1026 self.currentTheme();
1027 self.render( this );
1030 // Update theme count to full result set when available.
1031 this.listenTo( self.collection, 'query:success', function( count ) {
1032 if ( _.isNumber( count ) ) {
1033 self.count.text( count );
1034 self.announceSearchResults( count );
1036 self.count.text( self.collection.length );
1037 self.announceSearchResults( self.collection.length );
1041 this.listenTo( self.collection, 'query:empty', function() {
1042 $( 'body' ).addClass( 'no-results' );
1045 this.listenTo( this.parent, 'theme:scroll', function() {
1046 self.renderThemes( self.parent.page );
1049 this.listenTo( this.parent, 'theme:close', function() {
1050 if ( self.overlay ) {
1051 self.overlay.closeOverlay();
1055 // Bind keyboard events.
1056 $( 'body' ).on( 'keyup', function( event ) {
1057 if ( ! self.overlay ) {
1061 // Bail if the filesystem credentials dialog is shown.
1062 if ( $( '#request-filesystem-credentials-dialog' ).is( ':visible' ) ) {
1066 // Pressing the right arrow key fires a theme:next event
1067 if ( event.keyCode === 39 ) {
1068 self.overlay.nextTheme();
1071 // Pressing the left arrow key fires a theme:previous event
1072 if ( event.keyCode === 37 ) {
1073 self.overlay.previousTheme();
1076 // Pressing the escape key fires a theme:collapse event
1077 if ( event.keyCode === 27 ) {
1078 self.overlay.collapse( event );
1083 // Manages rendering of theme pages
1084 // and keeping theme count in sync
1085 render: function() {
1086 // Clear the DOM, please
1089 // If the user doesn't have switch capabilities
1090 // or there is only one theme in the collection
1091 // render the detailed view of the active theme
1092 if ( themes.data.themes.length === 1 ) {
1094 // Constructs the view
1095 this.singleTheme = new themes.view.Details({
1096 model: this.collection.models[0]
1099 // Render and apply a 'single-theme' class to our container
1100 this.singleTheme.render();
1101 this.$el.addClass( 'single-theme' );
1102 this.$el.append( this.singleTheme.el );
1105 // Generate the themes
1106 // Using page instance
1107 // While checking the collection has items
1108 if ( this.options.collection.size() > 0 ) {
1109 this.renderThemes( this.parent.page );
1112 // Display a live theme count for the collection
1113 this.liveThemeCount = this.collection.count ? this.collection.count : this.collection.length;
1114 this.count.text( this.liveThemeCount );
1117 * In the theme installer the themes count is already announced
1118 * because `announceSearchResults` is called on `query:success`.
1120 if ( ! themes.isInstall ) {
1121 this.announceSearchResults( this.liveThemeCount );
1125 // Iterates through each instance of the collection
1126 // and renders each theme module
1127 renderThemes: function( page ) {
1130 self.instance = self.collection.paginate( page );
1132 // If we have no more themes bail
1133 if ( self.instance.size() === 0 ) {
1134 // Fire a no-more-themes event.
1135 this.parent.trigger( 'theme:end' );
1139 // Make sure the add-new stays at the end
1140 if ( ! themes.isInstall && page >= 1 ) {
1141 $( '.add-new-theme' ).remove();
1144 // Loop through the themes and setup each theme view
1145 self.instance.each( function( theme ) {
1146 self.theme = new themes.view.Theme({
1151 // Render the views...
1152 self.theme.render();
1153 // and append them to div.themes
1154 self.$el.append( self.theme.el );
1156 // Binds to theme:expand to show the modal box
1157 // with the theme details
1158 self.listenTo( self.theme, 'theme:expand', self.expand, self );
1161 // 'Add new theme' element shown at the end of the grid
1162 if ( ! themes.isInstall && themes.data.settings.canInstall ) {
1163 this.$el.append( '<div class="theme add-new-theme"><a href="' + themes.data.settings.installURI + '"><div class="theme-screenshot"><span></span></div><h2 class="theme-name">' + l10n.addNew + '</h2></a></div>' );
1169 // Grabs current theme and puts it at the beginning of the collection
1170 currentTheme: function() {
1174 current = self.collection.findWhere({ active: true });
1176 // Move the active theme to the beginning of the collection
1178 self.collection.remove( current );
1179 self.collection.add( current, { at:0 } );
1183 // Sets current view
1184 setView: function( view ) {
1188 // Renders the overlay with the ThemeDetails view
1189 // Uses the current model data
1190 expand: function( id ) {
1191 var self = this, $card, $modal;
1193 // Set the current theme model
1194 this.model = self.collection.get( id );
1196 // Trigger a route update for the current model
1197 themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.id ) );
1199 // Sets this.view to 'detail'
1200 this.setView( 'detail' );
1201 $( 'body' ).addClass( 'modal-open' );
1203 // Set up the theme details view
1204 this.overlay = new themes.view.Details({
1208 this.overlay.render();
1210 if ( this.model.get( 'hasUpdate' ) ) {
1211 $card = $( '[data-slug="' + this.model.id + '"]' );
1212 $modal = $( this.overlay.el );
1214 if ( $card.find( '.updating-message' ).length ) {
1215 $modal.find( '.notice-warning h3' ).remove();
1216 $modal.find( '.notice-warning' )
1217 .removeClass( 'notice-large' )
1218 .addClass( 'updating-message' )
1219 .find( 'p' ).text( wp.updates.l10n.updating );
1220 } else if ( $card.find( '.notice-error' ).length ) {
1221 $modal.find( '.notice-warning' ).remove();
1225 this.$overlay.html( this.overlay.el );
1227 // Bind to theme:next and theme:previous
1228 // triggered by the arrow keys
1230 // Keep track of the current model so we
1231 // can infer an index position
1232 this.listenTo( this.overlay, 'theme:next', function() {
1233 // Renders the next theme on the overlay
1234 self.next( [ self.model.cid ] );
1237 .listenTo( this.overlay, 'theme:previous', function() {
1238 // Renders the previous theme on the overlay
1239 self.previous( [ self.model.cid ] );
1243 // This method renders the next theme on the overlay modal
1244 // based on the current position in the collection
1245 // @params [model cid]
1246 next: function( args ) {
1250 // Get the current theme
1251 model = self.collection.get( args[0] );
1252 // Find the next model within the collection
1253 nextModel = self.collection.at( self.collection.indexOf( model ) + 1 );
1255 // Sanity check which also serves as a boundary test
1256 if ( nextModel !== undefined ) {
1258 // We have a new theme...
1259 // Close the overlay
1260 this.overlay.closeOverlay();
1262 // Trigger a route update for the current model
1263 self.theme.trigger( 'theme:expand', nextModel.cid );
1268 // This method renders the previous theme on the overlay modal
1269 // based on the current position in the collection
1270 // @params [model cid]
1271 previous: function( args ) {
1273 model, previousModel;
1275 // Get the current theme
1276 model = self.collection.get( args[0] );
1277 // Find the previous model within the collection
1278 previousModel = self.collection.at( self.collection.indexOf( model ) - 1 );
1280 if ( previousModel !== undefined ) {
1282 // We have a new theme...
1283 // Close the overlay
1284 this.overlay.closeOverlay();
1286 // Trigger a route update for the current model
1287 self.theme.trigger( 'theme:expand', previousModel.cid );
1292 // Dispatch audible search results feedback message
1293 announceSearchResults: function( count ) {
1294 if ( 0 === count ) {
1295 wp.a11y.speak( l10n.noThemesFound );
1297 wp.a11y.speak( l10n.themesFound.replace( '%d', count ) );
1302 // Search input view controller.
1303 themes.view.Search = wp.Backbone.View.extend({
1306 className: 'wp-filter-search',
1307 id: 'wp-filter-search-input',
1311 placeholder: l10n.searchPlaceholder,
1313 'aria-describedby': 'live-search-desc'
1322 initialize: function( options ) {
1324 this.parent = options.parent;
1326 this.listenTo( this.parent, 'theme:close', function() {
1327 this.searching = false;
1332 search: function( event ) {
1334 if ( event.type === 'keyup' && event.which === 27 ) {
1335 event.target.value = '';
1339 * Since doSearch is debounced, it will only run when user input comes to a rest
1341 this.doSearch( event );
1344 // Runs a search on the theme collection.
1345 doSearch: _.debounce( function( event ) {
1348 this.collection.doSearch( event.target.value );
1350 // if search is initiated and key is not return
1351 if ( this.searching && event.which !== 13 ) {
1352 options.replace = true;
1354 this.searching = true;
1357 // Update the URL hash
1358 if ( event.target.value ) {
1359 themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + event.target.value ), options );
1361 themes.router.navigate( themes.router.baseUrl( '' ) );
1365 pushState: function( event ) {
1366 var url = themes.router.baseUrl( '' );
1368 if ( event.target.value ) {
1369 url = themes.router.baseUrl( themes.router.searchPath + event.target.value );
1372 this.searching = false;
1373 themes.router.navigate( url );
1378 // Sets up the routes events for relevant url queries
1379 // Listens to [theme] and [search] params
1380 themes.Router = Backbone.Router.extend({
1383 'themes.php?theme=:slug': 'theme',
1384 'themes.php?search=:query': 'search',
1385 'themes.php?s=:query': 'search',
1386 'themes.php': 'themes',
1390 baseUrl: function( url ) {
1391 return 'themes.php' + url;
1394 themePath: '?theme=',
1395 searchPath: '?search=',
1397 search: function( query ) {
1398 $( '.wp-filter-search' ).val( query );
1401 themes: function() {
1402 $( '.wp-filter-search' ).val( '' );
1405 navigate: function() {
1406 if ( Backbone.history._hasPushState ) {
1407 Backbone.Router.prototype.navigate.apply( this, arguments );
1413 // Execute and setup the application
1416 // Initializes the blog's theme library view
1417 // Create a new collection with data
1418 this.themes = new themes.Collection( themes.data.themes );
1421 this.view = new themes.view.Appearance({
1422 collection: this.themes
1428 render: function() {
1434 Backbone.history.start({
1435 root: themes.data.settings.adminUrl,
1441 routes: function() {
1443 // Bind to our global thx object
1444 // so that the object is available to sub-views
1445 themes.router = new themes.Router();
1447 // Handles theme details route event
1448 themes.router.on( 'route:theme', function( slug ) {
1449 self.view.view.expand( slug );
1452 themes.router.on( 'route:themes', function() {
1453 self.themes.doSearch( '' );
1454 self.view.trigger( 'theme:close' );
1457 // Handles search route event
1458 themes.router.on( 'route:search', function() {
1459 $( '.wp-filter-search' ).trigger( 'keyup' );
1465 extraRoutes: function() {
1470 // Extend the main Search view
1471 themes.view.InstallerSearch = themes.view.Search.extend({
1480 // Handles Ajax request for searching through themes in public repo
1481 search: function( event ) {
1483 // Tabbing or reverse tabbing into the search input shouldn't trigger a search
1484 if ( event.type === 'keyup' && ( event.which === 9 || event.which === 16 ) ) {
1488 this.collection = this.options.parent.view.collection;
1491 if ( event.type === 'keyup' && event.which === 27 ) {
1492 event.target.value = '';
1495 this.doSearch( event.target.value );
1498 doSearch: _.debounce( function( value ) {
1501 // Don't do anything if the search terms haven't changed.
1502 if ( this.terms === value ) {
1506 // Updates terms with the value passed.
1509 request.search = value;
1511 // Intercept an [author] search.
1513 // If input value starts with `author:` send a request
1514 // for `author` instead of a regular `search`
1515 if ( value.substring( 0, 7 ) === 'author:' ) {
1516 request.search = '';
1517 request.author = value.slice( 7 );
1520 // Intercept a [tag] search.
1522 // If input value starts with `tag:` send a request
1523 // for `tag` instead of a regular `search`
1524 if ( value.substring( 0, 4 ) === 'tag:' ) {
1525 request.search = '';
1526 request.tag = [ value.slice( 4 ) ];
1529 $( '.filter-links li > a.current' ).removeClass( 'current' );
1530 $( 'body' ).removeClass( 'show-filters filters-applied show-favorites-form' );
1531 $( '.drawer-toggle' ).attr( 'aria-expanded', 'false' );
1533 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1534 // or searching the local cache
1535 this.collection.query( request );
1538 themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + value ), { replace: true } );
1542 themes.view.Installer = themes.view.Appearance.extend({
1544 el: '#wpbody-content .wrap',
1546 // Register events for sorting and filters in theme-navigation
1548 'click .filter-links li > a': 'onSort',
1549 'click .theme-filter': 'onFilter',
1550 'click .drawer-toggle': 'moreFilters',
1551 'click .filter-drawer .apply-filters': 'applyFilters',
1552 'click .filter-group [type="checkbox"]': 'addFilter',
1553 'click .filter-drawer .clear-filters': 'clearFilters',
1554 'click .edit-filters': 'backToFilters',
1555 'click .favorites-form-submit' : 'saveUsername',
1556 'keyup #wporg-username-input': 'saveUsername'
1559 // Initial render method
1560 render: function() {
1566 this.collection = new themes.Collection();
1568 // Bump `collection.currentQuery.page` and request more themes if we hit the end of the page.
1569 this.listenTo( this, 'theme:end', function() {
1571 // Make sure we are not already loading
1572 if ( self.collection.loadingThemes ) {
1576 // Set loadingThemes to true and bump page instance of currentQuery.
1577 self.collection.loadingThemes = true;
1578 self.collection.currentQuery.page++;
1580 // Use currentQuery.page to build the themes request.
1581 _.extend( self.collection.currentQuery.request, { page: self.collection.currentQuery.page } );
1582 self.collection.query( self.collection.currentQuery.request );
1585 this.listenTo( this.collection, 'query:success', function() {
1586 $( 'body' ).removeClass( 'loading-content' );
1587 $( '.theme-browser' ).find( 'div.error' ).remove();
1590 this.listenTo( this.collection, 'query:fail', function() {
1591 $( 'body' ).removeClass( 'loading-content' );
1592 $( '.theme-browser' ).find( 'div.error' ).remove();
1593 $( '.theme-browser' ).find( 'div.themes' ).before( '<div class="error"><p>' + l10n.error + '</p></div>' );
1600 // Set ups the view and passes the section argument
1601 this.view = new themes.view.Themes({
1602 collection: this.collection,
1606 // Reset pagination every time the install view handler is run
1609 // Render and append
1610 this.$el.find( '.themes' ).remove();
1612 this.$el.find( '.theme-browser' ).append( this.view.el ).addClass( 'rendered' );
1615 // Handles all the rendering of the public theme directory
1616 browse: function( section ) {
1617 // Create a new collection with the proper theme data
1619 this.collection.query( { browse: section } );
1622 // Sorting navigation
1623 onSort: function( event ) {
1624 var $el = $( event.target ),
1625 sort = $el.data( 'sort' );
1627 event.preventDefault();
1629 $( 'body' ).removeClass( 'filters-applied show-filters' );
1630 $( '.drawer-toggle' ).attr( 'aria-expanded', 'false' );
1632 // Bail if this is already active
1633 if ( $el.hasClass( this.activeClass ) ) {
1639 // Trigger a router.naviagte update
1640 themes.router.navigate( themes.router.baseUrl( themes.router.browsePath + sort ) );
1643 sort: function( sort ) {
1646 $( '.filter-links li > a, .theme-filter' ).removeClass( this.activeClass );
1647 $( '[data-sort="' + sort + '"]' ).addClass( this.activeClass );
1649 if ( 'favorites' === sort ) {
1650 $( 'body' ).addClass( 'show-favorites-form' );
1652 $( 'body' ).removeClass( 'show-favorites-form' );
1655 this.browse( sort );
1659 onFilter: function( event ) {
1661 $el = $( event.target ),
1662 filter = $el.data( 'filter' );
1664 // Bail if this is already active
1665 if ( $el.hasClass( this.activeClass ) ) {
1669 $( '.filter-links li > a, .theme-section' ).removeClass( this.activeClass );
1670 $el.addClass( this.activeClass );
1676 // Construct the filter request
1677 // using the default values
1678 filter = _.union( [ filter, this.filtersChecked() ] );
1679 request = { tag: [ filter ] };
1681 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1682 // or searching the local cache
1683 this.collection.query( request );
1686 // Clicking on a checkbox to add another filter to the request
1687 addFilter: function() {
1688 this.filtersChecked();
1691 // Applying filters triggers a tag request
1692 applyFilters: function( event ) {
1694 tags = this.filtersChecked(),
1695 request = { tag: tags },
1696 filteringBy = $( '.filtered-by .tags' );
1699 event.preventDefault();
1703 wp.a11y.speak( l10n.selectFeatureFilter );
1707 $( 'body' ).addClass( 'filters-applied' );
1708 $( '.filter-links li > a.current' ).removeClass( 'current' );
1709 filteringBy.empty();
1711 _.each( tags, function( tag ) {
1712 name = $( 'label[for="filter-id-' + tag + '"]' ).text();
1713 filteringBy.append( '<span class="tag">' + name + '</span>' );
1716 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1717 // or searching the local cache
1718 this.collection.query( request );
1721 // Save the user's WordPress.org username and get his favorite themes.
1722 saveUsername: function ( event ) {
1723 var username = $( '#wporg-username-input' ).val(),
1724 nonce = $( '#wporg-username-nonce' ).val(),
1725 request = { browse: 'favorites', user: username },
1729 event.preventDefault();
1732 // save username on enter
1733 if ( event.type === 'keyup' && event.which !== 13 ) {
1737 return wp.ajax.send( 'save-wporg-username', {
1742 success: function () {
1743 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1744 // or searching the local cache
1745 that.collection.query( request );
1750 // Get the checked filters
1751 // @return {array} of tags or false
1752 filtersChecked: function() {
1753 var items = $( '.filter-group' ).find( ':checkbox' ),
1756 _.each( items.filter( ':checked' ), function( item ) {
1757 tags.push( $( item ).prop( 'value' ) );
1760 // When no filters are checked, restore initial state and return
1761 if ( tags.length === 0 ) {
1762 $( '.filter-drawer .apply-filters' ).find( 'span' ).text( '' );
1763 $( '.filter-drawer .clear-filters' ).hide();
1764 $( 'body' ).removeClass( 'filters-applied' );
1768 $( '.filter-drawer .apply-filters' ).find( 'span' ).text( tags.length );
1769 $( '.filter-drawer .clear-filters' ).css( 'display', 'inline-block' );
1774 activeClass: 'current',
1776 // Overwrite search container class to append search
1778 searchContainer: $( '.wp-filter .search-form' ),
1781 * When users press the "Upload Theme" button, show the upload form in place.
1783 uploader: function() {
1784 var uploadViewToggle = $( '.upload-view-toggle' ),
1785 $body = $( document.body );
1787 uploadViewToggle.on( 'click', function() {
1788 // Toggle the upload view.
1789 $body.toggleClass( 'show-upload-view' );
1790 // Toggle the `aria-expanded` button attribute.
1791 uploadViewToggle.attr( 'aria-expanded', $body.hasClass( 'show-upload-view' ) );
1795 // Toggle the full filters navigation
1796 moreFilters: function( event ) {
1797 var $body = $( 'body' ),
1798 $toggleButton = $( '.drawer-toggle' );
1800 event.preventDefault();
1802 if ( $body.hasClass( 'filters-applied' ) ) {
1803 return this.backToFilters();
1808 themes.router.navigate( themes.router.baseUrl( '' ) );
1809 // Toggle the feature filters view.
1810 $body.toggleClass( 'show-filters' );
1811 // Toggle the `aria-expanded` button attribute.
1812 $toggleButton.attr( 'aria-expanded', $body.hasClass( 'show-filters' ) );
1815 // Clears all the checked filters
1816 // @uses filtersChecked()
1817 clearFilters: function( event ) {
1818 var items = $( '.filter-group' ).find( ':checkbox' ),
1821 event.preventDefault();
1823 _.each( items.filter( ':checked' ), function( item ) {
1824 $( item ).prop( 'checked', false );
1825 return self.filtersChecked();
1829 backToFilters: function( event ) {
1831 event.preventDefault();
1834 $( 'body' ).removeClass( 'filters-applied' );
1837 clearSearch: function() {
1838 $( '#wp-filter-search-input').val( '' );
1842 themes.InstallerRouter = Backbone.Router.extend({
1844 'theme-install.php?theme=:slug': 'preview',
1845 'theme-install.php?browse=:sort': 'sort',
1846 'theme-install.php?search=:query': 'search',
1847 'theme-install.php': 'sort'
1850 baseUrl: function( url ) {
1851 return 'theme-install.php' + url;
1854 themePath: '?theme=',
1855 browsePath: '?browse=',
1856 searchPath: '?search=',
1858 search: function( query ) {
1859 $( '.wp-filter-search' ).val( query );
1862 navigate: function() {
1863 if ( Backbone.history._hasPushState ) {
1864 Backbone.Router.prototype.navigate.apply( this, arguments );
1870 themes.RunInstaller = {
1874 // Passes the default 'section' as an option
1875 this.view = new themes.view.Installer({
1876 section: 'featured',
1877 SearchView: themes.view.InstallerSearch
1885 render: function() {
1891 Backbone.history.start({
1892 root: themes.data.settings.adminUrl,
1898 routes: function() {
1902 // Bind to our global `wp.themes` object
1903 // so that the router is available to sub-views
1904 themes.router = new themes.InstallerRouter();
1906 // Handles `theme` route event
1907 // Queries the API for the passed theme slug
1908 themes.router.on( 'route:preview', function( slug ) {
1909 request.theme = slug;
1910 self.view.collection.query( request );
1911 self.view.collection.once( 'update', function() {
1912 self.view.view.theme.preview();
1916 // Handles sorting / browsing routes
1917 // Also handles the root URL triggering a sort request
1918 // for `featured`, the default view
1919 themes.router.on( 'route:sort', function( sort ) {
1923 self.view.sort( sort );
1924 self.view.trigger( 'theme:close' );
1927 // The `search` route event. The router populates the input field.
1928 themes.router.on( 'route:search', function() {
1929 $( '.wp-filter-search' ).focus().trigger( 'keyup' );
1935 extraRoutes: function() {
1941 $( document ).ready(function() {
1942 if ( themes.isInstall ) {
1943 themes.RunInstaller.init();
1948 $( '.broken-themes .delete-theme' ).on( 'click', function() {
1949 return confirm( _wpThemeSettings.settings.confirmDelete );
1955 // Align theme browser thickbox
1957 jQuery(document).ready( function($) {
1958 tb_position = function() {
1959 var tbWindow = $('#TB_window'),
1960 width = $(window).width(),
1961 H = $(window).height(),
1962 W = ( 1040 < width ) ? 1040 : width,
1963 adminbar_height = 0;
1965 if ( $('#wpadminbar').length ) {
1966 adminbar_height = parseInt( $('#wpadminbar').css('height'), 10 );
1969 if ( tbWindow.size() ) {
1970 tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
1971 $('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
1972 tbWindow.css({'margin-left': '-' + parseInt( ( ( W - 50 ) / 2 ), 10 ) + 'px'});
1973 if ( typeof document.body.style.maxWidth !== 'undefined' ) {
1974 tbWindow.css({'top': 20 + adminbar_height + 'px', 'margin-top': '0'});
1979 $(window).resize(function(){ tb_position(); });