1 /* global _wpThemeSettings, confirm */
2 window.wp = window.wp || {};
6 // Set up our namespace...
8 themes = wp.themes = wp.themes || {};
10 // Store the theme data and settings for organized and quick access
11 // themes.data.settings, themes.data.themes, themes.data.l10n
12 themes.data = _wpThemeSettings;
13 l10n = themes.data.l10n;
15 // Shortcut for isInstall check
16 themes.isInstall = !! themes.data.settings.isInstall;
18 // Setup app structure
19 _.extend( themes, { model: {}, view: {}, routes: {}, router: {}, template: wp.template });
21 themes.Model = Backbone.Model.extend({
22 // Adds attributes to the default data coming through the .org themes api
23 // Map `id` to `slug` for shared code
24 initialize: function() {
27 // If theme is already installed, set an attribute.
28 if ( _.indexOf( themes.data.installedThemes, this.get( 'slug' ) ) !== -1 ) {
29 this.set({ installed: true });
34 // slug is for installation, id is for existing.
35 id: this.get( 'slug' ) || this.get( 'id' )
38 // Map `section.description` to `description`
39 // as the API sometimes returns it differently
40 if ( this.has( 'sections' ) ) {
41 description = this.get( 'sections' ).description;
42 this.set({ description: description });
47 // Main view controller for themes.php
48 // Unifies and renders all available views
49 themes.view.Appearance = wp.Backbone.View.extend({
51 el: '#wpbody-content .wrap .theme-browser',
54 // Pagination instance
57 // Sets up a throttler for binding to 'scroll'
58 initialize: function( options ) {
59 // Scroller checks how far the scroll position is
60 _.bindAll( this, 'scroller' );
62 this.SearchView = options.SearchView ? options.SearchView : themes.view.Search;
63 // Bind to the scroll event and throttle
64 // the results from this.scroller
65 this.window.bind( 'scroll', _.throttle( this.scroller, 300 ) );
68 // Main render control
70 // Setup the main theme view
71 // with the current theme collection
72 this.view = new themes.view.Themes({
73 collection: this.collection,
77 // Render search form.
82 this.$el.empty().append( this.view.el ).addClass( 'rendered' );
83 this.$el.append( '<br class="clear"/>' );
86 // Defines search element container
87 searchContainer: $( '#wpbody h1:first' ),
89 // Search input and view
90 // for current theme collection
95 // Don't render the search if there is only one theme
96 if ( themes.data.themes.length === 1 ) {
100 view = new this.SearchView({
101 collection: self.collection,
105 // Render and append after screen title
108 .append( $.parseHTML( '<label class="screen-reader-text" for="wp-filter-search-input">' + l10n.search + '</label>' ) )
112 // Checks when the user gets close to the bottom
113 // of the mage and triggers a theme:scroll event
114 scroller: function() {
118 bottom = this.window.scrollTop() + self.window.height();
119 threshold = self.$el.offset().top + self.$el.outerHeight( false ) - self.window.height();
120 threshold = Math.round( threshold * 0.9 );
122 if ( bottom > threshold ) {
123 this.trigger( 'theme:scroll' );
128 // Set up the Collection for our theme data
129 // @has 'id' 'name' 'screenshot' 'author' 'authorURI' 'version' 'active' ...
130 themes.Collection = Backbone.Collection.extend({
137 // Controls searching on the current theme collection
138 // and triggers an update event
139 doSearch: function( value ) {
141 // Don't do anything if we've already done this search
142 // Useful because the Search handler fires multiple times per keystroke
143 if ( this.terms === value ) {
147 // Updates terms with the value passed
150 // If we have terms, run a search...
151 if ( this.terms.length > 0 ) {
152 this.search( this.terms );
155 // If search is blank, show all themes
156 // Useful for resetting the views when you clean the input
157 if ( this.terms === '' ) {
158 this.reset( themes.data.themes );
159 $( 'body' ).removeClass( 'no-results' );
162 // Trigger an 'update' event
163 this.trigger( 'update' );
166 // Performs a search within the collection
168 search: function( term ) {
169 var match, results, haystack, name, description, author;
171 // Start with a full collection
172 this.reset( themes.data.themes, { silent: true } );
174 // Escape the term string for RegExp meta characters
175 term = term.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' );
177 // Consider spaces as word delimiters and match the whole string
178 // so matching terms can be combined
179 term = term.replace( / /g, ')(?=.*' );
180 match = new RegExp( '^(?=.*' + term + ').+', 'i' );
183 // _.filter and .test
184 results = this.filter( function( data ) {
185 name = data.get( 'name' ).replace( /(<([^>]+)>)/ig, '' );
186 description = data.get( 'description' ).replace( /(<([^>]+)>)/ig, '' );
187 author = data.get( 'author' ).replace( /(<([^>]+)>)/ig, '' );
189 haystack = _.union( name, data.get( 'id' ), description, author, data.get( 'tags' ) );
191 if ( match.test( data.get( 'author' ) ) && term.length > 2 ) {
192 data.set( 'displayAuthor', true );
195 return match.test( haystack );
198 if ( results.length === 0 ) {
199 this.trigger( 'query:empty' );
201 $( 'body' ).removeClass( 'no-results' );
204 this.reset( results );
207 // Paginates the collection with a helper method
208 // that slices the collection
209 paginate: function( instance ) {
210 var collection = this;
211 instance = instance || 0;
213 // Themes per instance are set at 20
214 collection = _( collection.rest( 20 * instance ) );
215 collection = _( collection.first( 20 ) );
222 // Handles requests for more themes
223 // and caches results
225 // When we are missing a cache object we fire an apiCall()
226 // which triggers events of `query:success` or `query:fail`
227 query: function( request ) {
232 var queries = this.queries,
234 query, isPaginated, count;
236 // Store current query request args
237 // for later use with the event `theme:end`
238 this.currentQuery.request = request;
240 // Search the query cache for matches.
241 query = _.find( queries, function( query ) {
242 return _.isEqual( query.request, request );
245 // If the request matches the stored currentQuery.request
246 // it means we have a paginated request.
247 isPaginated = _.has( request, 'page' );
249 // Reset the internal api page counter for non paginated queries.
250 if ( ! isPaginated ) {
251 this.currentQuery.page = 1;
254 // Otherwise, send a new API call and add it to the cache.
255 if ( ! query && ! isPaginated ) {
256 query = this.apiCall( request ).done( function( data ) {
258 // Update the collection with the queried data.
260 self.reset( data.themes );
261 count = data.info.results;
262 // Store the results and the query request
263 queries.push( { themes: data.themes, request: request, total: count } );
266 // Trigger a collection refresh event
267 // and a `query:success` event with a `count` argument.
268 self.trigger( 'update' );
269 self.trigger( 'query:success', count );
271 if ( data.themes && data.themes.length === 0 ) {
272 self.trigger( 'query:empty' );
275 }).fail( function() {
276 self.trigger( 'query:fail' );
279 // If it's a paginated request we need to fetch more themes...
281 return this.apiCall( request, isPaginated ).done( function( data ) {
282 // Add the new themes to the current collection
283 // @todo update counter
284 self.add( data.themes );
285 self.trigger( 'query:success' );
287 // We are done loading themes for now.
288 self.loadingThemes = false;
290 }).fail( function() {
291 self.trigger( 'query:fail' );
295 if ( query.themes.length === 0 ) {
296 self.trigger( 'query:empty' );
298 $( 'body' ).removeClass( 'no-results' );
301 // Only trigger an update event since we already have the themes
302 // on our cached object
303 if ( _.isNumber( query.total ) ) {
304 this.count = query.total;
307 this.reset( query.themes );
308 if ( ! query.total ) {
309 this.count = this.length;
312 this.trigger( 'update' );
313 this.trigger( 'query:success', this.count );
317 // Local cache array for API queries
320 // Keep track of current query so we can handle pagination
326 // Send request to api.wordpress.org/themes
327 apiCall: function( request, paginated ) {
328 return wp.ajax.send( 'query-themes', {
347 beforeSend: function() {
350 $( 'body' ).addClass( 'loading-content' ).removeClass( 'no-results' );
356 // Static status controller for when we are loading themes.
360 // This is the view that controls each theme item
361 // that will be displayed on the screen
362 themes.view.Theme = wp.Backbone.View.extend({
364 // Wrap theme data on a div.theme element
367 // Reflects which theme view we have
368 // 'grid' (default) or 'detail'
371 // The HTML template for each element to be rendered
372 html: themes.template( 'theme' ),
375 'click': themes.isInstall ? 'preview': 'expand',
376 'keydown': themes.isInstall ? 'preview': 'expand',
377 'touchend': themes.isInstall ? 'preview': 'expand',
379 'touchmove': 'preventExpand'
385 var data = this.model.toJSON();
386 // Render themes using the html template
387 this.$el.html( this.html( data ) ).attr({
389 'aria-describedby' : data.id + '-action ' + data.id + '-name'
392 // Renders active theme styles
395 if ( this.model.get( 'displayAuthor' ) ) {
396 this.$el.addClass( 'display-author' );
399 if ( this.model.get( 'installed' ) ) {
400 this.$el.addClass( 'is-installed' );
404 // Adds a class to the currently active theme
405 // and to the overlay in detailed view mode
406 activeTheme: function() {
407 if ( this.model.get( 'active' ) ) {
408 this.$el.addClass( 'active' );
412 // Add class of focus to the theme we are focused on.
413 addFocus: function() {
414 var $themeToFocus = ( $( ':focus' ).hasClass( 'theme' ) ) ? $( ':focus' ) : $(':focus').parents('.theme');
416 $('.theme.focus').removeClass('focus');
417 $themeToFocus.addClass('focus');
420 // Single theme overlay screen
421 // It's shown when clicking a theme
422 expand: function( event ) {
425 event = event || window.event;
427 // 'enter' and 'space' keys expand the details view when a theme is :focused
428 if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
432 // Bail if the user scrolled on a touch device
433 if ( this.touchDrag === true ) {
434 return this.touchDrag = false;
437 // Prevent the modal from showing when the user clicks
438 // one of the direct action buttons
439 if ( $( event.target ).is( '.theme-actions a' ) ) {
443 // Set focused theme to current element
444 themes.focusedTheme = this.$el;
446 this.trigger( 'theme:expand', self.model.cid );
449 preventExpand: function() {
450 this.touchDrag = true;
453 preview: function( event ) {
457 // Bail if the user scrolled on a touch device
458 if ( this.touchDrag === true ) {
459 return this.touchDrag = false;
462 // Allow direct link path to installing a theme.
463 if ( $( event.target ).hasClass( 'button-primary' ) ) {
467 // 'enter' and 'space' keys expand the details view when a theme is :focused
468 if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
472 // pressing enter while focused on the buttons shouldn't open the preview
473 if ( event.type === 'keydown' && event.which !== 13 && $( ':focus' ).hasClass( 'button' ) ) {
477 event.preventDefault();
479 event = event || window.event;
481 // Set focus to current theme.
482 themes.focusedTheme = this.$el;
484 // Construct a new Preview view.
485 preview = new themes.view.Preview({
489 // Render the view and append it.
491 this.setNavButtonsState();
493 // Hide previous/next navigation if there is only one theme
494 if ( this.model.collection.length === 1 ) {
495 preview.$el.addClass( 'no-navigation' );
497 preview.$el.removeClass( 'no-navigation' );
501 $( 'div.wrap' ).append( preview.el );
503 // Listen to our preview object
504 // for `theme:next` and `theme:previous` events.
505 this.listenTo( preview, 'theme:next', function() {
507 // Keep local track of current theme model.
508 current = self.model;
510 // If we have ventured away from current model update the current model position.
511 if ( ! _.isUndefined( self.current ) ) {
512 current = self.current;
515 // Get next theme model.
516 self.current = self.model.collection.at( self.model.collection.indexOf( current ) + 1 );
518 // If we have no more themes, bail.
519 if ( _.isUndefined( self.current ) ) {
520 self.options.parent.parent.trigger( 'theme:end' );
521 return self.current = current;
524 preview.model = self.current;
526 // Render and append.
528 this.setNavButtonsState();
529 $( '.next-theme' ).focus();
531 .listenTo( preview, 'theme:previous', function() {
533 // Keep track of current theme model.
534 current = self.model;
536 // Bail early if we are at the beginning of the collection
537 if ( self.model.collection.indexOf( self.current ) === 0 ) {
541 // If we have ventured away from current model update the current model position.
542 if ( ! _.isUndefined( self.current ) ) {
543 current = self.current;
546 // Get previous theme model.
547 self.current = self.model.collection.at( self.model.collection.indexOf( current ) - 1 );
549 // If we have no more themes, bail.
550 if ( _.isUndefined( self.current ) ) {
554 preview.model = self.current;
556 // Render and append.
558 this.setNavButtonsState();
559 $( '.previous-theme' ).focus();
562 this.listenTo( preview, 'preview:close', function() {
563 self.current = self.model;
567 // Handles .disabled classes for previous/next buttons in theme installer preview
568 setNavButtonsState: function() {
569 var $themeInstaller = $( '.theme-install-overlay' ),
570 current = _.isUndefined( this.current ) ? this.model : this.current;
572 // Disable previous at the zero position
573 if ( 0 === this.model.collection.indexOf( current ) ) {
574 $themeInstaller.find( '.previous-theme' ).addClass( 'disabled' );
577 // Disable next if the next model is undefined
578 if ( _.isUndefined( this.model.collection.at( this.model.collection.indexOf( current ) + 1 ) ) ) {
579 $themeInstaller.find( '.next-theme' ).addClass( 'disabled' );
584 // Theme Details view
585 // Set ups a modal overlay with the expanded theme data
586 themes.view.Details = wp.Backbone.View.extend({
588 // Wrap theme data on a div.theme element
589 className: 'theme-overlay',
593 'click .delete-theme': 'deleteTheme',
594 'click .left': 'previousTheme',
595 'click .right': 'nextTheme'
598 // The HTML template for the theme overlay
599 html: themes.template( 'theme-single' ),
602 var data = this.model.toJSON();
603 this.$el.html( this.html( data ) );
604 // Renders active theme styles
606 // Set up navigation events
608 // Checks screenshot size
609 this.screenshotCheck( this.$el );
610 // Contain "tabbing" inside the overlay
611 this.containFocus( this.$el );
614 // Adds a class to the currently active theme
615 // and to the overlay in detailed view mode
616 activeTheme: function() {
617 // Check the model has the active property
618 this.$el.toggleClass( 'active', this.model.get( 'active' ) );
621 // Keeps :focus within the theme details elements
622 containFocus: function( $el ) {
625 // Move focus to the primary action
626 _.delay( function() {
627 $( '.theme-wrap a.button-primary:visible' ).focus();
630 $el.on( 'keydown.wp-themes', function( event ) {
633 if ( event.which === 9 ) {
634 $target = $( event.target );
636 // Keep focus within the overlay by making the last link on theme actions
637 // switch focus to button.left on tabbing and vice versa
638 if ( $target.is( 'button.left' ) && event.shiftKey ) {
639 $el.find( '.theme-actions a:last-child' ).focus();
640 event.preventDefault();
641 } else if ( $target.is( '.theme-actions a:last-child' ) ) {
642 $el.find( 'button.left' ).focus();
643 event.preventDefault();
649 // Single theme overlay screen
650 // It's shown when clicking a theme
651 collapse: function( event ) {
655 event = event || window.event;
657 // Prevent collapsing detailed view when there is only one theme available
658 if ( themes.data.themes.length === 1 ) {
662 // Detect if the click is inside the overlay
663 // and don't close it unless the target was
664 // the div.back button
665 if ( $( event.target ).is( '.theme-backdrop' ) || $( event.target ).is( '.close' ) || event.keyCode === 27 ) {
667 // Add a temporary closing class while overlay fades out
668 $( 'body' ).addClass( 'closing-overlay' );
670 // With a quick fade out animation
671 this.$el.fadeOut( 130, function() {
672 // Clicking outside the modal box closes the overlay
673 $( 'body' ).removeClass( 'closing-overlay' );
674 // Handle event cleanup
677 // Get scroll position to avoid jumping to the top
678 scroll = document.body.scrollTop;
680 // Clean the url structure
681 themes.router.navigate( themes.router.baseUrl( '' ) );
683 // Restore scroll position
684 document.body.scrollTop = scroll;
686 // Return focus to the theme div
687 if ( themes.focusedTheme ) {
688 themes.focusedTheme.focus();
694 // Handles .disabled classes for next/previous buttons
695 navigation: function() {
697 // Disable Left/Right when at the start or end of the collection
698 if ( this.model.cid === this.model.collection.at(0).cid ) {
699 this.$el.find( '.left' ).addClass( 'disabled' );
701 if ( this.model.cid === this.model.collection.at( this.model.collection.length - 1 ).cid ) {
702 this.$el.find( '.right' ).addClass( 'disabled' );
706 // Performs the actions to effectively close
707 // the theme details overlay
708 closeOverlay: function() {
709 $( 'body' ).removeClass( 'modal-open' );
712 this.trigger( 'theme:collapse' );
715 // Confirmation dialog for deleting a theme
716 deleteTheme: function() {
717 return confirm( themes.data.settings.confirmDelete );
720 nextTheme: function() {
722 self.trigger( 'theme:next', self.model.cid );
726 previousTheme: function() {
728 self.trigger( 'theme:previous', self.model.cid );
732 // Checks if the theme screenshot is the old 300px width version
733 // and adds a corresponding class if it's true
734 screenshotCheck: function( el ) {
735 var screenshot, image;
737 screenshot = el.find( '.screenshot img' );
739 image.src = screenshot.attr( 'src' );
742 if ( image.width && image.width <= 300 ) {
743 el.addClass( 'small-screenshot' );
748 // Theme Preview view
749 // Set ups a modal overlay with the expanded theme data
750 themes.view.Preview = themes.view.Details.extend({
752 className: 'wp-full-overlay expanded',
753 el: '.theme-install-overlay',
756 'click .close-full-overlay': 'close',
757 'click .collapse-sidebar': 'collapse',
758 'click .previous-theme': 'previousTheme',
759 'click .next-theme': 'nextTheme',
763 // The HTML template for the theme preview
764 html: themes.template( 'theme-preview' ),
767 var data = this.model.toJSON();
769 this.$el.html( this.html( data ) );
771 themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.get( 'id' ) ), { replace: true } );
773 this.$el.fadeIn( 200, function() {
774 $( 'body' ).addClass( 'theme-installer-active full-overlay-active' );
775 $( '.close-full-overlay' ).focus();
780 this.$el.fadeOut( 200, function() {
781 $( 'body' ).removeClass( 'theme-installer-active full-overlay-active' );
783 // Return focus to the theme div
784 if ( themes.focusedTheme ) {
785 themes.focusedTheme.focus();
789 themes.router.navigate( themes.router.baseUrl( '' ) );
790 this.trigger( 'preview:close' );
791 this.undelegateEvents();
796 collapse: function( event ) {
797 var $button = $( event.currentTarget );
798 if ( 'true' === $button.attr( 'aria-expanded' ) ) {
799 $button.attr({ 'aria-expanded': 'false', 'aria-label': l10n.expandSidebar });
801 $button.attr({ 'aria-expanded': 'true', 'aria-label': l10n.collapseSidebar });
804 this.$el.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
808 keyEvent: function( event ) {
809 // The escape key closes the preview
810 if ( event.keyCode === 27 ) {
811 this.undelegateEvents();
814 // The right arrow key, next theme
815 if ( event.keyCode === 39 ) {
816 _.once( this.nextTheme() );
819 // The left arrow key, previous theme
820 if ( event.keyCode === 37 ) {
821 this.previousTheme();
826 // Controls the rendering of div.themes,
827 // a wrapper that will hold all the theme elements
828 themes.view.Themes = wp.Backbone.View.extend({
831 $overlay: $( 'div.theme-overlay' ),
833 // Number to keep track of scroll position
834 // while in theme-overlay mode
837 // The theme count element
838 count: $( '.wp-core-ui .theme-count' ),
840 // The live themes count
843 initialize: function( options ) {
847 this.parent = options.parent;
849 // Set current view to [grid]
850 this.setView( 'grid' );
852 // Move the active theme to the beginning of the collection
855 // When the collection is updated by user input...
856 this.listenTo( self.collection, 'update', function() {
857 self.parent.page = 0;
862 // Update theme count to full result set when available.
863 this.listenTo( self.collection, 'query:success', function( count ) {
864 if ( _.isNumber( count ) ) {
865 self.count.text( count );
866 self.announceSearchResults( count );
868 self.count.text( self.collection.length );
869 self.announceSearchResults( self.collection.length );
873 this.listenTo( self.collection, 'query:empty', function() {
874 $( 'body' ).addClass( 'no-results' );
877 this.listenTo( this.parent, 'theme:scroll', function() {
878 self.renderThemes( self.parent.page );
881 this.listenTo( this.parent, 'theme:close', function() {
882 if ( self.overlay ) {
883 self.overlay.closeOverlay();
887 // Bind keyboard events.
888 $( 'body' ).on( 'keyup', function( event ) {
889 if ( ! self.overlay ) {
893 // Pressing the right arrow key fires a theme:next event
894 if ( event.keyCode === 39 ) {
895 self.overlay.nextTheme();
898 // Pressing the left arrow key fires a theme:previous event
899 if ( event.keyCode === 37 ) {
900 self.overlay.previousTheme();
903 // Pressing the escape key fires a theme:collapse event
904 if ( event.keyCode === 27 ) {
905 self.overlay.collapse( event );
910 // Manages rendering of theme pages
911 // and keeping theme count in sync
913 // Clear the DOM, please
916 // If the user doesn't have switch capabilities
917 // or there is only one theme in the collection
918 // render the detailed view of the active theme
919 if ( themes.data.themes.length === 1 ) {
921 // Constructs the view
922 this.singleTheme = new themes.view.Details({
923 model: this.collection.models[0]
926 // Render and apply a 'single-theme' class to our container
927 this.singleTheme.render();
928 this.$el.addClass( 'single-theme' );
929 this.$el.append( this.singleTheme.el );
932 // Generate the themes
933 // Using page instance
934 // While checking the collection has items
935 if ( this.options.collection.size() > 0 ) {
936 this.renderThemes( this.parent.page );
939 // Display a live theme count for the collection
940 this.liveThemeCount = this.collection.count ? this.collection.count : this.collection.length;
941 this.count.text( this.liveThemeCount );
943 this.announceSearchResults( this.liveThemeCount );
946 // Iterates through each instance of the collection
947 // and renders each theme module
948 renderThemes: function( page ) {
951 self.instance = self.collection.paginate( page );
953 // If we have no more themes bail
954 if ( self.instance.size() === 0 ) {
955 // Fire a no-more-themes event.
956 this.parent.trigger( 'theme:end' );
960 // Make sure the add-new stays at the end
962 $( '.add-new-theme' ).remove();
965 // Loop through the themes and setup each theme view
966 self.instance.each( function( theme ) {
967 self.theme = new themes.view.Theme({
972 // Render the views...
974 // and append them to div.themes
975 self.$el.append( self.theme.el );
977 // Binds to theme:expand to show the modal box
978 // with the theme details
979 self.listenTo( self.theme, 'theme:expand', self.expand, self );
982 // 'Add new theme' element shown at the end of the grid
983 if ( themes.data.settings.canInstall ) {
984 this.$el.append( '<div class="theme add-new-theme"><a href="' + themes.data.settings.installURI + '"><div class="theme-screenshot"><span></span></div><h3 class="theme-name">' + l10n.addNew + '</h3></a></div>' );
990 // Grabs current theme and puts it at the beginning of the collection
991 currentTheme: function() {
995 current = self.collection.findWhere({ active: true });
997 // Move the active theme to the beginning of the collection
999 self.collection.remove( current );
1000 self.collection.add( current, { at:0 } );
1004 // Sets current view
1005 setView: function( view ) {
1009 // Renders the overlay with the ThemeDetails view
1010 // Uses the current model data
1011 expand: function( id ) {
1014 // Set the current theme model
1015 this.model = self.collection.get( id );
1017 // Trigger a route update for the current model
1018 themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.id ) );
1020 // Sets this.view to 'detail'
1021 this.setView( 'detail' );
1022 $( 'body' ).addClass( 'modal-open' );
1024 // Set up the theme details view
1025 this.overlay = new themes.view.Details({
1029 this.overlay.render();
1030 this.$overlay.html( this.overlay.el );
1032 // Bind to theme:next and theme:previous
1033 // triggered by the arrow keys
1035 // Keep track of the current model so we
1036 // can infer an index position
1037 this.listenTo( this.overlay, 'theme:next', function() {
1038 // Renders the next theme on the overlay
1039 self.next( [ self.model.cid ] );
1042 .listenTo( this.overlay, 'theme:previous', function() {
1043 // Renders the previous theme on the overlay
1044 self.previous( [ self.model.cid ] );
1048 // This method renders the next theme on the overlay modal
1049 // based on the current position in the collection
1050 // @params [model cid]
1051 next: function( args ) {
1055 // Get the current theme
1056 model = self.collection.get( args[0] );
1057 // Find the next model within the collection
1058 nextModel = self.collection.at( self.collection.indexOf( model ) + 1 );
1060 // Sanity check which also serves as a boundary test
1061 if ( nextModel !== undefined ) {
1063 // We have a new theme...
1064 // Close the overlay
1065 this.overlay.closeOverlay();
1067 // Trigger a route update for the current model
1068 self.theme.trigger( 'theme:expand', nextModel.cid );
1073 // This method renders the previous theme on the overlay modal
1074 // based on the current position in the collection
1075 // @params [model cid]
1076 previous: function( args ) {
1078 model, previousModel;
1080 // Get the current theme
1081 model = self.collection.get( args[0] );
1082 // Find the previous model within the collection
1083 previousModel = self.collection.at( self.collection.indexOf( model ) - 1 );
1085 if ( previousModel !== undefined ) {
1087 // We have a new theme...
1088 // Close the overlay
1089 this.overlay.closeOverlay();
1091 // Trigger a route update for the current model
1092 self.theme.trigger( 'theme:expand', previousModel.cid );
1097 // Dispatch audible search results feedback message
1098 announceSearchResults: function( count ) {
1099 if ( 0 === count ) {
1100 wp.a11y.speak( l10n.noThemesFound );
1102 wp.a11y.speak( l10n.themesFound.replace( '%d', count ) );
1107 // Search input view controller.
1108 themes.view.Search = wp.Backbone.View.extend({
1111 className: 'wp-filter-search',
1112 id: 'wp-filter-search-input',
1116 placeholder: l10n.searchPlaceholder,
1118 'aria-describedby': 'live-search-desc'
1127 initialize: function( options ) {
1129 this.parent = options.parent;
1131 this.listenTo( this.parent, 'theme:close', function() {
1132 this.searching = false;
1137 search: function( event ) {
1139 if ( event.type === 'keyup' && event.which === 27 ) {
1140 event.target.value = '';
1144 * Since doSearch is debounced, it will only run when user input comes to a rest
1146 this.doSearch( event );
1149 // Runs a search on the theme collection.
1150 doSearch: _.debounce( function( event ) {
1153 this.collection.doSearch( event.target.value );
1155 // if search is initiated and key is not return
1156 if ( this.searching && event.which !== 13 ) {
1157 options.replace = true;
1159 this.searching = true;
1162 // Update the URL hash
1163 if ( event.target.value ) {
1164 themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + event.target.value ), options );
1166 themes.router.navigate( themes.router.baseUrl( '' ) );
1170 pushState: function( event ) {
1171 var url = themes.router.baseUrl( '' );
1173 if ( event.target.value ) {
1174 url = themes.router.baseUrl( themes.router.searchPath + event.target.value );
1177 this.searching = false;
1178 themes.router.navigate( url );
1183 // Sets up the routes events for relevant url queries
1184 // Listens to [theme] and [search] params
1185 themes.Router = Backbone.Router.extend({
1188 'themes.php?theme=:slug': 'theme',
1189 'themes.php?search=:query': 'search',
1190 'themes.php?s=:query': 'search',
1191 'themes.php': 'themes',
1195 baseUrl: function( url ) {
1196 return 'themes.php' + url;
1199 themePath: '?theme=',
1200 searchPath: '?search=',
1202 search: function( query ) {
1203 $( '.wp-filter-search' ).val( query );
1206 themes: function() {
1207 $( '.wp-filter-search' ).val( '' );
1210 navigate: function() {
1211 if ( Backbone.history._hasPushState ) {
1212 Backbone.Router.prototype.navigate.apply( this, arguments );
1218 // Execute and setup the application
1221 // Initializes the blog's theme library view
1222 // Create a new collection with data
1223 this.themes = new themes.Collection( themes.data.themes );
1226 this.view = new themes.view.Appearance({
1227 collection: this.themes
1233 render: function() {
1239 Backbone.history.start({
1240 root: themes.data.settings.adminUrl,
1246 routes: function() {
1248 // Bind to our global thx object
1249 // so that the object is available to sub-views
1250 themes.router = new themes.Router();
1252 // Handles theme details route event
1253 themes.router.on( 'route:theme', function( slug ) {
1254 self.view.view.expand( slug );
1257 themes.router.on( 'route:themes', function() {
1258 self.themes.doSearch( '' );
1259 self.view.trigger( 'theme:close' );
1262 // Handles search route event
1263 themes.router.on( 'route:search', function() {
1264 $( '.wp-filter-search' ).trigger( 'keyup' );
1270 extraRoutes: function() {
1275 // Extend the main Search view
1276 themes.view.InstallerSearch = themes.view.Search.extend({
1283 // Handles Ajax request for searching through themes in public repo
1284 search: function( event ) {
1286 // Tabbing or reverse tabbing into the search input shouldn't trigger a search
1287 if ( event.type === 'keyup' && ( event.which === 9 || event.which === 16 ) ) {
1291 this.collection = this.options.parent.view.collection;
1294 if ( event.type === 'keyup' && event.which === 27 ) {
1295 event.target.value = '';
1298 this.doSearch( event.target.value );
1301 doSearch: _.debounce( function( value ) {
1304 request.search = value;
1306 // Intercept an [author] search.
1308 // If input value starts with `author:` send a request
1309 // for `author` instead of a regular `search`
1310 if ( value.substring( 0, 7 ) === 'author:' ) {
1311 request.search = '';
1312 request.author = value.slice( 7 );
1315 // Intercept a [tag] search.
1317 // If input value starts with `tag:` send a request
1318 // for `tag` instead of a regular `search`
1319 if ( value.substring( 0, 4 ) === 'tag:' ) {
1320 request.search = '';
1321 request.tag = [ value.slice( 4 ) ];
1324 $( '.filter-links li > a.current' ).removeClass( 'current' );
1325 $( 'body' ).removeClass( 'show-filters filters-applied' );
1327 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1328 // or searching the local cache
1329 this.collection.query( request );
1332 themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + value ), { replace: true } );
1336 themes.view.Installer = themes.view.Appearance.extend({
1338 el: '#wpbody-content .wrap',
1340 // Register events for sorting and filters in theme-navigation
1342 'click .filter-links li > a': 'onSort',
1343 'click .theme-filter': 'onFilter',
1344 'click .drawer-toggle': 'moreFilters',
1345 'click .filter-drawer .apply-filters': 'applyFilters',
1346 'click .filter-group [type="checkbox"]': 'addFilter',
1347 'click .filter-drawer .clear-filters': 'clearFilters',
1348 'click .filtered-by': 'backToFilters'
1351 // Initial render method
1352 render: function() {
1358 this.collection = new themes.Collection();
1360 // Bump `collection.currentQuery.page` and request more themes if we hit the end of the page.
1361 this.listenTo( this, 'theme:end', function() {
1363 // Make sure we are not already loading
1364 if ( self.collection.loadingThemes ) {
1368 // Set loadingThemes to true and bump page instance of currentQuery.
1369 self.collection.loadingThemes = true;
1370 self.collection.currentQuery.page++;
1372 // Use currentQuery.page to build the themes request.
1373 _.extend( self.collection.currentQuery.request, { page: self.collection.currentQuery.page } );
1374 self.collection.query( self.collection.currentQuery.request );
1377 this.listenTo( this.collection, 'query:success', function() {
1378 $( 'body' ).removeClass( 'loading-content' );
1379 $( '.theme-browser' ).find( 'div.error' ).remove();
1382 this.listenTo( this.collection, 'query:fail', function() {
1383 $( 'body' ).removeClass( 'loading-content' );
1384 $( '.theme-browser' ).find( 'div.error' ).remove();
1385 $( '.theme-browser' ).find( 'div.themes' ).before( '<div class="error"><p>' + l10n.error + '</p></div>' );
1392 // Set ups the view and passes the section argument
1393 this.view = new themes.view.Themes({
1394 collection: this.collection,
1398 // Reset pagination every time the install view handler is run
1401 // Render and append
1402 this.$el.find( '.themes' ).remove();
1404 this.$el.find( '.theme-browser' ).append( this.view.el ).addClass( 'rendered' );
1407 // Handles all the rendering of the public theme directory
1408 browse: function( section ) {
1409 // Create a new collection with the proper theme data
1411 this.collection.query( { browse: section } );
1414 // Sorting navigation
1415 onSort: function( event ) {
1416 var $el = $( event.target ),
1417 sort = $el.data( 'sort' );
1419 event.preventDefault();
1421 $( 'body' ).removeClass( 'filters-applied show-filters' );
1423 // Bail if this is already active
1424 if ( $el.hasClass( this.activeClass ) ) {
1430 // Trigger a router.naviagte update
1431 themes.router.navigate( themes.router.baseUrl( themes.router.browsePath + sort ) );
1434 sort: function( sort ) {
1437 $( '.filter-links li > a, .theme-filter' ).removeClass( this.activeClass );
1438 $( '[data-sort="' + sort + '"]' ).addClass( this.activeClass );
1440 this.browse( sort );
1444 onFilter: function( event ) {
1446 $el = $( event.target ),
1447 filter = $el.data( 'filter' );
1449 // Bail if this is already active
1450 if ( $el.hasClass( this.activeClass ) ) {
1454 $( '.filter-links li > a, .theme-section' ).removeClass( this.activeClass );
1455 $el.addClass( this.activeClass );
1461 // Construct the filter request
1462 // using the default values
1463 filter = _.union( filter, this.filtersChecked() );
1464 request = { tag: [ filter ] };
1466 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1467 // or searching the local cache
1468 this.collection.query( request );
1471 // Clicking on a checkbox to add another filter to the request
1472 addFilter: function() {
1473 this.filtersChecked();
1476 // Applying filters triggers a tag request
1477 applyFilters: function( event ) {
1479 tags = this.filtersChecked(),
1480 request = { tag: tags },
1481 filteringBy = $( '.filtered-by .tags' );
1484 event.preventDefault();
1487 $( 'body' ).addClass( 'filters-applied' );
1488 $( '.filter-links li > a.current' ).removeClass( 'current' );
1489 filteringBy.empty();
1491 _.each( tags, function( tag ) {
1492 name = $( 'label[for="filter-id-' + tag + '"]' ).text();
1493 filteringBy.append( '<span class="tag">' + name + '</span>' );
1496 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1497 // or searching the local cache
1498 this.collection.query( request );
1501 // Get the checked filters
1502 // @return {array} of tags or false
1503 filtersChecked: function() {
1504 var items = $( '.filter-group' ).find( ':checkbox' ),
1507 _.each( items.filter( ':checked' ), function( item ) {
1508 tags.push( $( item ).prop( 'value' ) );
1511 // When no filters are checked, restore initial state and return
1512 if ( tags.length === 0 ) {
1513 $( '.filter-drawer .apply-filters' ).find( 'span' ).text( '' );
1514 $( '.filter-drawer .clear-filters' ).hide();
1515 $( 'body' ).removeClass( 'filters-applied' );
1519 $( '.filter-drawer .apply-filters' ).find( 'span' ).text( tags.length );
1520 $( '.filter-drawer .clear-filters' ).css( 'display', 'inline-block' );
1525 activeClass: 'current',
1527 // Overwrite search container class to append search
1529 searchContainer: $( '.wp-filter .search-form' ),
1531 uploader: function() {
1532 $( 'a.upload' ).on( 'click', function( event ) {
1533 event.preventDefault();
1534 $( 'body' ).addClass( 'show-upload-theme' );
1535 themes.router.navigate( themes.router.baseUrl( '?upload' ), { replace: true } );
1537 $( 'a.browse-themes' ).on( 'click', function( event ) {
1538 event.preventDefault();
1539 $( 'body' ).removeClass( 'show-upload-theme' );
1540 themes.router.navigate( themes.router.baseUrl( '' ), { replace: true } );
1544 // Toggle the full filters navigation
1545 moreFilters: function( event ) {
1546 event.preventDefault();
1548 if ( $( 'body' ).hasClass( 'filters-applied' ) ) {
1549 return this.backToFilters();
1552 // If the filters section is opened and filters are checked
1553 // run the relevant query collapsing to filtered-by state
1554 if ( $( 'body' ).hasClass( 'show-filters' ) && this.filtersChecked() ) {
1555 return this.addFilter();
1560 themes.router.navigate( themes.router.baseUrl( '' ) );
1561 $( 'body' ).toggleClass( 'show-filters' );
1564 // Clears all the checked filters
1565 // @uses filtersChecked()
1566 clearFilters: function( event ) {
1567 var items = $( '.filter-group' ).find( ':checkbox' ),
1570 event.preventDefault();
1572 _.each( items.filter( ':checked' ), function( item ) {
1573 $( item ).prop( 'checked', false );
1574 return self.filtersChecked();
1578 backToFilters: function( event ) {
1580 event.preventDefault();
1583 $( 'body' ).removeClass( 'filters-applied' );
1586 clearSearch: function() {
1587 $( '#wp-filter-search-input').val( '' );
1591 themes.InstallerRouter = Backbone.Router.extend({
1593 'theme-install.php?theme=:slug': 'preview',
1594 'theme-install.php?browse=:sort': 'sort',
1595 'theme-install.php?upload': 'upload',
1596 'theme-install.php?search=:query': 'search',
1597 'theme-install.php': 'sort'
1600 baseUrl: function( url ) {
1601 return 'theme-install.php' + url;
1604 themePath: '?theme=',
1605 browsePath: '?browse=',
1606 searchPath: '?search=',
1608 search: function( query ) {
1609 $( '.wp-filter-search' ).val( query );
1612 navigate: function() {
1613 if ( Backbone.history._hasPushState ) {
1614 Backbone.Router.prototype.navigate.apply( this, arguments );
1620 themes.RunInstaller = {
1624 // Passes the default 'section' as an option
1625 this.view = new themes.view.Installer({
1626 section: 'featured',
1627 SearchView: themes.view.InstallerSearch
1635 render: function() {
1641 Backbone.history.start({
1642 root: themes.data.settings.adminUrl,
1648 routes: function() {
1652 // Bind to our global `wp.themes` object
1653 // so that the router is available to sub-views
1654 themes.router = new themes.InstallerRouter();
1656 // Handles `theme` route event
1657 // Queries the API for the passed theme slug
1658 themes.router.on( 'route:preview', function( slug ) {
1659 request.theme = slug;
1660 self.view.collection.query( request );
1663 // Handles sorting / browsing routes
1664 // Also handles the root URL triggering a sort request
1665 // for `featured`, the default view
1666 themes.router.on( 'route:sort', function( sort ) {
1670 self.view.sort( sort );
1671 self.view.trigger( 'theme:close' );
1674 // Support the `upload` route by going straight to upload section
1675 themes.router.on( 'route:upload', function() {
1676 $( 'a.upload' ).trigger( 'click' );
1679 // The `search` route event. The router populates the input field.
1680 themes.router.on( 'route:search', function() {
1681 $( '.wp-filter-search' ).focus().trigger( 'keyup' );
1687 extraRoutes: function() {
1693 $( document ).ready(function() {
1694 if ( themes.isInstall ) {
1695 themes.RunInstaller.init();
1700 $( '.broken-themes .delete-theme' ).on( 'click', function() {
1701 return confirm( _wpThemeSettings.settings.confirmDelete );
1707 // Align theme browser thickbox
1709 jQuery(document).ready( function($) {
1710 tb_position = function() {
1711 var tbWindow = $('#TB_window'),
1712 width = $(window).width(),
1713 H = $(window).height(),
1714 W = ( 1040 < width ) ? 1040 : width,
1715 adminbar_height = 0;
1717 if ( $('#wpadminbar').length ) {
1718 adminbar_height = parseInt( $('#wpadminbar').css('height'), 10 );
1721 if ( tbWindow.size() ) {
1722 tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
1723 $('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
1724 tbWindow.css({'margin-left': '-' + parseInt( ( ( W - 50 ) / 2 ), 10 ) + 'px'});
1725 if ( typeof document.body.style.maxWidth !== 'undefined' ) {
1726 tbWindow.css({'top': 20 + adminbar_height + 'px', 'margin-top': '0'});
1731 $(window).resize(function(){ tb_position(); });