customizer.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. /*!
  2. * Copyright 2013 Twitter, Inc.
  3. *
  4. * Licensed under the Creative Commons Attribution 3.0 Unported License. For
  5. * details, see http://creativecommons.org/licenses/by/3.0/.
  6. */
  7. window.onload = function () { // wait for load in a dumb way because B-0
  8. var cw = '/*!\n * Bootstrap v3.0.3\n *\n * Copyright 2013 Twitter, Inc\n * Licensed under the Apache License v2.0\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Designed and built with all the love in the world @twitter by @mdo and @fat.\n */\n\n'
  9. function showError(msg, err) {
  10. $('<div id="bsCustomizerAlert" class="bs-customizer-alert">\
  11. <div class="container">\
  12. <a href="#bsCustomizerAlert" data-dismiss="alert" class="close pull-right">&times;</a>\
  13. <p class="bs-customizer-alert-text"><span class="glyphicon glyphicon-warning-sign"></span>' + msg + '</p>' +
  14. (err.extract ? '<pre class="bs-customizer-alert-extract">' + err.extract.join('\n') + '</pre>' : '') + '\
  15. </div>\
  16. </div>').appendTo('body').alert()
  17. throw err
  18. }
  19. function showCallout(msg, showUpTop) {
  20. var callout = $('<div class="bs-callout bs-callout-danger">\
  21. <h4>Attention!</h4>\
  22. <p>' + msg + '</p>\
  23. </div>')
  24. if (showUpTop) {
  25. callout.appendTo('.bs-docs-container')
  26. } else {
  27. callout.insertAfter('.bs-customize-download')
  28. }
  29. }
  30. function getQueryParam(key) {
  31. key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
  32. var match = location.search.match(new RegExp("[?&]"+key+"=([^&]+)(&|$)"));
  33. return match && decodeURIComponent(match[1].replace(/\+/g, " "));
  34. }
  35. function createGist(configJson) {
  36. var data = {
  37. "description": "Bootstrap Customizer Config",
  38. "public": true,
  39. "files": {
  40. "config.json": {
  41. "content": configJson
  42. }
  43. }
  44. }
  45. $.ajax({
  46. url: 'https://api.github.com/gists',
  47. type: 'POST',
  48. dataType: 'json',
  49. data: JSON.stringify(data)
  50. })
  51. .success(function(result) {
  52. var origin = window.location.protocol + "//" + window.location.host
  53. history.replaceState(false, document.title, origin + window.location.pathname + '?id=' + result.id)
  54. })
  55. .error(function(err) {
  56. showError('<strong>Ruh roh!</strong> Could not save gist file, configuration not saved.', err)
  57. })
  58. }
  59. function getCustomizerData() {
  60. var vars = {}
  61. $('#less-variables-section input')
  62. .each(function () {
  63. $(this).val() && (vars[ $(this).prev().text() ] = $(this).val())
  64. })
  65. var data = {
  66. vars: vars,
  67. css: $('#less-section input:checked') .map(function () { return this.value }).toArray(),
  68. js: $('#plugin-section input:checked').map(function () { return this.value }).toArray()
  69. }
  70. if ($.isEmptyObject(data.vars) && !data.css.length && !data.js.length) return
  71. return data
  72. }
  73. function parseUrl() {
  74. var id = getQueryParam('id')
  75. if (!id) return
  76. $.ajax({
  77. url: 'https://api.github.com/gists/' + id,
  78. type: 'GET',
  79. dataType: 'json'
  80. })
  81. .success(function(result) {
  82. var data = JSON.parse(result.files['config.json'].content)
  83. if (data.js) {
  84. $('#plugin-section input').each(function () {
  85. $(this).prop('checked', ~$.inArray(this.value, data.js))
  86. })
  87. }
  88. if (data.css) {
  89. $('#less-section input').each(function () {
  90. $(this).prop('checked', ~$.inArray(this.value, data.css))
  91. })
  92. }
  93. if (data.vars) {
  94. for (var i in data.vars) {
  95. $('input[data-var="' + i + '"]').val(data.vars[i])
  96. }
  97. }
  98. })
  99. .error(function(err) {
  100. showError('Error fetching bootstrap config file', err)
  101. })
  102. }
  103. function generateZip(css, js, fonts, config, complete) {
  104. if (!css && !js) return showError('<strong>Ruh roh!</strong> No Bootstrap files selected.', new Error('no Bootstrap'))
  105. var zip = new JSZip()
  106. if (css) {
  107. var cssFolder = zip.folder('css')
  108. for (var fileName in css) {
  109. cssFolder.file(fileName, css[fileName])
  110. }
  111. }
  112. if (js) {
  113. var jsFolder = zip.folder('js')
  114. for (var fileName in js) {
  115. jsFolder.file(fileName, js[fileName])
  116. }
  117. }
  118. if (fonts) {
  119. var fontsFolder = zip.folder('fonts')
  120. for (var fileName in fonts) {
  121. fontsFolder.file(fileName, fonts[fileName], {base64: true})
  122. }
  123. }
  124. if (config) {
  125. zip.file('config.json', config)
  126. }
  127. var content = zip.generate({type:"blob"})
  128. complete(content)
  129. }
  130. function generateCustomCSS(vars) {
  131. var result = ''
  132. for (var key in vars) {
  133. result += key + ': ' + vars[key] + ';\n'
  134. }
  135. return result + '\n\n'
  136. }
  137. function generateFonts() {
  138. var glyphicons = $('#less-section [value="glyphicons.less"]:checked')
  139. if (glyphicons.length) {
  140. return __fonts
  141. }
  142. }
  143. // Returns an Array of @import'd filenames from 'bootstrap.less' in the order
  144. // in which they appear in the file.
  145. function bootstrapLessFilenames() {
  146. var IMPORT_REGEX = /^@import \"(.*?)\";$/
  147. var bootstrapLessLines = __less['bootstrap.less'].split('\n')
  148. for (var i = 0, imports = []; i < bootstrapLessLines.length; i++) {
  149. var match = IMPORT_REGEX.exec(bootstrapLessLines[i])
  150. if (match) imports.push(match[1])
  151. }
  152. return imports
  153. }
  154. function generateCSS() {
  155. var oneChecked = false
  156. var lessFileIncludes = {}
  157. $('#less-section input').each(function() {
  158. var $this = $(this)
  159. var checked = $this.is(':checked')
  160. lessFileIncludes[$this.val()] = checked
  161. oneChecked = oneChecked || checked
  162. })
  163. if (!oneChecked) return false
  164. var result = {}
  165. var vars = {}
  166. var css = ''
  167. $('#less-variables-section input')
  168. .each(function () {
  169. $(this).val() && (vars[ $(this).prev().text() ] = $(this).val())
  170. })
  171. $.each(bootstrapLessFilenames(), function(index, filename) {
  172. var fileInclude = lessFileIncludes[filename]
  173. // Files not explicitly unchecked are compiled into the final stylesheet.
  174. // Core stylesheets like 'normalize.less' are not included in the form
  175. // since disabling them would wreck everything, and so their 'fileInclude'
  176. // will be 'undefined'.
  177. if (fileInclude || (fileInclude == null)) css += __less[filename]
  178. // Custom variables are added after Bootstrap variables so the custom
  179. // ones take precedence.
  180. if (('variables.less' === filename) && vars) css += generateCustomCSS(vars)
  181. })
  182. css = css.replace(/@import[^\n]*/gi, '') //strip any imports
  183. try {
  184. var parser = new less.Parser({
  185. paths: ['variables.less', 'mixins.less']
  186. , optimization: 0
  187. , filename: 'bootstrap.css'
  188. }).parse(css, function (err, tree) {
  189. if (err) {
  190. return showError('<strong>Ruh roh!</strong> Could not parse less files.', err)
  191. }
  192. result = {
  193. 'bootstrap.css' : cw + tree.toCSS(),
  194. 'bootstrap.min.css' : cw + tree.toCSS({ compress: true }).replace(/\n/g, '') // FIXME: remove newline hack once less.js upgraded to v1.4
  195. }
  196. })
  197. } catch (err) {
  198. return showError('<strong>Ruh roh!</strong> Could not parse less files.', err)
  199. }
  200. return result
  201. }
  202. function generateJavascript() {
  203. var $checked = $('#plugin-section input:checked')
  204. if (!$checked.length) return false
  205. var js = $checked
  206. .map(function () { return __js[this.value] })
  207. .toArray()
  208. .join('\n')
  209. return {
  210. 'bootstrap.js': js,
  211. 'bootstrap.min.js': cw + uglify(js)
  212. }
  213. }
  214. var inputsComponent = $('#less-section input')
  215. var inputsPlugin = $('#plugin-section input')
  216. var inputsVariables = $('#less-variables-section input')
  217. $('#less-section .toggle').on('click', function (e) {
  218. e.preventDefault()
  219. inputsComponent.prop('checked', !inputsComponent.is(':checked'))
  220. })
  221. $('#plugin-section .toggle').on('click', function (e) {
  222. e.preventDefault()
  223. inputsPlugin.prop('checked', !inputsPlugin.is(':checked'))
  224. })
  225. $('#less-variables-section .toggle').on('click', function (e) {
  226. e.preventDefault()
  227. inputsVariables.val('')
  228. })
  229. $('[data-dependencies]').on('click', function () {
  230. if (!$(this).is(':checked')) return
  231. var dependencies = this.getAttribute('data-dependencies')
  232. if (!dependencies) return
  233. dependencies = dependencies.split(',')
  234. for (var i = 0; i < dependencies.length; i++) {
  235. var dependency = $('[value="' + dependencies[i] + '"]')
  236. dependency && dependency.prop('checked', true)
  237. }
  238. })
  239. $('[data-dependents]').on('click', function () {
  240. if ($(this).is(':checked')) return
  241. var dependents = this.getAttribute('data-dependents')
  242. if (!dependents) return
  243. dependents = dependents.split(',')
  244. for (var i = 0; i < dependents.length; i++) {
  245. var dependent = $('[value="' + dependents[i] + '"]')
  246. dependent && dependent.prop('checked', false)
  247. }
  248. })
  249. var $compileBtn = $('#btn-compile')
  250. var $downloadBtn = $('#btn-download')
  251. $compileBtn.on('click', function (e) {
  252. var configData = getCustomizerData()
  253. var configJson = JSON.stringify(configData, null, 2)
  254. e.preventDefault()
  255. $compileBtn.attr('disabled', 'disabled')
  256. generateZip(generateCSS(), generateJavascript(), generateFonts(), configJson, function (blob) {
  257. $compileBtn.removeAttr('disabled')
  258. saveAs(blob, "bootstrap.zip")
  259. createGist(configJson)
  260. })
  261. })
  262. // browser support alerts
  263. if (!window.URL && navigator.userAgent.toLowerCase().indexOf('safari') != -1) {
  264. showCallout("Looks like you're using safari, which sadly doesn't have the best support\
  265. for HTML5 blobs. Because of this your file will be downloaded with the name <code>\"untitled\"</code>.\
  266. However, if you check your downloads folder, just rename this <code>\"untitled\"</code> file\
  267. to <code>\"bootstrap.zip\"</code> and you should be good to go!")
  268. } else if (!window.URL && !window.webkitURL) {
  269. $('.bs-docs-section, .bs-sidebar').css('display', 'none')
  270. showCallout("Looks like your current browser doesn't support the Bootstrap Customizer. Please take a second\
  271. to <a href=\"https://www.google.com/intl/en/chrome/browser/\"> upgrade to a more modern browser</a>.", true)
  272. }
  273. parseUrl()
  274. }