customizer.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. /*!
  2. * Bootstrap Customizer (http://getbootstrap.com/customize/)
  3. * Copyright 2011-2016 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.3.7 (http://getbootstrap.com)\n' +
  13. ' * Copyright 2011-' + new Date().getFullYear() + ' Twitter, Inc.\n' +
  14. ' * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)\n' +
  15. ' */\n\n'
  16. var supportsFile = window.File && window.FileReader && window.FileList && window.Blob
  17. var $importDropTarget = $('#import-drop-target')
  18. function showError(msg, err) {
  19. $('<div id="bsCustomizerAlert" class="bs-customizer-alert">' +
  20. '<div class="container">' +
  21. '<a href="#bsCustomizerAlert" data-dismiss="alert" class="close pull-right" aria-label="Close" role="button"><span aria-hidden="true">&times;</span></a>' +
  22. '<p class="bs-customizer-alert-text"><span class="glyphicon glyphicon-warning-sign" aria-hidden="true"></span><span class="sr-only">Warning:</span>' + msg + '</p>' +
  23. (err.message ? $('<p></p>').text('Error: ' + err.message)[0].outerHTML : '') +
  24. (err.extract ? $('<pre class="bs-customizer-alert-extract"></pre>').text(err.extract.join('\n'))[0].outerHTML : '') +
  25. '</div>' +
  26. '</div>').appendTo('body').alert()
  27. throw err
  28. }
  29. function showSuccess(msg) {
  30. $('<div class="bs-callout bs-callout-info">' +
  31. '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' + msg +
  32. '</div>').insertAfter('.bs-customize-download')
  33. }
  34. function showCallout(msg, showUpTop) {
  35. var $callout = $('<div class="bs-callout bs-callout-danger">' +
  36. '<h4>Attention!</h4>' +
  37. '<p>' + msg + '</p>' +
  38. '</div>')
  39. if (showUpTop) {
  40. $callout.appendTo('.bs-docs-container')
  41. } else {
  42. $callout.insertAfter('.bs-customize-download')
  43. }
  44. }
  45. function showAlert(type, msg, insertAfter) {
  46. $('<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>')
  47. .insertAfter(insertAfter)
  48. }
  49. function getQueryParam(key) {
  50. key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, '\\$&') // escape RegEx meta chars
  51. var match = location.search.match(new RegExp('[?&]' + key + '=([^&]+)(&|$)'))
  52. return match && decodeURIComponent(match[1].replace(/\+/g, ' '))
  53. }
  54. function createGist(configJson, callback) {
  55. var data = {
  56. description: 'Bootstrap Customizer Config',
  57. 'public': true,
  58. files: {
  59. 'config.json': {
  60. content: configJson
  61. }
  62. }
  63. }
  64. $.ajax({
  65. url: 'https://api.github.com/gists',
  66. type: 'POST',
  67. contentType: 'application/json; charset=UTF-8',
  68. dataType: 'json',
  69. data: JSON.stringify(data)
  70. })
  71. .success(function (result) {
  72. var gistUrl = result.html_url;
  73. var origin = window.location.protocol + '//' + window.location.host
  74. var customizerUrl = origin + window.location.pathname + '?id=' + result.id
  75. showSuccess('<strong>Success!</strong> Your configuration has been saved to <a href="' + gistUrl + '">' + gistUrl + '</a> ' +
  76. 'and can be revisited here at <a href="' + customizerUrl + '">' + customizerUrl + '</a> for further customization.')
  77. history.replaceState(false, document.title, customizerUrl)
  78. callback(gistUrl, customizerUrl)
  79. })
  80. .error(function (err) {
  81. try {
  82. showError('<strong>Ruh roh!</strong> Could not save gist file, configuration not saved.', err)
  83. } catch (sameErr) {
  84. // deliberately ignore the error
  85. }
  86. callback('<none>', '<none>')
  87. })
  88. }
  89. function getCustomizerData() {
  90. var vars = {}
  91. $('#less-variables-section input')
  92. .each(function () {
  93. $(this).val() && (vars[$(this).prev().text()] = $(this).val())
  94. })
  95. var data = {
  96. vars: vars,
  97. css: $('#less-section input:checked') .map(function () { return this.value }).toArray(),
  98. js: $('#plugin-section input:checked').map(function () { return this.value }).toArray()
  99. }
  100. if ($.isEmptyObject(data.vars) && !data.css.length && !data.js.length) return null
  101. return data
  102. }
  103. function updateCustomizerFromJson(data) {
  104. if (data.js) {
  105. $('#plugin-section input').each(function () {
  106. $(this).prop('checked', ~$.inArray(this.value, data.js))
  107. })
  108. }
  109. if (data.css) {
  110. $('#less-section input').each(function () {
  111. $(this).prop('checked', ~$.inArray(this.value, data.css))
  112. })
  113. }
  114. if (data.vars) {
  115. for (var i in data.vars) {
  116. $('input[data-var="' + i + '"]').val(data.vars[i])
  117. }
  118. }
  119. }
  120. function parseUrl() {
  121. var id = getQueryParam('id')
  122. if (!id) return
  123. $.ajax({
  124. url: 'https://api.github.com/gists/' + id,
  125. type: 'GET',
  126. dataType: 'json'
  127. })
  128. .success(function (result) {
  129. var data = JSON.parse(result.files['config.json'].content)
  130. updateCustomizerFromJson(data)
  131. })
  132. .error(function (err) {
  133. showError('Error fetching bootstrap config file', err)
  134. })
  135. }
  136. function generateZip(css, js, fonts, config, complete) {
  137. if (!css && !js) return showError('<strong>Ruh roh!</strong> No Bootstrap files selected.', new Error('no Bootstrap'))
  138. var zip = new JSZip()
  139. if (css) {
  140. var cssFolder = zip.folder('css')
  141. for (var fileName in css) {
  142. cssFolder.file(fileName, css[fileName])
  143. }
  144. }
  145. if (js) {
  146. var jsFolder = zip.folder('js')
  147. for (var jsFileName in js) {
  148. jsFolder.file(jsFileName, js[jsFileName])
  149. }
  150. }
  151. if (fonts) {
  152. var fontsFolder = zip.folder('fonts')
  153. for (var fontsFileName in fonts) {
  154. fontsFolder.file(fontsFileName, fonts[fontsFileName], { base64: true })
  155. }
  156. }
  157. if (config) {
  158. zip.file('config.json', config)
  159. }
  160. var content = zip.generate({ type: 'blob' })
  161. complete(content)
  162. }
  163. function generateCustomLess(vars) {
  164. var result = ''
  165. for (var key in vars) {
  166. result += key + ': ' + vars[key] + ';\n'
  167. }
  168. return result + '\n\n'
  169. }
  170. function generateFonts() {
  171. var $glyphicons = $('#less-section [value="glyphicons.less"]:checked')
  172. if ($glyphicons.length) {
  173. return __fonts
  174. }
  175. }
  176. // Returns an Array of @import'd filenames in the order
  177. // in which they appear in the file.
  178. function includedLessFilenames(lessFilename) {
  179. var IMPORT_REGEX = /^@import \"(.*?)\";$/
  180. var lessLines = __less[lessFilename].split('\n')
  181. var imports = []
  182. $.each(lessLines, function (index, lessLine) {
  183. var match = IMPORT_REGEX.exec(lessLine)
  184. if (match) {
  185. var importee = match[1]
  186. var transitiveImports = includedLessFilenames(importee)
  187. $.each(transitiveImports, function (index, transitiveImportee) {
  188. if ($.inArray(transitiveImportee, imports) === -1) {
  189. imports.push(transitiveImportee)
  190. }
  191. })
  192. imports.push(importee)
  193. }
  194. })
  195. return imports
  196. }
  197. function generateLESS(lessFilename, lessFileIncludes, vars) {
  198. var lessSource = __less[lessFilename]
  199. var lessFilenames = includedLessFilenames(lessFilename)
  200. $.each(lessFilenames, function (index, filename) {
  201. var fileInclude = lessFileIncludes[filename]
  202. // Files not explicitly unchecked are compiled into the final stylesheet.
  203. // Core stylesheets like 'normalize.less' are not included in the form
  204. // since disabling them would wreck everything, and so their 'fileInclude'
  205. // will be 'undefined'.
  206. if (fileInclude || fileInclude == null) lessSource += __less[filename]
  207. // Custom variables are added after Bootstrap variables so the custom
  208. // ones take precedence.
  209. if (filename === 'variables.less' && vars) lessSource += generateCustomLess(vars)
  210. })
  211. lessSource = lessSource.replace(/@import[^\n]*/gi, '') // strip any imports
  212. return lessSource
  213. }
  214. function compileLESS(lessSource, baseFilename, intoResult) {
  215. var promise = $.Deferred()
  216. var parser = new less.Parser({
  217. paths: ['variables.less', 'mixins.less'],
  218. optimization: 0,
  219. filename: baseFilename + '.css'
  220. })
  221. parser.parse(lessSource, function (parseErr, tree) {
  222. if (parseErr) {
  223. return promise.reject(parseErr)
  224. }
  225. try {
  226. intoResult[baseFilename + '.css'] = cw + tree.toCSS()
  227. intoResult[baseFilename + '.min.css'] = cw + tree.toCSS({ compress: true })
  228. } catch (compileErr) {
  229. return promise.reject(compileErr)
  230. }
  231. promise.resolve()
  232. })
  233. return promise.promise()
  234. }
  235. function generateCSS(preamble) {
  236. var promise = $.Deferred()
  237. var oneChecked = false
  238. var lessFileIncludes = {}
  239. $('#less-section input').each(function () {
  240. var $this = $(this)
  241. var checked = $this.is(':checked')
  242. lessFileIncludes[$this.val()] = checked
  243. oneChecked = oneChecked || checked
  244. })
  245. if (!oneChecked) return false
  246. var result = {}
  247. var vars = {}
  248. $('#less-variables-section input')
  249. .each(function () {
  250. $(this).val() && (vars[$(this).prev().text()] = $(this).val())
  251. })
  252. var bsLessSource = preamble + generateLESS('bootstrap.less', lessFileIncludes, vars)
  253. var themeLessSource = preamble + generateLESS('theme.less', lessFileIncludes, vars)
  254. var prefixer = autoprefixer({ browsers: __configBridge.autoprefixerBrowsers })
  255. $.when(
  256. compileLESS(bsLessSource, 'bootstrap', result),
  257. compileLESS(themeLessSource, 'bootstrap-theme', result)
  258. ).done(function () {
  259. for (var key in result) {
  260. result[key] = prefixer.process(result[key]).css
  261. }
  262. promise.resolve(result)
  263. }).fail(function (err) {
  264. showError('<strong>Ruh roh!</strong> Problem parsing or compiling Less files.', err)
  265. promise.reject()
  266. })
  267. return promise.promise()
  268. }
  269. function uglify(js) {
  270. var ast = UglifyJS.parse(js)
  271. ast.figure_out_scope()
  272. var compressor = UglifyJS.Compressor()
  273. var compressedAst = ast.transform(compressor)
  274. compressedAst.figure_out_scope()
  275. compressedAst.compute_char_frequency()
  276. compressedAst.mangle_names()
  277. var stream = UglifyJS.OutputStream()
  278. compressedAst.print(stream)
  279. return stream.toString()
  280. }
  281. function generateJS(preamble) {
  282. var $checked = $('#plugin-section input:checked')
  283. var jqueryCheck = __configBridge.jqueryCheck.join('\n')
  284. var jqueryVersionCheck = __configBridge.jqueryVersionCheck.join('\n')
  285. if (!$checked.length) return false
  286. var js = $checked
  287. .map(function () { return __js[this.value] })
  288. .toArray()
  289. .join('\n')
  290. preamble = cw + preamble
  291. js = jqueryCheck + jqueryVersionCheck + js
  292. return {
  293. 'bootstrap.js': preamble + js,
  294. 'bootstrap.min.js': preamble + uglify(js)
  295. }
  296. }
  297. function removeImportAlerts() {
  298. $importDropTarget.nextAll('.alert').remove()
  299. }
  300. function handleConfigFileSelect(e) {
  301. e.stopPropagation()
  302. e.preventDefault()
  303. var file = e.originalEvent.hasOwnProperty('dataTransfer') ? e.originalEvent.dataTransfer.files[0] : e.originalEvent.target.files[0]
  304. var reader = new FileReader()
  305. reader.onload = function (e) {
  306. var text = e.target.result
  307. try {
  308. var json = JSON.parse(text)
  309. if (!$.isPlainObject(json)) {
  310. throw new Error('JSON data from config file is not an object.')
  311. }
  312. updateCustomizerFromJson(json)
  313. showAlert('success', '<strong>Woohoo!</strong> Your configuration was successfully uploaded. Tweak your settings, then hit Download.', $importDropTarget)
  314. } catch (err) {
  315. return showAlert('danger', '<strong>Shucks.</strong> We can only read valid <code>.json</code> files. Please try again.', $importDropTarget)
  316. }
  317. }
  318. reader.readAsText(file, 'utf-8')
  319. }
  320. function handleConfigDragOver(e) {
  321. e.stopPropagation()
  322. e.preventDefault()
  323. e.originalEvent.dataTransfer.dropEffect = 'copy'
  324. removeImportAlerts()
  325. }
  326. if (supportsFile) {
  327. $importDropTarget
  328. .on('dragover', handleConfigDragOver)
  329. .on('drop', handleConfigFileSelect)
  330. }
  331. $('#import-file-select').on('change', handleConfigFileSelect)
  332. $('#import-manual-trigger').on('click', removeImportAlerts)
  333. var $inputsComponent = $('#less-section input')
  334. var $inputsPlugin = $('#plugin-section input')
  335. var $inputsVariables = $('#less-variables-section input')
  336. $('#less-section .toggle').on('click', function (e) {
  337. e.preventDefault()
  338. $inputsComponent.prop('checked', !$inputsComponent.is(':checked'))
  339. })
  340. $('#plugin-section .toggle').on('click', function (e) {
  341. e.preventDefault()
  342. $inputsPlugin.prop('checked', !$inputsPlugin.is(':checked'))
  343. })
  344. $('#less-variables-section .toggle').on('click', function (e) {
  345. e.preventDefault()
  346. $inputsVariables.val('')
  347. })
  348. $('[data-dependencies]').on('click', function () {
  349. if (!$(this).is(':checked')) return
  350. var dependencies = this.getAttribute('data-dependencies')
  351. if (!dependencies) return
  352. dependencies = dependencies.split(',')
  353. for (var i = 0; i < dependencies.length; i++) {
  354. var $dependency = $('[value="' + dependencies[i] + '"]')
  355. $dependency && $dependency.prop('checked', true)
  356. }
  357. })
  358. $('[data-dependents]').on('click', function () {
  359. if ($(this).is(':checked')) return
  360. var dependents = this.getAttribute('data-dependents')
  361. if (!dependents) return
  362. dependents = dependents.split(',')
  363. for (var i = 0; i < dependents.length; i++) {
  364. var $dependent = $('[value="' + dependents[i] + '"]')
  365. $dependent && $dependent.prop('checked', false)
  366. }
  367. })
  368. var $compileBtn = $('#btn-compile')
  369. $compileBtn.on('click', function (e) {
  370. var configData = getCustomizerData()
  371. var configJson = JSON.stringify(configData, null, 2)
  372. e.preventDefault()
  373. $compileBtn.attr('disabled', 'disabled')
  374. createGist(configJson, function (gistUrl, customizerUrl) {
  375. configData.customizerUrl = customizerUrl
  376. configJson = JSON.stringify(configData, null, 2)
  377. var preamble = '/*!\n' +
  378. ' * Generated using the Bootstrap Customizer (' + customizerUrl + ')\n' +
  379. ' * Config saved to config.json and ' + gistUrl + '\n' +
  380. ' */\n'
  381. $.when(
  382. generateCSS(preamble),
  383. generateJS(preamble),
  384. generateFonts()
  385. ).done(function (css, js, fonts) {
  386. generateZip(css, js, fonts, configJson, function (blob) {
  387. $compileBtn.removeAttr('disabled')
  388. setTimeout(function () {
  389. saveAs(blob, 'bootstrap.zip')
  390. }, 0)
  391. })
  392. })
  393. })
  394. });
  395. // browser support alert
  396. (function () {
  397. function failback() {
  398. $('.bs-docs-section, .bs-docs-sidebar').css('display', 'none')
  399. showCallout('Looks like your current browser doesn\'t support the Bootstrap Customizer. Please take a second ' +
  400. 'to <a href="http://browsehappy.com/">upgrade to a more modern browser</a> (other than Safari).', true)
  401. }
  402. /**
  403. * Based on:
  404. * Blob Feature Check v1.1.0
  405. * https://github.com/ssorallen/blob-feature-check/
  406. * License: Public domain (http://unlicense.org)
  407. */
  408. var url = window.webkitURL || window.URL // Safari 6 uses "webkitURL".
  409. var svg = new Blob(
  410. ['<svg xmlns=\'http://www.w3.org/2000/svg\'></svg>'],
  411. { type: 'image/svg+xml;charset=utf-8' }
  412. )
  413. var objectUrl = url.createObjectURL(svg);
  414. if (/^blob:/.exec(objectUrl) === null || !supportsFile) {
  415. // `URL.createObjectURL` created a URL that started with something other
  416. // than "blob:", which means it has been polyfilled and is not supported by
  417. // this browser.
  418. failback()
  419. } else {
  420. $('<img>')
  421. .on('load', function () {
  422. $compileBtn.prop('disabled', false)
  423. })
  424. .on('error', failback)
  425. .attr('src', objectUrl)
  426. }
  427. })();
  428. parseUrl()
  429. }