PageRenderTime 52ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-admin/js/theme.js

https://gitlab.com/eita/encontre-consumo-responsavel
JavaScript | 1726 lines | 1034 code | 361 blank | 331 comment | 125 complexity | ce08e4628996a70a5d5deac9221e1130 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. this.$el.append( '<br class="clear"/>' );
  67. },
  68. // Defines search element container
  69. searchContainer: $( '#wpbody h2:first' ),
  70. // Search input and view
  71. // for current theme collection
  72. search: function() {
  73. var view,
  74. self = this;
  75. // Don't render the search if there is only one theme
  76. if ( themes.data.themes.length === 1 ) {
  77. return;
  78. }
  79. view = new this.SearchView({
  80. collection: self.collection,
  81. parent: this
  82. });
  83. // Render and append after screen title
  84. view.render();
  85. this.searchContainer
  86. .append( $.parseHTML( '<label class="screen-reader-text" for="wp-filter-search-input">' + l10n.search + '</label>' ) )
  87. .append( view.el );
  88. },
  89. // Checks when the user gets close to the bottom
  90. // of the mage and triggers a theme:scroll event
  91. scroller: function() {
  92. var self = this,
  93. bottom, threshold;
  94. bottom = this.window.scrollTop() + self.window.height();
  95. threshold = self.$el.offset().top + self.$el.outerHeight( false ) - self.window.height();
  96. threshold = Math.round( threshold * 0.9 );
  97. if ( bottom > threshold ) {
  98. this.trigger( 'theme:scroll' );
  99. }
  100. }
  101. });
  102. // Set up the Collection for our theme data
  103. // @has 'id' 'name' 'screenshot' 'author' 'authorURI' 'version' 'active' ...
  104. themes.Collection = Backbone.Collection.extend({
  105. model: themes.Model,
  106. // Search terms
  107. terms: '',
  108. // Controls searching on the current theme collection
  109. // and triggers an update event
  110. doSearch: function( value ) {
  111. // Don't do anything if we've already done this search
  112. // Useful because the Search handler fires multiple times per keystroke
  113. if ( this.terms === value ) {
  114. return;
  115. }
  116. // Updates terms with the value passed
  117. this.terms = value;
  118. // If we have terms, run a search...
  119. if ( this.terms.length > 0 ) {
  120. this.search( this.terms );
  121. }
  122. // If search is blank, show all themes
  123. // Useful for resetting the views when you clean the input
  124. if ( this.terms === '' ) {
  125. this.reset( themes.data.themes );
  126. $( 'body' ).removeClass( 'no-results' );
  127. }
  128. // Trigger an 'update' event
  129. this.trigger( 'update' );
  130. },
  131. // Performs a search within the collection
  132. // @uses RegExp
  133. search: function( term ) {
  134. var match, results, haystack, name, description, author;
  135. // Start with a full collection
  136. this.reset( themes.data.themes, { silent: true } );
  137. // Escape the term string for RegExp meta characters
  138. term = term.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' );
  139. // Consider spaces as word delimiters and match the whole string
  140. // so matching terms can be combined
  141. term = term.replace( / /g, ')(?=.*' );
  142. match = new RegExp( '^(?=.*' + term + ').+', 'i' );
  143. // Find results
  144. // _.filter and .test
  145. results = this.filter( function( data ) {
  146. name = data.get( 'name' ).replace( /(<([^>]+)>)/ig, '' );
  147. description = data.get( 'description' ).replace( /(<([^>]+)>)/ig, '' );
  148. author = data.get( 'author' ).replace( /(<([^>]+)>)/ig, '' );
  149. haystack = _.union( name, data.get( 'id' ), description, author, data.get( 'tags' ) );
  150. if ( match.test( data.get( 'author' ) ) && term.length > 2 ) {
  151. data.set( 'displayAuthor', true );
  152. }
  153. return match.test( haystack );
  154. });
  155. if ( results.length === 0 ) {
  156. this.trigger( 'query:empty' );
  157. } else {
  158. $( 'body' ).removeClass( 'no-results' );
  159. }
  160. this.reset( results );
  161. },
  162. // Paginates the collection with a helper method
  163. // that slices the collection
  164. paginate: function( instance ) {
  165. var collection = this;
  166. instance = instance || 0;
  167. // Themes per instance are set at 20
  168. collection = _( collection.rest( 20 * instance ) );
  169. collection = _( collection.first( 20 ) );
  170. return collection;
  171. },
  172. count: false,
  173. // Handles requests for more themes
  174. // and caches results
  175. //
  176. // When we are missing a cache object we fire an apiCall()
  177. // which triggers events of `query:success` or `query:fail`
  178. query: function( request ) {
  179. /**
  180. * @static
  181. * @type Array
  182. */
  183. var queries = this.queries,
  184. self = this,
  185. query, isPaginated, count;
  186. // Store current query request args
  187. // for later use with the event `theme:end`
  188. this.currentQuery.request = request;
  189. // Search the query cache for matches.
  190. query = _.find( queries, function( query ) {
  191. return _.isEqual( query.request, request );
  192. });
  193. // If the request matches the stored currentQuery.request
  194. // it means we have a paginated request.
  195. isPaginated = _.has( request, 'page' );
  196. // Reset the internal api page counter for non paginated queries.
  197. if ( ! isPaginated ) {
  198. this.currentQuery.page = 1;
  199. }
  200. // Otherwise, send a new API call and add it to the cache.
  201. if ( ! query && ! isPaginated ) {
  202. query = this.apiCall( request ).done( function( data ) {
  203. // Update the collection with the queried data.
  204. if ( data.themes ) {
  205. self.reset( data.themes );
  206. count = data.info.results;
  207. // Store the results and the query request
  208. queries.push( { themes: data.themes, request: request, total: count } );
  209. }
  210. // Trigger a collection refresh event
  211. // and a `query:success` event with a `count` argument.
  212. self.trigger( 'update' );
  213. self.trigger( 'query:success', count );
  214. if ( data.themes && data.themes.length === 0 ) {
  215. self.trigger( 'query:empty' );
  216. }
  217. }).fail( function() {
  218. self.trigger( 'query:fail' );
  219. });
  220. } else {
  221. // If it's a paginated request we need to fetch more themes...
  222. if ( isPaginated ) {
  223. return this.apiCall( request, isPaginated ).done( function( data ) {
  224. // Add the new themes to the current collection
  225. // @todo update counter
  226. self.add( data.themes );
  227. self.trigger( 'query:success' );
  228. // We are done loading themes for now.
  229. self.loadingThemes = false;
  230. }).fail( function() {
  231. self.trigger( 'query:fail' );
  232. });
  233. }
  234. if ( query.themes.length === 0 ) {
  235. self.trigger( 'query:empty' );
  236. } else {
  237. $( 'body' ).removeClass( 'no-results' );
  238. }
  239. // Only trigger an update event since we already have the themes
  240. // on our cached object
  241. if ( _.isNumber( query.total ) ) {
  242. this.count = query.total;
  243. }
  244. this.reset( query.themes );
  245. if ( ! query.total ) {
  246. this.count = this.length;
  247. }
  248. this.trigger( 'update' );
  249. this.trigger( 'query:success', this.count );
  250. }
  251. },
  252. // Local cache array for API queries
  253. queries: [],
  254. // Keep track of current query so we can handle pagination
  255. currentQuery: {
  256. page: 1,
  257. request: {}
  258. },
  259. // Send request to api.wordpress.org/themes
  260. apiCall: function( request, paginated ) {
  261. return wp.ajax.send( 'query-themes', {
  262. data: {
  263. // Request data
  264. request: _.extend({
  265. per_page: 100,
  266. fields: {
  267. description: true,
  268. tested: true,
  269. requires: true,
  270. rating: true,
  271. downloaded: true,
  272. downloadLink: true,
  273. last_updated: true,
  274. homepage: true,
  275. num_ratings: true
  276. }
  277. }, request)
  278. },
  279. beforeSend: function() {
  280. if ( ! paginated ) {
  281. // Spin it
  282. $( 'body' ).addClass( 'loading-content' ).removeClass( 'no-results' );
  283. }
  284. }
  285. });
  286. },
  287. // Static status controller for when we are loading themes.
  288. loadingThemes: false
  289. });
  290. // This is the view that controls each theme item
  291. // that will be displayed on the screen
  292. themes.view.Theme = wp.Backbone.View.extend({
  293. // Wrap theme data on a div.theme element
  294. className: 'theme',
  295. // Reflects which theme view we have
  296. // 'grid' (default) or 'detail'
  297. state: 'grid',
  298. // The HTML template for each element to be rendered
  299. html: themes.template( 'theme' ),
  300. events: {
  301. 'click': themes.isInstall ? 'preview': 'expand',
  302. 'keydown': themes.isInstall ? 'preview': 'expand',
  303. 'touchend': themes.isInstall ? 'preview': 'expand',
  304. 'keyup': 'addFocus',
  305. 'touchmove': 'preventExpand'
  306. },
  307. touchDrag: false,
  308. render: function() {
  309. var data = this.model.toJSON();
  310. // Render themes using the html template
  311. this.$el.html( this.html( data ) ).attr({
  312. tabindex: 0,
  313. 'aria-describedby' : data.id + '-action ' + data.id + '-name'
  314. });
  315. // Renders active theme styles
  316. this.activeTheme();
  317. if ( this.model.get( 'displayAuthor' ) ) {
  318. this.$el.addClass( 'display-author' );
  319. }
  320. if ( this.model.get( 'installed' ) ) {
  321. this.$el.addClass( 'is-installed' );
  322. }
  323. },
  324. // Adds a class to the currently active theme
  325. // and to the overlay in detailed view mode
  326. activeTheme: function() {
  327. if ( this.model.get( 'active' ) ) {
  328. this.$el.addClass( 'active' );
  329. }
  330. },
  331. // Add class of focus to the theme we are focused on.
  332. addFocus: function() {
  333. var $themeToFocus = ( $( ':focus' ).hasClass( 'theme' ) ) ? $( ':focus' ) : $(':focus').parents('.theme');
  334. $('.theme.focus').removeClass('focus');
  335. $themeToFocus.addClass('focus');
  336. },
  337. // Single theme overlay screen
  338. // It's shown when clicking a theme
  339. expand: function( event ) {
  340. var self = this;
  341. event = event || window.event;
  342. // 'enter' and 'space' keys expand the details view when a theme is :focused
  343. if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
  344. return;
  345. }
  346. // Bail if the user scrolled on a touch device
  347. if ( this.touchDrag === true ) {
  348. return this.touchDrag = false;
  349. }
  350. // Prevent the modal from showing when the user clicks
  351. // one of the direct action buttons
  352. if ( $( event.target ).is( '.theme-actions a' ) ) {
  353. return;
  354. }
  355. // Set focused theme to current element
  356. themes.focusedTheme = this.$el;
  357. this.trigger( 'theme:expand', self.model.cid );
  358. },
  359. preventExpand: function() {
  360. this.touchDrag = true;
  361. },
  362. preview: function( event ) {
  363. var self = this,
  364. current, preview;
  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 .previous-theme': 'previousTheme',
  606. 'click .next-theme': 'nextTheme',
  607. 'keyup': 'keyEvent'
  608. },
  609. // The HTML template for the theme preview
  610. html: themes.template( 'theme-preview' ),
  611. render: function() {
  612. var data = this.model.toJSON();
  613. this.$el.html( this.html( data ) );
  614. themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.get( 'id' ) ), { replace: true } );
  615. this.$el.fadeIn( 200, function() {
  616. $( 'body' ).addClass( 'theme-installer-active full-overlay-active' );
  617. $( '.close-full-overlay' ).focus();
  618. });
  619. },
  620. close: function() {
  621. this.$el.fadeOut( 200, function() {
  622. $( 'body' ).removeClass( 'theme-installer-active full-overlay-active' );
  623. // Return focus to the theme div
  624. if ( themes.focusedTheme ) {
  625. themes.focusedTheme.focus();
  626. }
  627. });
  628. themes.router.navigate( themes.router.baseUrl( '' ) );
  629. this.trigger( 'preview:close' );
  630. this.undelegateEvents();
  631. this.unbind();
  632. return false;
  633. },
  634. collapse: function() {
  635. this.$el.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
  636. return false;
  637. },
  638. keyEvent: function( event ) {
  639. // The escape key closes the preview
  640. if ( event.keyCode === 27 ) {
  641. this.undelegateEvents();
  642. this.close();
  643. }
  644. // The right arrow key, next theme
  645. if ( event.keyCode === 39 ) {
  646. _.once( this.nextTheme() );
  647. }
  648. // The left arrow key, previous theme
  649. if ( event.keyCode === 37 ) {
  650. this.previousTheme();
  651. }
  652. }
  653. });
  654. // Controls the rendering of div.themes,
  655. // a wrapper that will hold all the theme elements
  656. themes.view.Themes = wp.Backbone.View.extend({
  657. className: 'themes',
  658. $overlay: $( 'div.theme-overlay' ),
  659. // Number to keep track of scroll position
  660. // while in theme-overlay mode
  661. index: 0,
  662. // The theme count element
  663. count: $( '.wp-core-ui .theme-count' ),
  664. // The live themes count
  665. liveThemeCount: 0,
  666. initialize: function( options ) {
  667. var self = this;
  668. // Set up parent
  669. this.parent = options.parent;
  670. // Set current view to [grid]
  671. this.setView( 'grid' );
  672. // Move the active theme to the beginning of the collection
  673. self.currentTheme();
  674. // When the collection is updated by user input...
  675. this.listenTo( self.collection, 'update', function() {
  676. self.parent.page = 0;
  677. self.currentTheme();
  678. self.render( this );
  679. });
  680. // Update theme count to full result set when available.
  681. this.listenTo( self.collection, 'query:success', function( count ) {
  682. if ( _.isNumber( count ) ) {
  683. self.count.text( count );
  684. self.announceSearchResults( count );
  685. } else {
  686. self.count.text( self.collection.length );
  687. self.announceSearchResults( self.collection.length );
  688. }
  689. });
  690. this.listenTo( self.collection, 'query:empty', function() {
  691. $( 'body' ).addClass( 'no-results' );
  692. });
  693. this.listenTo( this.parent, 'theme:scroll', function() {
  694. self.renderThemes( self.parent.page );
  695. });
  696. this.listenTo( this.parent, 'theme:close', function() {
  697. if ( self.overlay ) {
  698. self.overlay.closeOverlay();
  699. }
  700. } );
  701. // Bind keyboard events.
  702. $( 'body' ).on( 'keyup', function( event ) {
  703. if ( ! self.overlay ) {
  704. return;
  705. }
  706. // Pressing the right arrow key fires a theme:next event
  707. if ( event.keyCode === 39 ) {
  708. self.overlay.nextTheme();
  709. }
  710. // Pressing the left arrow key fires a theme:previous event
  711. if ( event.keyCode === 37 ) {
  712. self.overlay.previousTheme();
  713. }
  714. // Pressing the escape key fires a theme:collapse event
  715. if ( event.keyCode === 27 ) {
  716. self.overlay.collapse( event );
  717. }
  718. });
  719. },
  720. // Manages rendering of theme pages
  721. // and keeping theme count in sync
  722. render: function() {
  723. // Clear the DOM, please
  724. this.$el.empty();
  725. // If the user doesn't have switch capabilities
  726. // or there is only one theme in the collection
  727. // render the detailed view of the active theme
  728. if ( themes.data.themes.length === 1 ) {
  729. // Constructs the view
  730. this.singleTheme = new themes.view.Details({
  731. model: this.collection.models[0]
  732. });
  733. // Render and apply a 'single-theme' class to our container
  734. this.singleTheme.render();
  735. this.$el.addClass( 'single-theme' );
  736. this.$el.append( this.singleTheme.el );
  737. }
  738. // Generate the themes
  739. // Using page instance
  740. // While checking the collection has items
  741. if ( this.options.collection.size() > 0 ) {
  742. this.renderThemes( this.parent.page );
  743. }
  744. // Display a live theme count for the collection
  745. this.liveThemeCount = this.collection.count ? this.collection.count : this.collection.length;
  746. this.count.text( this.liveThemeCount );
  747. this.announceSearchResults( this.liveThemeCount );
  748. },
  749. // Iterates through each instance of the collection
  750. // and renders each theme module
  751. renderThemes: function( page ) {
  752. var self = this;
  753. self.instance = self.collection.paginate( page );
  754. // If we have no more themes bail
  755. if ( self.instance.size() === 0 ) {
  756. // Fire a no-more-themes event.
  757. this.parent.trigger( 'theme:end' );
  758. return;
  759. }
  760. // Make sure the add-new stays at the end
  761. if ( page >= 1 ) {
  762. $( '.add-new-theme' ).remove();
  763. }
  764. // Loop through the themes and setup each theme view
  765. self.instance.each( function( theme ) {
  766. self.theme = new themes.view.Theme({
  767. model: theme,
  768. parent: self
  769. });
  770. // Render the views...
  771. self.theme.render();
  772. // and append them to div.themes
  773. self.$el.append( self.theme.el );
  774. // Binds to theme:expand to show the modal box
  775. // with the theme details
  776. self.listenTo( self.theme, 'theme:expand', self.expand, self );
  777. });
  778. // 'Add new theme' element shown at the end of the grid
  779. if ( themes.data.settings.canInstall ) {
  780. this.$el.append( '<div class="theme add-new-theme"><a href="' + themes.data.settings.installURI + '"><div class="theme-screenshot"><span></span></div><h3 class="theme-name">' + l10n.addNew + '</h3></a></div>' );
  781. }
  782. this.parent.page++;
  783. },
  784. // Grabs current theme and puts it at the beginning of the collection
  785. currentTheme: function() {
  786. var self = this,
  787. current;
  788. current = self.collection.findWhere({ active: true });
  789. // Move the active theme to the beginning of the collection
  790. if ( current ) {
  791. self.collection.remove( current );
  792. self.collection.add( current, { at:0 } );
  793. }
  794. },
  795. // Sets current view
  796. setView: function( view ) {
  797. return view;
  798. },
  799. // Renders the overlay with the ThemeDetails view
  800. // Uses the current model data
  801. expand: function( id ) {
  802. var self = this;
  803. // Set the current theme model
  804. this.model = self.collection.get( id );
  805. // Trigger a route update for the current model
  806. themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.id ) );
  807. // Sets this.view to 'detail'
  808. this.setView( 'detail' );
  809. $( 'body' ).addClass( 'modal-open' );
  810. // Set up the theme details view
  811. this.overlay = new themes.view.Details({
  812. model: self.model
  813. });
  814. this.overlay.render();
  815. this.$overlay.html( this.overlay.el );
  816. // Bind to theme:next and theme:previous
  817. // triggered by the arrow keys
  818. //
  819. // Keep track of the current model so we
  820. // can infer an index position
  821. this.listenTo( this.overlay, 'theme:next', function() {
  822. // Renders the next theme on the overlay
  823. self.next( [ self.model.cid ] );
  824. })
  825. .listenTo( this.overlay, 'theme:previous', function() {
  826. // Renders the previous theme on the overlay
  827. self.previous( [ self.model.cid ] );
  828. });
  829. },
  830. // This method renders the next theme on the overlay modal
  831. // based on the current position in the collection
  832. // @params [model cid]
  833. next: function( args ) {
  834. var self = this,
  835. model, nextModel;
  836. // Get the current theme
  837. model = self.collection.get( args[0] );
  838. // Find the next model within the collection
  839. nextModel = self.collection.at( self.collection.indexOf( model ) + 1 );
  840. // Sanity check which also serves as a boundary test
  841. if ( nextModel !== undefined ) {
  842. // We have a new theme...
  843. // Close the overlay
  844. this.overlay.closeOverlay();
  845. // Trigger a route update for the current model
  846. self.theme.trigger( 'theme:expand', nextModel.cid );
  847. }
  848. },
  849. // This method renders the previous theme on the overlay modal
  850. // based on the current position in the collection
  851. // @params [model cid]
  852. previous: function( args ) {
  853. var self = this,
  854. model, previousModel;
  855. // Get the current theme
  856. model = self.collection.get( args[0] );
  857. // Find the previous model within the collection
  858. previousModel = self.collection.at( self.collection.indexOf( model ) - 1 );
  859. if ( previousModel !== undefined ) {
  860. // We have a new theme...
  861. // Close the overlay
  862. this.overlay.closeOverlay();
  863. // Trigger a route update for the current model
  864. self.theme.trigger( 'theme:expand', previousModel.cid );
  865. }
  866. },
  867. // Dispatch audible search results feedback message
  868. announceSearchResults: function( count ) {
  869. if ( 0 === count ) {
  870. wp.a11y.speak( l10n.noThemesFound );
  871. } else {
  872. wp.a11y.speak( l10n.themesFound.replace( '%d', count ) );
  873. }
  874. }
  875. });
  876. // Search input view controller.
  877. themes.view.Search = wp.Backbone.View.extend({
  878. tagName: 'input',
  879. className: 'wp-filter-search',
  880. id: 'wp-filter-search-input',
  881. searching: false,
  882. attributes: {
  883. placeholder: l10n.searchPlaceholder,
  884. type: 'search',
  885. 'aria-describedby': 'live-search-desc'
  886. },
  887. events: {
  888. 'input': 'search',
  889. 'keyup': 'search',
  890. 'blur': 'pushState'
  891. },
  892. initialize: function( options ) {
  893. this.parent = options.parent;
  894. this.listenTo( this.parent, 'theme:close', function() {
  895. this.searching = false;
  896. } );
  897. },
  898. search: function( event ) {
  899. // Clear on escape.
  900. if ( event.type === 'keyup' && event.which === 27 ) {
  901. event.target.value = '';
  902. }
  903. /**
  904. * Since doSearch is debounced, it will only run when user input comes to a rest
  905. */
  906. this.doSearch( event );
  907. },
  908. // Runs a search on the theme collection.
  909. doSearch: _.debounce( function( event ) {
  910. var options = {};
  911. this.collection.doSearch( event.target.value );
  912. // if search is initiated and key is not return
  913. if ( this.searching && event.which !== 13 ) {
  914. options.replace = true;
  915. } else {
  916. this.searching = true;
  917. }
  918. // Update the URL hash
  919. if ( event.target.value ) {
  920. themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + event.target.value ), options );
  921. } else {
  922. themes.router.navigate( themes.router.baseUrl( '' ) );
  923. }
  924. }, 500 ),
  925. pushState: function( event ) {
  926. var url = themes.router.baseUrl( '' );
  927. if ( event.target.value ) {
  928. url = themes.router.baseUrl( themes.router.searchPath + event.target.value );
  929. }
  930. this.searching = false;
  931. themes.router.navigate( url );
  932. }
  933. });
  934. // Sets up the routes events for relevant url queries
  935. // Listens to [theme] and [search] params
  936. themes.Router = Backbone.Router.extend({
  937. routes: {
  938. 'themes.php?theme=:slug': 'theme',
  939. 'themes.php?search=:query': 'search',
  940. 'themes.php?s=:query': 'search',
  941. 'themes.php': 'themes',
  942. '': 'themes'
  943. },
  944. baseUrl: function( url ) {
  945. return 'themes.php' + url;
  946. },
  947. themePath: '?theme=',
  948. searchPath: '?search=',
  949. search: function( query ) {
  950. $( '.wp-filter-search' ).val( query );
  951. },
  952. themes: function() {
  953. $( '.wp-filter-search' ).val( '' );
  954. },
  955. navigate: function() {
  956. if ( Backbone.history._hasPushState ) {
  957. Backbone.Router.prototype.navigate.apply( this, arguments );
  958. }
  959. }
  960. });
  961. // Execute and setup the application
  962. themes.Run = {
  963. init: function() {
  964. // Initializes the blog's theme library view
  965. // Create a new collection with data
  966. this.themes = new themes.Collection( themes.data.themes );
  967. // Set up the view
  968. this.view = new themes.view.Appearance({
  969. collection: this.themes
  970. });
  971. this.render();
  972. },
  973. render: function() {
  974. // Render results
  975. this.view.render();
  976. this.routes();
  977. Backbone.history.start({
  978. root: themes.data.settings.adminUrl,
  979. pushState: true,
  980. hashChange: false
  981. });
  982. },
  983. routes: function() {
  984. var self = this;
  985. // Bind to our global thx object
  986. // so that the object is available to sub-views
  987. themes.router = new themes.Router();
  988. // Handles theme details route event
  989. themes.router.on( 'route:theme', function( slug ) {
  990. self.view.view.expand( slug );
  991. });
  992. themes.router.on( 'route:themes', function() {
  993. self.themes.doSearch( '' );
  994. self.view.trigger( 'theme:close' );
  995. });
  996. // Handles search route event
  997. themes.router.on( 'route:search', function() {
  998. $( '.wp-filter-search' ).trigger( 'keyup' );
  999. });
  1000. this.extraRoutes();
  1001. },
  1002. extraRoutes: function() {
  1003. return false;
  1004. }
  1005. };
  1006. // Extend the main Search view
  1007. themes.view.InstallerSearch = themes.view.Search.extend({
  1008. events: {
  1009. 'input': 'search',
  1010. 'keyup': 'search'
  1011. },
  1012. // Handles Ajax request for searching through themes in public repo
  1013. search: function( event ) {
  1014. // Tabbing or reverse tabbing into the search input shouldn't trigger a search
  1015. if ( event.type === 'keyup' && ( event.which === 9 || event.which === 16 ) ) {
  1016. return;
  1017. }
  1018. this.collection = this.options.parent.view.collection;
  1019. // Clear on escape.
  1020. if ( event.type === 'keyup' && event.which === 27 ) {
  1021. event.target.value = '';
  1022. }
  1023. this.doSearch( event.target.value );
  1024. },
  1025. doSearch: _.debounce( function( value ) {
  1026. var request = {};
  1027. request.search = value;
  1028. // Intercept an [author] search.
  1029. //
  1030. // If input value starts with `author:` send a request
  1031. // for `author` instead of a regular `search`
  1032. if ( value.substring( 0, 7 ) === 'author:' ) {
  1033. request.search = '';
  1034. request.author = value.slice( 7 );
  1035. }
  1036. // Intercept a [tag] search.
  1037. //
  1038. // If input value starts with `tag:` send a request
  1039. // for `tag` instead of a regular `search`
  1040. if ( value.substring( 0, 4 ) === 'tag:' ) {
  1041. request.search = '';
  1042. request.tag = [ value.slice( 4 ) ];
  1043. }
  1044. $( '.filter-links li > a.current' ).removeClass( 'current' );
  1045. $( 'body' ).removeClass( 'show-filters filters-applied' );
  1046. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1047. // or searching the local cache
  1048. this.collection.query( request );
  1049. // Set route
  1050. themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + value ), { replace: true } );
  1051. }, 500 )
  1052. });
  1053. themes.view.Installer = themes.view.Appearance.extend({
  1054. el: '#wpbody-content .wrap',
  1055. // Register events for sorting and filters in theme-navigation
  1056. events: {
  1057. 'click .filter-links li > a': 'onSort',
  1058. 'click .theme-filter': 'onFilter',
  1059. 'click .drawer-toggle': 'moreFilters',
  1060. 'click .filter-drawer .apply-filters': 'applyFilters',
  1061. 'click .filter-group [type="checkbox"]': 'addFilter',
  1062. 'click .filter-drawer .clear-filters': 'clearFilters',
  1063. 'click .filtered-by': 'backToFilters'
  1064. },
  1065. // Initial render method
  1066. render: function() {
  1067. var self = this;
  1068. this.search();
  1069. this.uploader();
  1070. this.collection = new themes.Collection();
  1071. // Bump `collection.currentQuery.page` and request more themes if we hit the end of the page.
  1072. this.listenTo( this, 'theme:end', function() {
  1073. // Make sure we are not already loading
  1074. if ( self.collection.loadingThemes ) {
  1075. return;
  1076. }
  1077. // Set loadingThemes to true and bump page instance of currentQuery.
  1078. self.collection.loadingThemes = true;
  1079. self.collection.currentQuery.page++;
  1080. // Use currentQuery.page to build the themes request.
  1081. _.extend( self.collection.currentQuery.request, { page: self.collection.currentQuery.page } );
  1082. self.collection.query( self.collection.currentQuery.request );
  1083. });
  1084. this.listenTo( this.collection, 'query:success', function() {
  1085. $( 'body' ).removeClass( 'loading-content' );
  1086. $( '.theme-browser' ).find( 'div.error' ).remove();
  1087. });
  1088. this.listenTo( this.collection, 'query:fail', function() {
  1089. $( 'body' ).removeClass( 'loading-content' );
  1090. $( '.theme-browser' ).find( 'div.error' ).remove();
  1091. $( '.theme-browser' ).find( 'div.themes' ).before( '<div class="error"><p>' + l10n.error + '</p></div>' );
  1092. });
  1093. if ( this.view ) {
  1094. this.view.remove();
  1095. }
  1096. // Set ups the view and passes the section argument
  1097. this.view = new themes.view.Themes({
  1098. collection: this.collection,
  1099. parent: this
  1100. });
  1101. // Reset pagination every time the install view handler is run
  1102. this.page = 0;
  1103. // Render and append
  1104. this.$el.find( '.themes' ).remove();
  1105. this.view.render();
  1106. this.$el.find( '.theme-browser' ).append( this.view.el ).addClass( 'rendered' );
  1107. },
  1108. // Handles all the rendering of the public theme directory
  1109. browse: function( section ) {
  1110. // Create a new collection with the proper theme data
  1111. // for each section
  1112. this.collection.query( { browse: section } );
  1113. },
  1114. // Sorting navigation
  1115. onSort: function( event ) {
  1116. var $el = $( event.target ),
  1117. sort = $el.data( 'sort' );
  1118. event.preventDefault();
  1119. $( 'body' ).removeClass( 'filters-applied show-filters' );
  1120. // Bail if this is already active
  1121. if ( $el.hasClass( this.activeClass ) ) {
  1122. return;
  1123. }
  1124. this.sort( sort );
  1125. // Trigger a router.naviagte update
  1126. themes.router.navigate( themes.router.baseUrl( themes.router.browsePath + sort ) );
  1127. },
  1128. sort: function( sort ) {
  1129. this.clearSearch();
  1130. $( '.filter-links li > a, .theme-filter' ).removeClass( this.activeClass );
  1131. $( '[data-sort="' + sort + '"]' ).addClass( this.activeClass );
  1132. this.browse( sort );
  1133. },
  1134. // Filters and Tags
  1135. onFilter: function( event ) {
  1136. var request,
  1137. $el = $( event.target ),
  1138. filter = $el.data( 'filter' );
  1139. // Bail if this is already active
  1140. if ( $el.hasClass( this.activeClass ) ) {
  1141. return;
  1142. }
  1143. $( '.filter-links li > a, .theme-section' ).removeClass( this.activeClass );
  1144. $el.addClass( this.activeClass );
  1145. if ( ! filter ) {
  1146. return;
  1147. }
  1148. // Construct the filter request
  1149. // using the default values
  1150. filter = _.union( filter, this.filtersChecked() );
  1151. request = { tag: [ filter ] };
  1152. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1153. // or searching the local cache
  1154. this.collection.query( request );
  1155. },
  1156. // Clicking on a checkbox to add another filter to the request
  1157. addFilter: function() {
  1158. this.filtersChecked();
  1159. },
  1160. // Applying filters triggers a tag request
  1161. applyFilters: function( event ) {
  1162. var name,
  1163. tags = this.filtersChecked(),
  1164. request = { tag: tags },
  1165. filteringBy = $( '.filtered-by .tags' );
  1166. if ( event ) {
  1167. event.preventDefault();
  1168. }
  1169. $( 'body' ).addClass( 'filters-applied' );
  1170. $( '.filter-links li > a.current' ).removeClass( 'current' );
  1171. filteringBy.empty();
  1172. _.each( tags, function( tag ) {
  1173. name = $( 'label[for="filter-id-' + tag + '"]' ).text();
  1174. filteringBy.append( '<span class="tag">' + name + '</span>' );
  1175. });
  1176. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1177. // or searching the local cache
  1178. this.collection.query( request );
  1179. },
  1180. // Get the checked filters
  1181. // @return {array} of tags or false
  1182. filtersChecked: function() {
  1183. var items = $( '.filter-group' ).find( ':checkbox' ),
  1184. tags = [];
  1185. _.each( items.filter( ':checked' ), function( item ) {
  1186. tags.push( $( item ).prop( 'value' ) );
  1187. });
  1188. // When no filters are checked, restore initial state and return
  1189. if ( tags.length === 0 ) {
  1190. $( '.filter-drawer .apply-filters' ).find( 'span' ).text( '' );
  1191. $( '.filter-drawer .clear-filters' ).hide();
  1192. $( 'body' ).removeClass( 'filters-applied' );
  1193. return false;
  1194. }
  1195. $( '.filter-drawer .apply-filters' ).find( 'span' ).text( tags.length );
  1196. $( '.filter-drawer .clear-filters' ).css( 'display', 'inline-block' );
  1197. return tags;
  1198. },
  1199. activeClass: 'current',
  1200. // Overwrite search container class to append search
  1201. // in new location
  1202. searchContainer: $( '.wp-filter .search-form' ),
  1203. uploader: function() {
  1204. $( 'a.upload' ).on( 'click', function( event ) {
  1205. event.preventDefault();
  1206. $( 'body' ).addClass( 'show-upload-theme' );
  1207. themes.router.navigate( themes.router.baseUrl( '?upload' ), { replace: true } );
  1208. });
  1209. $( 'a.browse-themes' ).on( 'click', function( event ) {
  1210. event.preventDefault();
  1211. $( 'body' ).removeClass( 'show-upload-theme' );
  1212. themes.router.navigate( themes.router.baseUrl( '' ), { replace: true } );
  1213. });
  1214. },
  1215. // Toggle the full filters navigation
  1216. moreFilters: function( event ) {
  1217. event.preventDefault();
  1218. if ( $( 'body' ).hasClass( 'filters-applied' ) ) {
  1219. return this.backToFilters();
  1220. }
  1221. // If the filters section is opened and filters are checked
  1222. // run the relevant query collapsing to filtered-by state
  1223. if ( $( 'body' ).hasClass( 'show-filters' ) && this.filtersChecked() ) {
  1224. return this.addFilter();
  1225. }
  1226. this.clearSearch();
  1227. themes.router.navigate( themes.router.baseUrl( '' ) );
  1228. $( 'body' ).toggleClass( 'show-filters' );
  1229. },
  1230. // Clears all the checked filters
  1231. // @uses filtersChecked()
  1232. clearFilters: function( event ) {
  1233. var items = $( '.filter-group' ).find( ':checkbox' ),
  1234. self = this;
  1235. event.preventDefault();
  1236. _.each( items.filter( ':checked' ), function( item ) {
  1237. $( item ).prop( 'checked', false );
  1238. return self.filtersChecked();
  1239. });
  1240. },
  1241. backToFilters: function( event ) {
  1242. if ( event ) {
  1243. event.preventDefault();
  1244. }
  1245. $( 'body' ).removeClass( 'filters-applied' );
  1246. },
  1247. clearSearch: function() {
  1248. $( '#wp-filter-search-input').val( '' );
  1249. }
  1250. });
  1251. themes.InstallerRouter = Backbone.Router.extend({
  1252. routes: {
  1253. 'theme-install.php?theme=:slug': 'preview',
  1254. 'theme-install.php?browse=:sort': 'sort',
  1255. 'theme-install.php?upload': 'upload',
  1256. 'theme-install.php?search=:query': 'search',
  1257. 'theme-install.php': 'sort'
  1258. },
  1259. baseUrl: function( url ) {
  1260. return 'theme-install.php' + url;
  1261. },
  1262. themePath: '?theme=',
  1263. browsePath: '?browse=',
  1264. searchPath: '?search=',
  1265. search: function( query ) {
  1266. $( '.wp-filter-search' ).val( query );
  1267. },
  1268. navigate: function() {
  1269. if ( Backbone.history._hasPushState ) {
  1270. Backbone.Router.prototype.navigate.apply( this, arguments );
  1271. }
  1272. }
  1273. });
  1274. themes.RunInstaller = {
  1275. init: function() {
  1276. // Set up the view
  1277. // Passes the default 'section' as an option
  1278. this.view = new themes.view.Installer({
  1279. section: 'featured',
  1280. SearchView: themes.view.InstallerSearch
  1281. });
  1282. // Render results
  1283. this.render();
  1284. },
  1285. render: function() {
  1286. // Render results
  1287. this.view.render();
  1288. this.routes();
  1289. Backbone.history.start({
  1290. root: themes.data.settings.adminUrl,
  1291. pushState: true,
  1292. hashChange: false
  1293. });
  1294. },
  1295. routes: function() {
  1296. var self = this,
  1297. request = {};
  1298. // Bind to our global `wp.themes` object
  1299. // so that the router is available to sub-views
  1300. themes.router = new themes.InstallerRouter();
  1301. // Handles `theme` route event
  1302. // Queries the API for the passed theme slug
  1303. themes.router.on( 'route:preview', function( slug ) {
  1304. request.theme = slug;
  1305. self.view.collection.query( request );
  1306. });
  1307. // Handles sorting / browsing routes
  1308. // Also handles the root URL triggering a sort request
  1309. // for `featured`, the default view
  1310. themes.router.on( 'route:sort', function( sort ) {
  1311. if ( ! sort ) {
  1312. sort = 'featured';
  1313. }
  1314. self.view.sort( sort );
  1315. self.view.trigger( 'theme:close' );
  1316. });
  1317. // Support the `upload` route by going straight to upload section
  1318. themes.router.on( 'route:upload', function() {
  1319. $( 'a.upload' ).trigger( 'click' );
  1320. });
  1321. // The `search` route event. The router populates the input field.
  1322. themes.router.on( 'route:search', function() {
  1323. $( '.wp-filter-search' ).focus().trigger( 'keyup' );
  1324. });
  1325. this.extraRoutes();
  1326. },
  1327. extraRoutes: function() {
  1328. return false;
  1329. }
  1330. };
  1331. // Ready...
  1332. $( document ).ready(function() {
  1333. if ( themes.isInstall ) {
  1334. themes.RunInstaller.init();
  1335. } else {
  1336. themes.Run.init();
  1337. }
  1338. $( '.broken-themes .delete-theme' ).on( 'click', function() {
  1339. return confirm( _wpThemeSettings.settings.confirmDelete );
  1340. });
  1341. });
  1342. })( jQuery );
  1343. // Align theme browser thickbox
  1344. var tb_position;
  1345. jQuery(document).ready( function($) {
  1346. tb_position = function() {
  1347. var tbWindow = $('#TB_window'),
  1348. width = $(window).width(),
  1349. H = $(window).height(),
  1350. W = ( 1040 < width ) ? 1040 : width,
  1351. adminbar_height = 0;
  1352. if ( $('#wpadminbar').length ) {
  1353. adminbar_height = parseInt( $('#wpadminbar').css('height'), 10 );
  1354. }
  1355. if ( tbWindow.size() ) {
  1356. tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
  1357. $('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
  1358. tbWindow.css({'margin-left': '-' + parseInt( ( ( W - 50 ) / 2 ), 10 ) + 'px'});
  1359. if ( typeof document.body.style.maxWidth !== 'undefined' ) {
  1360. tbWindow.css({'top': 20 + adminbar_height + 'px', 'margin-top': '0'});
  1361. }
  1362. }
  1363. };
  1364. $(window).resize(function(){ tb_position(); });
  1365. });