/wp-admin/js/theme.js

https://gitlab.com/ReneMC/Custom-wordpress-theme · JavaScript · 1811 lines · 1100 code · 376 blank · 335 comment · 136 complexity · 4435548198f28946ced9fedefd78d486 MD5 · raw file

  1. /* global _wpThemeSettings, confirm */
  2. window.wp = window.wp || {};
  3. ( function($) {
  4. // Set up our namespace...
  5. var themes, l10n;
  6. themes = wp.themes = wp.themes || {};
  7. // Store the theme data and settings for organized and quick access
  8. // themes.data.settings, themes.data.themes, themes.data.l10n
  9. themes.data = _wpThemeSettings;
  10. l10n = themes.data.l10n;
  11. // Shortcut for isInstall check
  12. themes.isInstall = !! themes.data.settings.isInstall;
  13. // Setup app structure
  14. _.extend( themes, { model: {}, view: {}, routes: {}, router: {}, template: wp.template });
  15. themes.Model = Backbone.Model.extend({
  16. // Adds attributes to the default data coming through the .org themes api
  17. // Map `id` to `slug` for shared code
  18. initialize: function() {
  19. var description;
  20. // If theme is already installed, set an attribute.
  21. if ( _.indexOf( themes.data.installedThemes, this.get( 'slug' ) ) !== -1 ) {
  22. this.set({ installed: true });
  23. }
  24. // Set the attributes
  25. this.set({
  26. // slug is for installation, id is for existing.
  27. id: this.get( 'slug' ) || this.get( 'id' )
  28. });
  29. // Map `section.description` to `description`
  30. // as the API sometimes returns it differently
  31. if ( this.has( 'sections' ) ) {
  32. description = this.get( 'sections' ).description;
  33. this.set({ description: description });
  34. }
  35. }
  36. });
  37. // Main view controller for themes.php
  38. // Unifies and renders all available views
  39. themes.view.Appearance = wp.Backbone.View.extend({
  40. el: '#wpbody-content .wrap .theme-browser',
  41. window: $( window ),
  42. // Pagination instance
  43. page: 0,
  44. // Sets up a throttler for binding to 'scroll'
  45. initialize: function( options ) {
  46. // Scroller checks how far the scroll position is
  47. _.bindAll( this, 'scroller' );
  48. this.SearchView = options.SearchView ? options.SearchView : themes.view.Search;
  49. // Bind to the scroll event and throttle
  50. // the results from this.scroller
  51. this.window.bind( 'scroll', _.throttle( this.scroller, 300 ) );
  52. },
  53. // Main render control
  54. render: function() {
  55. // Setup the main theme view
  56. // with the current theme collection
  57. this.view = new themes.view.Themes({
  58. collection: this.collection,
  59. parent: this
  60. });
  61. // Render search form.
  62. this.search();
  63. // Render and append
  64. this.view.render();
  65. this.$el.empty().append( this.view.el ).addClass( 'rendered' );
  66. },
  67. // Defines search element container
  68. searchContainer: $( '#wpbody h1:first' ),
  69. // Search input and view
  70. // for current theme collection
  71. search: function() {
  72. var view,
  73. self = this;
  74. // Don't render the search if there is only one theme
  75. if ( themes.data.themes.length === 1 ) {
  76. return;
  77. }
  78. view = new this.SearchView({
  79. collection: self.collection,
  80. parent: this
  81. });
  82. // Render and append after screen title
  83. view.render();
  84. this.searchContainer
  85. .append( $.parseHTML( '<label class="screen-reader-text" for="wp-filter-search-input">' + l10n.search + '</label>' ) )
  86. .append( view.el );
  87. },
  88. // Checks when the user gets close to the bottom
  89. // of the mage and triggers a theme:scroll event
  90. scroller: function() {
  91. var self = this,
  92. bottom, threshold;
  93. bottom = this.window.scrollTop() + self.window.height();
  94. threshold = self.$el.offset().top + self.$el.outerHeight( false ) - self.window.height();
  95. threshold = Math.round( threshold * 0.9 );
  96. if ( bottom > threshold ) {
  97. this.trigger( 'theme:scroll' );
  98. }
  99. }
  100. });
  101. // Set up the Collection for our theme data
  102. // @has 'id' 'name' 'screenshot' 'author' 'authorURI' 'version' 'active' ...
  103. themes.Collection = Backbone.Collection.extend({
  104. model: themes.Model,
  105. // Search terms
  106. terms: '',
  107. // Controls searching on the current theme collection
  108. // and triggers an update event
  109. doSearch: function( value ) {
  110. // Don't do anything if we've already done this search
  111. // Useful because the Search handler fires multiple times per keystroke
  112. if ( this.terms === value ) {
  113. return;
  114. }
  115. // Updates terms with the value passed
  116. this.terms = value;
  117. // If we have terms, run a search...
  118. if ( this.terms.length > 0 ) {
  119. this.search( this.terms );
  120. }
  121. // If search is blank, show all themes
  122. // Useful for resetting the views when you clean the input
  123. if ( this.terms === '' ) {
  124. this.reset( themes.data.themes );
  125. $( 'body' ).removeClass( 'no-results' );
  126. }
  127. // Trigger a 'themes:update' event
  128. this.trigger( 'themes:update' );
  129. },
  130. // Performs a search within the collection
  131. // @uses RegExp
  132. search: function( term ) {
  133. var match, results, haystack, name, description, author;
  134. // Start with a full collection
  135. this.reset( themes.data.themes, { silent: true } );
  136. // Escape the term string for RegExp meta characters
  137. term = term.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' );
  138. // Consider spaces as word delimiters and match the whole string
  139. // so matching terms can be combined
  140. term = term.replace( / /g, ')(?=.*' );
  141. match = new RegExp( '^(?=.*' + term + ').+', 'i' );
  142. // Find results
  143. // _.filter and .test
  144. results = this.filter( function( data ) {
  145. name = data.get( 'name' ).replace( /(<([^>]+)>)/ig, '' );
  146. description = data.get( 'description' ).replace( /(<([^>]+)>)/ig, '' );
  147. author = data.get( 'author' ).replace( /(<([^>]+)>)/ig, '' );
  148. haystack = _.union( [ name, data.get( 'id' ), description, author, data.get( 'tags' ) ] );
  149. if ( match.test( data.get( 'author' ) ) && term.length > 2 ) {
  150. data.set( 'displayAuthor', true );
  151. }
  152. return match.test( haystack );
  153. });
  154. if ( results.length === 0 ) {
  155. this.trigger( 'query:empty' );
  156. } else {
  157. $( 'body' ).removeClass( 'no-results' );
  158. }
  159. this.reset( results );
  160. },
  161. // Paginates the collection with a helper method
  162. // that slices the collection
  163. paginate: function( instance ) {
  164. var collection = this;
  165. instance = instance || 0;
  166. // Themes per instance are set at 20
  167. collection = _( collection.rest( 20 * instance ) );
  168. collection = _( collection.first( 20 ) );
  169. return collection;
  170. },
  171. count: false,
  172. // Handles requests for more themes
  173. // and caches results
  174. //
  175. // When we are missing a cache object we fire an apiCall()
  176. // which triggers events of `query:success` or `query:fail`
  177. query: function( request ) {
  178. /**
  179. * @static
  180. * @type Array
  181. */
  182. var queries = this.queries,
  183. self = this,
  184. query, isPaginated, count;
  185. // Store current query request args
  186. // for later use with the event `theme:end`
  187. this.currentQuery.request = request;
  188. // Search the query cache for matches.
  189. query = _.find( queries, function( query ) {
  190. return _.isEqual( query.request, request );
  191. });
  192. // If the request matches the stored currentQuery.request
  193. // it means we have a paginated request.
  194. isPaginated = _.has( request, 'page' );
  195. // Reset the internal api page counter for non paginated queries.
  196. if ( ! isPaginated ) {
  197. this.currentQuery.page = 1;
  198. }
  199. // Otherwise, send a new API call and add it to the cache.
  200. if ( ! query && ! isPaginated ) {
  201. query = this.apiCall( request ).done( function( data ) {
  202. // Update the collection with the queried data.
  203. if ( data.themes ) {
  204. self.reset( data.themes );
  205. count = data.info.results;
  206. // Store the results and the query request
  207. queries.push( { themes: data.themes, request: request, total: count } );
  208. }
  209. // Trigger a collection refresh event
  210. // and a `query:success` event with a `count` argument.
  211. self.trigger( 'themes:update' );
  212. self.trigger( 'query:success', count );
  213. if ( data.themes && data.themes.length === 0 ) {
  214. self.trigger( 'query:empty' );
  215. }
  216. }).fail( function() {
  217. self.trigger( 'query:fail' );
  218. });
  219. } else {
  220. // If it's a paginated request we need to fetch more themes...
  221. if ( isPaginated ) {
  222. return this.apiCall( request, isPaginated ).done( function( data ) {
  223. // Add the new themes to the current collection
  224. // @todo update counter
  225. self.add( data.themes );
  226. self.trigger( 'query:success' );
  227. // We are done loading themes for now.
  228. self.loadingThemes = false;
  229. }).fail( function() {
  230. self.trigger( 'query:fail' );
  231. });
  232. }
  233. if ( query.themes.length === 0 ) {
  234. self.trigger( 'query:empty' );
  235. } else {
  236. $( 'body' ).removeClass( 'no-results' );
  237. }
  238. // Only trigger an update event since we already have the themes
  239. // on our cached object
  240. if ( _.isNumber( query.total ) ) {
  241. this.count = query.total;
  242. }
  243. this.reset( query.themes );
  244. if ( ! query.total ) {
  245. this.count = this.length;
  246. }
  247. this.trigger( 'themes:update' );
  248. this.trigger( 'query:success', this.count );
  249. }
  250. },
  251. // Local cache array for API queries
  252. queries: [],
  253. // Keep track of current query so we can handle pagination
  254. currentQuery: {
  255. page: 1,
  256. request: {}
  257. },
  258. // Send request to api.wordpress.org/themes
  259. apiCall: function( request, paginated ) {
  260. return wp.ajax.send( 'query-themes', {
  261. data: {
  262. // Request data
  263. request: _.extend({
  264. per_page: 100,
  265. fields: {
  266. description: true,
  267. tested: true,
  268. requires: true,
  269. rating: true,
  270. downloaded: true,
  271. downloadLink: true,
  272. last_updated: true,
  273. homepage: true,
  274. num_ratings: true
  275. }
  276. }, request)
  277. },
  278. beforeSend: function() {
  279. if ( ! paginated ) {
  280. // Spin it
  281. $( 'body' ).addClass( 'loading-content' ).removeClass( 'no-results' );
  282. }
  283. }
  284. });
  285. },
  286. // Static status controller for when we are loading themes.
  287. loadingThemes: false
  288. });
  289. // This is the view that controls each theme item
  290. // that will be displayed on the screen
  291. themes.view.Theme = wp.Backbone.View.extend({
  292. // Wrap theme data on a div.theme element
  293. className: 'theme',
  294. // Reflects which theme view we have
  295. // 'grid' (default) or 'detail'
  296. state: 'grid',
  297. // The HTML template for each element to be rendered
  298. html: themes.template( 'theme' ),
  299. events: {
  300. 'click': themes.isInstall ? 'preview': 'expand',
  301. 'keydown': themes.isInstall ? 'preview': 'expand',
  302. 'touchend': themes.isInstall ? 'preview': 'expand',
  303. 'keyup': 'addFocus',
  304. 'touchmove': 'preventExpand'
  305. },
  306. touchDrag: false,
  307. render: function() {
  308. var data = this.model.toJSON();
  309. // Render themes using the html template
  310. this.$el.html( this.html( data ) ).attr({
  311. tabindex: 0,
  312. 'aria-describedby' : data.id + '-action ' + data.id + '-name'
  313. });
  314. // Renders active theme styles
  315. this.activeTheme();
  316. if ( this.model.get( 'displayAuthor' ) ) {
  317. this.$el.addClass( 'display-author' );
  318. }
  319. if ( this.model.get( 'installed' ) ) {
  320. this.$el.addClass( 'is-installed' );
  321. }
  322. },
  323. // Adds a class to the currently active theme
  324. // and to the overlay in detailed view mode
  325. activeTheme: function() {
  326. if ( this.model.get( 'active' ) ) {
  327. this.$el.addClass( 'active' );
  328. }
  329. },
  330. // Add class of focus to the theme we are focused on.
  331. addFocus: function() {
  332. var $themeToFocus = ( $( ':focus' ).hasClass( 'theme' ) ) ? $( ':focus' ) : $(':focus').parents('.theme');
  333. $('.theme.focus').removeClass('focus');
  334. $themeToFocus.addClass('focus');
  335. },
  336. // Single theme overlay screen
  337. // It's shown when clicking a theme
  338. expand: function( event ) {
  339. var self = this;
  340. event = event || window.event;
  341. // 'enter' and 'space' keys expand the details view when a theme is :focused
  342. if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
  343. return;
  344. }
  345. // Bail if the user scrolled on a touch device
  346. if ( this.touchDrag === true ) {
  347. return this.touchDrag = false;
  348. }
  349. // Prevent the modal from showing when the user clicks
  350. // one of the direct action buttons
  351. if ( $( event.target ).is( '.theme-actions a' ) ) {
  352. return;
  353. }
  354. // Set focused theme to current element
  355. themes.focusedTheme = this.$el;
  356. this.trigger( 'theme:expand', self.model.cid );
  357. },
  358. preventExpand: function() {
  359. this.touchDrag = true;
  360. },
  361. preview: function( event ) {
  362. var self = this,
  363. current, preview;
  364. event = event || window.event;
  365. // Bail if the user scrolled on a touch device
  366. if ( this.touchDrag === true ) {
  367. return this.touchDrag = false;
  368. }
  369. // Allow direct link path to installing a theme.
  370. if ( $( event.target ).hasClass( 'button-primary' ) ) {
  371. return;
  372. }
  373. // 'enter' and 'space' keys expand the details view when a theme is :focused
  374. if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
  375. return;
  376. }
  377. // pressing enter while focused on the buttons shouldn't open the preview
  378. if ( event.type === 'keydown' && event.which !== 13 && $( ':focus' ).hasClass( 'button' ) ) {
  379. return;
  380. }
  381. event.preventDefault();
  382. event = event || window.event;
  383. // Set focus to current theme.
  384. themes.focusedTheme = this.$el;
  385. // Construct a new Preview view.
  386. preview = new themes.view.Preview({
  387. model: this.model
  388. });
  389. // Render the view and append it.
  390. preview.render();
  391. this.setNavButtonsState();
  392. // Hide previous/next navigation if there is only one theme
  393. if ( this.model.collection.length === 1 ) {
  394. preview.$el.addClass( 'no-navigation' );
  395. } else {
  396. preview.$el.removeClass( 'no-navigation' );
  397. }
  398. // Append preview
  399. $( 'div.wrap' ).append( preview.el );
  400. // Listen to our preview object
  401. // for `theme:next` and `theme:previous` events.
  402. this.listenTo( preview, 'theme:next', function() {
  403. // Keep local track of current theme model.
  404. current = self.model;
  405. // If we have ventured away from current model update the current model position.
  406. if ( ! _.isUndefined( self.current ) ) {
  407. current = self.current;
  408. }
  409. // Get next theme model.
  410. self.current = self.model.collection.at( self.model.collection.indexOf( current ) + 1 );
  411. // If we have no more themes, bail.
  412. if ( _.isUndefined( self.current ) ) {
  413. self.options.parent.parent.trigger( 'theme:end' );
  414. return self.current = current;
  415. }
  416. preview.model = self.current;
  417. // Render and append.
  418. preview.render();
  419. this.setNavButtonsState();
  420. $( '.next-theme' ).focus();
  421. })
  422. .listenTo( preview, 'theme:previous', function() {
  423. // Keep track of current theme model.
  424. current = self.model;
  425. // Bail early if we are at the beginning of the collection
  426. if ( self.model.collection.indexOf( self.current ) === 0 ) {
  427. return;
  428. }
  429. // If we have ventured away from current model update the current model position.
  430. if ( ! _.isUndefined( self.current ) ) {
  431. current = self.current;
  432. }
  433. // Get previous theme model.
  434. self.current = self.model.collection.at( self.model.collection.indexOf( current ) - 1 );
  435. // If we have no more themes, bail.
  436. if ( _.isUndefined( self.current ) ) {
  437. return;
  438. }
  439. preview.model = self.current;
  440. // Render and append.
  441. preview.render();
  442. this.setNavButtonsState();
  443. $( '.previous-theme' ).focus();
  444. });
  445. this.listenTo( preview, 'preview:close', function() {
  446. self.current = self.model;
  447. });
  448. },
  449. // Handles .disabled classes for previous/next buttons in theme installer preview
  450. setNavButtonsState: function() {
  451. var $themeInstaller = $( '.theme-install-overlay' ),
  452. current = _.isUndefined( this.current ) ? this.model : this.current;
  453. // Disable previous at the zero position
  454. if ( 0 === this.model.collection.indexOf( current ) ) {
  455. $themeInstaller.find( '.previous-theme' ).addClass( 'disabled' );
  456. }
  457. // Disable next if the next model is undefined
  458. if ( _.isUndefined( this.model.collection.at( this.model.collection.indexOf( current ) + 1 ) ) ) {
  459. $themeInstaller.find( '.next-theme' ).addClass( 'disabled' );
  460. }
  461. }
  462. });
  463. // Theme Details view
  464. // Set ups a modal overlay with the expanded theme data
  465. themes.view.Details = wp.Backbone.View.extend({
  466. // Wrap theme data on a div.theme element
  467. className: 'theme-overlay',
  468. events: {
  469. 'click': 'collapse',
  470. 'click .delete-theme': 'deleteTheme',
  471. 'click .left': 'previousTheme',
  472. 'click .right': 'nextTheme'
  473. },
  474. // The HTML template for the theme overlay
  475. html: themes.template( 'theme-single' ),
  476. render: function() {
  477. var data = this.model.toJSON();
  478. this.$el.html( this.html( data ) );
  479. // Renders active theme styles
  480. this.activeTheme();
  481. // Set up navigation events
  482. this.navigation();
  483. // Checks screenshot size
  484. this.screenshotCheck( this.$el );
  485. // Contain "tabbing" inside the overlay
  486. this.containFocus( this.$el );
  487. },
  488. // Adds a class to the currently active theme
  489. // and to the overlay in detailed view mode
  490. activeTheme: function() {
  491. // Check the model has the active property
  492. this.$el.toggleClass( 'active', this.model.get( 'active' ) );
  493. },
  494. // Keeps :focus within the theme details elements
  495. containFocus: function( $el ) {
  496. var $target;
  497. // Move focus to the primary action
  498. _.delay( function() {
  499. $( '.theme-wrap a.button-primary:visible' ).focus();
  500. }, 500 );
  501. $el.on( 'keydown.wp-themes', function( event ) {
  502. // Tab key
  503. if ( event.which === 9 ) {
  504. $target = $( event.target );
  505. // Keep focus within the overlay by making the last link on theme actions
  506. // switch focus to button.left on tabbing and vice versa
  507. if ( $target.is( 'button.left' ) && event.shiftKey ) {
  508. $el.find( '.theme-actions a:last-child' ).focus();
  509. event.preventDefault();
  510. } else if ( $target.is( '.theme-actions a:last-child' ) ) {
  511. $el.find( 'button.left' ).focus();
  512. event.preventDefault();
  513. }
  514. }
  515. });
  516. },
  517. // Single theme overlay screen
  518. // It's shown when clicking a theme
  519. collapse: function( event ) {
  520. var self = this,
  521. scroll;
  522. event = event || window.event;
  523. // Prevent collapsing detailed view when there is only one theme available
  524. if ( themes.data.themes.length === 1 ) {
  525. return;
  526. }
  527. // Detect if the click is inside the overlay
  528. // and don't close it unless the target was
  529. // the div.back button
  530. if ( $( event.target ).is( '.theme-backdrop' ) || $( event.target ).is( '.close' ) || event.keyCode === 27 ) {
  531. // Add a temporary closing class while overlay fades out
  532. $( 'body' ).addClass( 'closing-overlay' );
  533. // With a quick fade out animation
  534. this.$el.fadeOut( 130, function() {
  535. // Clicking outside the modal box closes the overlay
  536. $( 'body' ).removeClass( 'closing-overlay' );
  537. // Handle event cleanup
  538. self.closeOverlay();
  539. // Get scroll position to avoid jumping to the top
  540. scroll = document.body.scrollTop;
  541. // Clean the url structure
  542. themes.router.navigate( themes.router.baseUrl( '' ) );
  543. // Restore scroll position
  544. document.body.scrollTop = scroll;
  545. // Return focus to the theme div
  546. if ( themes.focusedTheme ) {
  547. themes.focusedTheme.focus();
  548. }
  549. });
  550. }
  551. },
  552. // Handles .disabled classes for next/previous buttons
  553. navigation: function() {
  554. // Disable Left/Right when at the start or end of the collection
  555. if ( this.model.cid === this.model.collection.at(0).cid ) {
  556. this.$el.find( '.left' ).addClass( 'disabled' );
  557. }
  558. if ( this.model.cid === this.model.collection.at( this.model.collection.length - 1 ).cid ) {
  559. this.$el.find( '.right' ).addClass( 'disabled' );
  560. }
  561. },
  562. // Performs the actions to effectively close
  563. // the theme details overlay
  564. closeOverlay: function() {
  565. $( 'body' ).removeClass( 'modal-open' );
  566. this.remove();
  567. this.unbind();
  568. this.trigger( 'theme:collapse' );
  569. },
  570. // Confirmation dialog for deleting a theme
  571. deleteTheme: function() {
  572. return confirm( themes.data.settings.confirmDelete );
  573. },
  574. nextTheme: function() {
  575. var self = this;
  576. self.trigger( 'theme:next', self.model.cid );
  577. return false;
  578. },
  579. previousTheme: function() {
  580. var self = this;
  581. self.trigger( 'theme:previous', self.model.cid );
  582. return false;
  583. },
  584. // Checks if the theme screenshot is the old 300px width version
  585. // and adds a corresponding class if it's true
  586. screenshotCheck: function( el ) {
  587. var screenshot, image;
  588. screenshot = el.find( '.screenshot img' );
  589. image = new Image();
  590. image.src = screenshot.attr( 'src' );
  591. // Width check
  592. if ( image.width && image.width <= 300 ) {
  593. el.addClass( 'small-screenshot' );
  594. }
  595. }
  596. });
  597. // Theme Preview view
  598. // Set ups a modal overlay with the expanded theme data
  599. themes.view.Preview = themes.view.Details.extend({
  600. className: 'wp-full-overlay expanded',
  601. el: '.theme-install-overlay',
  602. events: {
  603. 'click .close-full-overlay': 'close',
  604. 'click .collapse-sidebar': 'collapse',
  605. 'click .devices button': 'previewDevice',
  606. 'click .previous-theme': 'previousTheme',
  607. 'click .next-theme': 'nextTheme',
  608. 'keyup': 'keyEvent'
  609. },
  610. // The HTML template for the theme preview
  611. html: themes.template( 'theme-preview' ),
  612. render: function() {
  613. var self = this, currentPreviewDevice,
  614. data = this.model.toJSON();
  615. this.$el.removeClass( 'iframe-ready' ).html( this.html( data ) );
  616. currentPreviewDevice = this.$el.data( 'current-preview-device' );
  617. if ( currentPreviewDevice ) {
  618. self.tooglePreviewDeviceButtons( currentPreviewDevice );
  619. }
  620. themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.get( 'id' ) ), { replace: true } );
  621. this.$el.fadeIn( 200, function() {
  622. $( 'body' ).addClass( 'theme-installer-active full-overlay-active' );
  623. $( '.close-full-overlay' ).focus();
  624. });
  625. this.$el.find( 'iframe' ).one( 'load', function() {
  626. self.iframeLoaded();
  627. });
  628. },
  629. iframeLoaded: function() {
  630. this.$el.addClass( 'iframe-ready' );
  631. },
  632. close: function() {
  633. this.$el.fadeOut( 200, function() {
  634. $( 'body' ).removeClass( 'theme-installer-active full-overlay-active' );
  635. // Return focus to the theme div
  636. if ( themes.focusedTheme ) {
  637. themes.focusedTheme.focus();
  638. }
  639. }).removeClass( 'iframe-ready' );
  640. themes.router.navigate( themes.router.baseUrl( '' ) );
  641. this.trigger( 'preview:close' );
  642. this.undelegateEvents();
  643. this.unbind();
  644. return false;
  645. },
  646. collapse: function( event ) {
  647. var $button = $( event.currentTarget );
  648. if ( 'true' === $button.attr( 'aria-expanded' ) ) {
  649. $button.attr({ 'aria-expanded': 'false', 'aria-label': l10n.expandSidebar });
  650. } else {
  651. $button.attr({ 'aria-expanded': 'true', 'aria-label': l10n.collapseSidebar });
  652. }
  653. this.$el.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
  654. return false;
  655. },
  656. previewDevice: function( event ) {
  657. var device = $( event.currentTarget ).data( 'device' );
  658. this.$el
  659. .removeClass( 'preview-desktop preview-tablet preview-mobile' )
  660. .addClass( 'preview-' + device )
  661. .data( 'current-preview-device', device );
  662. this.tooglePreviewDeviceButtons( device );
  663. },
  664. tooglePreviewDeviceButtons: function( newDevice ) {
  665. var $devices = $( '.wp-full-overlay-footer .devices' );
  666. $devices.find( 'button' )
  667. .removeClass( 'active' )
  668. .attr( 'aria-pressed', false );
  669. $devices.find( 'button.preview-' + newDevice )
  670. .addClass( 'active' )
  671. .attr( 'aria-pressed', true );
  672. },
  673. keyEvent: function( event ) {
  674. // The escape key closes the preview
  675. if ( event.keyCode === 27 ) {
  676. this.undelegateEvents();
  677. this.close();
  678. }
  679. // The right arrow key, next theme
  680. if ( event.keyCode === 39 ) {
  681. _.once( this.nextTheme() );
  682. }
  683. // The left arrow key, previous theme
  684. if ( event.keyCode === 37 ) {
  685. this.previousTheme();
  686. }
  687. }
  688. });
  689. // Controls the rendering of div.themes,
  690. // a wrapper that will hold all the theme elements
  691. themes.view.Themes = wp.Backbone.View.extend({
  692. className: 'themes wp-clearfix',
  693. $overlay: $( 'div.theme-overlay' ),
  694. // Number to keep track of scroll position
  695. // while in theme-overlay mode
  696. index: 0,
  697. // The theme count element
  698. count: $( '.wrap .theme-count' ),
  699. // The live themes count
  700. liveThemeCount: 0,
  701. initialize: function( options ) {
  702. var self = this;
  703. // Set up parent
  704. this.parent = options.parent;
  705. // Set current view to [grid]
  706. this.setView( 'grid' );
  707. // Move the active theme to the beginning of the collection
  708. self.currentTheme();
  709. // When the collection is updated by user input...
  710. this.listenTo( self.collection, 'themes:update', function() {
  711. self.parent.page = 0;
  712. self.currentTheme();
  713. self.render( this );
  714. } );
  715. // Update theme count to full result set when available.
  716. this.listenTo( self.collection, 'query:success', function( count ) {
  717. if ( _.isNumber( count ) ) {
  718. self.count.text( count );
  719. self.announceSearchResults( count );
  720. } else {
  721. self.count.text( self.collection.length );
  722. self.announceSearchResults( self.collection.length );
  723. }
  724. });
  725. this.listenTo( self.collection, 'query:empty', function() {
  726. $( 'body' ).addClass( 'no-results' );
  727. });
  728. this.listenTo( this.parent, 'theme:scroll', function() {
  729. self.renderThemes( self.parent.page );
  730. });
  731. this.listenTo( this.parent, 'theme:close', function() {
  732. if ( self.overlay ) {
  733. self.overlay.closeOverlay();
  734. }
  735. } );
  736. // Bind keyboard events.
  737. $( 'body' ).on( 'keyup', function( event ) {
  738. if ( ! self.overlay ) {
  739. return;
  740. }
  741. // Pressing the right arrow key fires a theme:next event
  742. if ( event.keyCode === 39 ) {
  743. self.overlay.nextTheme();
  744. }
  745. // Pressing the left arrow key fires a theme:previous event
  746. if ( event.keyCode === 37 ) {
  747. self.overlay.previousTheme();
  748. }
  749. // Pressing the escape key fires a theme:collapse event
  750. if ( event.keyCode === 27 ) {
  751. self.overlay.collapse( event );
  752. }
  753. });
  754. },
  755. // Manages rendering of theme pages
  756. // and keeping theme count in sync
  757. render: function() {
  758. // Clear the DOM, please
  759. this.$el.empty();
  760. // If the user doesn't have switch capabilities
  761. // or there is only one theme in the collection
  762. // render the detailed view of the active theme
  763. if ( themes.data.themes.length === 1 ) {
  764. // Constructs the view
  765. this.singleTheme = new themes.view.Details({
  766. model: this.collection.models[0]
  767. });
  768. // Render and apply a 'single-theme' class to our container
  769. this.singleTheme.render();
  770. this.$el.addClass( 'single-theme' );
  771. this.$el.append( this.singleTheme.el );
  772. }
  773. // Generate the themes
  774. // Using page instance
  775. // While checking the collection has items
  776. if ( this.options.collection.size() > 0 ) {
  777. this.renderThemes( this.parent.page );
  778. }
  779. // Display a live theme count for the collection
  780. this.liveThemeCount = this.collection.count ? this.collection.count : this.collection.length;
  781. this.count.text( this.liveThemeCount );
  782. this.announceSearchResults( this.liveThemeCount );
  783. },
  784. // Iterates through each instance of the collection
  785. // and renders each theme module
  786. renderThemes: function( page ) {
  787. var self = this;
  788. self.instance = self.collection.paginate( page );
  789. // If we have no more themes bail
  790. if ( self.instance.size() === 0 ) {
  791. // Fire a no-more-themes event.
  792. this.parent.trigger( 'theme:end' );
  793. return;
  794. }
  795. // Make sure the add-new stays at the end
  796. if ( ! themes.isInstall && page >= 1 ) {
  797. $( '.add-new-theme' ).remove();
  798. }
  799. // Loop through the themes and setup each theme view
  800. self.instance.each( function( theme ) {
  801. self.theme = new themes.view.Theme({
  802. model: theme,
  803. parent: self
  804. });
  805. // Render the views...
  806. self.theme.render();
  807. // and append them to div.themes
  808. self.$el.append( self.theme.el );
  809. // Binds to theme:expand to show the modal box
  810. // with the theme details
  811. self.listenTo( self.theme, 'theme:expand', self.expand, self );
  812. });
  813. // 'Add new theme' element shown at the end of the grid
  814. if ( ! themes.isInstall && themes.data.settings.canInstall ) {
  815. this.$el.append( '<div class="theme add-new-theme"><a href="' + themes.data.settings.installURI + '"><div class="theme-screenshot"><span></span></div><h2 class="theme-name">' + l10n.addNew + '</h2></a></div>' );
  816. }
  817. this.parent.page++;
  818. },
  819. // Grabs current theme and puts it at the beginning of the collection
  820. currentTheme: function() {
  821. var self = this,
  822. current;
  823. current = self.collection.findWhere({ active: true });
  824. // Move the active theme to the beginning of the collection
  825. if ( current ) {
  826. self.collection.remove( current );
  827. self.collection.add( current, { at:0 } );
  828. }
  829. },
  830. // Sets current view
  831. setView: function( view ) {
  832. return view;
  833. },
  834. // Renders the overlay with the ThemeDetails view
  835. // Uses the current model data
  836. expand: function( id ) {
  837. var self = this;
  838. // Set the current theme model
  839. this.model = self.collection.get( id );
  840. // Trigger a route update for the current model
  841. themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.id ) );
  842. // Sets this.view to 'detail'
  843. this.setView( 'detail' );
  844. $( 'body' ).addClass( 'modal-open' );
  845. // Set up the theme details view
  846. this.overlay = new themes.view.Details({
  847. model: self.model
  848. });
  849. this.overlay.render();
  850. this.$overlay.html( this.overlay.el );
  851. // Bind to theme:next and theme:previous
  852. // triggered by the arrow keys
  853. //
  854. // Keep track of the current model so we
  855. // can infer an index position
  856. this.listenTo( this.overlay, 'theme:next', function() {
  857. // Renders the next theme on the overlay
  858. self.next( [ self.model.cid ] );
  859. })
  860. .listenTo( this.overlay, 'theme:previous', function() {
  861. // Renders the previous theme on the overlay
  862. self.previous( [ self.model.cid ] );
  863. });
  864. },
  865. // This method renders the next theme on the overlay modal
  866. // based on the current position in the collection
  867. // @params [model cid]
  868. next: function( args ) {
  869. var self = this,
  870. model, nextModel;
  871. // Get the current theme
  872. model = self.collection.get( args[0] );
  873. // Find the next model within the collection
  874. nextModel = self.collection.at( self.collection.indexOf( model ) + 1 );
  875. // Sanity check which also serves as a boundary test
  876. if ( nextModel !== undefined ) {
  877. // We have a new theme...
  878. // Close the overlay
  879. this.overlay.closeOverlay();
  880. // Trigger a route update for the current model
  881. self.theme.trigger( 'theme:expand', nextModel.cid );
  882. }
  883. },
  884. // This method renders the previous theme on the overlay modal
  885. // based on the current position in the collection
  886. // @params [model cid]
  887. previous: function( args ) {
  888. var self = this,
  889. model, previousModel;
  890. // Get the current theme
  891. model = self.collection.get( args[0] );
  892. // Find the previous model within the collection
  893. previousModel = self.collection.at( self.collection.indexOf( model ) - 1 );
  894. if ( previousModel !== undefined ) {
  895. // We have a new theme...
  896. // Close the overlay
  897. this.overlay.closeOverlay();
  898. // Trigger a route update for the current model
  899. self.theme.trigger( 'theme:expand', previousModel.cid );
  900. }
  901. },
  902. // Dispatch audible search results feedback message
  903. announceSearchResults: function( count ) {
  904. if ( 0 === count ) {
  905. wp.a11y.speak( l10n.noThemesFound );
  906. } else {
  907. wp.a11y.speak( l10n.themesFound.replace( '%d', count ) );
  908. }
  909. }
  910. });
  911. // Search input view controller.
  912. themes.view.Search = wp.Backbone.View.extend({
  913. tagName: 'input',
  914. className: 'wp-filter-search',
  915. id: 'wp-filter-search-input',
  916. searching: false,
  917. attributes: {
  918. placeholder: l10n.searchPlaceholder,
  919. type: 'search',
  920. 'aria-describedby': 'live-search-desc'
  921. },
  922. events: {
  923. 'input': 'search',
  924. 'keyup': 'search',
  925. 'blur': 'pushState'
  926. },
  927. initialize: function( options ) {
  928. this.parent = options.parent;
  929. this.listenTo( this.parent, 'theme:close', function() {
  930. this.searching = false;
  931. } );
  932. },
  933. search: function( event ) {
  934. // Clear on escape.
  935. if ( event.type === 'keyup' && event.which === 27 ) {
  936. event.target.value = '';
  937. }
  938. /**
  939. * Since doSearch is debounced, it will only run when user input comes to a rest
  940. */
  941. this.doSearch( event );
  942. },
  943. // Runs a search on the theme collection.
  944. doSearch: _.debounce( function( event ) {
  945. var options = {};
  946. this.collection.doSearch( event.target.value );
  947. // if search is initiated and key is not return
  948. if ( this.searching && event.which !== 13 ) {
  949. options.replace = true;
  950. } else {
  951. this.searching = true;
  952. }
  953. // Update the URL hash
  954. if ( event.target.value ) {
  955. themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + event.target.value ), options );
  956. } else {
  957. themes.router.navigate( themes.router.baseUrl( '' ) );
  958. }
  959. }, 500 ),
  960. pushState: function( event ) {
  961. var url = themes.router.baseUrl( '' );
  962. if ( event.target.value ) {
  963. url = themes.router.baseUrl( themes.router.searchPath + event.target.value );
  964. }
  965. this.searching = false;
  966. themes.router.navigate( url );
  967. }
  968. });
  969. // Sets up the routes events for relevant url queries
  970. // Listens to [theme] and [search] params
  971. themes.Router = Backbone.Router.extend({
  972. routes: {
  973. 'themes.php?theme=:slug': 'theme',
  974. 'themes.php?search=:query': 'search',
  975. 'themes.php?s=:query': 'search',
  976. 'themes.php': 'themes',
  977. '': 'themes'
  978. },
  979. baseUrl: function( url ) {
  980. return 'themes.php' + url;
  981. },
  982. themePath: '?theme=',
  983. searchPath: '?search=',
  984. search: function( query ) {
  985. $( '.wp-filter-search' ).val( query );
  986. },
  987. themes: function() {
  988. $( '.wp-filter-search' ).val( '' );
  989. },
  990. navigate: function() {
  991. if ( Backbone.history._hasPushState ) {
  992. Backbone.Router.prototype.navigate.apply( this, arguments );
  993. }
  994. }
  995. });
  996. // Execute and setup the application
  997. themes.Run = {
  998. init: function() {
  999. // Initializes the blog's theme library view
  1000. // Create a new collection with data
  1001. this.themes = new themes.Collection( themes.data.themes );
  1002. // Set up the view
  1003. this.view = new themes.view.Appearance({
  1004. collection: this.themes
  1005. });
  1006. this.render();
  1007. },
  1008. render: function() {
  1009. // Render results
  1010. this.view.render();
  1011. this.routes();
  1012. Backbone.history.start({
  1013. root: themes.data.settings.adminUrl,
  1014. pushState: true,
  1015. hashChange: false
  1016. });
  1017. },
  1018. routes: function() {
  1019. var self = this;
  1020. // Bind to our global thx object
  1021. // so that the object is available to sub-views
  1022. themes.router = new themes.Router();
  1023. // Handles theme details route event
  1024. themes.router.on( 'route:theme', function( slug ) {
  1025. self.view.view.expand( slug );
  1026. });
  1027. themes.router.on( 'route:themes', function() {
  1028. self.themes.doSearch( '' );
  1029. self.view.trigger( 'theme:close' );
  1030. });
  1031. // Handles search route event
  1032. themes.router.on( 'route:search', function() {
  1033. $( '.wp-filter-search' ).trigger( 'keyup' );
  1034. });
  1035. this.extraRoutes();
  1036. },
  1037. extraRoutes: function() {
  1038. return false;
  1039. }
  1040. };
  1041. // Extend the main Search view
  1042. themes.view.InstallerSearch = themes.view.Search.extend({
  1043. events: {
  1044. 'input': 'search',
  1045. 'keyup': 'search'
  1046. },
  1047. // Handles Ajax request for searching through themes in public repo
  1048. search: function( event ) {
  1049. // Tabbing or reverse tabbing into the search input shouldn't trigger a search
  1050. if ( event.type === 'keyup' && ( event.which === 9 || event.which === 16 ) ) {
  1051. return;
  1052. }
  1053. this.collection = this.options.parent.view.collection;
  1054. // Clear on escape.
  1055. if ( event.type === 'keyup' && event.which === 27 ) {
  1056. event.target.value = '';
  1057. }
  1058. this.doSearch( event.target.value );
  1059. },
  1060. doSearch: _.debounce( function( value ) {
  1061. var request = {};
  1062. request.search = value;
  1063. // Intercept an [author] search.
  1064. //
  1065. // If input value starts with `author:` send a request
  1066. // for `author` instead of a regular `search`
  1067. if ( value.substring( 0, 7 ) === 'author:' ) {
  1068. request.search = '';
  1069. request.author = value.slice( 7 );
  1070. }
  1071. // Intercept a [tag] search.
  1072. //
  1073. // If input value starts with `tag:` send a request
  1074. // for `tag` instead of a regular `search`
  1075. if ( value.substring( 0, 4 ) === 'tag:' ) {
  1076. request.search = '';
  1077. request.tag = [ value.slice( 4 ) ];
  1078. }
  1079. $( '.filter-links li > a.current' ).removeClass( 'current' );
  1080. $( 'body' ).removeClass( 'show-filters filters-applied show-favorites-form' );
  1081. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1082. // or searching the local cache
  1083. this.collection.query( request );
  1084. // Set route
  1085. themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + value ), { replace: true } );
  1086. }, 500 )
  1087. });
  1088. themes.view.Installer = themes.view.Appearance.extend({
  1089. el: '#wpbody-content .wrap',
  1090. // Register events for sorting and filters in theme-navigation
  1091. events: {
  1092. 'click .filter-links li > a': 'onSort',
  1093. 'click .theme-filter': 'onFilter',
  1094. 'click .drawer-toggle': 'moreFilters',
  1095. 'click .filter-drawer .apply-filters': 'applyFilters',
  1096. 'click .filter-group [type="checkbox"]': 'addFilter',
  1097. 'click .filter-drawer .clear-filters': 'clearFilters',
  1098. 'click .filtered-by': 'backToFilters',
  1099. 'click .favorites-form-submit' : 'saveUsername',
  1100. 'keyup #wporg-username-input': 'saveUsername'
  1101. },
  1102. // Initial render method
  1103. render: function() {
  1104. var self = this;
  1105. this.search();
  1106. this.uploader();
  1107. this.collection = new themes.Collection();
  1108. // Bump `collection.currentQuery.page` and request more themes if we hit the end of the page.
  1109. this.listenTo( this, 'theme:end', function() {
  1110. // Make sure we are not already loading
  1111. if ( self.collection.loadingThemes ) {
  1112. return;
  1113. }
  1114. // Set loadingThemes to true and bump page instance of currentQuery.
  1115. self.collection.loadingThemes = true;
  1116. self.collection.currentQuery.page++;
  1117. // Use currentQuery.page to build the themes request.
  1118. _.extend( self.collection.currentQuery.request, { page: self.collection.currentQuery.page } );
  1119. self.collection.query( self.collection.currentQuery.request );
  1120. });
  1121. this.listenTo( this.collection, 'query:success', function() {
  1122. $( 'body' ).removeClass( 'loading-content' );
  1123. $( '.theme-browser' ).find( 'div.error' ).remove();
  1124. });
  1125. this.listenTo( this.collection, 'query:fail', function() {
  1126. $( 'body' ).removeClass( 'loading-content' );
  1127. $( '.theme-browser' ).find( 'div.error' ).remove();
  1128. $( '.theme-browser' ).find( 'div.themes' ).before( '<div class="error"><p>' + l10n.error + '</p></div>' );
  1129. });
  1130. if ( this.view ) {
  1131. this.view.remove();
  1132. }
  1133. // Set ups the view and passes the section argument
  1134. this.view = new themes.view.Themes({
  1135. collection: this.collection,
  1136. parent: this
  1137. });
  1138. // Reset pagination every time the install view handler is run
  1139. this.page = 0;
  1140. // Render and append
  1141. this.$el.find( '.themes' ).remove();
  1142. this.view.render();
  1143. this.$el.find( '.theme-browser' ).append( this.view.el ).addClass( 'rendered' );
  1144. },
  1145. // Handles all the rendering of the public theme directory
  1146. browse: function( section ) {
  1147. // Create a new collection with the proper theme data
  1148. // for each section
  1149. this.collection.query( { browse: section } );
  1150. },
  1151. // Sorting navigation
  1152. onSort: function( event ) {
  1153. var $el = $( event.target ),
  1154. sort = $el.data( 'sort' );
  1155. event.preventDefault();
  1156. $( 'body' ).removeClass( 'filters-applied show-filters' );
  1157. // Bail if this is already active
  1158. if ( $el.hasClass( this.activeClass ) ) {
  1159. return;
  1160. }
  1161. this.sort( sort );
  1162. // Trigger a router.naviagte update
  1163. themes.router.navigate( themes.router.baseUrl( themes.router.browsePath + sort ) );
  1164. },
  1165. sort: function( sort ) {
  1166. this.clearSearch();
  1167. $( '.filter-links li > a, .theme-filter' ).removeClass( this.activeClass );
  1168. $( '[data-sort="' + sort + '"]' ).addClass( this.activeClass );
  1169. if ( 'favorites' === sort ) {
  1170. $ ( 'body' ).addClass( 'show-favorites-form' );
  1171. } else {
  1172. $ ( 'body' ).removeClass( 'show-favorites-form' );
  1173. }
  1174. this.browse( sort );
  1175. },
  1176. // Filters and Tags
  1177. onFilter: function( event ) {
  1178. var request,
  1179. $el = $( event.target ),
  1180. filter = $el.data( 'filter' );
  1181. // Bail if this is already active
  1182. if ( $el.hasClass( this.activeClass ) ) {
  1183. return;
  1184. }
  1185. $( '.filter-links li > a, .theme-section' ).removeClass( this.activeClass );
  1186. $el.addClass( this.activeClass );
  1187. if ( ! filter ) {
  1188. return;
  1189. }
  1190. // Construct the filter request
  1191. // using the default values
  1192. filter = _.union( [ filter, this.filtersChecked() ] );
  1193. request = { tag: [ filter ] };
  1194. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1195. // or searching the local cache
  1196. this.collection.query( request );
  1197. },
  1198. // Clicking on a checkbox to add another filter to the request
  1199. addFilter: function() {
  1200. this.filtersChecked();
  1201. },
  1202. // Applying filters triggers a tag request
  1203. applyFilters: function( event ) {
  1204. var name,
  1205. tags = this.filtersChecked(),
  1206. request = { tag: tags },
  1207. filteringBy = $( '.filtered-by .tags' );
  1208. if ( event ) {
  1209. event.preventDefault();
  1210. }
  1211. $( 'body' ).addClass( 'filters-applied' );
  1212. $( '.filter-links li > a.current' ).removeClass( 'current' );
  1213. filteringBy.empty();
  1214. _.each( tags, function( tag ) {
  1215. name = $( 'label[for="filter-id-' + tag + '"]' ).text();
  1216. filteringBy.append( '<span class="tag">' + name + '</span>' );
  1217. });
  1218. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1219. // or searching the local cache
  1220. this.collection.query( request );
  1221. },
  1222. // Save the user's WordPress.org username and get his favorite themes.
  1223. saveUsername: function ( event ) {
  1224. var username = $( '#wporg-username-input' ).val(),
  1225. nonce = $( '#wporg-username-nonce' ).val(),
  1226. request = { browse: 'favorites', user: username },
  1227. that = this;
  1228. if ( event ) {
  1229. event.preventDefault();
  1230. }
  1231. // save username on enter
  1232. if ( event.type === 'keyup' && event.which !== 13 ) {
  1233. return;
  1234. }
  1235. return wp.ajax.send( 'save-wporg-username', {
  1236. data: {
  1237. _wpnonce: nonce,
  1238. username: username
  1239. },
  1240. success: function () {
  1241. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1242. // or searching the local cache
  1243. that.collection.query( request );
  1244. }
  1245. } );
  1246. },
  1247. // Get the checked filters
  1248. // @return {array} of tags or false
  1249. filtersChecked: function() {
  1250. var items = $( '.filter-group' ).find( ':checkbox' ),
  1251. tags = [];
  1252. _.each( items.filter( ':checked' ), function( item ) {
  1253. tags.push( $( item ).prop( 'value' ) );
  1254. });
  1255. // When no filters are checked, restore initial state and return
  1256. if ( tags.length === 0 ) {
  1257. $( '.filter-drawer .apply-filters' ).find( 'span' ).text( '' );
  1258. $( '.filter-drawer .clear-filters' ).hide();
  1259. $( 'body' ).removeClass( 'filters-applied' );
  1260. return false;
  1261. }
  1262. $( '.filter-drawer .apply-filters' ).find( 'span' ).text( tags.length );
  1263. $( '.filter-drawer .clear-filters' ).css( 'display', 'inline-block' );
  1264. return tags;
  1265. },
  1266. activeClass: 'current',
  1267. // Overwrite search container class to append search
  1268. // in new location
  1269. searchContainer: $( '.wp-filter .search-form' ),
  1270. uploader: function() {
  1271. $( 'a.upload' ).on( 'click', function( event ) {
  1272. event.preventDefault();
  1273. $( 'body' ).addClass( 'show-upload-theme' );
  1274. themes.router.navigate( themes.router.baseUrl( '?upload' ), { replace: true } );
  1275. });
  1276. $( 'a.browse-themes' ).on( 'click', function( event ) {
  1277. event.preventDefault();
  1278. $( 'body' ).removeClass( 'show-upload-theme' );
  1279. themes.router.navigate( themes.router.baseUrl( '' ), { replace: true } );
  1280. });
  1281. },
  1282. // Toggle the full filters navigation
  1283. moreFilters: function( event ) {
  1284. event.preventDefault();
  1285. if ( $( 'body' ).hasClass( 'filters-applied' ) ) {
  1286. return this.backToFilters();
  1287. }
  1288. // If the filters section is opened and filters are checked
  1289. // run the relevant query collapsing to filtered-by state
  1290. if ( $( 'body' ).hasClass( 'show-filters' ) && this.filtersChecked() ) {
  1291. return this.addFilter();
  1292. }
  1293. this.clearSearch();
  1294. themes.router.navigate( themes.router.baseUrl( '' ) );
  1295. $( 'body' ).toggleClass( 'show-filters' );
  1296. },
  1297. // Clears all the checked filters
  1298. // @uses filtersChecked()
  1299. clearFilters: function( event ) {
  1300. var items = $( '.filter-group' ).find( ':checkbox' ),
  1301. self = this;
  1302. event.preventDefault();
  1303. _.each( items.filter( ':checked' ), function( item ) {
  1304. $( item ).prop( 'checked', false );
  1305. return self.filtersChecked();
  1306. });
  1307. },
  1308. backToFilters: function( event ) {
  1309. if ( event ) {
  1310. event.preventDefault();
  1311. }
  1312. $( 'body' ).removeClass( 'filters-applied' );
  1313. },
  1314. clearSearch: function() {
  1315. $( '#wp-filter-search-input').val( '' );
  1316. }
  1317. });
  1318. themes.InstallerRouter = Backbone.Router.extend({
  1319. routes: {
  1320. 'theme-install.php?theme=:slug': 'preview',
  1321. 'theme-install.php?browse=:sort': 'sort',
  1322. 'theme-install.php?upload': 'upload',
  1323. 'theme-install.php?search=:query': 'search',
  1324. 'theme-install.php': 'sort'
  1325. },
  1326. baseUrl: function( url ) {
  1327. return 'theme-install.php' + url;
  1328. },
  1329. themePath: '?theme=',
  1330. browsePath: '?browse=',
  1331. searchPath: '?search=',
  1332. search: function( query ) {
  1333. $( '.wp-filter-search' ).val( query );
  1334. },
  1335. navigate: function() {
  1336. if ( Backbone.history._hasPushState ) {
  1337. Backbone.Router.prototype.navigate.apply( this, arguments );
  1338. }
  1339. }
  1340. });
  1341. themes.RunInstaller = {
  1342. init: function() {
  1343. // Set up the view
  1344. // Passes the default 'section' as an option
  1345. this.view = new themes.view.Installer({
  1346. section: 'featured',
  1347. SearchView: themes.view.InstallerSearch
  1348. });
  1349. // Render results
  1350. this.render();
  1351. },
  1352. render: function() {
  1353. // Render results
  1354. this.view.render();
  1355. this.routes();
  1356. Backbone.history.start({
  1357. root: themes.data.settings.adminUrl,
  1358. pushState: true,
  1359. hashChange: false
  1360. });
  1361. },
  1362. routes: function() {
  1363. var self = this,
  1364. request = {};
  1365. // Bind to our global `wp.themes` object
  1366. // so that the router is available to sub-views
  1367. themes.router = new themes.InstallerRouter();
  1368. // Handles `theme` route event
  1369. // Queries the API for the passed theme slug
  1370. themes.router.on( 'route:preview', function( slug ) {
  1371. request.theme = slug;
  1372. self.view.collection.query( request );
  1373. self.view.collection.once( 'update', function() {
  1374. self.view.view.theme.preview();
  1375. });
  1376. });
  1377. // Handles sorting / browsing routes
  1378. // Also handles the root URL triggering a sort request
  1379. // for `featured`, the default view
  1380. themes.router.on( 'route:sort', function( sort ) {
  1381. if ( ! sort ) {
  1382. sort = 'featured';
  1383. }
  1384. self.view.sort( sort );
  1385. self.view.trigger( 'theme:close' );
  1386. });
  1387. // Support the `upload` route by going straight to upload section
  1388. themes.router.on( 'route:upload', function() {
  1389. $( 'a.upload' ).trigger( 'click' );
  1390. });
  1391. // The `search` route event. The router populates the input field.
  1392. themes.router.on( 'route:search', function() {
  1393. $( '.wp-filter-search' ).focus().trigger( 'keyup' );
  1394. });
  1395. this.extraRoutes();
  1396. },
  1397. extraRoutes: function() {
  1398. return false;
  1399. }
  1400. };
  1401. // Ready...
  1402. $( document ).ready(function() {
  1403. if ( themes.isInstall ) {
  1404. themes.RunInstaller.init();
  1405. } else {
  1406. themes.Run.init();
  1407. }
  1408. $( '.broken-themes .delete-theme' ).on( 'click', function() {
  1409. return confirm( _wpThemeSettings.settings.confirmDelete );
  1410. });
  1411. });
  1412. })( jQuery );
  1413. // Align theme browser thickbox
  1414. var tb_position;
  1415. jQuery(document).ready( function($) {
  1416. tb_position = function() {
  1417. var tbWindow = $('#TB_window'),
  1418. width = $(window).width(),
  1419. H = $(window).height(),
  1420. W = ( 1040 < width ) ? 1040 : width,
  1421. adminbar_height = 0;
  1422. if ( $('#wpadminbar').length ) {
  1423. adminbar_height = parseInt( $('#wpadminbar').css('height'), 10 );
  1424. }
  1425. if ( tbWindow.size() ) {
  1426. tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
  1427. $('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
  1428. tbWindow.css({'margin-left': '-' + parseInt( ( ( W - 50 ) / 2 ), 10 ) + 'px'});
  1429. if ( typeof document.body.style.maxWidth !== 'undefined' ) {
  1430. tbWindow.css({'top': 20 + adminbar_height + 'px', 'margin-top': '0'});
  1431. }
  1432. }
  1433. };
  1434. $(window).resize(function(){ tb_position(); });
  1435. });