theme.js 54 KB

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