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 ) {
613 event.preventDefault();
615 wp.updates.maybeRequestFilesystemCredentials( event );
617 $( document ).on( 'wp-theme-update-success', function( event, response ) {
618 _this.model.off( 'change', _this.render, _this );
619 if ( _this.model.get( 'id' ) === response.slug ) {
622 version: response.newVersion
625 _this.model.on( 'change', _this.render, _this );
628 wp.updates.updateTheme( {
629 slug: $( event.target ).parents( 'div.theme' ).first().data( 'slug' )
634 // Theme Details view
635 // Set ups a modal overlay with the expanded theme data
636 themes.view.Details = wp.Backbone.View.extend({
638 // Wrap theme data on a div.theme element
639 className: 'theme-overlay',
643 'click .delete-theme': 'deleteTheme',
644 'click .left': 'previousTheme',
645 'click .right': 'nextTheme',
646 'click #update-theme': 'updateTheme'
649 // The HTML template for the theme overlay
650 html: themes.template( 'theme-single' ),
653 var data = this.model.toJSON();
654 this.$el.html( this.html( data ) );
655 // Renders active theme styles
657 // Set up navigation events
659 // Checks screenshot size
660 this.screenshotCheck( this.$el );
661 // Contain "tabbing" inside the overlay
662 this.containFocus( this.$el );
665 // Adds a class to the currently active theme
666 // and to the overlay in detailed view mode
667 activeTheme: function() {
668 // Check the model has the active property
669 this.$el.toggleClass( 'active', this.model.get( 'active' ) );
672 // Set initial focus and constrain tabbing within the theme browser modal.
673 containFocus: function( $el ) {
675 // Set initial focus on the primary action control.
676 _.delay( function() {
677 $( '.theme-wrap a.button-primary:visible' ).focus();
680 // Constrain tabbing within the modal.
681 $el.on( 'keydown.wp-themes', function( event ) {
682 var $firstFocusable = $el.find( '.theme-header button:not(.disabled)' ).first(),
683 $lastFocusable = $el.find( '.theme-actions a:visible' ).last();
685 // Check for the Tab key.
686 if ( 9 === event.which ) {
687 if ( $firstFocusable[0] === event.target && event.shiftKey ) {
688 $lastFocusable.focus();
689 event.preventDefault();
690 } else if ( $lastFocusable[0] === event.target && ! event.shiftKey ) {
691 $firstFocusable.focus();
692 event.preventDefault();
698 // Single theme overlay screen
699 // It's shown when clicking a theme
700 collapse: function( event ) {
704 event = event || window.event;
706 // Prevent collapsing detailed view when there is only one theme available
707 if ( themes.data.themes.length === 1 ) {
711 // Detect if the click is inside the overlay
712 // and don't close it unless the target was
713 // the div.back button
714 if ( $( event.target ).is( '.theme-backdrop' ) || $( event.target ).is( '.close' ) || event.keyCode === 27 ) {
716 // Add a temporary closing class while overlay fades out
717 $( 'body' ).addClass( 'closing-overlay' );
719 // With a quick fade out animation
720 this.$el.fadeOut( 130, function() {
721 // Clicking outside the modal box closes the overlay
722 $( 'body' ).removeClass( 'closing-overlay' );
723 // Handle event cleanup
726 // Get scroll position to avoid jumping to the top
727 scroll = document.body.scrollTop;
729 // Clean the url structure
730 themes.router.navigate( themes.router.baseUrl( '' ) );
732 // Restore scroll position
733 document.body.scrollTop = scroll;
735 // Return focus to the theme div
736 if ( themes.focusedTheme ) {
737 themes.focusedTheme.focus();
743 // Handles .disabled classes for next/previous buttons
744 navigation: function() {
746 // Disable Left/Right when at the start or end of the collection
747 if ( this.model.cid === this.model.collection.at(0).cid ) {
748 this.$el.find( '.left' )
749 .addClass( 'disabled' )
750 .prop( 'disabled', true );
752 if ( this.model.cid === this.model.collection.at( this.model.collection.length - 1 ).cid ) {
753 this.$el.find( '.right' )
754 .addClass( 'disabled' )
755 .prop( 'disabled', true );
759 // Performs the actions to effectively close
760 // the theme details overlay
761 closeOverlay: function() {
762 $( 'body' ).removeClass( 'modal-open' );
765 this.trigger( 'theme:collapse' );
768 updateTheme: function( event ) {
770 event.preventDefault();
772 wp.updates.maybeRequestFilesystemCredentials( event );
774 $( document ).on( 'wp-theme-update-success', function( event, response ) {
775 if ( _this.model.get( 'id' ) === response.slug ) {
778 version: response.newVersion
784 wp.updates.updateTheme( {
785 slug: $( event.target ).data( 'slug' )
789 deleteTheme: function( event ) {
791 _collection = _this.model.collection,
793 event.preventDefault();
795 // Confirmation dialog for deleting a theme.
796 if ( ! window.confirm( wp.themes.data.settings.confirmDelete ) ) {
800 wp.updates.maybeRequestFilesystemCredentials( event );
802 $( document ).one( 'wp-theme-delete-success', function( event, response ) {
803 _this.$el.find( '.close' ).trigger( 'click' );
804 $( '[data-slug="' + response.slug + '"' ).css( { backgroundColor:'#faafaa' } ).fadeOut( 350, function() {
806 _themes.data.themes = _.without( _themes.data.themes, _.findWhere( _themes.data.themes, { id: response.slug } ) );
808 $( '.wp-filter-search' ).val( '' );
809 _collection.doSearch( '' );
810 _collection.remove( _this.model );
811 _collection.trigger( 'themes:update' );
815 wp.updates.deleteTheme( {
816 slug: this.model.get( 'id' )
820 nextTheme: function() {
822 self.trigger( 'theme:next', self.model.cid );
826 previousTheme: function() {
828 self.trigger( 'theme:previous', self.model.cid );
832 // Checks if the theme screenshot is the old 300px width version
833 // and adds a corresponding class if it's true
834 screenshotCheck: function( el ) {
835 var screenshot, image;
837 screenshot = el.find( '.screenshot img' );
839 image.src = screenshot.attr( 'src' );
842 if ( image.width && image.width <= 300 ) {
843 el.addClass( 'small-screenshot' );
848 // Theme Preview view
849 // Set ups a modal overlay with the expanded theme data
850 themes.view.Preview = themes.view.Details.extend({
852 className: 'wp-full-overlay expanded',
853 el: '.theme-install-overlay',
856 'click .close-full-overlay': 'close',
857 'click .collapse-sidebar': 'collapse',
858 'click .devices button': 'previewDevice',
859 'click .previous-theme': 'previousTheme',
860 'click .next-theme': 'nextTheme',
862 'click .theme-install': 'installTheme'
865 // The HTML template for the theme preview
866 html: themes.template( 'theme-preview' ),
869 var self = this, currentPreviewDevice,
870 data = this.model.toJSON();
872 this.$el.removeClass( 'iframe-ready' ).html( this.html( data ) );
874 currentPreviewDevice = this.$el.data( 'current-preview-device' );
875 if ( currentPreviewDevice ) {
876 self.tooglePreviewDeviceButtons( currentPreviewDevice );
879 themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.get( 'id' ) ), { replace: true } );
881 this.$el.fadeIn( 200, function() {
882 $( 'body' ).addClass( 'theme-installer-active full-overlay-active' );
883 $( '.close-full-overlay' ).focus();
886 this.$el.find( 'iframe' ).one( 'load', function() {
891 iframeLoaded: function() {
892 this.$el.addClass( 'iframe-ready' );
896 this.$el.fadeOut( 200, function() {
897 $( 'body' ).removeClass( 'theme-installer-active full-overlay-active' );
899 // Return focus to the theme div
900 if ( themes.focusedTheme ) {
901 themes.focusedTheme.focus();
903 }).removeClass( 'iframe-ready' );
905 themes.router.navigate( themes.router.baseUrl( '' ) );
906 this.trigger( 'preview:close' );
907 this.undelegateEvents();
912 collapse: function( event ) {
913 var $button = $( event.currentTarget );
914 if ( 'true' === $button.attr( 'aria-expanded' ) ) {
915 $button.attr({ 'aria-expanded': 'false', 'aria-label': l10n.expandSidebar });
917 $button.attr({ 'aria-expanded': 'true', 'aria-label': l10n.collapseSidebar });
920 this.$el.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
924 previewDevice: function( event ) {
925 var device = $( event.currentTarget ).data( 'device' );
928 .removeClass( 'preview-desktop preview-tablet preview-mobile' )
929 .addClass( 'preview-' + device )
930 .data( 'current-preview-device', device );
932 this.tooglePreviewDeviceButtons( device );
935 tooglePreviewDeviceButtons: function( newDevice ) {
936 var $devices = $( '.wp-full-overlay-footer .devices' );
938 $devices.find( 'button' )
939 .removeClass( 'active' )
940 .attr( 'aria-pressed', false );
942 $devices.find( 'button.preview-' + newDevice )
943 .addClass( 'active' )
944 .attr( 'aria-pressed', true );
947 keyEvent: function( event ) {
948 // The escape key closes the preview
949 if ( event.keyCode === 27 ) {
950 this.undelegateEvents();
953 // The right arrow key, next theme
954 if ( event.keyCode === 39 ) {
955 _.once( this.nextTheme() );
958 // The left arrow key, previous theme
959 if ( event.keyCode === 37 ) {
960 this.previousTheme();
964 installTheme: function( event ) {
966 $target = $( event.target );
967 event.preventDefault();
969 if ( $target.hasClass( 'disabled' ) ) {
973 wp.updates.maybeRequestFilesystemCredentials( event );
975 $( document ).on( 'wp-theme-install-success', function() {
976 _this.model.set( { 'installed': true } );
979 wp.updates.installTheme( {
980 slug: $target.data( 'slug' )
985 // Controls the rendering of div.themes,
986 // a wrapper that will hold all the theme elements
987 themes.view.Themes = wp.Backbone.View.extend({
989 className: 'themes wp-clearfix',
990 $overlay: $( 'div.theme-overlay' ),
992 // Number to keep track of scroll position
993 // while in theme-overlay mode
996 // The theme count element
997 count: $( '.wrap .theme-count' ),
999 // The live themes count
1002 initialize: function( options ) {
1006 this.parent = options.parent;
1008 // Set current view to [grid]
1009 this.setView( 'grid' );
1011 // Move the active theme to the beginning of the collection
1012 self.currentTheme();
1014 // When the collection is updated by user input...
1015 this.listenTo( self.collection, 'themes:update', function() {
1016 self.parent.page = 0;
1017 self.currentTheme();
1018 self.render( this );
1021 // Update theme count to full result set when available.
1022 this.listenTo( self.collection, 'query:success', function( count ) {
1023 if ( _.isNumber( count ) ) {
1024 self.count.text( count );
1025 self.announceSearchResults( count );
1027 self.count.text( self.collection.length );
1028 self.announceSearchResults( self.collection.length );
1032 this.listenTo( self.collection, 'query:empty', function() {
1033 $( 'body' ).addClass( 'no-results' );
1036 this.listenTo( this.parent, 'theme:scroll', function() {
1037 self.renderThemes( self.parent.page );
1040 this.listenTo( this.parent, 'theme:close', function() {
1041 if ( self.overlay ) {
1042 self.overlay.closeOverlay();
1046 // Bind keyboard events.
1047 $( 'body' ).on( 'keyup', function( event ) {
1048 if ( ! self.overlay ) {
1052 // Bail if the filesystem credentials dialog is shown.
1053 if ( $( '#request-filesystem-credentials-dialog' ).is( ':visible' ) ) {
1057 // Pressing the right arrow key fires a theme:next event
1058 if ( event.keyCode === 39 ) {
1059 self.overlay.nextTheme();
1062 // Pressing the left arrow key fires a theme:previous event
1063 if ( event.keyCode === 37 ) {
1064 self.overlay.previousTheme();
1067 // Pressing the escape key fires a theme:collapse event
1068 if ( event.keyCode === 27 ) {
1069 self.overlay.collapse( event );
1074 // Manages rendering of theme pages
1075 // and keeping theme count in sync
1076 render: function() {
1077 // Clear the DOM, please
1080 // If the user doesn't have switch capabilities
1081 // or there is only one theme in the collection
1082 // render the detailed view of the active theme
1083 if ( themes.data.themes.length === 1 ) {
1085 // Constructs the view
1086 this.singleTheme = new themes.view.Details({
1087 model: this.collection.models[0]
1090 // Render and apply a 'single-theme' class to our container
1091 this.singleTheme.render();
1092 this.$el.addClass( 'single-theme' );
1093 this.$el.append( this.singleTheme.el );
1096 // Generate the themes
1097 // Using page instance
1098 // While checking the collection has items
1099 if ( this.options.collection.size() > 0 ) {
1100 this.renderThemes( this.parent.page );
1103 // Display a live theme count for the collection
1104 this.liveThemeCount = this.collection.count ? this.collection.count : this.collection.length;
1105 this.count.text( this.liveThemeCount );
1108 * In the theme installer the themes count is already announced
1109 * because `announceSearchResults` is called on `query:success`.
1111 if ( ! themes.isInstall ) {
1112 this.announceSearchResults( this.liveThemeCount );
1116 // Iterates through each instance of the collection
1117 // and renders each theme module
1118 renderThemes: function( page ) {
1121 self.instance = self.collection.paginate( page );
1123 // If we have no more themes bail
1124 if ( self.instance.size() === 0 ) {
1125 // Fire a no-more-themes event.
1126 this.parent.trigger( 'theme:end' );
1130 // Make sure the add-new stays at the end
1131 if ( ! themes.isInstall && page >= 1 ) {
1132 $( '.add-new-theme' ).remove();
1135 // Loop through the themes and setup each theme view
1136 self.instance.each( function( theme ) {
1137 self.theme = new themes.view.Theme({
1142 // Render the views...
1143 self.theme.render();
1144 // and append them to div.themes
1145 self.$el.append( self.theme.el );
1147 // Binds to theme:expand to show the modal box
1148 // with the theme details
1149 self.listenTo( self.theme, 'theme:expand', self.expand, self );
1152 // 'Add new theme' element shown at the end of the grid
1153 if ( ! themes.isInstall && themes.data.settings.canInstall ) {
1154 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>' );
1160 // Grabs current theme and puts it at the beginning of the collection
1161 currentTheme: function() {
1165 current = self.collection.findWhere({ active: true });
1167 // Move the active theme to the beginning of the collection
1169 self.collection.remove( current );
1170 self.collection.add( current, { at:0 } );
1174 // Sets current view
1175 setView: function( view ) {
1179 // Renders the overlay with the ThemeDetails view
1180 // Uses the current model data
1181 expand: function( id ) {
1182 var self = this, $card, $modal;
1184 // Set the current theme model
1185 this.model = self.collection.get( id );
1187 // Trigger a route update for the current model
1188 themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.id ) );
1190 // Sets this.view to 'detail'
1191 this.setView( 'detail' );
1192 $( 'body' ).addClass( 'modal-open' );
1194 // Set up the theme details view
1195 this.overlay = new themes.view.Details({
1199 this.overlay.render();
1201 if ( this.model.get( 'hasUpdate' ) ) {
1202 $card = $( '[data-slug="' + this.model.id + '"]' );
1203 $modal = $( this.overlay.el );
1205 if ( $card.find( '.updating-message' ).length ) {
1206 $modal.find( '.notice-warning h3' ).remove();
1207 $modal.find( '.notice-warning' )
1208 .removeClass( 'notice-large' )
1209 .addClass( 'updating-message' )
1210 .find( 'p' ).text( wp.updates.l10n.updating );
1211 } else if ( $card.find( '.notice-error' ).length ) {
1212 $modal.find( '.notice-warning' ).remove();
1216 this.$overlay.html( this.overlay.el );
1218 // Bind to theme:next and theme:previous
1219 // triggered by the arrow keys
1221 // Keep track of the current model so we
1222 // can infer an index position
1223 this.listenTo( this.overlay, 'theme:next', function() {
1224 // Renders the next theme on the overlay
1225 self.next( [ self.model.cid ] );
1228 .listenTo( this.overlay, 'theme:previous', function() {
1229 // Renders the previous theme on the overlay
1230 self.previous( [ self.model.cid ] );
1234 // This method renders the next theme on the overlay modal
1235 // based on the current position in the collection
1236 // @params [model cid]
1237 next: function( args ) {
1241 // Get the current theme
1242 model = self.collection.get( args[0] );
1243 // Find the next model within the collection
1244 nextModel = self.collection.at( self.collection.indexOf( model ) + 1 );
1246 // Sanity check which also serves as a boundary test
1247 if ( nextModel !== undefined ) {
1249 // We have a new theme...
1250 // Close the overlay
1251 this.overlay.closeOverlay();
1253 // Trigger a route update for the current model
1254 self.theme.trigger( 'theme:expand', nextModel.cid );
1259 // This method renders the previous theme on the overlay modal
1260 // based on the current position in the collection
1261 // @params [model cid]
1262 previous: function( args ) {
1264 model, previousModel;
1266 // Get the current theme
1267 model = self.collection.get( args[0] );
1268 // Find the previous model within the collection
1269 previousModel = self.collection.at( self.collection.indexOf( model ) - 1 );
1271 if ( previousModel !== undefined ) {
1273 // We have a new theme...
1274 // Close the overlay
1275 this.overlay.closeOverlay();
1277 // Trigger a route update for the current model
1278 self.theme.trigger( 'theme:expand', previousModel.cid );
1283 // Dispatch audible search results feedback message
1284 announceSearchResults: function( count ) {
1285 if ( 0 === count ) {
1286 wp.a11y.speak( l10n.noThemesFound );
1288 wp.a11y.speak( l10n.themesFound.replace( '%d', count ) );
1293 // Search input view controller.
1294 themes.view.Search = wp.Backbone.View.extend({
1297 className: 'wp-filter-search',
1298 id: 'wp-filter-search-input',
1302 placeholder: l10n.searchPlaceholder,
1304 'aria-describedby': 'live-search-desc'
1313 initialize: function( options ) {
1315 this.parent = options.parent;
1317 this.listenTo( this.parent, 'theme:close', function() {
1318 this.searching = false;
1323 search: function( event ) {
1325 if ( event.type === 'keyup' && event.which === 27 ) {
1326 event.target.value = '';
1330 * Since doSearch is debounced, it will only run when user input comes to a rest
1332 this.doSearch( event );
1335 // Runs a search on the theme collection.
1336 doSearch: _.debounce( function( event ) {
1339 this.collection.doSearch( event.target.value );
1341 // if search is initiated and key is not return
1342 if ( this.searching && event.which !== 13 ) {
1343 options.replace = true;
1345 this.searching = true;
1348 // Update the URL hash
1349 if ( event.target.value ) {
1350 themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + event.target.value ), options );
1352 themes.router.navigate( themes.router.baseUrl( '' ) );
1356 pushState: function( event ) {
1357 var url = themes.router.baseUrl( '' );
1359 if ( event.target.value ) {
1360 url = themes.router.baseUrl( themes.router.searchPath + event.target.value );
1363 this.searching = false;
1364 themes.router.navigate( url );
1369 // Sets up the routes events for relevant url queries
1370 // Listens to [theme] and [search] params
1371 themes.Router = Backbone.Router.extend({
1374 'themes.php?theme=:slug': 'theme',
1375 'themes.php?search=:query': 'search',
1376 'themes.php?s=:query': 'search',
1377 'themes.php': 'themes',
1381 baseUrl: function( url ) {
1382 return 'themes.php' + url;
1385 themePath: '?theme=',
1386 searchPath: '?search=',
1388 search: function( query ) {
1389 $( '.wp-filter-search' ).val( query );
1392 themes: function() {
1393 $( '.wp-filter-search' ).val( '' );
1396 navigate: function() {
1397 if ( Backbone.history._hasPushState ) {
1398 Backbone.Router.prototype.navigate.apply( this, arguments );
1404 // Execute and setup the application
1407 // Initializes the blog's theme library view
1408 // Create a new collection with data
1409 this.themes = new themes.Collection( themes.data.themes );
1412 this.view = new themes.view.Appearance({
1413 collection: this.themes
1419 render: function() {
1425 Backbone.history.start({
1426 root: themes.data.settings.adminUrl,
1432 routes: function() {
1434 // Bind to our global thx object
1435 // so that the object is available to sub-views
1436 themes.router = new themes.Router();
1438 // Handles theme details route event
1439 themes.router.on( 'route:theme', function( slug ) {
1440 self.view.view.expand( slug );
1443 themes.router.on( 'route:themes', function() {
1444 self.themes.doSearch( '' );
1445 self.view.trigger( 'theme:close' );
1448 // Handles search route event
1449 themes.router.on( 'route:search', function() {
1450 $( '.wp-filter-search' ).trigger( 'keyup' );
1456 extraRoutes: function() {
1461 // Extend the main Search view
1462 themes.view.InstallerSearch = themes.view.Search.extend({
1471 // Handles Ajax request for searching through themes in public repo
1472 search: function( event ) {
1474 // Tabbing or reverse tabbing into the search input shouldn't trigger a search
1475 if ( event.type === 'keyup' && ( event.which === 9 || event.which === 16 ) ) {
1479 this.collection = this.options.parent.view.collection;
1482 if ( event.type === 'keyup' && event.which === 27 ) {
1483 event.target.value = '';
1486 this.doSearch( event.target.value );
1489 doSearch: _.debounce( function( value ) {
1492 // Don't do anything if the search terms haven't changed.
1493 if ( this.terms === value ) {
1497 // Updates terms with the value passed.
1500 request.search = value;
1502 // Intercept an [author] search.
1504 // If input value starts with `author:` send a request
1505 // for `author` instead of a regular `search`
1506 if ( value.substring( 0, 7 ) === 'author:' ) {
1507 request.search = '';
1508 request.author = value.slice( 7 );
1511 // Intercept a [tag] search.
1513 // If input value starts with `tag:` send a request
1514 // for `tag` instead of a regular `search`
1515 if ( value.substring( 0, 4 ) === 'tag:' ) {
1516 request.search = '';
1517 request.tag = [ value.slice( 4 ) ];
1520 $( '.filter-links li > a.current' ).removeClass( 'current' );
1521 $( 'body' ).removeClass( 'show-filters filters-applied show-favorites-form' );
1523 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1524 // or searching the local cache
1525 this.collection.query( request );
1528 themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + value ), { replace: true } );
1532 themes.view.Installer = themes.view.Appearance.extend({
1534 el: '#wpbody-content .wrap',
1536 // Register events for sorting and filters in theme-navigation
1538 'click .filter-links li > a': 'onSort',
1539 'click .theme-filter': 'onFilter',
1540 'click .drawer-toggle': 'moreFilters',
1541 'click .filter-drawer .apply-filters': 'applyFilters',
1542 'click .filter-group [type="checkbox"]': 'addFilter',
1543 'click .filter-drawer .clear-filters': 'clearFilters',
1544 'click .filtered-by': 'backToFilters',
1545 'click .favorites-form-submit' : 'saveUsername',
1546 'keyup #wporg-username-input': 'saveUsername'
1549 // Initial render method
1550 render: function() {
1556 this.collection = new themes.Collection();
1558 // Bump `collection.currentQuery.page` and request more themes if we hit the end of the page.
1559 this.listenTo( this, 'theme:end', function() {
1561 // Make sure we are not already loading
1562 if ( self.collection.loadingThemes ) {
1566 // Set loadingThemes to true and bump page instance of currentQuery.
1567 self.collection.loadingThemes = true;
1568 self.collection.currentQuery.page++;
1570 // Use currentQuery.page to build the themes request.
1571 _.extend( self.collection.currentQuery.request, { page: self.collection.currentQuery.page } );
1572 self.collection.query( self.collection.currentQuery.request );
1575 this.listenTo( this.collection, 'query:success', function() {
1576 $( 'body' ).removeClass( 'loading-content' );
1577 $( '.theme-browser' ).find( 'div.error' ).remove();
1580 this.listenTo( this.collection, 'query:fail', function() {
1581 $( 'body' ).removeClass( 'loading-content' );
1582 $( '.theme-browser' ).find( 'div.error' ).remove();
1583 $( '.theme-browser' ).find( 'div.themes' ).before( '<div class="error"><p>' + l10n.error + '</p></div>' );
1590 // Set ups the view and passes the section argument
1591 this.view = new themes.view.Themes({
1592 collection: this.collection,
1596 // Reset pagination every time the install view handler is run
1599 // Render and append
1600 this.$el.find( '.themes' ).remove();
1602 this.$el.find( '.theme-browser' ).append( this.view.el ).addClass( 'rendered' );
1605 // Handles all the rendering of the public theme directory
1606 browse: function( section ) {
1607 // Create a new collection with the proper theme data
1609 this.collection.query( { browse: section } );
1612 // Sorting navigation
1613 onSort: function( event ) {
1614 var $el = $( event.target ),
1615 sort = $el.data( 'sort' );
1617 event.preventDefault();
1619 $( 'body' ).removeClass( 'filters-applied show-filters' );
1621 // Bail if this is already active
1622 if ( $el.hasClass( this.activeClass ) ) {
1628 // Trigger a router.naviagte update
1629 themes.router.navigate( themes.router.baseUrl( themes.router.browsePath + sort ) );
1632 sort: function( sort ) {
1635 $( '.filter-links li > a, .theme-filter' ).removeClass( this.activeClass );
1636 $( '[data-sort="' + sort + '"]' ).addClass( this.activeClass );
1638 if ( 'favorites' === sort ) {
1639 $ ( 'body' ).addClass( 'show-favorites-form' );
1641 $ ( 'body' ).removeClass( 'show-favorites-form' );
1644 this.browse( sort );
1648 onFilter: function( event ) {
1650 $el = $( event.target ),
1651 filter = $el.data( 'filter' );
1653 // Bail if this is already active
1654 if ( $el.hasClass( this.activeClass ) ) {
1658 $( '.filter-links li > a, .theme-section' ).removeClass( this.activeClass );
1659 $el.addClass( this.activeClass );
1665 // Construct the filter request
1666 // using the default values
1667 filter = _.union( [ filter, this.filtersChecked() ] );
1668 request = { tag: [ filter ] };
1670 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1671 // or searching the local cache
1672 this.collection.query( request );
1675 // Clicking on a checkbox to add another filter to the request
1676 addFilter: function() {
1677 this.filtersChecked();
1680 // Applying filters triggers a tag request
1681 applyFilters: function( event ) {
1683 tags = this.filtersChecked(),
1684 request = { tag: tags },
1685 filteringBy = $( '.filtered-by .tags' );
1688 event.preventDefault();
1691 $( 'body' ).addClass( 'filters-applied' );
1692 $( '.filter-links li > a.current' ).removeClass( 'current' );
1693 filteringBy.empty();
1695 _.each( tags, function( tag ) {
1696 name = $( 'label[for="filter-id-' + tag + '"]' ).text();
1697 filteringBy.append( '<span class="tag">' + name + '</span>' );
1700 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1701 // or searching the local cache
1702 this.collection.query( request );
1705 // Save the user's WordPress.org username and get his favorite themes.
1706 saveUsername: function ( event ) {
1707 var username = $( '#wporg-username-input' ).val(),
1708 nonce = $( '#wporg-username-nonce' ).val(),
1709 request = { browse: 'favorites', user: username },
1713 event.preventDefault();
1716 // save username on enter
1717 if ( event.type === 'keyup' && event.which !== 13 ) {
1721 return wp.ajax.send( 'save-wporg-username', {
1726 success: function () {
1727 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1728 // or searching the local cache
1729 that.collection.query( request );
1734 // Get the checked filters
1735 // @return {array} of tags or false
1736 filtersChecked: function() {
1737 var items = $( '.filter-group' ).find( ':checkbox' ),
1740 _.each( items.filter( ':checked' ), function( item ) {
1741 tags.push( $( item ).prop( 'value' ) );
1744 // When no filters are checked, restore initial state and return
1745 if ( tags.length === 0 ) {
1746 $( '.filter-drawer .apply-filters' ).find( 'span' ).text( '' );
1747 $( '.filter-drawer .clear-filters' ).hide();
1748 $( 'body' ).removeClass( 'filters-applied' );
1752 $( '.filter-drawer .apply-filters' ).find( 'span' ).text( tags.length );
1753 $( '.filter-drawer .clear-filters' ).css( 'display', 'inline-block' );
1758 activeClass: 'current',
1760 // Overwrite search container class to append search
1762 searchContainer: $( '.wp-filter .search-form' ),
1765 * When users press the "Upload Theme" button, show the upload form in place.
1767 uploader: function() {
1768 var uploadViewToggle = $( '.upload-view-toggle' ),
1769 $body = $( document.body );
1771 uploadViewToggle.on( 'click', function() {
1772 // Toggle the upload view.
1773 $body.toggleClass( 'show-upload-view' );
1774 // Toggle the `aria-expanded` button attribute.
1775 uploadViewToggle.attr( 'aria-expanded', $body.hasClass( 'show-upload-view' ) );
1779 // Toggle the full filters navigation
1780 moreFilters: function( event ) {
1781 event.preventDefault();
1783 if ( $( 'body' ).hasClass( 'filters-applied' ) ) {
1784 return this.backToFilters();
1787 // If the filters section is opened and filters are checked
1788 // run the relevant query collapsing to filtered-by state
1789 if ( $( 'body' ).hasClass( 'show-filters' ) && this.filtersChecked() ) {
1790 return this.addFilter();
1795 themes.router.navigate( themes.router.baseUrl( '' ) );
1796 $( 'body' ).toggleClass( 'show-filters' );
1799 // Clears all the checked filters
1800 // @uses filtersChecked()
1801 clearFilters: function( event ) {
1802 var items = $( '.filter-group' ).find( ':checkbox' ),
1805 event.preventDefault();
1807 _.each( items.filter( ':checked' ), function( item ) {
1808 $( item ).prop( 'checked', false );
1809 return self.filtersChecked();
1813 backToFilters: function( event ) {
1815 event.preventDefault();
1818 $( 'body' ).removeClass( 'filters-applied' );
1821 clearSearch: function() {
1822 $( '#wp-filter-search-input').val( '' );
1826 themes.InstallerRouter = Backbone.Router.extend({
1828 'theme-install.php?theme=:slug': 'preview',
1829 'theme-install.php?browse=:sort': 'sort',
1830 'theme-install.php?search=:query': 'search',
1831 'theme-install.php': 'sort'
1834 baseUrl: function( url ) {
1835 return 'theme-install.php' + url;
1838 themePath: '?theme=',
1839 browsePath: '?browse=',
1840 searchPath: '?search=',
1842 search: function( query ) {
1843 $( '.wp-filter-search' ).val( query );
1846 navigate: function() {
1847 if ( Backbone.history._hasPushState ) {
1848 Backbone.Router.prototype.navigate.apply( this, arguments );
1854 themes.RunInstaller = {
1858 // Passes the default 'section' as an option
1859 this.view = new themes.view.Installer({
1860 section: 'featured',
1861 SearchView: themes.view.InstallerSearch
1869 render: function() {
1875 Backbone.history.start({
1876 root: themes.data.settings.adminUrl,
1882 routes: function() {
1886 // Bind to our global `wp.themes` object
1887 // so that the router is available to sub-views
1888 themes.router = new themes.InstallerRouter();
1890 // Handles `theme` route event
1891 // Queries the API for the passed theme slug
1892 themes.router.on( 'route:preview', function( slug ) {
1893 request.theme = slug;
1894 self.view.collection.query( request );
1895 self.view.collection.once( 'update', function() {
1896 self.view.view.theme.preview();
1900 // Handles sorting / browsing routes
1901 // Also handles the root URL triggering a sort request
1902 // for `featured`, the default view
1903 themes.router.on( 'route:sort', function( sort ) {
1907 self.view.sort( sort );
1908 self.view.trigger( 'theme:close' );
1911 // The `search` route event. The router populates the input field.
1912 themes.router.on( 'route:search', function() {
1913 $( '.wp-filter-search' ).focus().trigger( 'keyup' );
1919 extraRoutes: function() {
1925 $( document ).ready(function() {
1926 if ( themes.isInstall ) {
1927 themes.RunInstaller.init();
1932 $( '.broken-themes .delete-theme' ).on( 'click', function() {
1933 return confirm( _wpThemeSettings.settings.confirmDelete );
1939 // Align theme browser thickbox
1941 jQuery(document).ready( function($) {
1942 tb_position = function() {
1943 var tbWindow = $('#TB_window'),
1944 width = $(window).width(),
1945 H = $(window).height(),
1946 W = ( 1040 < width ) ? 1040 : width,
1947 adminbar_height = 0;
1949 if ( $('#wpadminbar').length ) {
1950 adminbar_height = parseInt( $('#wpadminbar').css('height'), 10 );
1953 if ( tbWindow.size() ) {
1954 tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
1955 $('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
1956 tbWindow.css({'margin-left': '-' + parseInt( ( ( W - 50 ) / 2 ), 10 ) + 'px'});
1957 if ( typeof document.body.style.maxWidth !== 'undefined' ) {
1958 tbWindow.css({'top': 20 + adminbar_height + 'px', 'margin-top': '0'});
1963 $(window).resize(function(){ tb_position(); });