customizer.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. /*!
  2. * Bootstrap Customizer (https://getbootstrap.com/customize/)
  3. * Copyright 2011-2019 Twitter, Inc.
  4. *
  5. * Licensed under the Creative Commons Attribution 3.0 Unported License. For
  6. * details, see https://creativecommons.org/licenses/by/3.0/.
  7. */
  8. /* global JSON, JSZip, less, autoprefixer, saveAs, UglifyJS, __configBridge, __js, __less, __fonts */
  9. window.onload = function () { // wait for load in a dumb way because B-0
  10. 'use strict';
  11. var cw = '/*!\n' +
  12. ' * Bootstrap v3.4.1 (https://getbootstrap.com/)\n' +
  13. ' * Copyright 2011-' + new Date().getFullYear() + ' Twitter, Inc.\n' +
  14. ' * Licensed under the MIT license\n' +
  15. ' */\n\n'
  16. var $importDropTarget = $('#import-drop-target')
  17. function showError(msg, err) {
  18. $('<div id="bsCustomizerAlert" class="bs-customizer-alert">' +
  19. '<div class="container">' +
  20. '<a href="#bsCustomizerAlert" data-dismiss="alert" class="close pull-right" aria-label="Close" role="button"><span aria-hidden="true">&times;</span></a>' +
  21. '<p class="bs-customizer-alert-text"><span class="glyphicon glyphicon-warning-sign" aria-hidden="true"></span><span class="sr-only">Warning:</span>' + msg + '</p>' +
  22. (err.message ? $('<p></p>').text('Error: ' + err.message)[0].outerHTML : '') +
  23. (err.extract ? $('<pre class="bs-customizer-alert-extract"></pre>').text(err.extract.join('\n'))[0].outerHTML : '') +
  24. '</div>' +
  25. '</div>').appendTo('body').alert()
  26. throw err
  27. }
  28. function showAlert(type, msg, insertAfter) {
  29. $('<div class="alert alert-' + type + '">' + msg + '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>')
  30. .insertAfter(insertAfter)
  31. }
  32. function getQueryParam(key) {
  33. key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, '\\$&') // escape RegEx meta chars
  34. var match = location.search.match(new RegExp('[?&]' + key + '=([^&]+)(&|$)'))
  35. return match && decodeURIComponent(match[1].replace(/\+/g, ' '))
  36. }
  37. function getCustomizerData() {
  38. var vars = {}
  39. $('#less-variables-section input')
  40. .each(function () {
  41. $(this).val() && (vars[$(this).prev().text()] = $(this).val())
  42. })
  43. var data = {
  44. vars: vars,
  45. css: $('#less-section input:checked') .map(function () { return this.value }).toArray(),
  46. js: $('#plugin-section input:checked').map(function () { return this.value }).toArray()
  47. }
  48. if ($.isEmptyObject(data.vars) && !data.css.length && !data.js.length) return null
  49. return data
  50. }
  51. function updateCustomizerFromJson(data) {
  52. if (data.js) {
  53. $('#plugin-section input').each(function () {
  54. $(this).prop('checked', ~$.inArray(this.value, data.js))
  55. })
  56. }
  57. if (data.css) {
  58. $('#less-section input').each(function () {
  59. $(this).prop('checked', ~$.inArray(this.value, data.css))
  60. })
  61. }
  62. if (data.vars) {
  63. for (var i in data.vars) {
  64. $('input[data-var="' + i + '"]').val(data.vars[i])
  65. }
  66. }
  67. }
  68. function parseUrl() {
  69. var id = getQueryParam('id')
  70. if (!id) return
  71. $.ajax({
  72. url: 'https://api.github.com/gists/' + id,
  73. type: 'GET',
  74. dataType: 'json'
  75. })
  76. .success(function (result) {
  77. var data = JSON.parse(result.files['config.json'].content)
  78. updateCustomizerFromJson(data)
  79. })
  80. .error(function (err) {
  81. showError('Error fetching bootstrap config file', err)
  82. })
  83. }
  84. function generateZip(css, js, fonts, config, complete) {
  85. if (!css && !js) return showError('<strong>Ruh roh!</strong> No Bootstrap files selected.', new Error('no Bootstrap'))
  86. var zip = new JSZip()
  87. if (css) {
  88. var cssFolder = zip.folder('css')
  89. for (var fileName in css) {
  90. cssFolder.file(fileName, css[fileName])
  91. }
  92. }
  93. if (js) {
  94. var jsFolder = zip.folder('js')
  95. for (var jsFileName in js) {
  96. jsFolder.file(jsFileName, js[jsFileName])
  97. }
  98. }
  99. if (fonts) {
  100. var fontsFolder = zip.folder('fonts')
  101. for (var fontsFileName in fonts) {
  102. fontsFolder.file(fontsFileName, fonts[fontsFileName], { base64: true })
  103. }
  104. }
  105. if (config) {
  106. zip.file('config.json', config)
  107. }
  108. var content = zip.generate({ type: 'blob' })
  109. complete(content)
  110. }
  111. function generateCustomLess(vars) {
  112. var result = ''
  113. for (var key in vars) {
  114. result += key + ': ' + vars[key] + ';\n'
  115. }
  116. return result + '\n\n'
  117. }
  118. function generateFonts() {
  119. var $glyphicons = $('#less-section [value="glyphicons.less"]:checked')
  120. if ($glyphicons.length) {
  121. return __fonts
  122. }
  123. }
  124. // Returns an Array of @import'd filenames in the order
  125. // in which they appear in the file.
  126. function includedLessFilenames(lessFilename) {
  127. var IMPORT_REGEX = /^@import \"(.*?)\";$/
  128. var lessLines = __less[lessFilename].split('\n')
  129. var imports = []
  130. $.each(lessLines, function (index, lessLine) {
  131. var match = IMPORT_REGEX.exec(lessLine)
  132. if (match) {
  133. var importee = match[1]
  134. var transitiveImports = includedLessFilenames(importee)
  135. $.each(transitiveImports, function (index, transitiveImportee) {
  136. if ($.inArray(transitiveImportee, imports) === -1) {
  137. imports.push(transitiveImportee)
  138. }
  139. })
  140. imports.push(importee)
  141. }
  142. })
  143. return imports
  144. }
  145. function generateLESS(lessFilename, lessFileIncludes, vars) {
  146. var lessSource = __less[lessFilename]
  147. var lessFilenames = includedLessFilenames(lessFilename)
  148. $.each(lessFilenames, function (index, filename) {
  149. var fileInclude = lessFileIncludes[filename]
  150. // Files not explicitly unchecked are compiled into the final stylesheet.
  151. // Core stylesheets like 'normalize.less' are not included in the form
  152. // since disabling them would wreck everything, and so their 'fileInclude'
  153. // will be 'undefined'.
  154. if (fileInclude || fileInclude == null) lessSource += __less[filename]
  155. // Custom variables are added after Bootstrap variables so the custom
  156. // ones take precedence.
  157. if (filename === 'variables.less' && vars) lessSource += generateCustomLess(vars)
  158. })
  159. lessSource = lessSource.replace(/@import[^\n]*/gi, '') // strip any imports
  160. return lessSource
  161. }
  162. function compileLESS(lessSource, baseFilename, intoResult) {
  163. var promise = $.Deferred()
  164. var parser = new less.Parser({
  165. paths: ['variables.less', 'mixins.less'],
  166. optimization: 0,
  167. filename: baseFilename + '.css'
  168. })
  169. parser.parse(lessSource, function (parseErr, tree) {
  170. if (parseErr) {
  171. return promise.reject(parseErr)
  172. }
  173. try {
  174. intoResult[baseFilename + '.css'] = tree.toCSS()
  175. intoResult[baseFilename + '.min.css'] = tree.toCSS({ compress: true })
  176. } catch (compileErr) {
  177. return promise.reject(compileErr)
  178. }
  179. promise.resolve()
  180. })
  181. return promise.promise()
  182. }
  183. function generateCSS(preamble) {
  184. var promise = $.Deferred()
  185. var oneChecked = false
  186. var lessFileIncludes = {}
  187. $('#less-section input').each(function () {
  188. var $this = $(this)
  189. var checked = $this.is(':checked')
  190. lessFileIncludes[$this.val()] = checked
  191. oneChecked = oneChecked || checked
  192. })
  193. if (!oneChecked) return false
  194. var result = {}
  195. var vars = {}
  196. $('#less-variables-section input')
  197. .each(function () {
  198. $(this).val() && (vars[$(this).prev().text()] = $(this).val())
  199. })
  200. var bsLessSource = preamble + generateLESS('bootstrap.less', lessFileIncludes, vars)
  201. var themeLessSource = preamble + generateLESS('theme.less', lessFileIncludes, vars)
  202. var prefixer = autoprefixer(__configBridge.autoprefixer)
  203. $.when(
  204. compileLESS(bsLessSource, 'bootstrap', result),
  205. compileLESS(themeLessSource, 'bootstrap-theme', result)
  206. ).done(function () {
  207. for (var key in result) {
  208. result[key] = prefixer.process(result[key]).css
  209. }
  210. promise.resolve(result)
  211. }).fail(function (err) {
  212. showError('<strong>Ruh roh!</strong> Problem parsing or compiling Less files.', err)
  213. promise.reject()
  214. })
  215. return promise.promise()
  216. }
  217. function uglify(js) {
  218. var ast = UglifyJS.parse(js)
  219. ast.figure_out_scope()
  220. var compressor = UglifyJS.Compressor()
  221. var compressedAst = ast.transform(compressor)
  222. compressedAst.figure_out_scope()
  223. compressedAst.compute_char_frequency()
  224. compressedAst.mangle_names()
  225. var stream = UglifyJS.OutputStream()
  226. compressedAst.print(stream)
  227. return stream.toString()
  228. }
  229. function generateJS(preamble) {
  230. var $checked = $('#plugin-section input:checked')
  231. var jqueryCheck = __configBridge.jqueryCheck.join('\n')
  232. var jqueryVersionCheck = __configBridge.jqueryVersionCheck.join('\n')
  233. if (!$checked.length) return false
  234. var js = $checked
  235. .map(function () { return __js[this.value] })
  236. .toArray()
  237. .join('\n')
  238. preamble = preamble + cw
  239. js = jqueryCheck + jqueryVersionCheck + js
  240. return {
  241. 'bootstrap.js': preamble + js,
  242. 'bootstrap.min.js': preamble + uglify(js)
  243. }
  244. }
  245. function removeImportAlerts() {
  246. $importDropTarget.nextAll('.alert').remove()
  247. }
  248. function handleConfigFileSelect(e) {
  249. e.stopPropagation()
  250. e.preventDefault()
  251. var file = e.originalEvent.target.files[0]
  252. var reader = new FileReader()
  253. reader.onload = function (e) {
  254. var text = e.target.result
  255. try {
  256. var json = JSON.parse(text)
  257. if (!$.isPlainObject(json)) {
  258. throw new Error('JSON data from config file is not an object.')
  259. }
  260. updateCustomizerFromJson(json)
  261. showAlert('success', '<strong>Woohoo!</strong> Your configuration was successfully uploaded. Tweak your settings, then hit Download.', $importDropTarget)
  262. } catch (err) {
  263. return showAlert('danger', '<strong>Shucks.</strong> We can only read valid <code>.json</code> files. Please try again.', $importDropTarget)
  264. }
  265. }
  266. reader.readAsText(file, 'utf-8')
  267. }
  268. $('#import-file-select').on('change', handleConfigFileSelect)
  269. $('#import-manual-trigger').on('click', removeImportAlerts)
  270. var $inputsComponent = $('#less-section input')
  271. var $inputsPlugin = $('#plugin-section input')
  272. var $inputsVariables = $('#less-variables-section input')
  273. $('#less-section .toggle').on('click', function (e) {
  274. e.preventDefault()
  275. $inputsComponent.prop('checked', !$inputsComponent.is(':checked'))
  276. })
  277. $('#plugin-section .toggle').on('click', function (e) {
  278. e.preventDefault()
  279. $inputsPlugin.prop('checked', !$inputsPlugin.is(':checked'))
  280. })
  281. $('#less-variables-section .toggle').on('click', function (e) {
  282. e.preventDefault()
  283. $inputsVariables.val('')
  284. })
  285. $('[data-dependencies]').on('click', function () {
  286. if (!$(this).is(':checked')) return
  287. var dependencies = this.getAttribute('data-dependencies')
  288. if (!dependencies) return
  289. dependencies = dependencies.split(',')
  290. for (var i = 0, len = dependencies.length; i < len; i++) {
  291. var $dependency = $('[value="' + dependencies[i] + '"]')
  292. $dependency && $dependency.prop('checked', true)
  293. }
  294. })
  295. $('[data-dependents]').on('click', function () {
  296. if ($(this).is(':checked')) return
  297. var dependents = this.getAttribute('data-dependents')
  298. if (!dependents) return
  299. dependents = dependents.split(',')
  300. for (var i = 0, len = dependents.length; i < len; i++) {
  301. var $dependent = $('[value="' + dependents[i] + '"]')
  302. $dependent && $dependent.prop('checked', false)
  303. }
  304. })
  305. var $compileBtn = $('#btn-compile')
  306. $compileBtn.on('click', function (e) {
  307. e.preventDefault()
  308. $compileBtn.attr('disabled', 'disabled')
  309. function generate() {
  310. var configData = getCustomizerData()
  311. var configJson = JSON.stringify(configData, null, 2)
  312. var origin = window.location.protocol + '//' + window.location.host
  313. var customizerUrl = origin + window.location.pathname
  314. var preamble = '/*!\n' +
  315. ' * Generated using the Bootstrap Customizer (' + customizerUrl + ')\n' +
  316. ' */\n\n'
  317. $.when(
  318. generateCSS(preamble),
  319. generateJS(preamble),
  320. generateFonts()
  321. ).done(function (css, js, fonts) {
  322. generateZip(css, js, fonts, configJson, function (blob) {
  323. $compileBtn.removeAttr('disabled')
  324. setTimeout(function () {
  325. saveAs(blob, 'bootstrap.zip')
  326. }, 0)
  327. })
  328. })
  329. }
  330. generate()
  331. });
  332. parseUrl()
  333. }