Nav apraksta

theme.js 54KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112
  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. } );
  492. wp.updates.installTheme( {
  493. slug: $( event.target ).data( 'slug' )
  494. } );
  495. },
  496. updateTheme: function( event ) {
  497. var _this = this;
  498. if ( ! this.model.get( 'hasPackage' ) ) {
  499. return;
  500. }
  501. event.preventDefault();
  502. wp.updates.maybeRequestFilesystemCredentials( event );
  503. $( document ).on( 'wp-theme-update-success', function( event, response ) {
  504. _this.model.off( 'change', _this.render, _this );
  505. if ( _this.model.get( 'id' ) === response.slug ) {
  506. _this.model.set( {
  507. hasUpdate: false,
  508. version: response.newVersion
  509. } );
  510. }
  511. _this.model.on( 'change', _this.render, _this );
  512. } );
  513. wp.updates.updateTheme( {
  514. slug: $( event.target ).parents( 'div.theme' ).first().data( 'slug' )
  515. } );
  516. }
  517. });
  518. // Theme Details view.
  519. // Sets up a modal overlay with the expanded theme data.
  520. themes.view.Details = wp.Backbone.View.extend({
  521. // Wrap theme data on a div.theme element.
  522. className: 'theme-overlay',
  523. events: {
  524. 'click': 'collapse',
  525. 'click .delete-theme': 'deleteTheme',
  526. 'click .left': 'previousTheme',
  527. 'click .right': 'nextTheme',
  528. 'click #update-theme': 'updateTheme',
  529. 'click .toggle-auto-update': 'autoupdateState'
  530. },
  531. // The HTML template for the theme overlay.
  532. html: themes.template( 'theme-single' ),
  533. render: function() {
  534. var data = this.model.toJSON();
  535. this.$el.html( this.html( data ) );
  536. // Renders active theme styles.
  537. this.activeTheme();
  538. // Set up navigation events.
  539. this.navigation();
  540. // Checks screenshot size.
  541. this.screenshotCheck( this.$el );
  542. // Contain "tabbing" inside the overlay.
  543. this.containFocus( this.$el );
  544. },
  545. // Adds a class to the currently active theme
  546. // and to the overlay in detailed view mode.
  547. activeTheme: function() {
  548. // Check the model has the active property.
  549. this.$el.toggleClass( 'active', this.model.get( 'active' ) );
  550. },
  551. // Set initial focus and constrain tabbing within the theme browser modal.
  552. containFocus: function( $el ) {
  553. // Set initial focus on the primary action control.
  554. _.delay( function() {
  555. $( '.theme-overlay' ).trigger( 'focus' );
  556. }, 100 );
  557. // Constrain tabbing within the modal.
  558. $el.on( 'keydown.wp-themes', function( event ) {
  559. var $firstFocusable = $el.find( '.theme-header button:not(.disabled)' ).first(),
  560. $lastFocusable = $el.find( '.theme-actions a:visible' ).last();
  561. // Check for the Tab key.
  562. if ( 9 === event.which ) {
  563. if ( $firstFocusable[0] === event.target && event.shiftKey ) {
  564. $lastFocusable.trigger( 'focus' );
  565. event.preventDefault();
  566. } else if ( $lastFocusable[0] === event.target && ! event.shiftKey ) {
  567. $firstFocusable.trigger( 'focus' );
  568. event.preventDefault();
  569. }
  570. }
  571. });
  572. },
  573. // Single theme overlay screen.
  574. // It's shown when clicking a theme.
  575. collapse: function( event ) {
  576. var self = this,
  577. scroll;
  578. event = event || window.event;
  579. // Prevent collapsing detailed view when there is only one theme available.
  580. if ( themes.data.themes.length === 1 ) {
  581. return;
  582. }
  583. // Detect if the click is inside the overlay and don't close it
  584. // unless the target was the div.back button.
  585. if ( $( event.target ).is( '.theme-backdrop' ) || $( event.target ).is( '.close' ) || event.keyCode === 27 ) {
  586. // Add a temporary closing class while overlay fades out.
  587. $( 'body' ).addClass( 'closing-overlay' );
  588. // With a quick fade out animation.
  589. this.$el.fadeOut( 130, function() {
  590. // Clicking outside the modal box closes the overlay.
  591. $( 'body' ).removeClass( 'closing-overlay' );
  592. // Handle event cleanup.
  593. self.closeOverlay();
  594. // Get scroll position to avoid jumping to the top.
  595. scroll = document.body.scrollTop;
  596. // Clean the URL structure.
  597. themes.router.navigate( themes.router.baseUrl( '' ) );
  598. // Restore scroll position.
  599. document.body.scrollTop = scroll;
  600. // Return focus to the theme div.
  601. if ( themes.focusedTheme ) {
  602. themes.focusedTheme.find('.more-details').trigger( 'focus' );
  603. }
  604. });
  605. }
  606. },
  607. // Handles .disabled classes for next/previous buttons.
  608. navigation: function() {
  609. // Disable Left/Right when at the start or end of the collection.
  610. if ( this.model.cid === this.model.collection.at(0).cid ) {
  611. this.$el.find( '.left' )
  612. .addClass( 'disabled' )
  613. .prop( 'disabled', true );
  614. }
  615. if ( this.model.cid === this.model.collection.at( this.model.collection.length - 1 ).cid ) {
  616. this.$el.find( '.right' )
  617. .addClass( 'disabled' )
  618. .prop( 'disabled', true );
  619. }
  620. },
  621. // Performs the actions to effectively close
  622. // the theme details overlay.
  623. closeOverlay: function() {
  624. $( 'body' ).removeClass( 'modal-open' );
  625. this.remove();
  626. this.unbind();
  627. this.trigger( 'theme:collapse' );
  628. },
  629. // Set state of the auto-update settings link after it has been changed and saved.
  630. autoupdateState: function() {
  631. var callback,
  632. _this = this;
  633. // Support concurrent clicks in different Theme Details overlays.
  634. callback = function( event, data ) {
  635. var autoupdate;
  636. if ( _this.model.get( 'id' ) === data.asset ) {
  637. autoupdate = _this.model.get( 'autoupdate' );
  638. autoupdate.enabled = 'enable' === data.state;
  639. _this.model.set( { autoupdate: autoupdate } );
  640. $( document ).off( 'wp-auto-update-setting-changed', callback );
  641. }
  642. };
  643. // Triggered in updates.js
  644. $( document ).on( 'wp-auto-update-setting-changed', callback );
  645. },
  646. updateTheme: function( event ) {
  647. var _this = this;
  648. event.preventDefault();
  649. wp.updates.maybeRequestFilesystemCredentials( event );
  650. $( document ).on( 'wp-theme-update-success', function( event, response ) {
  651. if ( _this.model.get( 'id' ) === response.slug ) {
  652. _this.model.set( {
  653. hasUpdate: false,
  654. version: response.newVersion
  655. } );
  656. }
  657. _this.render();
  658. } );
  659. wp.updates.updateTheme( {
  660. slug: $( event.target ).data( 'slug' )
  661. } );
  662. },
  663. deleteTheme: function( event ) {
  664. var _this = this,
  665. _collection = _this.model.collection,
  666. _themes = themes;
  667. event.preventDefault();
  668. // Confirmation dialog for deleting a theme.
  669. if ( ! window.confirm( wp.themes.data.settings.confirmDelete ) ) {
  670. return;
  671. }
  672. wp.updates.maybeRequestFilesystemCredentials( event );
  673. $( document ).one( 'wp-theme-delete-success', function( event, response ) {
  674. _this.$el.find( '.close' ).trigger( 'click' );
  675. $( '[data-slug="' + response.slug + '"]' ).css( { backgroundColor:'#faafaa' } ).fadeOut( 350, function() {
  676. $( this ).remove();
  677. _themes.data.themes = _.without( _themes.data.themes, _.findWhere( _themes.data.themes, { id: response.slug } ) );
  678. $( '.wp-filter-search' ).val( '' );
  679. _collection.doSearch( '' );
  680. _collection.remove( _this.model );
  681. _collection.trigger( 'themes:update' );
  682. } );
  683. } );
  684. wp.updates.deleteTheme( {
  685. slug: this.model.get( 'id' )
  686. } );
  687. },
  688. nextTheme: function() {
  689. var self = this;
  690. self.trigger( 'theme:next', self.model.cid );
  691. return false;
  692. },
  693. previousTheme: function() {
  694. var self = this;
  695. self.trigger( 'theme:previous', self.model.cid );
  696. return false;
  697. },
  698. // Checks if the theme screenshot is the old 300px width version
  699. // and adds a corresponding class if it's true.
  700. screenshotCheck: function( el ) {
  701. var screenshot, image;
  702. screenshot = el.find( '.screenshot img' );
  703. image = new Image();
  704. image.src = screenshot.attr( 'src' );
  705. // Width check.
  706. if ( image.width && image.width <= 300 ) {
  707. el.addClass( 'small-screenshot' );
  708. }
  709. }
  710. });
  711. // Theme Preview view.
  712. // Sets up a modal overlay with the expanded theme data.
  713. themes.view.Preview = themes.view.Details.extend({
  714. className: 'wp-full-overlay expanded',
  715. el: '.theme-install-overlay',
  716. events: {
  717. 'click .close-full-overlay': 'close',
  718. 'click .collapse-sidebar': 'collapse',
  719. 'click .devices button': 'previewDevice',
  720. 'click .previous-theme': 'previousTheme',
  721. 'click .next-theme': 'nextTheme',
  722. 'keyup': 'keyEvent',
  723. 'click .theme-install': 'installTheme'
  724. },
  725. // The HTML template for the theme preview.
  726. html: themes.template( 'theme-preview' ),
  727. render: function() {
  728. var self = this,
  729. currentPreviewDevice,
  730. data = this.model.toJSON(),
  731. $body = $( document.body );
  732. $body.attr( 'aria-busy', 'true' );
  733. this.$el.removeClass( 'iframe-ready' ).html( this.html( data ) );
  734. currentPreviewDevice = this.$el.data( 'current-preview-device' );
  735. if ( currentPreviewDevice ) {
  736. self.tooglePreviewDeviceButtons( currentPreviewDevice );
  737. }
  738. themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.get( 'id' ) ), { replace: false } );
  739. this.$el.fadeIn( 200, function() {
  740. $body.addClass( 'theme-installer-active full-overlay-active' );
  741. });
  742. this.$el.find( 'iframe' ).one( 'load', function() {
  743. self.iframeLoaded();
  744. });
  745. },
  746. iframeLoaded: function() {
  747. this.$el.addClass( 'iframe-ready' );
  748. $( document.body ).attr( 'aria-busy', 'false' );
  749. },
  750. close: function() {
  751. this.$el.fadeOut( 200, function() {
  752. $( 'body' ).removeClass( 'theme-installer-active full-overlay-active' );
  753. // Return focus to the theme div.
  754. if ( themes.focusedTheme ) {
  755. themes.focusedTheme.find('.more-details').trigger( 'focus' );
  756. }
  757. }).removeClass( 'iframe-ready' );
  758. // Restore the previous browse tab if available.
  759. if ( themes.router.selectedTab ) {
  760. themes.router.navigate( themes.router.baseUrl( '?browse=' + themes.router.selectedTab ) );
  761. themes.router.selectedTab = false;
  762. } else {
  763. themes.router.navigate( themes.router.baseUrl( '' ) );
  764. }
  765. this.trigger( 'preview:close' );
  766. this.undelegateEvents();
  767. this.unbind();
  768. return false;
  769. },
  770. collapse: function( event ) {
  771. var $button = $( event.currentTarget );
  772. if ( 'true' === $button.attr( 'aria-expanded' ) ) {
  773. $button.attr({ 'aria-expanded': 'false', 'aria-label': l10n.expandSidebar });
  774. } else {
  775. $button.attr({ 'aria-expanded': 'true', 'aria-label': l10n.collapseSidebar });
  776. }
  777. this.$el.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
  778. return false;
  779. },
  780. previewDevice: function( event ) {
  781. var device = $( event.currentTarget ).data( 'device' );
  782. this.$el
  783. .removeClass( 'preview-desktop preview-tablet preview-mobile' )
  784. .addClass( 'preview-' + device )
  785. .data( 'current-preview-device', device );
  786. this.tooglePreviewDeviceButtons( device );
  787. },
  788. tooglePreviewDeviceButtons: function( newDevice ) {
  789. var $devices = $( '.wp-full-overlay-footer .devices' );
  790. $devices.find( 'button' )
  791. .removeClass( 'active' )
  792. .attr( 'aria-pressed', false );
  793. $devices.find( 'button.preview-' + newDevice )
  794. .addClass( 'active' )
  795. .attr( 'aria-pressed', true );
  796. },
  797. keyEvent: function( event ) {
  798. // The escape key closes the preview.
  799. if ( event.keyCode === 27 ) {
  800. this.undelegateEvents();
  801. this.close();
  802. }
  803. // The right arrow key, next theme.
  804. if ( event.keyCode === 39 ) {
  805. _.once( this.nextTheme() );
  806. }
  807. // The left arrow key, previous theme.
  808. if ( event.keyCode === 37 ) {
  809. this.previousTheme();
  810. }
  811. },
  812. installTheme: function( event ) {
  813. var _this = this,
  814. $target = $( event.target );
  815. event.preventDefault();
  816. if ( $target.hasClass( 'disabled' ) ) {
  817. return;
  818. }
  819. wp.updates.maybeRequestFilesystemCredentials( event );
  820. $( document ).on( 'wp-theme-install-success', function() {
  821. _this.model.set( { 'installed': true } );
  822. } );
  823. wp.updates.installTheme( {
  824. slug: $target.data( 'slug' )
  825. } );
  826. }
  827. });
  828. // Controls the rendering of div.themes,
  829. // a wrapper that will hold all the theme elements.
  830. themes.view.Themes = wp.Backbone.View.extend({
  831. className: 'themes wp-clearfix',
  832. $overlay: $( 'div.theme-overlay' ),
  833. // Number to keep track of scroll position
  834. // while in theme-overlay mode.
  835. index: 0,
  836. // The theme count element.
  837. count: $( '.wrap .theme-count' ),
  838. // The live themes count.
  839. liveThemeCount: 0,
  840. initialize: function( options ) {
  841. var self = this;
  842. // Set up parent.
  843. this.parent = options.parent;
  844. // Set current view to [grid].
  845. this.setView( 'grid' );
  846. // Move the active theme to the beginning of the collection.
  847. self.currentTheme();
  848. // When the collection is updated by user input...
  849. this.listenTo( self.collection, 'themes:update', function() {
  850. self.parent.page = 0;
  851. self.currentTheme();
  852. self.render( this );
  853. } );
  854. // Update theme count to full result set when available.
  855. this.listenTo( self.collection, 'query:success', function( count ) {
  856. if ( _.isNumber( count ) ) {
  857. self.count.text( count );
  858. self.announceSearchResults( count );
  859. } else {
  860. self.count.text( self.collection.length );
  861. self.announceSearchResults( self.collection.length );
  862. }
  863. });
  864. this.listenTo( self.collection, 'query:empty', function() {
  865. $( 'body' ).addClass( 'no-results' );
  866. });
  867. this.listenTo( this.parent, 'theme:scroll', function() {
  868. self.renderThemes( self.parent.page );
  869. });
  870. this.listenTo( this.parent, 'theme:close', function() {
  871. if ( self.overlay ) {
  872. self.overlay.closeOverlay();
  873. }
  874. } );
  875. // Bind keyboard events.
  876. $( 'body' ).on( 'keyup', function( event ) {
  877. if ( ! self.overlay ) {
  878. return;
  879. }
  880. // Bail if the filesystem credentials dialog is shown.
  881. if ( $( '#request-filesystem-credentials-dialog' ).is( ':visible' ) ) {
  882. return;
  883. }
  884. // Pressing the right arrow key fires a theme:next event.
  885. if ( event.keyCode === 39 ) {
  886. self.overlay.nextTheme();
  887. }
  888. // Pressing the left arrow key fires a theme:previous event.
  889. if ( event.keyCode === 37 ) {
  890. self.overlay.previousTheme();
  891. }
  892. // Pressing the escape key fires a theme:collapse event.
  893. if ( event.keyCode === 27 ) {
  894. self.overlay.collapse( event );
  895. }
  896. });
  897. },
  898. // Manages rendering of theme pages
  899. // and keeping theme count in sync.
  900. render: function() {
  901. // Clear the DOM, please.
  902. this.$el.empty();
  903. // If the user doesn't have switch capabilities or there is only one theme
  904. // in the collection, render the detailed view of the active theme.
  905. if ( themes.data.themes.length === 1 ) {
  906. // Constructs the view.
  907. this.singleTheme = new themes.view.Details({
  908. model: this.collection.models[0]
  909. });
  910. // Render and apply a 'single-theme' class to our container.
  911. this.singleTheme.render();
  912. this.$el.addClass( 'single-theme' );
  913. this.$el.append( this.singleTheme.el );
  914. }
  915. // Generate the themes using page instance
  916. // while checking the collection has items.
  917. if ( this.options.collection.size() > 0 ) {
  918. this.renderThemes( this.parent.page );
  919. }
  920. // Display a live theme count for the collection.
  921. this.liveThemeCount = this.collection.count ? this.collection.count : this.collection.length;
  922. this.count.text( this.liveThemeCount );
  923. /*
  924. * In the theme installer the themes count is already announced
  925. * because `announceSearchResults` is called on `query:success`.
  926. */
  927. if ( ! themes.isInstall ) {
  928. this.announceSearchResults( this.liveThemeCount );
  929. }
  930. },
  931. // Iterates through each instance of the collection
  932. // and renders each theme module.
  933. renderThemes: function( page ) {
  934. var self = this;
  935. self.instance = self.collection.paginate( page );
  936. // If we have no more themes, bail.
  937. if ( self.instance.size() === 0 ) {
  938. // Fire a no-more-themes event.
  939. this.parent.trigger( 'theme:end' );
  940. return;
  941. }
  942. // Make sure the add-new stays at the end.
  943. if ( ! themes.isInstall && page >= 1 ) {
  944. $( '.add-new-theme' ).remove();
  945. }
  946. // Loop through the themes and setup each theme view.
  947. self.instance.each( function( theme ) {
  948. self.theme = new themes.view.Theme({
  949. model: theme,
  950. parent: self
  951. });
  952. // Render the views...
  953. self.theme.render();
  954. // ...and append them to div.themes.
  955. self.$el.append( self.theme.el );
  956. // Binds to theme:expand to show the modal box
  957. // with the theme details.
  958. self.listenTo( self.theme, 'theme:expand', self.expand, self );
  959. });
  960. // 'Add new theme' element shown at the end of the grid.
  961. if ( ! themes.isInstall && themes.data.settings.canInstall ) {
  962. 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>' );
  963. }
  964. this.parent.page++;
  965. },
  966. // Grabs current theme and puts it at the beginning of the collection.
  967. currentTheme: function() {
  968. var self = this,
  969. current;
  970. current = self.collection.findWhere({ active: true });
  971. // Move the active theme to the beginning of the collection.
  972. if ( current ) {
  973. self.collection.remove( current );
  974. self.collection.add( current, { at:0 } );
  975. }
  976. },
  977. // Sets current view.
  978. setView: function( view ) {
  979. return view;
  980. },
  981. // Renders the overlay with the ThemeDetails view.
  982. // Uses the current model data.
  983. expand: function( id ) {
  984. var self = this, $card, $modal;
  985. // Set the current theme model.
  986. this.model = self.collection.get( id );
  987. // Trigger a route update for the current model.
  988. themes.router.navigate( themes.router.baseUrl( themes.router.themePath + this.model.id ) );
  989. // Sets this.view to 'detail'.
  990. this.setView( 'detail' );
  991. $( 'body' ).addClass( 'modal-open' );
  992. // Set up the theme details view.
  993. this.overlay = new themes.view.Details({
  994. model: self.model
  995. });
  996. this.overlay.render();
  997. if ( this.model.get( 'hasUpdate' ) ) {
  998. $card = $( '[data-slug="' + this.model.id + '"]' );
  999. $modal = $( this.overlay.el );
  1000. if ( $card.find( '.updating-message' ).length ) {
  1001. $modal.find( '.notice-warning h3' ).remove();
  1002. $modal.find( '.notice-warning' )
  1003. .removeClass( 'notice-large' )
  1004. .addClass( 'updating-message' )
  1005. .find( 'p' ).text( wp.updates.l10n.updating );
  1006. } else if ( $card.find( '.notice-error' ).length ) {
  1007. $modal.find( '.notice-warning' ).remove();
  1008. }
  1009. }
  1010. this.$overlay.html( this.overlay.el );
  1011. // Bind to theme:next and theme:previous triggered by the arrow keys.
  1012. // Keep track of the current model so we can infer an index position.
  1013. this.listenTo( this.overlay, 'theme:next', function() {
  1014. // Renders the next theme on the overlay.
  1015. self.next( [ self.model.cid ] );
  1016. })
  1017. .listenTo( this.overlay, 'theme:previous', function() {
  1018. // Renders the previous theme on the overlay.
  1019. self.previous( [ self.model.cid ] );
  1020. });
  1021. },
  1022. /*
  1023. * This method renders the next theme on the overlay modal
  1024. * based on the current position in the collection.
  1025. *
  1026. * @params [model cid]
  1027. */
  1028. next: function( args ) {
  1029. var self = this,
  1030. model, nextModel;
  1031. // Get the current theme.
  1032. model = self.collection.get( args[0] );
  1033. // Find the next model within the collection.
  1034. nextModel = self.collection.at( self.collection.indexOf( model ) + 1 );
  1035. // Sanity check which also serves as a boundary test.
  1036. if ( nextModel !== undefined ) {
  1037. // We have a new theme...
  1038. // Close the overlay.
  1039. this.overlay.closeOverlay();
  1040. // Trigger a route update for the current model.
  1041. self.theme.trigger( 'theme:expand', nextModel.cid );
  1042. }
  1043. },
  1044. /*
  1045. * This method renders the previous theme on the overlay modal
  1046. * based on the current position in the collection.
  1047. *
  1048. * @params [model cid]
  1049. */
  1050. previous: function( args ) {
  1051. var self = this,
  1052. model, previousModel;
  1053. // Get the current theme.
  1054. model = self.collection.get( args[0] );
  1055. // Find the previous model within the collection.
  1056. previousModel = self.collection.at( self.collection.indexOf( model ) - 1 );
  1057. if ( previousModel !== undefined ) {
  1058. // We have a new theme...
  1059. // Close the overlay.
  1060. this.overlay.closeOverlay();
  1061. // Trigger a route update for the current model.
  1062. self.theme.trigger( 'theme:expand', previousModel.cid );
  1063. }
  1064. },
  1065. // Dispatch audible search results feedback message.
  1066. announceSearchResults: function( count ) {
  1067. if ( 0 === count ) {
  1068. wp.a11y.speak( l10n.noThemesFound );
  1069. } else {
  1070. wp.a11y.speak( l10n.themesFound.replace( '%d', count ) );
  1071. }
  1072. }
  1073. });
  1074. // Search input view controller.
  1075. themes.view.Search = wp.Backbone.View.extend({
  1076. tagName: 'input',
  1077. className: 'wp-filter-search',
  1078. id: 'wp-filter-search-input',
  1079. searching: false,
  1080. attributes: {
  1081. placeholder: l10n.searchPlaceholder,
  1082. type: 'search',
  1083. 'aria-describedby': 'live-search-desc'
  1084. },
  1085. events: {
  1086. 'input': 'search',
  1087. 'keyup': 'search',
  1088. 'blur': 'pushState'
  1089. },
  1090. initialize: function( options ) {
  1091. this.parent = options.parent;
  1092. this.listenTo( this.parent, 'theme:close', function() {
  1093. this.searching = false;
  1094. } );
  1095. },
  1096. search: function( event ) {
  1097. // Clear on escape.
  1098. if ( event.type === 'keyup' && event.which === 27 ) {
  1099. event.target.value = '';
  1100. }
  1101. // Since doSearch is debounced, it will only run when user input comes to a rest.
  1102. this.doSearch( event );
  1103. },
  1104. // Runs a search on the theme collection.
  1105. doSearch: function( event ) {
  1106. var options = {};
  1107. this.collection.doSearch( event.target.value.replace( /\+/g, ' ' ) );
  1108. // if search is initiated and key is not return.
  1109. if ( this.searching && event.which !== 13 ) {
  1110. options.replace = true;
  1111. } else {
  1112. this.searching = true;
  1113. }
  1114. // Update the URL hash.
  1115. if ( event.target.value ) {
  1116. themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + event.target.value ), options );
  1117. } else {
  1118. themes.router.navigate( themes.router.baseUrl( '' ) );
  1119. }
  1120. },
  1121. pushState: function( event ) {
  1122. var url = themes.router.baseUrl( '' );
  1123. if ( event.target.value ) {
  1124. url = themes.router.baseUrl( themes.router.searchPath + encodeURIComponent( event.target.value ) );
  1125. }
  1126. this.searching = false;
  1127. themes.router.navigate( url );
  1128. }
  1129. });
  1130. /**
  1131. * Navigate router.
  1132. *
  1133. * @since 4.9.0
  1134. *
  1135. * @param {string} url - URL to navigate to.
  1136. * @param {Object} state - State.
  1137. * @return {void}
  1138. */
  1139. function navigateRouter( url, state ) {
  1140. var router = this;
  1141. if ( Backbone.history._hasPushState ) {
  1142. Backbone.Router.prototype.navigate.call( router, url, state );
  1143. }
  1144. }
  1145. // Sets up the routes events for relevant url queries.
  1146. // Listens to [theme] and [search] params.
  1147. themes.Router = Backbone.Router.extend({
  1148. routes: {
  1149. 'themes.php?theme=:slug': 'theme',
  1150. 'themes.php?search=:query': 'search',
  1151. 'themes.php?s=:query': 'search',
  1152. 'themes.php': 'themes',
  1153. '': 'themes'
  1154. },
  1155. baseUrl: function( url ) {
  1156. return 'themes.php' + url;
  1157. },
  1158. themePath: '?theme=',
  1159. searchPath: '?search=',
  1160. search: function( query ) {
  1161. $( '.wp-filter-search' ).val( query.replace( /\+/g, ' ' ) );
  1162. },
  1163. themes: function() {
  1164. $( '.wp-filter-search' ).val( '' );
  1165. },
  1166. navigate: navigateRouter
  1167. });
  1168. // Execute and setup the application.
  1169. themes.Run = {
  1170. init: function() {
  1171. // Initializes the blog's theme library view.
  1172. // Create a new collection with data.
  1173. this.themes = new themes.Collection( themes.data.themes );
  1174. // Set up the view.
  1175. this.view = new themes.view.Appearance({
  1176. collection: this.themes
  1177. });
  1178. this.render();
  1179. // Start debouncing user searches after Backbone.history.start().
  1180. this.view.SearchView.doSearch = _.debounce( this.view.SearchView.doSearch, 500 );
  1181. },
  1182. render: function() {
  1183. // Render results.
  1184. this.view.render();
  1185. this.routes();
  1186. if ( Backbone.History.started ) {
  1187. Backbone.history.stop();
  1188. }
  1189. Backbone.history.start({
  1190. root: themes.data.settings.adminUrl,
  1191. pushState: true,
  1192. hashChange: false
  1193. });
  1194. },
  1195. routes: function() {
  1196. var self = this;
  1197. // Bind to our global thx object
  1198. // so that the object is available to sub-views.
  1199. themes.router = new themes.Router();
  1200. // Handles theme details route event.
  1201. themes.router.on( 'route:theme', function( slug ) {
  1202. self.view.view.expand( slug );
  1203. });
  1204. themes.router.on( 'route:themes', function() {
  1205. self.themes.doSearch( '' );
  1206. self.view.trigger( 'theme:close' );
  1207. });
  1208. // Handles search route event.
  1209. themes.router.on( 'route:search', function() {
  1210. $( '.wp-filter-search' ).trigger( 'keyup' );
  1211. });
  1212. this.extraRoutes();
  1213. },
  1214. extraRoutes: function() {
  1215. return false;
  1216. }
  1217. };
  1218. // Extend the main Search view.
  1219. themes.view.InstallerSearch = themes.view.Search.extend({
  1220. events: {
  1221. 'input': 'search',
  1222. 'keyup': 'search'
  1223. },
  1224. terms: '',
  1225. // Handles Ajax request for searching through themes in public repo.
  1226. search: function( event ) {
  1227. // Tabbing or reverse tabbing into the search input shouldn't trigger a search.
  1228. if ( event.type === 'keyup' && ( event.which === 9 || event.which === 16 ) ) {
  1229. return;
  1230. }
  1231. this.collection = this.options.parent.view.collection;
  1232. // Clear on escape.
  1233. if ( event.type === 'keyup' && event.which === 27 ) {
  1234. event.target.value = '';
  1235. }
  1236. this.doSearch( event.target.value );
  1237. },
  1238. doSearch: function( value ) {
  1239. var request = {};
  1240. // Don't do anything if the search terms haven't changed.
  1241. if ( this.terms === value ) {
  1242. return;
  1243. }
  1244. // Updates terms with the value passed.
  1245. this.terms = value;
  1246. request.search = value;
  1247. /*
  1248. * Intercept an [author] search.
  1249. *
  1250. * If input value starts with `author:` send a request
  1251. * for `author` instead of a regular `search`.
  1252. */
  1253. if ( value.substring( 0, 7 ) === 'author:' ) {
  1254. request.search = '';
  1255. request.author = value.slice( 7 );
  1256. }
  1257. /*
  1258. * Intercept a [tag] search.
  1259. *
  1260. * If input value starts with `tag:` send a request
  1261. * for `tag` instead of a regular `search`.
  1262. */
  1263. if ( value.substring( 0, 4 ) === 'tag:' ) {
  1264. request.search = '';
  1265. request.tag = [ value.slice( 4 ) ];
  1266. }
  1267. $( '.filter-links li > a.current' )
  1268. .removeClass( 'current' )
  1269. .removeAttr( 'aria-current' );
  1270. $( 'body' ).removeClass( 'show-filters filters-applied show-favorites-form' );
  1271. $( '.drawer-toggle' ).attr( 'aria-expanded', 'false' );
  1272. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1273. // or searching the local cache.
  1274. this.collection.query( request );
  1275. // Set route.
  1276. themes.router.navigate( themes.router.baseUrl( themes.router.searchPath + encodeURIComponent( value ) ), { replace: true } );
  1277. }
  1278. });
  1279. themes.view.Installer = themes.view.Appearance.extend({
  1280. el: '#wpbody-content .wrap',
  1281. // Register events for sorting and filters in theme-navigation.
  1282. events: {
  1283. 'click .filter-links li > a': 'onSort',
  1284. 'click .theme-filter': 'onFilter',
  1285. 'click .drawer-toggle': 'moreFilters',
  1286. 'click .filter-drawer .apply-filters': 'applyFilters',
  1287. 'click .filter-group [type="checkbox"]': 'addFilter',
  1288. 'click .filter-drawer .clear-filters': 'clearFilters',
  1289. 'click .edit-filters': 'backToFilters',
  1290. 'click .favorites-form-submit' : 'saveUsername',
  1291. 'keyup #wporg-username-input': 'saveUsername'
  1292. },
  1293. // Initial render method.
  1294. render: function() {
  1295. var self = this;
  1296. this.search();
  1297. this.uploader();
  1298. this.collection = new themes.Collection();
  1299. // Bump `collection.currentQuery.page` and request more themes if we hit the end of the page.
  1300. this.listenTo( this, 'theme:end', function() {
  1301. // Make sure we are not already loading.
  1302. if ( self.collection.loadingThemes ) {
  1303. return;
  1304. }
  1305. // Set loadingThemes to true and bump page instance of currentQuery.
  1306. self.collection.loadingThemes = true;
  1307. self.collection.currentQuery.page++;
  1308. // Use currentQuery.page to build the themes request.
  1309. _.extend( self.collection.currentQuery.request, { page: self.collection.currentQuery.page } );
  1310. self.collection.query( self.collection.currentQuery.request );
  1311. });
  1312. this.listenTo( this.collection, 'query:success', function() {
  1313. $( 'body' ).removeClass( 'loading-content' );
  1314. $( '.theme-browser' ).find( 'div.error' ).remove();
  1315. });
  1316. this.listenTo( this.collection, 'query:fail', function() {
  1317. $( 'body' ).removeClass( 'loading-content' );
  1318. $( '.theme-browser' ).find( 'div.error' ).remove();
  1319. $( '.theme-browser' ).find( 'div.themes' ).before( '<div class="error"><p>' + l10n.error + '</p><p><button class="button try-again">' + l10n.tryAgain + '</button></p></div>' );
  1320. $( '.theme-browser .error .try-again' ).on( 'click', function( e ) {
  1321. e.preventDefault();
  1322. $( 'input.wp-filter-search' ).trigger( 'input' );
  1323. } );
  1324. });
  1325. if ( this.view ) {
  1326. this.view.remove();
  1327. }
  1328. // Sets up the view and passes the section argument.
  1329. this.view = new themes.view.Themes({
  1330. collection: this.collection,
  1331. parent: this
  1332. });
  1333. // Reset pagination every time the install view handler is run.
  1334. this.page = 0;
  1335. // Render and append.
  1336. this.$el.find( '.themes' ).remove();
  1337. this.view.render();
  1338. this.$el.find( '.theme-browser' ).append( this.view.el ).addClass( 'rendered' );
  1339. },
  1340. // Handles all the rendering of the public theme directory.
  1341. browse: function( section ) {
  1342. // Create a new collection with the proper theme data
  1343. // for each section.
  1344. this.collection.query( { browse: section } );
  1345. },
  1346. // Sorting navigation.
  1347. onSort: function( event ) {
  1348. var $el = $( event.target ),
  1349. sort = $el.data( 'sort' );
  1350. event.preventDefault();
  1351. $( 'body' ).removeClass( 'filters-applied show-filters' );
  1352. $( '.drawer-toggle' ).attr( 'aria-expanded', 'false' );
  1353. // Bail if this is already active.
  1354. if ( $el.hasClass( this.activeClass ) ) {
  1355. return;
  1356. }
  1357. this.sort( sort );
  1358. // Trigger a router.navigate update.
  1359. themes.router.navigate( themes.router.baseUrl( themes.router.browsePath + sort ) );
  1360. },
  1361. sort: function( sort ) {
  1362. this.clearSearch();
  1363. // Track sorting so we can restore the correct tab when closing preview.
  1364. themes.router.selectedTab = sort;
  1365. $( '.filter-links li > a, .theme-filter' )
  1366. .removeClass( this.activeClass )
  1367. .removeAttr( 'aria-current' );
  1368. $( '[data-sort="' + sort + '"]' )
  1369. .addClass( this.activeClass )
  1370. .attr( 'aria-current', 'page' );
  1371. if ( 'favorites' === sort ) {
  1372. $( 'body' ).addClass( 'show-favorites-form' );
  1373. } else {
  1374. $( 'body' ).removeClass( 'show-favorites-form' );
  1375. }
  1376. this.browse( sort );
  1377. },
  1378. // Filters and Tags.
  1379. onFilter: function( event ) {
  1380. var request,
  1381. $el = $( event.target ),
  1382. filter = $el.data( 'filter' );
  1383. // Bail if this is already active.
  1384. if ( $el.hasClass( this.activeClass ) ) {
  1385. return;
  1386. }
  1387. $( '.filter-links li > a, .theme-section' )
  1388. .removeClass( this.activeClass )
  1389. .removeAttr( 'aria-current' );
  1390. $el
  1391. .addClass( this.activeClass )
  1392. .attr( 'aria-current', 'page' );
  1393. if ( ! filter ) {
  1394. return;
  1395. }
  1396. // Construct the filter request
  1397. // using the default values.
  1398. filter = _.union( [ filter, this.filtersChecked() ] );
  1399. request = { tag: [ filter ] };
  1400. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1401. // or searching the local cache.
  1402. this.collection.query( request );
  1403. },
  1404. // Clicking on a checkbox to add another filter to the request.
  1405. addFilter: function() {
  1406. this.filtersChecked();
  1407. },
  1408. // Applying filters triggers a tag request.
  1409. applyFilters: function( event ) {
  1410. var name,
  1411. tags = this.filtersChecked(),
  1412. request = { tag: tags },
  1413. filteringBy = $( '.filtered-by .tags' );
  1414. if ( event ) {
  1415. event.preventDefault();
  1416. }
  1417. if ( ! tags ) {
  1418. wp.a11y.speak( l10n.selectFeatureFilter );
  1419. return;
  1420. }
  1421. $( 'body' ).addClass( 'filters-applied' );
  1422. $( '.filter-links li > a.current' )
  1423. .removeClass( 'current' )
  1424. .removeAttr( 'aria-current' );
  1425. filteringBy.empty();
  1426. _.each( tags, function( tag ) {
  1427. name = $( 'label[for="filter-id-' + tag + '"]' ).text();
  1428. filteringBy.append( '<span class="tag">' + name + '</span>' );
  1429. });
  1430. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1431. // or searching the local cache.
  1432. this.collection.query( request );
  1433. },
  1434. // Save the user's WordPress.org username and get his favorite themes.
  1435. saveUsername: function ( event ) {
  1436. var username = $( '#wporg-username-input' ).val(),
  1437. nonce = $( '#wporg-username-nonce' ).val(),
  1438. request = { browse: 'favorites', user: username },
  1439. that = this;
  1440. if ( event ) {
  1441. event.preventDefault();
  1442. }
  1443. // Save username on enter.
  1444. if ( event.type === 'keyup' && event.which !== 13 ) {
  1445. return;
  1446. }
  1447. return wp.ajax.send( 'save-wporg-username', {
  1448. data: {
  1449. _wpnonce: nonce,
  1450. username: username
  1451. },
  1452. success: function () {
  1453. // Get the themes by sending Ajax POST request to api.wordpress.org/themes
  1454. // or searching the local cache.
  1455. that.collection.query( request );
  1456. }
  1457. } );
  1458. },
  1459. /**
  1460. * Get the checked filters.
  1461. *
  1462. * @return {Array} of tags or false
  1463. */
  1464. filtersChecked: function() {
  1465. var items = $( '.filter-group' ).find( ':checkbox' ),
  1466. tags = [];
  1467. _.each( items.filter( ':checked' ), function( item ) {
  1468. tags.push( $( item ).prop( 'value' ) );
  1469. });
  1470. // When no filters are checked, restore initial state and return.
  1471. if ( tags.length === 0 ) {
  1472. $( '.filter-drawer .apply-filters' ).find( 'span' ).text( '' );
  1473. $( '.filter-drawer .clear-filters' ).hide();
  1474. $( 'body' ).removeClass( 'filters-applied' );
  1475. return false;
  1476. }
  1477. $( '.filter-drawer .apply-filters' ).find( 'span' ).text( tags.length );
  1478. $( '.filter-drawer .clear-filters' ).css( 'display', 'inline-block' );
  1479. return tags;
  1480. },
  1481. activeClass: 'current',
  1482. /**
  1483. * When users press the "Upload Theme" button, show the upload form in place.
  1484. */
  1485. uploader: function() {
  1486. var uploadViewToggle = $( '.upload-view-toggle' ),
  1487. $body = $( document.body );
  1488. uploadViewToggle.on( 'click', function() {
  1489. // Toggle the upload view.
  1490. $body.toggleClass( 'show-upload-view' );
  1491. // Toggle the `aria-expanded` button attribute.
  1492. uploadViewToggle.attr( 'aria-expanded', $body.hasClass( 'show-upload-view' ) );
  1493. });
  1494. },
  1495. // Toggle the full filters navigation.
  1496. moreFilters: function( event ) {
  1497. var $body = $( 'body' ),
  1498. $toggleButton = $( '.drawer-toggle' );
  1499. event.preventDefault();
  1500. if ( $body.hasClass( 'filters-applied' ) ) {
  1501. return this.backToFilters();
  1502. }
  1503. this.clearSearch();
  1504. themes.router.navigate( themes.router.baseUrl( '' ) );
  1505. // Toggle the feature filters view.
  1506. $body.toggleClass( 'show-filters' );
  1507. // Toggle the `aria-expanded` button attribute.
  1508. $toggleButton.attr( 'aria-expanded', $body.hasClass( 'show-filters' ) );
  1509. },
  1510. /**
  1511. * Clears all the checked filters.
  1512. *
  1513. * @uses filtersChecked()
  1514. */
  1515. clearFilters: function( event ) {
  1516. var items = $( '.filter-group' ).find( ':checkbox' ),
  1517. self = this;
  1518. event.preventDefault();
  1519. _.each( items.filter( ':checked' ), function( item ) {
  1520. $( item ).prop( 'checked', false );
  1521. return self.filtersChecked();
  1522. });
  1523. },
  1524. backToFilters: function( event ) {
  1525. if ( event ) {
  1526. event.preventDefault();
  1527. }
  1528. $( 'body' ).removeClass( 'filters-applied' );
  1529. },
  1530. clearSearch: function() {
  1531. $( '#wp-filter-search-input').val( '' );
  1532. }
  1533. });
  1534. themes.InstallerRouter = Backbone.Router.extend({
  1535. routes: {
  1536. 'theme-install.php?theme=:slug': 'preview',
  1537. 'theme-install.php?browse=:sort': 'sort',
  1538. 'theme-install.php?search=:query': 'search',
  1539. 'theme-install.php': 'sort'
  1540. },
  1541. baseUrl: function( url ) {
  1542. return 'theme-install.php' + url;
  1543. },
  1544. themePath: '?theme=',
  1545. browsePath: '?browse=',
  1546. searchPath: '?search=',
  1547. search: function( query ) {
  1548. $( '.wp-filter-search' ).val( query.replace( /\+/g, ' ' ) );
  1549. },
  1550. navigate: navigateRouter
  1551. });
  1552. themes.RunInstaller = {
  1553. init: function() {
  1554. // Set up the view.
  1555. // Passes the default 'section' as an option.
  1556. this.view = new themes.view.Installer({
  1557. section: 'popular',
  1558. SearchView: themes.view.InstallerSearch
  1559. });
  1560. // Render results.
  1561. this.render();
  1562. // Start debouncing user searches after Backbone.history.start().
  1563. this.view.SearchView.doSearch = _.debounce( this.view.SearchView.doSearch, 500 );
  1564. },
  1565. render: function() {
  1566. // Render results.
  1567. this.view.render();
  1568. this.routes();
  1569. if ( Backbone.History.started ) {
  1570. Backbone.history.stop();
  1571. }
  1572. Backbone.history.start({
  1573. root: themes.data.settings.adminUrl,
  1574. pushState: true,
  1575. hashChange: false
  1576. });
  1577. },
  1578. routes: function() {
  1579. var self = this,
  1580. request = {};
  1581. // Bind to our global `wp.themes` object
  1582. // so that the router is available to sub-views.
  1583. themes.router = new themes.InstallerRouter();
  1584. // Handles `theme` route event.
  1585. // Queries the API for the passed theme slug.
  1586. themes.router.on( 'route:preview', function( slug ) {
  1587. // Remove existing handlers.
  1588. if ( themes.preview ) {
  1589. themes.preview.undelegateEvents();
  1590. themes.preview.unbind();
  1591. }
  1592. // If the theme preview is active, set the current theme.
  1593. if ( self.view.view.theme && self.view.view.theme.preview ) {
  1594. self.view.view.theme.model = self.view.collection.findWhere( { 'slug': slug } );
  1595. self.view.view.theme.preview();
  1596. } else {
  1597. // Select the theme by slug.
  1598. request.theme = slug;
  1599. self.view.collection.query( request );
  1600. self.view.collection.trigger( 'update' );
  1601. // Open the theme preview.
  1602. self.view.collection.once( 'query:success', function() {
  1603. $( 'div[data-slug="' + slug + '"]' ).trigger( 'click' );
  1604. });
  1605. }
  1606. });
  1607. /*
  1608. * Handles sorting / browsing routes.
  1609. * Also handles the root URL triggering a sort request
  1610. * for `popular`, the default view.
  1611. */
  1612. themes.router.on( 'route:sort', function( sort ) {
  1613. if ( ! sort ) {
  1614. sort = 'popular';
  1615. themes.router.navigate( themes.router.baseUrl( '?browse=popular' ), { replace: true } );
  1616. }
  1617. self.view.sort( sort );
  1618. // Close the preview if open.
  1619. if ( themes.preview ) {
  1620. themes.preview.close();
  1621. }
  1622. });
  1623. // The `search` route event. The router populates the input field.
  1624. themes.router.on( 'route:search', function() {
  1625. $( '.wp-filter-search' ).trigger( 'focus' ).trigger( 'keyup' );
  1626. });
  1627. this.extraRoutes();
  1628. },
  1629. extraRoutes: function() {
  1630. return false;
  1631. }
  1632. };
  1633. // Ready...
  1634. $( function() {
  1635. if ( themes.isInstall ) {
  1636. themes.RunInstaller.init();
  1637. } else {
  1638. themes.Run.init();
  1639. }
  1640. // Update the return param just in time.
  1641. $( document.body ).on( 'click', '.load-customize', function() {
  1642. var link = $( this ), urlParser = document.createElement( 'a' );
  1643. urlParser.href = link.prop( 'href' );
  1644. urlParser.search = $.param( _.extend(
  1645. wp.customize.utils.parseQueryString( urlParser.search.substr( 1 ) ),
  1646. {
  1647. 'return': window.location.href
  1648. }
  1649. ) );
  1650. link.prop( 'href', urlParser.href );
  1651. });
  1652. $( '.broken-themes .delete-theme' ).on( 'click', function() {
  1653. return confirm( _wpThemeSettings.settings.confirmDelete );
  1654. });
  1655. });
  1656. })( jQuery );
  1657. // Align theme browser thickbox.
  1658. jQuery( function($) {
  1659. window.tb_position = function() {
  1660. var tbWindow = $('#TB_window'),
  1661. width = $(window).width(),
  1662. H = $(window).height(),
  1663. W = ( 1040 < width ) ? 1040 : width,
  1664. adminbar_height = 0;
  1665. if ( $('#wpadminbar').length ) {
  1666. adminbar_height = parseInt( $('#wpadminbar').css('height'), 10 );
  1667. }
  1668. if ( tbWindow.length >= 1 ) {
  1669. tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
  1670. $('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
  1671. tbWindow.css({'margin-left': '-' + parseInt( ( ( W - 50 ) / 2 ), 10 ) + 'px'});
  1672. if ( typeof document.body.style.maxWidth !== 'undefined' ) {
  1673. tbWindow.css({'top': 20 + adminbar_height + 'px', 'margin-top': '0'});
  1674. }
  1675. }
  1676. };
  1677. $(window).on( 'resize', function(){ tb_position(); });
  1678. });