theme.js 53 KB

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