1
/* global _wpThemeSettings, confirm */
2
window.wp = window.wp || {};
6
// Set up our namespace...
8
themes = wp.themes = wp.themes || {};
10
// Store the theme data and settings for organized and quick access
11
// themes.data.settings, themes.data.themes, themes.data.l10n
12
themes.data = _wpThemeSettings;
13
l10n = themes.data.l10n;
15
// Shortcut for isInstall check
16
themes.isInstall = !! themes.data.settings.isInstall;
18
// Setup app structure
19
_.extend( themes, { model: {}, view: {}, routes: {}, router: {}, template: wp.template });
21
themes.Model = Backbone.Model.extend({
22
// Adds attributes to the default data coming through the .org themes api
23
// Map `id` to `slug` for shared code
24
initialize: function() {
27
// If theme is already installed, set an attribute.
28
if ( _.indexOf( themes.data.installedThemes, this.get( 'slug' ) ) !== -1 ) {
29
this.set({ installed: true });
34
// slug is for installation, id is for existing.
35
id: this.get( 'slug' ) || this.get( 'id' )
38
// Map `section.description` to `description`
39
// as the API sometimes returns it differently
40
if ( this.has( 'sections' ) ) {
41
description = this.get( 'sections' ).description;
42
this.set({ description: description });
47
// Main view controller for themes.php
48
// Unifies and renders all available views
49
themes.view.Appearance = wp.Backbone.View.extend({
51
el: '#wpbody-content .wrap .theme-browser',
54
// Pagination instance
57
// Sets up a throttler for binding to 'scroll'
58
initialize: function( options ) {
59
// Scroller checks how far the scroll position is
60
_.bindAll( this, 'scroller' );
62
this.SearchView = options.SearchView ? options.SearchView : themes.view.Search;
63
// Bind to the scroll event and throttle
64
// the results from this.scroller
65
this.window.bind( 'scroll', _.throttle( this.scroller, 300 ) );
68
// Main render control
70
// Setup the main theme view
71
// with the current theme collection
72
this.view = new themes.view.Themes({
73
collection: this.collection,
77
// Render search form.
82
this.$el.empty().append( this.view.el ).addClass('rendered');
83
this.$el.append( '<br class="clear"/>' );
86
// Defines search element container
87
searchContainer: $( '#wpbody h2:first' ),
89
// Search input and view
90
// for current theme collection
95
// Don't render the search if there is only one theme
96
if ( themes.data.themes.length === 1 ) {
100
view = new this.SearchView({
101
collection: self.collection,
105
// Render and append after screen title
108
.append( $.parseHTML( '<label class="screen-reader-text" for="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 );
161
// Trigger an 'update' event
162
this.trigger( 'update' );
165
// Performs a search within the collection
167
search: function( term ) {
168
var match, results, haystack;
170
// Start with a full collection
171
this.reset( themes.data.themes, { silent: true } );
173
// Escape the term string for RegExp meta characters
174
term = term.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' );
176
// Consider spaces as word delimiters and match the whole string
177
// so matching terms can be combined
178
term = term.replace( / /g, ')(?=.*' );
179
match = new RegExp( '^(?=.*' + term + ').+', 'i' );
182
// _.filter and .test
183
results = this.filter( function( data ) {
184
haystack = _.union( data.get( 'name' ), data.get( 'id' ), data.get( 'description' ), data.get( 'author' ), data.get( 'tags' ) );
186
if ( match.test( data.get( 'author' ) ) && term.length > 2 ) {
187
data.set( 'displayAuthor', true );
190
return match.test( haystack );
193
if ( results.length === 0 ) {
194
this.trigger( 'query:empty' );
196
$( 'body' ).removeClass( 'no-results' );
199
this.reset( results );
202
// Paginates the collection with a helper method
203
// that slices the collection
204
paginate: function( instance ) {
205
var collection = this;
206
instance = instance || 0;
208
// Themes per instance are set at 20
209
collection = _( collection.rest( 20 * instance ) );
210
collection = _( collection.first( 20 ) );
217
// Handles requests for more themes
218
// and caches results
220
// When we are missing a cache object we fire an apiCall()
221
// which triggers events of `query:success` or `query:fail`
222
query: function( request ) {
227
var queries = this.queries,
229
query, isPaginated, count;
231
// Store current query request args
232
// for later use with the event `theme:end`
233
this.currentQuery.request = request;
235
// Search the query cache for matches.
236
query = _.find( queries, function( query ) {
237
return _.isEqual( query.request, request );
240
// If the request matches the stored currentQuery.request
241
// it means we have a paginated request.
242
isPaginated = _.has( request, 'page' );
244
// Reset the internal api page counter for non paginated queries.
245
if ( ! isPaginated ) {
246
this.currentQuery.page = 1;
249
// Otherwise, send a new API call and add it to the cache.
250
if ( ! query && ! isPaginated ) {
251
query = this.apiCall( request ).done( function( data ) {
253
// Update the collection with the queried data.
255
self.reset( data.themes );
256
count = data.info.results;
257
// Store the results and the query request
258
queries.push( { themes: data.themes, request: request, total: count } );
261
// Trigger a collection refresh event
262
// and a `query:success` event with a `count` argument.
263
self.trigger( 'update' );
264
self.trigger( 'query:success', count );
266
if ( data.themes && data.themes.length === 0 ) {
267
self.trigger( 'query:empty' );
270
}).fail( function() {
271
self.trigger( 'query:fail' );
274
// If it's a paginated request we need to fetch more themes...
276
return this.apiCall( request, isPaginated ).done( function( data ) {
277
// Add the new themes to the current collection
278
// @todo update counter
279
self.add( data.themes );
280
self.trigger( 'query:success' );
282
// We are done loading themes for now.
283
self.loadingThemes = false;
285
}).fail( function() {
286
self.trigger( 'query:fail' );
290
if ( query.themes.length === 0 ) {
291
self.trigger( 'query:empty' );
293
$( 'body' ).removeClass( 'no-results' );
296
// Only trigger an update event since we already have the themes
297
// on our cached object
298
if ( _.isNumber( query.total ) ) {
299
this.count = query.total;
302
this.reset( query.themes );
303
if ( ! query.total ) {
304
this.count = this.length;
307
this.trigger( 'update' );
308
this.trigger( 'query:success', this.count );
312
// Local cache array for API queries
315
// Keep track of current query so we can handle pagination
321
// Send request to api.wordpress.org/themes
322
apiCall: function( request, paginated ) {
323
return wp.ajax.send( 'query-themes', {
342
beforeSend: function() {
345
$( 'body' ).addClass( 'loading-content' ).removeClass( 'no-results' );
351
// Static status controller for when we are loading themes.
355
// This is the view that controls each theme item
356
// that will be displayed on the screen
357
themes.view.Theme = wp.Backbone.View.extend({
359
// Wrap theme data on a div.theme element
362
// Reflects which theme view we have
363
// 'grid' (default) or 'detail'
366
// The HTML template for each element to be rendered
367
html: themes.template( 'theme' ),
370
'click': themes.isInstall ? 'preview': 'expand',
371
'keydown': themes.isInstall ? 'preview': 'expand',
372
'touchend': themes.isInstall ? 'preview': 'expand',
374
'touchmove': 'preventExpand'
380
var data = this.model.toJSON();
381
// Render themes using the html template
382
this.$el.html( this.html( data ) ).attr({
384
'aria-describedby' : data.id + '-action ' + data.id + '-name'
387
// Renders active theme styles
390
if ( this.model.get( 'displayAuthor' ) ) {
391
this.$el.addClass( 'display-author' );
394
if ( this.model.get( 'installed' ) ) {
395
this.$el.addClass( 'is-installed' );
399
// Adds a class to the currently active theme
400
// and to the overlay in detailed view mode
401
activeTheme: function() {
402
if ( this.model.get( 'active' ) ) {
403
this.$el.addClass( 'active' );
407
// Add class of focus to the theme we are focused on.
408
addFocus: function() {
409
var $themeToFocus = ( $( ':focus' ).hasClass( 'theme' ) ) ? $( ':focus' ) : $(':focus').parents('.theme');
411
$('.theme.focus').removeClass('focus');
412
$themeToFocus.addClass('focus');
415
// Single theme overlay screen
416
// It's shown when clicking a theme
417
expand: function( event ) {
420
event = event || window.event;
422
// 'enter' and 'space' keys expand the details view when a theme is :focused
423
if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
427
// Bail if the user scrolled on a touch device
428
if ( this.touchDrag === true ) {
429
return this.touchDrag = false;
432
// Prevent the modal from showing when the user clicks
433
// one of the direct action buttons
434
if ( $( event.target ).is( '.theme-actions a' ) ) {
438
// Set focused theme to current element
439
themes.focusedTheme = this.$el;
441
this.trigger( 'theme:expand', self.model.cid );
444
preventExpand: function() {
445
this.touchDrag = true;
448
preview: function( event ) {
452
// Bail if the user scrolled on a touch device
453
if ( this.touchDrag === true ) {
454
return this.touchDrag = false;
457
// Allow direct link path to installing a theme.
458
if ( $( event.target ).hasClass( 'button-primary' ) ) {
462
// 'enter' and 'space' keys expand the details view when a theme is :focused
463
if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
467
// pressing enter while focused on the buttons shouldn't open the preview
468
if ( event.type === 'keydown' && event.which !== 13 && $( ':focus' ).hasClass( 'button' ) ) {
472
event.preventDefault();
474
event = event || window.event;
476
// Set focus to current theme.
477
themes.focusedTheme = this.$el;
479
// Construct a new Preview view.
480
preview = new themes.view.Preview({
484
// Render the view and append it.
486
this.setNavButtonsState();
488
// Hide previous/next navigation if there is only one theme
489
if ( this.model.collection.length === 1 ) {
490
preview.$el.addClass( 'no-navigation' );
492
preview.$el.removeClass( 'no-navigation' );
496
$( 'div.wrap' ).append( preview.el );
498
// Listen to our preview object
499
// for `theme:next` and `theme:previous` events.
500
this.listenTo( preview, 'theme:next', function() {
502
// Keep local track of current theme model.
503
current = self.model;
505
// If we have ventured away from current model update the current model position.
506
if ( ! _.isUndefined( self.current ) ) {
507
current = self.current;
510
// Get next theme model.
511
self.current = self.model.collection.at( self.model.collection.indexOf( current ) + 1 );
513
// If we have no more themes, bail.
514
if ( _.isUndefined( self.current ) ) {
515
self.options.parent.parent.trigger( 'theme:end' );
516
return self.current = current;
519
preview.model = self.current;
521
// Render and append.
523
this.setNavButtonsState();
524
$( '.next-theme' ).focus();
526
.listenTo( preview, 'theme:previous', function() {
528
// Keep track of current theme model.
529
current = self.model;
531
// Bail early if we are at the beginning of the collection
532
if ( self.model.collection.indexOf( self.current ) === 0 ) {
536
// If we have ventured away from current model update the current model position.
537
if ( ! _.isUndefined( self.current ) ) {
538
current = self.current;
541
// Get previous theme model.
542
self.current = self.model.collection.at( self.model.collection.indexOf( current ) - 1 );
544
// If we have no more themes, bail.
545
if ( _.isUndefined( self.current ) ) {
549
preview.model = self.current;
551
// Render and append.
553
this.setNavButtonsState();
554
$( '.previous-theme' ).focus();
557
this.listenTo( preview, 'preview:close', function() {
558
self.current = self.model;
562
// Handles .disabled classes for previous/next buttons in theme installer preview
563
setNavButtonsState: function() {
564
var $themeInstaller = $( '.theme-install-overlay' ),
565
current = _.isUndefined( this.current ) ? this.model : this.current;
567
// Disable previous at the zero position
568
if ( 0 === this.model.collection.indexOf( current ) ) {
569
$themeInstaller.find( '.previous-theme' ).addClass( 'disabled' );
572
// Disable next if the next model is undefined
573
if ( _.isUndefined( this.model.collection.at( this.model.collection.indexOf( current ) + 1 ) ) ) {
574
$themeInstaller.find( '.next-theme' ).addClass( 'disabled' );
579
// Theme Details view
580
// Set ups a modal overlay with the expanded theme data
581
themes.view.Details = wp.Backbone.View.extend({
583
// Wrap theme data on a div.theme element
584
className: 'theme-overlay',
588
'click .delete-theme': 'deleteTheme',
589
'click .left': 'previousTheme',
590
'click .right': 'nextTheme'
593
// The HTML template for the theme overlay
594
html: themes.template( 'theme-single' ),
597
var data = this.model.toJSON();
598
this.$el.html( this.html( data ) );
599
// Renders active theme styles
601
// Set up navigation events
603
// Checks screenshot size
604
this.screenshotCheck( this.$el );
605
// Contain "tabbing" inside the overlay
606
this.containFocus( this.$el );
609
// Adds a class to the currently active theme
610
// and to the overlay in detailed view mode
611
activeTheme: function() {
612
// Check the model has the active property
613
this.$el.toggleClass( 'active', this.model.get( 'active' ) );
616
// Keeps :focus within the theme details elements
617
containFocus: function( $el ) {
620
// Move focus to the primary action
621
_.delay( function() {
622
$( '.theme-wrap a.button-primary:visible' ).focus();
625
$el.on( 'keydown.wp-themes', function( event ) {
628
if ( event.which === 9 ) {
629
$target = $( event.target );
631
// Keep focus within the overlay by making the last link on theme actions
632
// switch focus to button.left on tabbing and vice versa
633
if ( $target.is( 'button.left' ) && event.shiftKey ) {
634
$el.find( '.theme-actions a:last-child' ).focus();
635
event.preventDefault();
636
} else if ( $target.is( '.theme-actions a:last-child' ) ) {
637
$el.find( 'button.left' ).focus();
638
event.preventDefault();
644
// Single theme overlay screen
645
// It's shown when clicking a theme
646
collapse: function( event ) {
650
event = event || window.event;
652
// Prevent collapsing detailed view when there is only one theme available
653
if ( themes.data.themes.length === 1 ) {
657
// Detect if the click is inside the overlay
658
// and don't close it unless the target was
659
// the div.back button
660
if ( $( event.target ).is( '.theme-backdrop' ) || $( event.target ).is( '.close' ) || event.keyCode === 27 ) {
662
// Add a temporary closing class while overlay fades out
663
$( 'body' ).addClass( 'closing-overlay' );
665
// With a quick fade out animation
666
this.$el.fadeOut( 130, function() {
667
// Clicking outside the modal box closes the overlay
668
$( 'body' ).removeClass( 'closing-overlay' );
669
// Handle event cleanup
672
// Get scroll position to avoid jumping to the top
673
scroll = document.body.scrollTop;
675
// Clean the url structure
676
themes.router.navigate( themes.router.baseUrl( '' ) );
678
// Restore scroll position
679
document.body.scrollTop = scroll;
681
// Return focus to the theme div
682
if ( themes.focusedTheme ) {
683
themes.focusedTheme.focus();
689
// Handles .disabled classes for next/previous buttons
690
navigation: function() {
692
// Disable Left/Right when at the start or end of the collection
693
if ( this.model.cid === this.model.collection.at(0).cid ) {
694
this.$el.find( '.left' ).addClass( 'disabled' );
696
if ( this.model.cid === this.model.collection.at( this.model.collection.length - 1 ).cid ) {
697
this.$el.find( '.right' ).addClass( 'disabled' );
701
// Performs the actions to effectively close
702
// the theme details overlay
703
closeOverlay: function() {
704
$( 'body' ).removeClass( 'modal-open' );
707
this.trigger( 'theme:collapse' );
710
// Confirmation dialog for deleting a theme
711
deleteTheme: function() {
712
return confirm( themes.data.settings.confirmDelete );
715
nextTheme: function() {
717
self.trigger( 'theme:next', self.model.cid );
721
previousTheme: function() {
723
self.trigger( 'theme:previous', self.model.cid );
727
// Checks if the theme screenshot is the old 300px width version
728
// and adds a corresponding class if it's true
729
screenshotCheck: function( el ) {
730
var screenshot, image;
732
screenshot = el.find( '.screenshot img' );
734
image.src = screenshot.attr( 'src' );
737
if ( image.width && image.width <= 300 ) {
738
el.addClass( 'small-screenshot' );
743
// Theme Preview view
744
// Set ups a modal overlay with the expanded theme data
745
themes.view.Preview = themes.view.Details.extend({
747
className: 'wp-full-overlay expanded',
748
el: '.theme-install-overlay',
751
'click .close-full-overlay': 'close',
752
'click .collapse-sidebar': 'collapse',
753
'click .previous-theme': 'previousTheme',
754
'click .next-theme': 'nextTheme',
758
// The HTML template for the theme preview
759
html: themes.template( 'theme-preview' ),
762
var data = this.model.toJSON();
764
this.$el.html( this.html( data ) );
766
themes.router.navigate( themes.router.baseUrl( '?theme=' + this.model.get( 'id' ) ), { replace: true } );
768
this.$el.fadeIn( 200, function() {
769
$( 'body' ).addClass( 'theme-installer-active full-overlay-active' );
770
$( '.close-full-overlay' ).focus();
775
this.$el.fadeOut( 200, function() {
776
$( 'body' ).removeClass( 'theme-installer-active full-overlay-active' );
778
// Return focus to the theme div
779
if ( themes.focusedTheme ) {
780
themes.focusedTheme.focus();
784
themes.router.navigate( themes.router.baseUrl( '' ) );
785
this.trigger( 'preview:close' );
786
this.undelegateEvents();
791
collapse: function() {
793
this.$el.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
797
keyEvent: function( event ) {
798
// The escape key closes the preview
799
if ( event.keyCode === 27 ) {
800
this.undelegateEvents();
803
// The right arrow key, next theme
804
if ( event.keyCode === 39 ) {
805
_.once( this.nextTheme() );
808
// The left arrow key, previous theme
809
if ( event.keyCode === 37 ) {
810
this.previousTheme();
815
// Controls the rendering of div.themes,
816
// a wrapper that will hold all the theme elements
817
themes.view.Themes = wp.Backbone.View.extend({
820
$overlay: $( 'div.theme-overlay' ),
822
// Number to keep track of scroll position
823
// while in theme-overlay mode
826
// The theme count element
827
count: $( '.theme-count' ),
829
initialize: function( options ) {
833
this.parent = options.parent;
835
// Set current view to [grid]
836
this.setView( 'grid' );
838
// Move the active theme to the beginning of the collection
841
// When the collection is updated by user input...
842
this.listenTo( self.collection, 'update', function() {
843
self.parent.page = 0;
848
// Update theme count to full result set when available.
849
this.listenTo( self.collection, 'query:success', function( count ) {
850
if ( _.isNumber( count ) ) {
851
self.count.text( count );
853
self.count.text( self.collection.length );
857
this.listenTo( self.collection, 'query:empty', function() {
858
$( 'body' ).addClass( 'no-results' );
861
this.listenTo( this.parent, 'theme:scroll', function() {
862
self.renderThemes( self.parent.page );
865
this.listenTo( this.parent, 'theme:close', function() {
866
if ( self.overlay ) {
867
self.overlay.closeOverlay();
871
// Bind keyboard events.
872
$( 'body' ).on( 'keyup', function( event ) {
873
if ( ! self.overlay ) {
877
// Pressing the right arrow key fires a theme:next event
878
if ( event.keyCode === 39 ) {
879
self.overlay.nextTheme();
882
// Pressing the left arrow key fires a theme:previous event
883
if ( event.keyCode === 37 ) {
884
self.overlay.previousTheme();
887
// Pressing the escape key fires a theme:collapse event
888
if ( event.keyCode === 27 ) {
889
self.overlay.collapse( event );
894
// Manages rendering of theme pages
895
// and keeping theme count in sync
897
// Clear the DOM, please
900
// If the user doesn't have switch capabilities
901
// or there is only one theme in the collection
902
// render the detailed view of the active theme
903
if ( themes.data.themes.length === 1 ) {
905
// Constructs the view
906
this.singleTheme = new themes.view.Details({
907
model: this.collection.models[0]
910
// Render and apply a 'single-theme' class to our container
911
this.singleTheme.render();
912
this.$el.addClass( 'single-theme' );
913
this.$el.append( this.singleTheme.el );
916
// Generate the themes
917
// Using page instance
918
// While checking the collection has items
919
if ( this.options.collection.size() > 0 ) {
920
this.renderThemes( this.parent.page );
923
// Display a live theme count for the collection
924
this.count.text( this.collection.count ? this.collection.count : this.collection.length );
927
// Iterates through each instance of the collection
928
// and renders each theme module
929
renderThemes: function( page ) {
932
self.instance = self.collection.paginate( page );
934
// If we have no more themes bail
935
if ( self.instance.size() === 0 ) {
936
// Fire a no-more-themes event.
937
this.parent.trigger( 'theme:end' );
941
// Make sure the add-new stays at the end
943
$( '.add-new-theme' ).remove();
946
// Loop through the themes and setup each theme view
947
self.instance.each( function( theme ) {
948
self.theme = new themes.view.Theme({
953
// Render the views...
955
// and append them to div.themes
956
self.$el.append( self.theme.el );
958
// Binds to theme:expand to show the modal box
959
// with the theme details
960
self.listenTo( self.theme, 'theme:expand', self.expand, self );
963
// 'Add new theme' element shown at the end of the grid
964
if ( themes.data.settings.canInstall ) {
965
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>' );
971
// Grabs current theme and puts it at the beginning of the collection
972
currentTheme: function() {
976
current = self.collection.findWhere({ active: true });
978
// Move the active theme to the beginning of the collection
980
self.collection.remove( current );
981
self.collection.add( current, { at:0 } );
986
setView: function( view ) {
990
// Renders the overlay with the ThemeDetails view
991
// Uses the current model data
992
expand: function( id ) {
995
// Set the current theme model
996
this.model = self.collection.get( id );
998
// Trigger a route update for the current model
999
themes.router.navigate( themes.router.baseUrl( '?theme=' + this.model.id ) );
1001
// Sets this.view to 'detail'
1002
this.setView( 'detail' );
1003
$( 'body' ).addClass( 'modal-open' );
1005
// Set up the theme details view
1006
this.overlay = new themes.view.Details({
1010
this.overlay.render();
1011
this.$overlay.html( this.overlay.el );
1013
// Bind to theme:next and theme:previous
1014
// triggered by the arrow keys
1016
// Keep track of the current model so we
1017
// can infer an index position
1018
this.listenTo( this.overlay, 'theme:next', function() {
1019
// Renders the next theme on the overlay
1020
self.next( [ self.model.cid ] );
1023
.listenTo( this.overlay, 'theme:previous', function() {
1024
// Renders the previous theme on the overlay
1025
self.previous( [ self.model.cid ] );
1029
// This method renders the next theme on the overlay modal
1030
// based on the current position in the collection
1031
// @params [model cid]
1032
next: function( args ) {
1036
// Get the current theme
1037
model = self.collection.get( args[0] );
1038
// Find the next model within the collection
1039
nextModel = self.collection.at( self.collection.indexOf( model ) + 1 );
1041
// Sanity check which also serves as a boundary test
1042
if ( nextModel !== undefined ) {
1044
// We have a new theme...
1045
// Close the overlay
1046
this.overlay.closeOverlay();
1048
// Trigger a route update for the current model
1049
self.theme.trigger( 'theme:expand', nextModel.cid );
1054
// This method renders the previous theme on the overlay modal
1055
// based on the current position in the collection
1056
// @params [model cid]
1057
previous: function( args ) {
1059
model, previousModel;
1061
// Get the current theme
1062
model = self.collection.get( args[0] );
1063
// Find the previous model within the collection
1064
previousModel = self.collection.at( self.collection.indexOf( model ) - 1 );
1066
if ( previousModel !== undefined ) {
1068
// We have a new theme...
1069
// Close the overlay
1070
this.overlay.closeOverlay();
1072
// Trigger a route update for the current model
1073
self.theme.trigger( 'theme:expand', previousModel.cid );
1079
// Search input view controller.
1080
themes.view.Search = wp.Backbone.View.extend({
1083
className: 'wp-filter-search',
1084
id: 'wp-filter-search-input',
1088
placeholder: l10n.searchPlaceholder,
1100
initialize: function( options ) {
1102
this.parent = options.parent;
1104
this.listenTo( this.parent, 'theme:close', function() {
1105
this.searching = false;
1110
// Runs a search on the theme collection.
1111
search: function( event ) {
1115
if ( event.type === 'keyup' && event.which === 27 ) {
1116
event.target.value = '';
1119
// Lose input focus when pressing enter
1120
if ( event.which === 13 ) {
1121
this.$el.trigger( 'blur' );
1124
this.collection.doSearch( event.target.value );
1126
// if search is initiated and key is not return
1127
if ( this.searching && event.which !== 13 ) {
1128
options.replace = true;
1130
this.searching = true;
1133
// Update the URL hash
1134
if ( event.target.value ) {
1135
themes.router.navigate( themes.router.baseUrl( '?search=' + event.target.value ), options );
1137
themes.router.navigate( themes.router.baseUrl( '' ) );
1141
pushState: function( event ) {
1142
var url = themes.router.baseUrl( '' );
1144
if ( event.target.value ) {
1145
url = themes.router.baseUrl( '?search=' + event.target.value );
1148
this.searching = false;
1149
themes.router.navigate( url );
1154
// Sets up the routes events for relevant url queries
1155
// Listens to [theme] and [search] params
1156
themes.Router = Backbone.Router.extend({
1159
'themes.php?theme=:slug': 'theme',
1160
'themes.php?search=:query': 'search',
1161
'themes.php?s=:query': 'search',
1162
'themes.php': 'themes',
1166
baseUrl: function( url ) {
1167
return 'themes.php' + url;
1170
search: function( query ) {
1171
$( '.wp-filter-search' ).val( query );
1174
themes: function() {
1175
$( '.wp-filter-search' ).val( '' );
1178
navigate: function() {
1179
if ( Backbone.history._hasPushState ) {
1180
Backbone.Router.prototype.navigate.apply( this, arguments );
1186
// Execute and setup the application
1189
// Initializes the blog's theme library view
1190
// Create a new collection with data
1191
this.themes = new themes.Collection( themes.data.themes );
1194
this.view = new themes.view.Appearance({
1195
collection: this.themes
1201
render: function() {
1207
Backbone.history.start({
1208
root: themes.data.settings.adminUrl,
1214
routes: function() {
1216
// Bind to our global thx object
1217
// so that the object is available to sub-views
1218
themes.router = new themes.Router();
1220
// Handles theme details route event
1221
themes.router.on( 'route:theme', function( slug ) {
1222
self.view.view.expand( slug );
1225
themes.router.on( 'route:themes', function() {
1226
self.themes.doSearch( '' );
1227
self.view.trigger( 'theme:close' );
1230
// Handles search route event
1231
themes.router.on( 'route:search', function() {
1232
$( '.wp-filter-search' ).trigger( 'keyup' );
1238
extraRoutes: function() {
1243
// Extend the main Search view
1244
themes.view.InstallerSearch = themes.view.Search.extend({
1250
// Handles Ajax request for searching through themes in public repo
1251
search: function( event ) {
1253
// Tabbing or reverse tabbing into the search input shouldn't trigger a search
1254
if ( event.type === 'keyup' && ( event.which === 9 || event.which === 16 ) ) {
1258
this.collection = this.options.parent.view.collection;
1261
if ( event.type === 'keyup' && event.which === 27 ) {
1262
event.target.value = '';
1265
_.debounce( _.bind( this.doSearch, this ), 300 )( event.target.value );
1268
doSearch: _.debounce( function( value ) {
1271
request.search = value;
1273
// Intercept an [author] search.
1275
// If input value starts with `author:` send a request
1276
// for `author` instead of a regular `search`
1277
if ( value.substring( 0, 7 ) === 'author:' ) {
1278
request.search = '';
1279
request.author = value.slice( 7 );
1282
// Intercept a [tag] search.
1284
// If input value starts with `tag:` send a request
1285
// for `tag` instead of a regular `search`
1286
if ( value.substring( 0, 4 ) === 'tag:' ) {
1287
request.search = '';
1288
request.tag = [ value.slice( 4 ) ];
1291
$( '.filter-links li > a.current' ).removeClass( 'current' );
1292
$( 'body' ).removeClass( 'show-filters filters-applied' );
1294
// Get the themes by sending Ajax POST request to api.wordpress.org/themes
1295
// or searching the local cache
1296
this.collection.query( request );
1299
themes.router.navigate( themes.router.baseUrl( '?search=' + value ), { replace: true } );
1303
themes.view.Installer = themes.view.Appearance.extend({
1305
el: '#wpbody-content .wrap',
1307
// Register events for sorting and filters in theme-navigation
1309
'click .filter-links li > a': 'onSort',
1310
'click .theme-filter': 'onFilter',
1311
'click .drawer-toggle': 'moreFilters',
1312
'click .filter-drawer .apply-filters': 'applyFilters',
1313
'click .filter-group [type="checkbox"]': 'addFilter',
1314
'click .filter-drawer .clear-filters': 'clearFilters',
1315
'click .filtered-by': 'backToFilters'
1318
// Initial render method
1319
render: function() {
1325
this.collection = new themes.Collection();
1327
// Bump `collection.currentQuery.page` and request more themes if we hit the end of the page.
1328
this.listenTo( this, 'theme:end', function() {
1330
// Make sure we are not already loading
1331
if ( self.collection.loadingThemes ) {
1335
// Set loadingThemes to true and bump page instance of currentQuery.
1336
self.collection.loadingThemes = true;
1337
self.collection.currentQuery.page++;
1339
// Use currentQuery.page to build the themes request.
1340
_.extend( self.collection.currentQuery.request, { page: self.collection.currentQuery.page } );
1341
self.collection.query( self.collection.currentQuery.request );
1344
this.listenTo( this.collection, 'query:success', function() {
1345
$( 'body' ).removeClass( 'loading-content' );
1346
$( '.theme-browser' ).find( 'div.error' ).remove();
1349
this.listenTo( this.collection, 'query:fail', function() {
1350
$( 'body' ).removeClass( 'loading-content' );
1351
$( '.theme-browser' ).find( 'div.error' ).remove();
1352
$( '.theme-browser' ).find( 'div.themes' ).before( '<div class="error"><p>' + l10n.error + '</p></div>' );
1359
// Set ups the view and passes the section argument
1360
this.view = new themes.view.Themes({
1361
collection: this.collection,
1365
// Reset pagination every time the install view handler is run
1368
// Render and append
1369
this.$el.find( '.themes' ).remove();
1371
this.$el.find( '.theme-browser' ).append( this.view.el ).addClass( 'rendered' );
1374
// Handles all the rendering of the public theme directory
1375
browse: function( section ) {
1376
// Create a new collection with the proper theme data
1378
this.collection.query( { browse: section } );
1381
// Sorting navigation
1382
onSort: function( event ) {
1383
var $el = $( event.target ),
1384
sort = $el.data( 'sort' );
1386
event.preventDefault();
1388
$( 'body' ).removeClass( 'filters-applied show-filters' );
1390
// Bail if this is already active
1391
if ( $el.hasClass( this.activeClass ) ) {
1397
// Trigger a router.naviagte update
1398
themes.router.navigate( themes.router.baseUrl( '?browse=' + sort ) );
1401
sort: function( sort ) {
1404
$( '.filter-links li > a, .theme-filter' ).removeClass( this.activeClass );
1405
$( '[data-sort="' + sort + '"]' ).addClass( this.activeClass );
1407
this.browse( sort );
1411
onFilter: function( event ) {
1413
$el = $( event.target ),
1414
filter = $el.data( 'filter' );
1416
// Bail if this is already active
1417
if ( $el.hasClass( this.activeClass ) ) {
1421
$( '.filter-links li > a, .theme-section' ).removeClass( this.activeClass );
1422
$el.addClass( this.activeClass );
1428
// Construct the filter request
1429
// using the default values
1430
filter = _.union( filter, this.filtersChecked() );
1431
request = { tag: [ filter ] };
1433
// Get the themes by sending Ajax POST request to api.wordpress.org/themes
1434
// or searching the local cache
1435
this.collection.query( request );
1438
// Clicking on a checkbox to add another filter to the request
1439
addFilter: function() {
1440
this.filtersChecked();
1443
// Applying filters triggers a tag request
1444
applyFilters: function( event ) {
1446
tags = this.filtersChecked(),
1447
request = { tag: tags },
1448
filteringBy = $( '.filtered-by .tags' );
1451
event.preventDefault();
1454
$( 'body' ).addClass( 'filters-applied' );
1455
$( '.filter-links li > a.current' ).removeClass( 'current' );
1456
filteringBy.empty();
1458
_.each( tags, function( tag ) {
1459
name = $( 'label[for="filter-id-' + tag + '"]' ).text();
1460
filteringBy.append( '<span class="tag">' + name + '</span>' );
1463
// Get the themes by sending Ajax POST request to api.wordpress.org/themes
1464
// or searching the local cache
1465
this.collection.query( request );
1468
// Get the checked filters
1469
// @return {array} of tags or false
1470
filtersChecked: function() {
1471
var items = $( '.filter-group' ).find( ':checkbox' ),
1474
_.each( items.filter( ':checked' ), function( item ) {
1475
tags.push( $( item ).prop( 'value' ) );
1478
// When no filters are checked, restore initial state and return
1479
if ( tags.length === 0 ) {
1480
$( '.filter-drawer .apply-filters' ).find( 'span' ).text( '' );
1481
$( '.filter-drawer .clear-filters' ).hide();
1482
$( 'body' ).removeClass( 'filters-applied' );
1486
$( '.filter-drawer .apply-filters' ).find( 'span' ).text( tags.length );
1487
$( '.filter-drawer .clear-filters' ).css( 'display', 'inline-block' );
1492
activeClass: 'current',
1494
// Overwrite search container class to append search
1496
searchContainer: $( '.wp-filter .search-form' ),
1498
uploader: function() {
1499
$( 'a.upload' ).on( 'click', function( event ) {
1500
event.preventDefault();
1501
$( 'body' ).addClass( 'show-upload-theme' );
1502
themes.router.navigate( themes.router.baseUrl( '?upload' ), { replace: true } );
1504
$( 'a.browse-themes' ).on( 'click', function( event ) {
1505
event.preventDefault();
1506
$( 'body' ).removeClass( 'show-upload-theme' );
1507
themes.router.navigate( themes.router.baseUrl( '' ), { replace: true } );
1511
// Toggle the full filters navigation
1512
moreFilters: function( event ) {
1513
event.preventDefault();
1515
if ( $( 'body' ).hasClass( 'filters-applied' ) ) {
1516
return this.backToFilters();
1519
// If the filters section is opened and filters are checked
1520
// run the relevant query collapsing to filtered-by state
1521
if ( $( 'body' ).hasClass( 'show-filters' ) && this.filtersChecked() ) {
1522
return this.addFilter();
1527
themes.router.navigate( themes.router.baseUrl( '' ) );
1528
$( 'body' ).toggleClass( 'show-filters' );
1531
// Clears all the checked filters
1532
// @uses filtersChecked()
1533
clearFilters: function( event ) {
1534
var items = $( '.filter-group' ).find( ':checkbox' ),
1537
event.preventDefault();
1539
_.each( items.filter( ':checked' ), function( item ) {
1540
$( item ).prop( 'checked', false );
1541
return self.filtersChecked();
1545
backToFilters: function( event ) {
1547
event.preventDefault();
1550
$( 'body' ).removeClass( 'filters-applied' );
1553
clearSearch: function() {
1554
$( '#wp-filter-search-input').val( '' );
1558
themes.InstallerRouter = Backbone.Router.extend({
1560
'theme-install.php?theme=:slug': 'preview',
1561
'theme-install.php?browse=:sort': 'sort',
1562
'theme-install.php?upload': 'upload',
1563
'theme-install.php?search=:query': 'search',
1564
'theme-install.php': 'sort'
1567
baseUrl: function( url ) {
1568
return 'theme-install.php' + url;
1571
search: function( query ) {
1572
$( '.wp-filter-search' ).val( query );
1575
navigate: function() {
1576
if ( Backbone.history._hasPushState ) {
1577
Backbone.Router.prototype.navigate.apply( this, arguments );
1583
themes.RunInstaller = {
1587
// Passes the default 'section' as an option
1588
this.view = new themes.view.Installer({
1589
section: 'featured',
1590
SearchView: themes.view.InstallerSearch
1598
render: function() {
1604
Backbone.history.start({
1605
root: themes.data.settings.adminUrl,
1611
routes: function() {
1615
// Bind to our global `wp.themes` object
1616
// so that the router is available to sub-views
1617
themes.router = new themes.InstallerRouter();
1619
// Handles `theme` route event
1620
// Queries the API for the passed theme slug
1621
themes.router.on( 'route:preview', function( slug ) {
1622
request.theme = slug;
1623
self.view.collection.query( request );
1626
// Handles sorting / browsing routes
1627
// Also handles the root URL triggering a sort request
1628
// for `featured`, the default view
1629
themes.router.on( 'route:sort', function( sort ) {
1633
self.view.sort( sort );
1634
self.view.trigger( 'theme:close' );
1637
// Support the `upload` route by going straight to upload section
1638
themes.router.on( 'route:upload', function() {
1639
$( 'a.upload' ).trigger( 'click' );
1642
// The `search` route event. The router populates the input field.
1643
themes.router.on( 'route:search', function() {
1644
$( '.wp-filter-search' ).focus().trigger( 'keyup' );
1650
extraRoutes: function() {
1656
$( document ).ready(function() {
1657
if ( themes.isInstall ) {
1658
themes.RunInstaller.init();
1666
// Align theme browser thickbox
1668
jQuery(document).ready( function($) {
1669
tb_position = function() {
1670
var tbWindow = $('#TB_window'),
1671
width = $(window).width(),
1672
H = $(window).height(),
1673
W = ( 1040 < width ) ? 1040 : width,
1674
adminbar_height = 0;
1676
if ( $('#wpadminbar').length ) {
1677
adminbar_height = parseInt( $('#wpadminbar').css('height'), 10 );
1680
if ( tbWindow.size() ) {
1681
tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
1682
$('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
1683
tbWindow.css({'margin-left': '-' + parseInt( ( ( W - 50 ) / 2 ), 10 ) + 'px'});
1684
if ( typeof document.body.style.maxWidth !== 'undefined' ) {
1685
tbWindow.css({'top': 20 + adminbar_height + 'px', 'margin-top': '0'});
1690
$(window).resize(function(){ tb_position(); });