PageRenderTime 60ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-admin/js/theme.js

https://gitlab.com/spot-software/company-website
JavaScript | 1781 lines | 1077 code | 369 blank | 335 comment | 135 complexity | 3715b37b10edab644542406f0caca236 MD5 | raw file
Possible License(s): MIT, Apache-2.0, GPL-3.0
  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 h1: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. event = event || window.event;
  366. // Bail if the user scrolled on a touch device
  367. if ( this.touchDrag === true ) {
  368. return this.touchDrag = false;
  369. }
  370. // Allow direct link path to installing a theme.
  371. if ( $( event.target ).hasClass( 'button-primary' ) ) {
  372. return;
  373. }
  374. // 'enter' and 'space' keys expand the details view when a theme is :focused
  375. if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
  376. return;
  377. }
  378. // pressing enter while focused on the buttons shouldn't open the preview
  379. if ( event.type === 'keydown' && event.which !== 13 && $( ':focus' ).hasClass( 'button' ) ) {
  380. return;
  381. }
  382. event.preventDefault();
  383. event = event || window.event;
  384. // Set focus to current theme.
  385. themes.focusedTheme = this.$el;
  386. // Construct a new Preview view.
  387. preview = new themes.view.Preview({
  388. model: this.model
  389. });
  390. // Render the view and append it.
  391. preview.render();
  392. this.setNavButtonsState();
  393. // Hide previous/next navigation if there is only one theme
  394. if ( this.model.collection.length === 1 ) {
  395. preview.$el.addClass( 'no-navigation' );
  396. } else {
  397. preview.$el.removeClass( 'no-navigation' );
  398. }
  399. // Append preview
  400. $( 'div.wrap' ).append( preview.el );
  401. // Listen to our preview object
  402. // for `theme:next` and `theme:previous` events.
  403. this.listenTo( preview, 'theme:next', function() {
  404. // Keep local track of current theme model.
  405. current = self.model;
  406. // If we have ventured away from current model update the current model position.
  407. if ( ! _.isUndefined( self.current ) ) {
  408. current = self.current;
  409. }
  410. // Get next theme model.
  411. self.current = self.model.collection.at( self.model.collection.indexOf( current ) + 1 );
  412. // If we have no more themes, bail.
  413. if ( _.isUndefined( self.current ) ) {
  414. self.options.parent.parent.trigger( 'theme:end' );
  415. return self.current = current;
  416. }
  417. preview.model = self.current;
  418. // Render and append.
  419. preview.render();
  420. this.setNavButtonsState();
  421. $( '.next-theme' ).focus();
  422. })
  423. .listenTo( preview, 'theme:previous', function() {
  424. // Keep track of current theme model.
  425. current = self.model;
  426. // Bail early if we are at the beginning of the collection
  427. if ( self.model.collection.indexOf( self.current ) === 0 ) {
  428. return;
  429. }
  430. // If we have ventured away from current model update the current model position.
  431. if ( ! _.isUndefined( self.current ) ) {
  432. current = self.current;
  433. }
  434. // Get previous theme model.
  435. self.current = self.model.collection.at( self.model.collection.indexOf( current ) - 1 );
  436. // If we have no more themes, bail.
  437. if ( _.isUndefined( self.current ) ) {
  438. return;
  439. }
  440. preview.model = self.current;
  441. // Render and append.
  442. preview.render();
  443. this.setNavButtonsState();
  444. $( '.previous-theme' ).focus();
  445. });
  446. this.listenTo( preview, 'preview:close', function() {
  447. self.current = self.model;
  448. });
  449. },
  450. // Handles .disabled classes for previous/next buttons in theme installer preview
  451. setNavButtonsState: function() {
  452. var $themeInstaller = $( '.theme-install-overlay' ),
  453. current = _.isUndefined( this.current ) ? this.model : this.current;
  454. // Disable previous at the zero position
  455. if ( 0 === this.model.collection.indexOf( current ) ) {
  456. $themeInstaller.find( '.previous-theme' ).addClass( 'disabled' );
  457. }
  458. // Disable next if the next model is undefined
  459. if ( _.isUndefined( this.model.collection.at( this.model.collection.indexOf( current ) + 1 ) ) ) {
  460. $themeInstaller.find( '.next-theme' ).addClass( 'disabled' );
  461. }
  462. }
  463. });
  464. // Theme Details view
  465. // Set ups a modal overlay with the expanded theme data
  466. themes.view.Details = wp.Backbone.View.extend({
  467. // Wrap theme data on a div.theme element
  468. className: 'theme-overlay',
  469. events: {
  470. 'click': 'collapse',
  471. 'click .delete-theme': 'deleteTheme',
  472. 'click .left': 'previousTheme',
  473. 'click .right': 'nextTheme'
  474. },
  475. // The HTML template for the theme overlay
  476. html: themes.template( 'theme-single' ),
  477. render: function() {
  478. var data = this.model.toJSON();
  479. this.$el.html( this.html( data ) );
  480. // Renders active theme styles
  481. this.activeTheme();
  482. // Set up navigation events
  483. this.navigation();
  484. // Checks screenshot size
  485. this.screenshotCheck( this.$el );
  486. // Contain "tabbing" inside the overlay
  487. this.containFocus( this.$el );
  488. },
  489. // Adds a class to the currently active theme
  490. // and to the overlay in detailed view mode
  491. activeTheme: function() {
  492. // Check the model has the active property
  493. this.$el.toggleClass( 'active', this.model.get( 'active' ) );
  494. },
  495. // Keeps :focus within the theme details elements
  496. containFocus: function( $el ) {
  497. var $target;
  498. // Move focus to the primary action
  499. _.delay( function() {
  500. $( '.theme-wrap a.button-primary:visible' ).focus();
  501. }, 500 );
  502. $el.on( 'keydown.wp-themes', function( event ) {
  503. // Tab key
  504. if ( event.which === 9 ) {
  505. $target = $( event.target );
  506. // Keep focus within the overlay by making the last link on theme actions
  507. // switch focus to button.left on tabbing and vice versa
  508. if ( $target.is( 'button.left' ) && event.shiftKey ) {
  509. $el.find( '.theme-actions a:last-child' ).focus();
  510. event.preventDefault();
  511. } else if ( $target.is( '.theme-actions a:last-child' ) ) {
  512. $el.find( 'button.left' ).focus();
  513. event.preventDefault();
  514. }
  515. }
  516. });
  517. },
  518. // Single theme overlay screen
  519. // It's shown when clicking a theme
  520. collapse: function( event ) {
  521. var self = this,
  522. scroll;
  523. event = event || window.event;
  524. // Prevent collapsing detailed view when there is only one theme available
  525. if ( themes.data.themes.length === 1 ) {
  526. return;
  527. }
  528. // Detect if the click is inside the overlay
  529. // and don't close it unless the target was
  530. // the div.back button
  531. if ( $( event.target ).is( '.theme-backdrop' ) || $( event.target ).is( '.close' ) || event.keyCode === 27 ) {
  532. // Add a temporary closing class while overlay fades out
  533. $( 'body' ).addClass( 'closing-overlay' );
  534. // With a quick fade out animation
  535. this.$el.fadeOut( 130, function() {
  536. // Clicking outside the modal box closes the overlay
  537. $( 'body' ).removeClass( 'closing-overlay' );
  538. // Handle event cleanup
  539. self.closeOverlay();
  540. // Get scroll position to avoid jumping to the top
  541. scroll = document.body.scrollTop;
  542. // Clean the url structure
  543. themes.router.navigate( themes.router.baseUrl( '' ) );
  544. // Restore scroll position
  545. document.body.scrollTop = scroll;
  546. // Return focus to the theme div
  547. if ( themes.focusedTheme ) {
  548. themes.focusedTheme.focus();
  549. }
  550. });
  551. }
  552. },
  553. // Handles .disabled classes for next/previous buttons
  554. navigation: function() {
  555. // Disable Left/Right when at the start or end of the collection
  556. if ( this.model.cid === this.model.collection.at(0).cid ) {
  557. this.$el.find( '.left' ).addClass( 'disabled' );
  558. }
  559. if ( this.model.cid === this.model.collection.at( this.model.collection.length - 1 ).cid ) {
  560. this.$el.find( '.right' ).addClass( 'disabled' );
  561. }
  562. },
  563. // Performs the actions to effectively close
  564. // the theme details overlay
  565. closeOverlay: function() {
  566. $( 'body' ).removeClass( 'modal-open' );
  567. this.remove();
  568. this.unbind();
  569. this.trigger( 'theme:collapse' );
  570. },
  571. // Confirmation dialog for deleting a theme
  572. deleteTheme: function() {
  573. return confirm( themes.data.settings.confirmDelete );
  574. },
  575. nextTheme: function() {
  576. var self = this;
  577. self.trigger( 'theme:next', self.model.cid );
  578. return false;
  579. },
  580. previousTheme: function() {
  581. var self = this;
  582. self.trigger( 'theme:previous', self.model.cid );
  583. return false;
  584. },
  585. // Checks if the theme screenshot is the old 300px width version
  586. // and adds a corresponding class if it's true
  587. screenshotCheck: function( el ) {
  588. var screenshot, image;
  589. screenshot = el.find( '.screenshot img' );
  590. image = new Image();
  591. image.src = screenshot.attr( 'src' );
  592. // Width check
  593. if ( image.width && image.width <= 300 ) {
  594. el.addClass( 'small-screenshot' );
  595. }
  596. }
  597. });
  598. // Theme Preview view
  599. // Set ups a modal overlay with the expanded theme data
  600. themes.view.Preview = themes.view.Details.extend({
  601. className: 'wp-full-overlay expanded',
  602. el: '.theme-install-overlay',
  603. events: {
  604. 'click .close-full-overlay': 'close',
  605. 'click .collapse-sidebar': 'collapse',
  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,
  614. data = this.model.toJSON();
  615. this.$el.removeClass( 'iframe-ready' ).html( this.html( data ) );
  616. themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.get( 'id' ) ), { replace: true } );
  617. this.$el.fadeIn( 200, function() {
  618. $( 'body' ).addClass( 'theme-installer-active full-overlay-active' );
  619. $( '.close-full-overlay' ).focus();
  620. });
  621. this.$el.find( 'iframe' ).one( 'load', function() {
  622. self.iframeLoaded();
  623. });
  624. },
  625. iframeLoaded: function() {
  626. this.$el.addClass( 'iframe-ready' );
  627. },
  628. close: function() {
  629. this.$el.fadeOut( 200, function() {
  630. $( 'body' ).removeClass( 'theme-installer-active full-overlay-active' );
  631. // Return focus to the theme div
  632. if ( themes.focusedTheme ) {
  633. themes.focusedTheme.focus();
  634. }
  635. }).removeClass( 'iframe-ready' );
  636. themes.router.navigate( themes.router.baseUrl( '' ) );
  637. this.trigger( 'preview:close' );
  638. this.undelegateEvents();
  639. this.unbind();
  640. return false;
  641. },
  642. collapse: function( event ) {
  643. var $button = $( event.currentTarget );
  644. if ( 'true' === $button.attr( 'aria-expanded' ) ) {
  645. $button.attr({ 'aria-expanded': 'false', 'aria-label': l10n.expandSidebar });
  646. } else {
  647. $button.attr({ 'aria-expanded': 'true', 'aria-label': l10n.collapseSidebar });
  648. }
  649. this.$el.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
  650. return false;
  651. },
  652. keyEvent: function( event ) {
  653. // The escape key closes the preview
  654. if ( event.keyCode === 27 ) {
  655. this.undelegateEvents();
  656. this.close();
  657. }
  658. // The right arrow key, next theme
  659. if ( event.keyCode === 39 ) {
  660. _.once( this.nextTheme() );
  661. }
  662. // The left arrow key, previous theme
  663. if ( event.keyCode === 37 ) {
  664. this.previousTheme();
  665. }
  666. }
  667. });
  668. // Controls the rendering of div.themes,
  669. // a wrapper that will hold all the theme elements
  670. themes.view.Themes = wp.Backbone.View.extend({
  671. className: 'themes',
  672. $overlay: $( 'div.theme-overlay' ),
  673. // Number to keep track of scroll position
  674. // while in theme-overlay mode
  675. index: 0,
  676. // The theme count element
  677. count: $( '.wp-core-ui .theme-count' ),
  678. // The live themes count
  679. liveThemeCount: 0,
  680. initialize: function( options ) {
  681. var self = this;
  682. // Set up parent
  683. this.parent = options.parent;
  684. // Set current view to [grid]
  685. this.setView( 'grid' );
  686. // Move the active theme to the beginning of the collection
  687. self.currentTheme();
  688. // When the collection is updated by user input...
  689. this.listenTo( self.collection, 'update', function() {
  690. self.parent.page = 0;
  691. self.currentTheme();
  692. self.render( this );
  693. });
  694. // Update theme count to full result set when available.
  695. this.listenTo( self.collection, 'query:success', function( count ) {
  696. if ( _.isNumber( count ) ) {
  697. self.count.text( count );
  698. self.announceSearchResults( count );
  699. } else {
  700. self.count.text( self.collection.length );
  701. self.announceSearchResults( self.collection.length );
  702. }
  703. });
  704. this.listenTo( self.collection, 'query:empty', function() {
  705. $( 'body' ).addClass( 'no-results' );
  706. });
  707. this.listenTo( this.parent, 'theme:scroll', function() {
  708. self.renderThemes( self.parent.page );
  709. });
  710. this.listenTo( this.parent, 'theme:close', function() {
  711. if ( self.overlay ) {
  712. self.overlay.closeOverlay();
  713. }
  714. } );
  715. // Bind keyboard events.
  716. $( 'body' ).on( 'keyup', function( event ) {
  717. if ( ! self.overlay ) {
  718. return;
  719. }
  720. // Pressing the right arrow key fires a theme:next event
  721. if ( event.keyCode === 39 ) {
  722. self.overlay.nextTheme();
  723. }
  724. // Pressing the left arrow key fires a theme:previous event
  725. if ( event.keyCode === 37 ) {
  726. self.overlay.previousTheme();
  727. }
  728. // Pressing the escape key fires a theme:collapse event
  729. if ( event.keyCode === 27 ) {
  730. self.overlay.collapse( event );
  731. }
  732. });
  733. },
  734. // Manages rendering of theme pages
  735. // and keeping theme count in sync
  736. render: function() {
  737. // Clear the DOM, please
  738. this.$el.empty();
  739. // If the user doesn't have switch capabilities
  740. // or there is only one theme in the collection
  741. // render the detailed view of the active theme
  742. if ( themes.data.themes.length === 1 ) {
  743. // Constructs the view
  744. this.singleTheme = new themes.view.Details({
  745. model: this.collection.models[0]
  746. });
  747. // Render and apply a 'single-theme' class to our container
  748. this.singleTheme.render();
  749. this.$el.addClass( 'single-theme' );
  750. this.$el.append( this.singleTheme.el );
  751. }
  752. // Generate the themes
  753. // Using page instance
  754. // While checking the collection has items
  755. if ( this.options.collection.size() > 0 ) {
  756. this.renderThemes( this.parent.page );
  757. }
  758. // Display a live theme count for the collection
  759. this.liveThemeCount = this.collection.count ? this.collection.count : this.collection.length;
  760. this.count.text( this.liveThemeCount );
  761. this.announceSearchResults( this.liveThemeCount );
  762. },
  763. // Iterates through each instance of the collection
  764. // and renders each theme module
  765. renderThemes: function( page ) {
  766. var self = this;
  767. self.instance = self.collection.paginate( page );
  768. // If we have no more themes bail
  769. if ( self.instance.size() === 0 ) {
  770. // Fire a no-more-themes event.
  771. this.parent.trigger( 'theme:end' );
  772. return;
  773. }
  774. // Make sure the add-new stays at the end
  775. if ( ! themes.isInstall && page >= 1 ) {
  776. $( '.add-new-theme' ).remove();
  777. }
  778. // Loop through the themes and setup each theme view
  779. self.instance.each( function( theme ) {
  780. self.theme = new themes.view.Theme({
  781. model: theme,
  782. parent: self
  783. });
  784. // Render the views...
  785. self.theme.render();
  786. // and append them to div.themes
  787. self.$el.append( self.theme.el );
  788. // Binds to theme:expand to show the modal box
  789. // with the theme details
  790. self.listenTo( self.theme, 'theme:expand', self.expand, self );
  791. });
  792. // 'Add new theme' element shown at the end of the grid
  793. if ( ! themes.isInstall && themes.data.settings.canInstall ) {
  794. 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>' );
  795. }
  796. this.parent.page++;
  797. },
  798. // Grabs current theme and puts it at the beginning of the collection
  799. currentTheme: function() {
  800. var self = this,
  801. current;
  802. current = self.collection.findWhere({ active: true });
  803. // Move the active theme to the beginning of the collection
  804. if ( current ) {
  805. self.collection.remove( current );
  806. self.collection.add( current, { at:0 } );
  807. }
  808. },
  809. // Sets current view
  810. setView: function( view ) {
  811. return view;
  812. },
  813. // Renders the overlay with the ThemeDetails view
  814. // Uses the current model data
  815. expand: function( id ) {
  816. var self = this;
  817. // Set the current theme model
  818. this.model = self.collection.get( id );
  819. // Trigger a route update for the current model
  820. themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.id ) );
  821. // Sets this.view to 'detail'
  822. this.setView( 'detail' );
  823. $( 'body' ).addClass( 'modal-open' );
  824. // Set up the theme details view
  825. this.overlay = new themes.view.Details({
  826. model: self.model
  827. });
  828. this.overlay.render();
  829. this.$overlay.html( this.overlay.el );
  830. // Bind to theme:next and theme:previous
  831. // triggered by the arrow keys
  832. //
  833. // Keep track of the current model so we
  834. // can infer an index position
  835. this.listenTo( this.overlay, 'theme:next', function() {
  836. // Renders the next theme on the overlay
  837. self.next( [ self.model.cid ] );
  838. })
  839. .listenTo( this.overlay, 'theme:previous', function() {
  840. // Renders the previous theme on the overlay
  841. self.previous( [ self.model.cid ] );
  842. });
  843. },
  844. // This method renders the next theme on the overlay modal
  845. // based on the current position in the collection
  846. // @params [model cid]
  847. next: function( args ) {
  848. var self = this,
  849. model, nextModel;
  850. // Get the current theme
  851. model = self.collection.get( args[0] );
  852. // Find the next model within the collection
  853. nextModel = self.collection.at( self.collection.indexOf( model ) + 1 );
  854. // Sanity check which also serves as a boundary test
  855. if ( nextModel !== undefined ) {
  856. // We have a new theme...
  857. // Close the overlay
  858. this.overlay.closeOverlay();
  859. // Trigger a route update for the current model
  860. self.theme.trigger( 'theme:expand', nextModel.cid );
  861. }
  862. },
  863. // This method renders the previous theme on the overlay modal
  864. // based on the current position in the collection
  865. // @params [model cid]
  866. previous: function( args ) {
  867. var self = this,
  868. model, previousModel;
  869. // Get the current theme
  870. model = self.collection.get( args[0] );
  871. // Find the previous model within the collection
  872. previousModel = self.collection.at( self.collection.indexOf( model ) - 1 );
  873. if ( previousModel !== undefined ) {
  874. // We have a new theme...
  875. // Close the overlay
  876. this.overlay.closeOverlay();
  877. // Trigger a route update for the current model
  878. self.theme.trigger( 'theme:expand', previousModel.cid );
  879. }
  880. },
  881. // Dispatch audible search results feedback message
  882. announceSearchResults: function( count ) {
  883. if ( 0 === count ) {
  884. wp.a11y.speak( l10n.noThemesFound );
  885. } else {
  886. wp.a11y.speak( l10n.themesFound.replace( '%d', count ) );
  887. }
  888. }
  889. });
  890. // Search input view controller.
  891. themes.view.Search = wp.Backbone.View.extend({
  892. tagName: 'input',
  893. className: 'wp-filter-search',
  894. id: 'wp-filter-search-input',
  895. searching: false,
  896. attributes: {
  897. placeholder: l10n.searchPlaceholder,
  898. type: 'search',
  899. 'aria-describedby': 'live-search-desc'
  900. },
  901. events: {
  902. 'input': 'search',
  903. 'keyup': 'search',
  904. 'blur': 'pushState'
  905. },
  906. initialize: function( options ) {
  907. this.parent = options.parent;
  908. this.listenTo( this.parent, 'theme:close', function() {
  909. this.searching = false;
  910. } );
  911. },
  912. search: function( event ) {
  913. // Clear on escape.
  914. if ( event.type === 'keyup' && event.which === 27 ) {
  915. event.target.value = '';
  916. }
  917. /**
  918. * Since doSearch is debounced, it will only run when user input comes to a rest
  919. */
  920. this.doSearch( event );
  921. },
  922. // Runs a search on the theme collection.
  923. doSearch: _.debounce( function( event ) {
  924. var options = {};
  925. this.collection.doSearch( event.target.value );
  926. // if search is initiated and key is not return
  927. if ( this.searching && event.which !== 13 ) {
  928. options.replace = true;
  929. } else {
  930. this.searching = true;
  931. }
  932. // Update the URL hash
  933. if ( event.target.value ) {
  934. themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + event.target.value ), options );
  935. } else {
  936. themes.router.navigate( themes.router.baseUrl( '' ) );
  937. }
  938. }, 500 ),
  939. pushState: function( event ) {
  940. var url = themes.router.baseUrl( '' );
  941. if ( event.target.value ) {
  942. url = themes.router.baseUrl( themes.router.searchPath + event.target.value );
  943. }
  944. this.searching = false;
  945. themes.router.navigate( url );
  946. }
  947. });
  948. // Sets up the routes events for relevant url queries
  949. // Listens to [theme] and [search] params
  950. themes.Router = Backbone.Router.extend({
  951. routes: {
  952. 'themes.php?theme=:slug': 'theme',
  953. 'themes.php?search=:query': 'search',
  954. 'themes.php?s=:query': 'search',
  955. 'themes.php': 'themes',
  956. '': 'themes'
  957. },
  958. baseUrl: function( url ) {
  959. return 'themes.php' + url;
  960. },
  961. themePath: '?theme=',
  962. searchPath: '?search=',
  963. search: function( query ) {
  964. $( '.wp-filter-search' ).val( query );
  965. },
  966. themes: function() {
  967. $( '.wp-filter-search' ).val( '' );
  968. },
  969. navigate: function() {
  970. if ( Backbone.history._hasPushState ) {
  971. Backbone.Router.prototype.navigate.apply( this, arguments );
  972. }
  973. }
  974. });
  975. // Execute and setup the application
  976. themes.Run = {
  977. init: function() {
  978. // Initializes the blog's theme library view
  979. // Create a new collection with data
  980. this.themes = new themes.Collection( themes.data.themes );
  981. // Set up the view
  982. this.view = new themes.view.Appearance({
  983. collection: this.themes
  984. });
  985. this.render();
  986. },
  987. render: function() {
  988. // Render results
  989. this.view.render();
  990. this.routes();
  991. Backbone.history.start({
  992. root: themes.data.settings.adminUrl,
  993. pushState: true,
  994. hashChange: false
  995. });
  996. },
  997. routes: function() {
  998. var self = this;
  999. // Bind to our global thx object
  1000. // so that the object is available to sub-views
  1001. themes.router = new themes.Router();
  1002. // Handles theme details route event
  1003. themes.router.on( 'route:theme', function( slug ) {
  1004. self.view.view.expand( slug );
  1005. });
  1006. themes.router.on( 'route:themes', function() {
  1007. self.themes.doSearch( '' );
  1008. self.view.trigger( 'theme:close' );
  1009. });
  1010. // Handles search route event
  1011. themes.router.on( 'route:search', function() {
  1012. $( '.wp-filter-search' ).trigger( 'keyup' );
  1013. });
  1014. this.extraRoutes();
  1015. },
  1016. extraRoutes: function() {
  1017. return false;
  1018. }
  1019. };
  1020. // Extend the main Search view
  1021. themes.view.InstallerSearch = themes.view.Search.extend({
  1022. events: {
  1023. 'input': 'search',
  1024. 'keyup': 'search'
  1025. },
  1026. // Handles Ajax request for searching through themes in public repo
  1027. search: function( event ) {
  1028. // Tabbing or reverse tabbing into the search input shouldn't trigger a search
  1029. if ( event.type === 'keyup' && ( event.which === 9 || event.which === 16 ) ) {
  1030. return;
  1031. }
  1032. this.collection = this.options.parent.view.collection;
  1033. // Clear on escape.
  1034. if ( event.type === 'keyup' && event.which === 27 ) {
  1035. event.target.value = '';
  1036. }
  1037. this.doSearch( event.target.value );
  1038. },
  1039. doSearch: _.debounce( function( value ) {
  1040. var request = {};
  1041. request.search = value;
  1042. // Intercept an [author] search.
  1043. //
  1044. // If input value starts with `author:` send a request
  1045. // for `author` instead of a regular `search`
  1046. if ( value.substring( 0, 7 ) === 'author:' ) {
  1047. request.search = '';
  1048. request.author = value.slice( 7 );
  1049. }
  1050. // Intercept a [tag] search.
  1051. //
  1052. // If input value starts with `tag:` send a request
  1053. // for `tag` instead of a regular `search`
  1054. if ( value.substring( 0, 4 ) === 'tag:' ) {
  1055. request.search = '';
  1056. request.tag = [ value.slice( 4 ) ];
  1057. }
  1058. $( '.filter-links li > a.current' ).removeClass( 'current' );
  1059. $( 'body' ).removeClass( 'show-filters filters-applied show-favorites-form' );
  1060. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1061. // or searching the local cache
  1062. this.collection.query( request );
  1063. // Set route
  1064. themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + value ), { replace: true } );
  1065. }, 500 )
  1066. });
  1067. themes.view.Installer = themes.view.Appearance.extend({
  1068. el: '#wpbody-content .wrap',
  1069. // Register events for sorting and filters in theme-navigation
  1070. events: {
  1071. 'click .filter-links li > a': 'onSort',
  1072. 'click .theme-filter': 'onFilter',
  1073. 'click .drawer-toggle': 'moreFilters',
  1074. 'click .filter-drawer .apply-filters': 'applyFilters',
  1075. 'click .filter-group [type="checkbox"]': 'addFilter',
  1076. 'click .filter-drawer .clear-filters': 'clearFilters',
  1077. 'click .filtered-by': 'backToFilters',
  1078. 'click .favorites-form-submit' : 'saveUsername',
  1079. 'keyup #wporg-username-input': 'saveUsername'
  1080. },
  1081. // Initial render method
  1082. render: function() {
  1083. var self = this;
  1084. this.search();
  1085. this.uploader();
  1086. this.collection = new themes.Collection();
  1087. // Bump `collection.currentQuery.page` and request more themes if we hit the end of the page.
  1088. this.listenTo( this, 'theme:end', function() {
  1089. // Make sure we are not already loading
  1090. if ( self.collection.loadingThemes ) {
  1091. return;
  1092. }
  1093. // Set loadingThemes to true and bump page instance of currentQuery.
  1094. self.collection.loadingThemes = true;
  1095. self.collection.currentQuery.page++;
  1096. // Use currentQuery.page to build the themes request.
  1097. _.extend( self.collection.currentQuery.request, { page: self.collection.currentQuery.page } );
  1098. self.collection.query( self.collection.currentQuery.request );
  1099. });
  1100. this.listenTo( this.collection, 'query:success', function() {
  1101. $( 'body' ).removeClass( 'loading-content' );
  1102. $( '.theme-browser' ).find( 'div.error' ).remove();
  1103. });
  1104. this.listenTo( this.collection, 'query:fail', function() {
  1105. $( 'body' ).removeClass( 'loading-content' );
  1106. $( '.theme-browser' ).find( 'div.error' ).remove();
  1107. $( '.theme-browser' ).find( 'div.themes' ).before( '<div class="error"><p>' + l10n.error + '</p></div>' );
  1108. });
  1109. if ( this.view ) {
  1110. this.view.remove();
  1111. }
  1112. // Set ups the view and passes the section argument
  1113. this.view = new themes.view.Themes({
  1114. collection: this.collection,
  1115. parent: this
  1116. });
  1117. // Reset pagination every time the install view handler is run
  1118. this.page = 0;
  1119. // Render and append
  1120. this.$el.find( '.themes' ).remove();
  1121. this.view.render();
  1122. this.$el.find( '.theme-browser' ).append( this.view.el ).addClass( 'rendered' );
  1123. },
  1124. // Handles all the rendering of the public theme directory
  1125. browse: function( section ) {
  1126. // Create a new collection with the proper theme data
  1127. // for each section
  1128. this.collection.query( { browse: section } );
  1129. },
  1130. // Sorting navigation
  1131. onSort: function( event ) {
  1132. var $el = $( event.target ),
  1133. sort = $el.data( 'sort' );
  1134. event.preventDefault();
  1135. $( 'body' ).removeClass( 'filters-applied show-filters' );
  1136. // Bail if this is already active
  1137. if ( $el.hasClass( this.activeClass ) ) {
  1138. return;
  1139. }
  1140. this.sort( sort );
  1141. // Trigger a router.naviagte update
  1142. themes.router.navigate( themes.router.baseUrl( themes.router.browsePath + sort ) );
  1143. },
  1144. sort: function( sort ) {
  1145. this.clearSearch();
  1146. $( '.filter-links li > a, .theme-filter' ).removeClass( this.activeClass );
  1147. $( '[data-sort="' + sort + '"]' ).addClass( this.activeClass );
  1148. if ( 'favorites' === sort ) {
  1149. $ ( 'body' ).addClass( 'show-favorites-form' );
  1150. } else {
  1151. $ ( 'body' ).removeClass( 'show-favorites-form' );
  1152. }
  1153. this.browse( sort );
  1154. },
  1155. // Filters and Tags
  1156. onFilter: function( event ) {
  1157. var request,
  1158. $el = $( event.target ),
  1159. filter = $el.data( 'filter' );
  1160. // Bail if this is already active
  1161. if ( $el.hasClass( this.activeClass ) ) {
  1162. return;
  1163. }
  1164. $( '.filter-links li > a, .theme-section' ).removeClass( this.activeClass );
  1165. $el.addClass( this.activeClass );
  1166. if ( ! filter ) {
  1167. return;
  1168. }
  1169. // Construct the filter request
  1170. // using the default values
  1171. filter = _.union( filter, this.filtersChecked() );
  1172. request = { tag: [ filter ] };
  1173. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1174. // or searching the local cache
  1175. this.collection.query( request );
  1176. },
  1177. // Clicking on a checkbox to add another filter to the request
  1178. addFilter: function() {
  1179. this.filtersChecked();
  1180. },
  1181. // Applying filters triggers a tag request
  1182. applyFilters: function( event ) {
  1183. var name,
  1184. tags = this.filtersChecked(),
  1185. request = { tag: tags },
  1186. filteringBy = $( '.filtered-by .tags' );
  1187. if ( event ) {
  1188. event.preventDefault();
  1189. }
  1190. $( 'body' ).addClass( 'filters-applied' );
  1191. $( '.filter-links li > a.current' ).removeClass( 'current' );
  1192. filteringBy.empty();
  1193. _.each( tags, function( tag ) {
  1194. name = $( 'label[for="filter-id-' + tag + '"]' ).text();
  1195. filteringBy.append( '<span class="tag">' + name + '</span>' );
  1196. });
  1197. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1198. // or searching the local cache
  1199. this.collection.query( request );
  1200. },
  1201. // Save the user's WordPress.org username and get his favorite themes.
  1202. saveUsername: function ( event ) {
  1203. var username = $( '#wporg-username-input' ).val(),
  1204. request = { browse: 'favorites', user: username },
  1205. that = this;
  1206. if ( event ) {
  1207. event.preventDefault();
  1208. }
  1209. // save username on enter
  1210. if ( event.type === 'keyup' && event.which !== 13 ) {
  1211. return;
  1212. }
  1213. return wp.ajax.send( 'save-wporg-username', {
  1214. data: {
  1215. username: username
  1216. },
  1217. success: function () {
  1218. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1219. // or searching the local cache
  1220. that.collection.query( request );
  1221. }
  1222. } );
  1223. },
  1224. // Get the checked filters
  1225. // @return {array} of tags or false
  1226. filtersChecked: function() {
  1227. var items = $( '.filter-group' ).find( ':checkbox' ),
  1228. tags = [];
  1229. _.each( items.filter( ':checked' ), function( item ) {
  1230. tags.push( $( item ).prop( 'value' ) );
  1231. });
  1232. // When no filters are checked, restore initial state and return
  1233. if ( tags.length === 0 ) {
  1234. $( '.filter-drawer .apply-filters' ).find( 'span' ).text( '' );
  1235. $( '.filter-drawer .clear-filters' ).hide();
  1236. $( 'body' ).removeClass( 'filters-applied' );
  1237. return false;
  1238. }
  1239. $( '.filter-drawer .apply-filters' ).find( 'span' ).text( tags.length );
  1240. $( '.filter-drawer .clear-filters' ).css( 'display', 'inline-block' );
  1241. return tags;
  1242. },
  1243. activeClass: 'current',
  1244. // Overwrite search container class to append search
  1245. // in new location
  1246. searchContainer: $( '.wp-filter .search-form' ),
  1247. uploader: function() {
  1248. $( 'a.upload' ).on( 'click', function( event ) {
  1249. event.preventDefault();
  1250. $( 'body' ).addClass( 'show-upload-theme' );
  1251. themes.router.navigate( themes.router.baseUrl( '?upload' ), { replace: true } );
  1252. });
  1253. $( 'a.browse-themes' ).on( 'click', function( event ) {
  1254. event.preventDefault();
  1255. $( 'body' ).removeClass( 'show-upload-theme' );
  1256. themes.router.navigate( themes.router.baseUrl( '' ), { replace: true } );
  1257. });
  1258. },
  1259. // Toggle the full filters navigation
  1260. moreFilters: function( event ) {
  1261. event.preventDefault();
  1262. if ( $( 'body' ).hasClass( 'filters-applied' ) ) {
  1263. return this.backToFilters();
  1264. }
  1265. // If the filters section is opened and filters are checked
  1266. // run the relevant query collapsing to filtered-by state
  1267. if ( $( 'body' ).hasClass( 'show-filters' ) && this.filtersChecked() ) {
  1268. return this.addFilter();
  1269. }
  1270. this.clearSearch();
  1271. themes.router.navigate( themes.router.baseUrl( '' ) );
  1272. $( 'body' ).toggleClass( 'show-filters' );
  1273. },
  1274. // Clears all the checked filters
  1275. // @uses filtersChecked()
  1276. clearFilters: function( event ) {
  1277. var items = $( '.filter-group' ).find( ':checkbox' ),
  1278. self = this;
  1279. event.preventDefault();
  1280. _.each( items.filter( ':checked' ), function( item ) {
  1281. $( item ).prop( 'checked', false );
  1282. return self.filtersChecked();
  1283. });
  1284. },
  1285. backToFilters: function( event ) {
  1286. if ( event ) {
  1287. event.preventDefault();
  1288. }
  1289. $( 'body' ).removeClass( 'filters-applied' );
  1290. },
  1291. clearSearch: function() {
  1292. $( '#wp-filter-search-input').val( '' );
  1293. }
  1294. });
  1295. themes.InstallerRouter = Backbone.Router.extend({
  1296. routes: {
  1297. 'theme-install.php?theme=:slug': 'preview',
  1298. 'theme-install.php?browse=:sort': 'sort',
  1299. 'theme-install.php?upload': 'upload',
  1300. 'theme-install.php?search=:query': 'search',
  1301. 'theme-install.php': 'sort'
  1302. },
  1303. baseUrl: function( url ) {
  1304. return 'theme-install.php' + url;
  1305. },
  1306. themePath: '?theme=',
  1307. browsePath: '?browse=',
  1308. searchPath: '?search=',
  1309. search: function( query ) {
  1310. $( '.wp-filter-search' ).val( query );
  1311. },
  1312. navigate: function() {
  1313. if ( Backbone.history._hasPushState ) {
  1314. Backbone.Router.prototype.navigate.apply( this, arguments );
  1315. }
  1316. }
  1317. });
  1318. themes.RunInstaller = {
  1319. init: function() {
  1320. // Set up the view
  1321. // Passes the default 'section' as an option
  1322. this.view = new themes.view.Installer({
  1323. section: 'featured',
  1324. SearchView: themes.view.InstallerSearch
  1325. });
  1326. // Render results
  1327. this.render();
  1328. },
  1329. render: function() {
  1330. // Render results
  1331. this.view.render();
  1332. this.routes();
  1333. Backbone.history.start({
  1334. root: themes.data.settings.adminUrl,
  1335. pushState: true,
  1336. hashChange: false
  1337. });
  1338. },
  1339. routes: function() {
  1340. var self = this,
  1341. request = {};
  1342. // Bind to our global `wp.themes` object
  1343. // so that the router is available to sub-views
  1344. themes.router = new themes.InstallerRouter();
  1345. // Handles `theme` route event
  1346. // Queries the API for the passed theme slug
  1347. themes.router.on( 'route:preview', function( slug ) {
  1348. request.theme = slug;
  1349. self.view.collection.query( request );
  1350. self.view.collection.once( 'update', function() {
  1351. self.view.view.theme.preview();
  1352. });
  1353. });
  1354. // Handles sorting / browsing routes
  1355. // Also handles the root URL triggering a sort request
  1356. // for `featured`, the default view
  1357. themes.router.on( 'route:sort', function( sort ) {
  1358. if ( ! sort ) {
  1359. sort = 'featured';
  1360. }
  1361. self.view.sort( sort );
  1362. self.view.trigger( 'theme:close' );
  1363. });
  1364. // Support the `upload` route by going straight to upload section
  1365. themes.router.on( 'route:upload', function() {
  1366. $( 'a.upload' ).trigger( 'click' );
  1367. });
  1368. // The `search` route event. The router populates the input field.
  1369. themes.router.on( 'route:search', function() {
  1370. $( '.wp-filter-search' ).focus().trigger( 'keyup' );
  1371. });
  1372. this.extraRoutes();
  1373. },
  1374. extraRoutes: function() {
  1375. return false;
  1376. }
  1377. };
  1378. // Ready...
  1379. $( document ).ready(function() {
  1380. if ( themes.isInstall ) {
  1381. themes.RunInstaller.init();
  1382. } else {
  1383. themes.Run.init();
  1384. }
  1385. $( '.broken-themes .delete-theme' ).on( 'click', function() {
  1386. return confirm( _wpThemeSettings.settings.confirmDelete );
  1387. });
  1388. });
  1389. })( jQuery );
  1390. // Align theme browser thickbox
  1391. var tb_position;
  1392. jQuery(document).ready( function($) {
  1393. tb_position = function() {
  1394. var tbWindow = $('#TB_window'),
  1395. width = $(window).width(),
  1396. H = $(window).height(),
  1397. W = ( 1040 < width ) ? 1040 : width,
  1398. adminbar_height = 0;
  1399. if ( $('#wpadminbar').length ) {
  1400. adminbar_height = parseInt( $('#wpadminbar').css('height'), 10 );
  1401. }
  1402. if ( tbWindow.size() ) {
  1403. tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
  1404. $('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
  1405. tbWindow.css({'margin-left': '-' + parseInt( ( ( W - 50 ) / 2 ), 10 ) + 'px'});
  1406. if ( typeof document.body.style.maxWidth !== 'undefined' ) {
  1407. tbWindow.css({'top': 20 + adminbar_height + 'px', 'margin-top': '0'});
  1408. }
  1409. }
  1410. };
  1411. $(window).resize(function(){ tb_position(); });
  1412. });