PageRenderTime 51ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/files/wordpress/3.8/js/theme.js

https://gitlab.com/Mirros/jsdelivr
JavaScript | 738 lines | 401 code | 157 blank | 180 comment | 48 complexity | e3a25a3cb6290e46ba89b17a32c62f6c 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. // Setup app structure
  12. _.extend( themes, { model: {}, view: {}, routes: {}, router: {}, template: wp.template });
  13. themes.model = Backbone.Model.extend({});
  14. // Main view controller for themes.php
  15. // Unifies and renders all available views
  16. themes.view.Appearance = wp.Backbone.View.extend({
  17. el: '#wpbody-content .wrap .theme-browser',
  18. window: $( window ),
  19. // Pagination instance
  20. page: 0,
  21. // Sets up a throttler for binding to 'scroll'
  22. initialize: function() {
  23. // Scroller checks how far the scroll position is
  24. _.bindAll( this, 'scroller' );
  25. // Bind to the scroll event and throttle
  26. // the results from this.scroller
  27. this.window.bind( 'scroll', _.throttle( this.scroller, 300 ) );
  28. },
  29. // Main render control
  30. render: function() {
  31. // Setup the main theme view
  32. // with the current theme collection
  33. this.view = new themes.view.Themes({
  34. collection: this.collection,
  35. parent: this
  36. });
  37. // Render search form.
  38. this.search();
  39. // Render and append
  40. this.view.render();
  41. this.$el.empty().append( this.view.el ).addClass('rendered');
  42. this.$el.append( '<br class="clear"/>' );
  43. },
  44. // Search input and view
  45. // for current theme collection
  46. search: function() {
  47. var view,
  48. self = this;
  49. // Don't render the search if there is only one theme
  50. if ( themes.data.themes.length === 1 ) {
  51. return;
  52. }
  53. view = new themes.view.Search({ collection: self.collection });
  54. // Render and append after screen title
  55. view.render();
  56. $('#wpbody h2:first')
  57. .append( $.parseHTML( '<label class="screen-reader-text" for="theme-search-input">' + l10n.search + '</label>' ) )
  58. .append( view.el );
  59. },
  60. // Checks when the user gets close to the bottom
  61. // of the mage and triggers a theme:scroll event
  62. scroller: function() {
  63. var self = this,
  64. bottom, threshold;
  65. bottom = this.window.scrollTop() + self.window.height();
  66. threshold = self.$el.offset().top + self.$el.outerHeight( false ) - self.window.height();
  67. threshold = Math.round( threshold * 0.9 );
  68. if ( bottom > threshold ) {
  69. this.trigger( 'theme:scroll' );
  70. }
  71. }
  72. });
  73. // Set up the Collection for our theme data
  74. // @has 'id' 'name' 'screenshot' 'author' 'authorURI' 'version' 'active' ...
  75. themes.Collection = Backbone.Collection.extend({
  76. model: themes.model,
  77. // Search terms
  78. terms: '',
  79. // Controls searching on the current theme collection
  80. // and triggers an update event
  81. doSearch: function( value ) {
  82. // Don't do anything if we've already done this search
  83. // Useful because the Search handler fires multiple times per keystroke
  84. if ( this.terms === value ) {
  85. return;
  86. }
  87. // Updates terms with the value passed
  88. this.terms = value;
  89. // If we have terms, run a search...
  90. if ( this.terms.length > 0 ) {
  91. this.search( this.terms );
  92. }
  93. // If search is blank, show all themes
  94. // Useful for resetting the views when you clean the input
  95. if ( this.terms === '' ) {
  96. this.reset( themes.data.themes );
  97. }
  98. // Trigger an 'update' event
  99. this.trigger( 'update' );
  100. },
  101. // Performs a search within the collection
  102. // @uses RegExp
  103. search: function( term ) {
  104. var match, results, haystack;
  105. // Start with a full collection
  106. this.reset( themes.data.themes, { silent: true } );
  107. // The RegExp object to match
  108. //
  109. // Consider spaces as word delimiters and match the whole string
  110. // so matching terms can be combined
  111. term = term.replace( ' ', ')(?=.*' );
  112. match = new RegExp( '^(?=.*' + term + ').+', 'i' );
  113. // Find results
  114. // _.filter and .test
  115. results = this.filter( function( data ) {
  116. haystack = _.union( data.get( 'name' ), data.get( 'description' ), data.get( 'author' ), data.get( 'tags' ) );
  117. if ( match.test( data.get( 'author' ) ) && term.length > 2 ) {
  118. data.set( 'displayAuthor', true );
  119. }
  120. return match.test( haystack );
  121. });
  122. this.reset( results );
  123. },
  124. // Paginates the collection with a helper method
  125. // that slices the collection
  126. paginate: function( instance ) {
  127. var collection = this;
  128. instance = instance || 0;
  129. // Themes per instance are set at 15
  130. collection = _( collection.rest( 15 * instance ) );
  131. collection = _( collection.first( 15 ) );
  132. return collection;
  133. }
  134. });
  135. // This is the view that controls each theme item
  136. // that will be displayed on the screen
  137. themes.view.Theme = wp.Backbone.View.extend({
  138. // Wrap theme data on a div.theme element
  139. className: 'theme',
  140. // Reflects which theme view we have
  141. // 'grid' (default) or 'detail'
  142. state: 'grid',
  143. // The HTML template for each element to be rendered
  144. html: themes.template( 'theme' ),
  145. events: {
  146. 'click': 'expand',
  147. 'touchend': 'expand',
  148. 'touchmove': 'preventExpand'
  149. },
  150. touchDrag: false,
  151. render: function() {
  152. var data = this.model.toJSON();
  153. // Render themes using the html template
  154. this.$el.html( this.html( data ) );
  155. // Renders active theme styles
  156. this.activeTheme();
  157. if ( this.model.get( 'displayAuthor' ) ) {
  158. this.$el.addClass( 'display-author' );
  159. }
  160. },
  161. // Adds a class to the currently active theme
  162. // and to the overlay in detailed view mode
  163. activeTheme: function() {
  164. if ( this.model.get( 'active' ) ) {
  165. this.$el.addClass( 'active' );
  166. }
  167. },
  168. // Single theme overlay screen
  169. // It's shown when clicking a theme
  170. expand: function( event ) {
  171. var self = this;
  172. // Bail if the user scrolled on a touch device
  173. if ( this.touchDrag === true ) {
  174. return this.touchDrag = false;
  175. }
  176. event = event || window.event;
  177. // Prevent the modal from showing when the user clicks
  178. // one of the direct action buttons
  179. if ( $( event.target ).is( '.theme-actions a' ) ) {
  180. return;
  181. }
  182. this.trigger( 'theme:expand', self.model.cid );
  183. },
  184. preventExpand: function() {
  185. this.touchDrag = true;
  186. }
  187. });
  188. // Theme Details view
  189. // Set ups a modal overlay with the expanded theme data
  190. themes.view.Details = wp.Backbone.View.extend({
  191. // Wrap theme data on a div.theme element
  192. className: 'theme-overlay',
  193. events: {
  194. 'click': 'collapse',
  195. 'click .delete-theme': 'deleteTheme',
  196. 'click .left': 'previousTheme',
  197. 'click .right': 'nextTheme'
  198. },
  199. // The HTML template for the theme overlay
  200. html: themes.template( 'theme-single' ),
  201. render: function() {
  202. var data = this.model.toJSON();
  203. this.$el.html( this.html( data ) );
  204. // Renders active theme styles
  205. this.activeTheme();
  206. // Set up navigation events
  207. this.navigation();
  208. // Checks screenshot size
  209. this.screenshotCheck( this.$el );
  210. },
  211. // Adds a class to the currently active theme
  212. // and to the overlay in detailed view mode
  213. activeTheme: function() {
  214. // Check the model has the active property
  215. this.$el.toggleClass( 'active', this.model.get( 'active' ) );
  216. },
  217. // Single theme overlay screen
  218. // It's shown when clicking a theme
  219. collapse: function( event ) {
  220. var self = this,
  221. scroll;
  222. event = event || window.event;
  223. // Prevent collapsing detailed view when there is only one theme available
  224. if ( themes.data.themes.length === 1 ) {
  225. return;
  226. }
  227. // Detect if the click is inside the overlay
  228. // and don't close it unless the target was
  229. // the div.back button
  230. if ( $( event.target ).is( '.theme-backdrop' ) || $( event.target ).is( 'div.close' ) || event.keyCode === 27 ) {
  231. // Add a temporary closing class while overlay fades out
  232. $( 'body' ).addClass( 'closing-overlay' );
  233. // With a quick fade out animation
  234. this.$el.fadeOut( 130, function() {
  235. // Clicking outside the modal box closes the overlay
  236. $( 'body' ).removeClass( 'theme-overlay-open closing-overlay' );
  237. // Handle event cleanup
  238. self.closeOverlay();
  239. // Get scroll position to avoid jumping to the top
  240. scroll = document.body.scrollTop;
  241. // Clean the url structure
  242. themes.router.navigate( themes.router.baseUrl( '' ), { replace: true } );
  243. // Restore scroll position
  244. document.body.scrollTop = scroll;
  245. });
  246. }
  247. },
  248. // Handles .disabled classes for next/previous buttons
  249. navigation: function() {
  250. // Disable Left/Right when at the start or end of the collection
  251. if ( this.model.cid === this.model.collection.at(0).cid ) {
  252. this.$el.find( '.left' ).addClass( 'disabled' );
  253. }
  254. if ( this.model.cid === this.model.collection.at( this.model.collection.length - 1 ).cid ) {
  255. this.$el.find( '.right' ).addClass( 'disabled' );
  256. }
  257. },
  258. // Performs the actions to effectively close
  259. // the theme details overlay
  260. closeOverlay: function() {
  261. this.remove();
  262. this.unbind();
  263. this.trigger( 'theme:collapse' );
  264. },
  265. // Confirmation dialoge for deleting a theme
  266. deleteTheme: function() {
  267. return confirm( themes.data.settings.confirmDelete );
  268. },
  269. nextTheme: function() {
  270. var self = this;
  271. self.trigger( 'theme:next', self.model.cid );
  272. },
  273. previousTheme: function() {
  274. var self = this;
  275. self.trigger( 'theme:previous', self.model.cid );
  276. },
  277. // Checks if the theme screenshot is the old 300px width version
  278. // and adds a corresponding class if it's true
  279. screenshotCheck: function( el ) {
  280. var screenshot, image;
  281. screenshot = el.find( '.screenshot img' );
  282. image = new Image();
  283. image.src = screenshot.attr( 'src' );
  284. // Width check
  285. if ( image.width && image.width <= 300 ) {
  286. el.addClass( 'small-screenshot' );
  287. }
  288. }
  289. });
  290. // Controls the rendering of div.themes,
  291. // a wrapper that will hold all the theme elements
  292. themes.view.Themes = wp.Backbone.View.extend({
  293. className: 'themes',
  294. $overlay: $( 'div.theme-overlay' ),
  295. // Number to keep track of scroll position
  296. // while in theme-overlay mode
  297. index: 0,
  298. // The theme count element
  299. count: $( '.theme-count' ),
  300. initialize: function( options ) {
  301. var self = this;
  302. // Set up parent
  303. this.parent = options.parent;
  304. // Set current view to [grid]
  305. this.setView( 'grid' );
  306. // Move the active theme to the beginning of the collection
  307. self.currentTheme();
  308. // When the collection is updated by user input...
  309. this.listenTo( self.collection, 'update', function() {
  310. self.parent.page = 0;
  311. self.currentTheme();
  312. self.render( this );
  313. });
  314. this.listenTo( this.parent, 'theme:scroll', function() {
  315. self.renderThemes( self.parent.page );
  316. });
  317. // Bind keyboard events.
  318. $('body').on( 'keyup', function( event ) {
  319. if ( ! self.overlay ) {
  320. return;
  321. }
  322. // Pressing the right arrow key fires a theme:next event
  323. if ( event.keyCode === 39 ) {
  324. self.overlay.nextTheme();
  325. }
  326. // Pressing the left arrow key fires a theme:previous event
  327. if ( event.keyCode === 37 ) {
  328. self.overlay.previousTheme();
  329. }
  330. // Pressing the escape key fires a theme:collapse event
  331. if ( event.keyCode === 27 ) {
  332. self.overlay.collapse( event );
  333. }
  334. });
  335. },
  336. // Manages rendering of theme pages
  337. // and keeping theme count in sync
  338. render: function() {
  339. // Clear the DOM, please
  340. this.$el.html( '' );
  341. // If the user doesn't have switch capabilities
  342. // or there is only one theme in the collection
  343. // render the detailed view of the active theme
  344. if ( themes.data.themes.length === 1 ) {
  345. // Constructs the view
  346. this.singleTheme = new themes.view.Details({
  347. model: this.collection.models[0]
  348. });
  349. // Render and apply a 'single-theme' class to our container
  350. this.singleTheme.render();
  351. this.$el.addClass( 'single-theme' );
  352. this.$el.append( this.singleTheme.el );
  353. }
  354. // Generate the themes
  355. // Using page instance
  356. this.renderThemes( this.parent.page );
  357. // Display a live theme count for the collection
  358. this.count.text( this.collection.length );
  359. },
  360. // Iterates through each instance of the collection
  361. // and renders each theme module
  362. renderThemes: function( page ) {
  363. var self = this;
  364. self.instance = self.collection.paginate( page );
  365. // If we have no more themes bail
  366. if ( self.instance.length === 0 ) {
  367. return;
  368. }
  369. // Make sure the add-new stays at the end
  370. if ( page >= 1 ) {
  371. $( '.add-new-theme' ).remove();
  372. }
  373. // Loop through the themes and setup each theme view
  374. self.instance.each( function( theme ) {
  375. self.theme = new themes.view.Theme({
  376. model: theme
  377. });
  378. // Render the views...
  379. self.theme.render();
  380. // and append them to div.themes
  381. self.$el.append( self.theme.el );
  382. // Binds to theme:expand to show the modal box
  383. // with the theme details
  384. self.listenTo( self.theme, 'theme:expand', self.expand, self );
  385. });
  386. // 'Add new theme' element shown at the end of the grid
  387. if ( themes.data.settings.canInstall ) {
  388. 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>' );
  389. }
  390. this.parent.page++;
  391. },
  392. // Grabs current theme and puts it at the beginning of the collection
  393. currentTheme: function() {
  394. var self = this,
  395. current;
  396. current = self.collection.findWhere({ active: true });
  397. // Move the active theme to the beginning of the collection
  398. if ( current ) {
  399. self.collection.remove( current );
  400. self.collection.add( current, { at:0 } );
  401. }
  402. },
  403. // Sets current view
  404. setView: function( view ) {
  405. return view;
  406. },
  407. // Renders the overlay with the ThemeDetails view
  408. // Uses the current model data
  409. expand: function( id ) {
  410. var self = this;
  411. // Set the current theme model
  412. this.model = self.collection.get( id );
  413. // Trigger a route update for the current model
  414. themes.router.navigate( themes.router.baseUrl( '?theme=' + this.model.id ), { replace: true } );
  415. // Sets this.view to 'detail'
  416. this.setView( 'detail' );
  417. $( 'body' ).addClass( 'theme-overlay-open' );
  418. // Set up the theme details view
  419. this.overlay = new themes.view.Details({
  420. model: self.model
  421. });
  422. this.overlay.render();
  423. this.$overlay.html( this.overlay.el );
  424. // Bind to theme:next and theme:previous
  425. // triggered by the arrow keys
  426. //
  427. // Keep track of the current model so we
  428. // can infer an index position
  429. this.listenTo( this.overlay, 'theme:next', function() {
  430. // Renders the next theme on the overlay
  431. self.next( [ self.model.cid ] );
  432. })
  433. .listenTo( this.overlay, 'theme:previous', function() {
  434. // Renders the previous theme on the overlay
  435. self.previous( [ self.model.cid ] );
  436. });
  437. },
  438. // This method renders the next theme on the overlay modal
  439. // based on the current position in the collection
  440. // @params [model cid]
  441. next: function( args ) {
  442. var self = this,
  443. model, nextModel;
  444. // Get the current theme
  445. model = self.collection.get( args[0] );
  446. // Find the next model within the collection
  447. nextModel = self.collection.at( self.collection.indexOf( model ) + 1 );
  448. // Sanity check which also serves as a boundary test
  449. if ( nextModel !== undefined ) {
  450. // We have a new theme...
  451. // Close the overlay
  452. this.overlay.closeOverlay();
  453. // Trigger a route update for the current model
  454. self.theme.trigger( 'theme:expand', nextModel.cid );
  455. }
  456. },
  457. // This method renders the previous theme on the overlay modal
  458. // based on the current position in the collection
  459. // @params [model cid]
  460. previous: function( args ) {
  461. var self = this,
  462. model, previousModel;
  463. // Get the current theme
  464. model = self.collection.get( args[0] );
  465. // Find the previous model within the collection
  466. previousModel = self.collection.at( self.collection.indexOf( model ) - 1 );
  467. if ( previousModel !== undefined ) {
  468. // We have a new theme...
  469. // Close the overlay
  470. this.overlay.closeOverlay();
  471. // Trigger a route update for the current model
  472. self.theme.trigger( 'theme:expand', previousModel.cid );
  473. }
  474. }
  475. });
  476. // Search input view controller.
  477. themes.view.Search = wp.Backbone.View.extend({
  478. tagName: 'input',
  479. className: 'theme-search',
  480. attributes: {
  481. placeholder: l10n.searchPlaceholder,
  482. type: 'search'
  483. },
  484. events: {
  485. 'input': 'search',
  486. 'keyup': 'search',
  487. 'change': 'search',
  488. 'search': 'search'
  489. },
  490. // Runs a search on the theme collection.
  491. search: function( event ) {
  492. // Clear on escape.
  493. if ( event.type === 'keyup' && event.which === 27 ) {
  494. event.target.value = '';
  495. }
  496. this.collection.doSearch( event.target.value );
  497. // Update the URL hash
  498. if ( event.target.value ) {
  499. themes.router.navigate( themes.router.baseUrl( '?search=' + event.target.value ), { replace: true } );
  500. } else {
  501. themes.router.navigate( themes.router.baseUrl( '' ), { replace: true } );
  502. }
  503. }
  504. });
  505. // Sets up the routes events for relevant url queries
  506. // Listens to [theme] and [search] params
  507. themes.routes = Backbone.Router.extend({
  508. initialize: function() {
  509. this.routes = _.object([
  510. ]);
  511. },
  512. baseUrl: function( url ) {
  513. return themes.data.settings.root + url;
  514. }
  515. });
  516. // Execute and setup the application
  517. themes.Run = {
  518. init: function() {
  519. // Initializes the blog's theme library view
  520. // Create a new collection with data
  521. this.themes = new themes.Collection( themes.data.themes );
  522. // Set up the view
  523. this.view = new themes.view.Appearance({
  524. collection: this.themes
  525. });
  526. this.render();
  527. },
  528. render: function() {
  529. // Render results
  530. this.view.render();
  531. this.routes();
  532. // Set the initial theme
  533. if ( 'undefined' !== typeof themes.data.settings.theme && '' !== themes.data.settings.theme ){
  534. this.view.view.theme.trigger( 'theme:expand', this.view.collection.findWhere( { id: themes.data.settings.theme } ) );
  535. }
  536. // Set the initial search
  537. if ( 'undefined' !== typeof themes.data.settings.search && '' !== themes.data.settings.search ){
  538. $( '.theme-search' ).val( themes.data.settings.search );
  539. this.themes.doSearch( themes.data.settings.search );
  540. }
  541. // Start the router if browser supports History API
  542. if ( window.history && window.history.pushState ) {
  543. // Calls the routes functionality
  544. Backbone.history.start({ pushState: true, silent: true });
  545. }
  546. },
  547. routes: function() {
  548. // Bind to our global thx object
  549. // so that the object is available to sub-views
  550. themes.router = new themes.routes();
  551. }
  552. };
  553. // Ready...
  554. jQuery( document ).ready(
  555. // Bring on the themes
  556. _.bind( themes.Run.init, themes.Run )
  557. );
  558. })( jQuery );
  559. // Align theme browser thickbox
  560. var tb_position;
  561. jQuery(document).ready( function($) {
  562. tb_position = function() {
  563. var tbWindow = $('#TB_window'),
  564. width = $(window).width(),
  565. H = $(window).height(),
  566. W = ( 1040 < width ) ? 1040 : width,
  567. adminbar_height = 0;
  568. if ( $('body.admin-bar').length ) {
  569. adminbar_height = parseInt( jQuery('#wpadminbar').css('height'), 10 );
  570. }
  571. if ( tbWindow.size() ) {
  572. tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
  573. $('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
  574. tbWindow.css({'margin-left': '-' + parseInt( ( ( W - 50 ) / 2 ), 10 ) + 'px'});
  575. if ( typeof document.body.style.maxWidth !== 'undefined' ) {
  576. tbWindow.css({'top': 20 + adminbar_height + 'px', 'margin-top': '0'});
  577. }
  578. }
  579. };
  580. $(window).resize(function(){ tb_position(); });
  581. });