customizer.js 10.2 KB
Newer Older
1
2
/*!
 * Copyright 2013 Twitter, Inc.
3
4
5
 *
 * Licensed under the Creative Commons Attribution 3.0 Unported License. For
 * details, see http://creativecommons.org/licenses/by/3.0/.
6
7
8
 */


fat's avatar
fat committed
9
window.onload = function () { // wait for load in a dumb way because B-0
Mark Otto's avatar
Mark Otto committed
10
  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'
fat's avatar
fat committed
11

fat's avatar
fat committed
12
  function showError(msg, err) {
fat's avatar
fat committed
13
14
15
    $('<div id="bsCustomizerAlert" class="bs-customizer-alert">\
        <div class="container">\
          <a href="#bsCustomizerAlert" data-dismiss="alert" class="close pull-right">&times;</a>\
16
          <p class="bs-customizer-alert-text"><span class="glyphicon glyphicon-warning-sign"></span>' + msg + '</p>' +
fat's avatar
fat committed
17
18
19
20
21
22
          (err.extract ? '<pre class="bs-customizer-alert-extract">' + err.extract.join('\n') + '</pre>' : '') + '\
        </div>\
      </div>').appendTo('body').alert()
    throw err
  }

fat's avatar
fat committed
23
24
25
26
27
28
29
30
31
32
33
34
35
  function showCallout(msg, showUpTop) {
    var callout = $('<div class="bs-callout bs-callout-danger">\
       <h4>Attention!</h4>\
      <p>' + msg + '</p>\
    </div>')

    if (showUpTop) {
      callout.appendTo('.bs-docs-container')
    } else {
      callout.insertAfter('.bs-customize-download')
    }
  }

fat's avatar
fat committed
36
37
38
39
40
41
  function getQueryParam(key) {
    key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
    var match = location.search.match(new RegExp("[?&]"+key+"=([^&]+)(&|$)"));
    return match && decodeURIComponent(match[1].replace(/\+/g, " "));
  }

42
  function createGist(configJson) {
fat's avatar
fat committed
43
44
45
46
47
    var data = {
      "description": "Bootstrap Customizer Config",
      "public": true,
      "files": {
        "config.json": {
48
          "content": configJson
fat's avatar
fat committed
49
50
51
52
53
54
55
56
57
        }
      }
    }
    $.ajax({
      url: 'https://api.github.com/gists',
      type: 'POST',
      dataType: 'json',
      data: JSON.stringify(data)
    })
fat's avatar
fat committed
58
    .success(function(result) {
59
60
      var origin = window.location.protocol + "//" + window.location.host
      history.replaceState(false, document.title, origin + window.location.pathname + '?id=' + result.id)
fat's avatar
fat committed
61
    })
fat's avatar
fat committed
62
    .error(function(err) {
63
      showError('<strong>Ruh roh!</strong> Could not save gist file, configuration not saved.', err)
fat's avatar
fat committed
64
65
66
    })
  }

fat's avatar
fat committed
67
  function getCustomizerData() {
fat's avatar
fat committed
68
69
70
71
72
73
74
75
76
    var vars = {}

    $('#less-variables-section input')
        .each(function () {
          $(this).val() && (vars[ $(this).prev().text() ] = $(this).val())
        })

    var data = {
      vars: vars,
fat's avatar
fat committed
77
78
      css: $('#less-section input:checked')  .map(function () { return this.value }).toArray(),
      js:  $('#plugin-section input:checked').map(function () { return this.value }).toArray()
fat's avatar
fat committed
79
80
81
82
    }

    if ($.isEmptyObject(data.vars) && !data.css.length && !data.js.length) return

fat's avatar
fat committed
83
    return data
fat's avatar
fat committed
84
85
86
  }

  function parseUrl() {
fat's avatar
fat committed
87
    var id = getQueryParam('id')
fat's avatar
fat committed
88

fat's avatar
fat committed
89
    if (!id) return
fat's avatar
fat committed
90

fat's avatar
fat committed
91
92
93
94
95
96
97
98
99
100
101
    $.ajax({
      url: 'https://api.github.com/gists/' + id,
      type: 'GET',
      dataType: 'json'
    })
    .success(function(result) {
      var data = JSON.parse(result.files['config.json'].content)
      if (data.js) {
        $('#plugin-section input').each(function () {
          $(this).prop('checked', ~$.inArray(this.value, data.js))
        })
fat's avatar
fat committed
102
      }
fat's avatar
fat committed
103
104
105
106
107
108
109
110
111
112
113
      if (data.css) {
        $('#less-section input').each(function () {
          $(this).prop('checked', ~$.inArray(this.value, data.css))
        })
      }
      if (data.vars) {
        for (var i in data.vars) {
          $('input[data-var="' + i + '"]').val(data.vars[i])
        }
      }
    })
fat's avatar
fat committed
114
115
    .error(function(err) {
      showError('Error fetching bootstrap config file', err)
fat's avatar
fat committed
116
    })
fat's avatar
fat committed
117
118
  }

119
  function generateZip(css, js, fonts, config, complete) {
120
    if (!css && !js) return showError('<strong>Ruh roh!</strong> No Bootstrap files selected.', new Error('no Bootstrap'))
fat's avatar
fat committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137

    var zip = new JSZip()

    if (css) {
      var cssFolder = zip.folder('css')
      for (var fileName in css) {
        cssFolder.file(fileName, css[fileName])
      }
    }

    if (js) {
      var jsFolder = zip.folder('js')
      for (var fileName in js) {
        jsFolder.file(fileName, js[fileName])
      }
    }

fat's avatar
fat committed
138
139
140
    if (fonts) {
      var fontsFolder = zip.folder('fonts')
      for (var fileName in fonts) {
141
        fontsFolder.file(fileName, fonts[fileName], {base64: true})
fat's avatar
fat committed
142
143
144
      }
    }

145
146
147
148
    if (config) {
      zip.file('config.json', config)
    }

fat's avatar
fat committed
149
150
151
    var content = zip.generate({type:"blob"})

    complete(content)
fat's avatar
fat committed
152
153
154
155
156
157
158
159
160
161
162
163
  }

  function generateCustomCSS(vars) {
    var result = ''

    for (var key in vars) {
      result += key + ': ' + vars[key] + ';\n'
    }

    return result + '\n\n'
  }

fat's avatar
fat committed
164
165
166
167
168
169
170
  function generateFonts() {
    var glyphicons = $('#less-section [value="glyphicons.less"]:checked')
    if (glyphicons.length) {
      return __fonts
    }
  }

171
172
173
174
175
176
177
178
179
180
181
182
183
184
  // Returns an Array of @import'd filenames from 'bootstrap.less' in the order
  // in which they appear in the file.
  function bootstrapLessFilenames() {
    var IMPORT_REGEX = /^@import \"(.*?)\";$/
    var bootstrapLessLines = __less['bootstrap.less'].split('\n')

    for (var i = 0, imports = []; i < bootstrapLessLines.length; i++) {
      var match = IMPORT_REGEX.exec(bootstrapLessLines[i])
      if (match) imports.push(match[1])
    }

    return imports
  }

fat's avatar
fat committed
185
  function generateCSS() {
186
187
188
189
190
191
192
193
194
    var oneChecked = false
    var lessFileIncludes = {}
    $('#less-section input').each(function() {
      var $this = $(this)
      var checked = $this.is(':checked')
      lessFileIncludes[$this.val()] = checked

      oneChecked = oneChecked || checked
    })
fat's avatar
fat committed
195

196
    if (!oneChecked) return false
fat's avatar
fat committed
197
198
199
200
201
202
203
204
205
206

    var result = {}
    var vars = {}
    var css = ''

    $('#less-variables-section input')
        .each(function () {
          $(this).val() && (vars[ $(this).prev().text() ] = $(this).val())
        })

207
208
209
210
211
212
213
214
215
216
217
218
219
    $.each(bootstrapLessFilenames(), function(index, filename) {
      var fileInclude = lessFileIncludes[filename]

      // Files not explicitly unchecked are compiled into the final stylesheet.
      // Core stylesheets like 'normalize.less' are not included in the form
      // since disabling them would wreck everything, and so their 'fileInclude'
      // will be 'undefined'.
      if (fileInclude || (fileInclude == null)) css += __less[filename]

      // Custom variables are added after Bootstrap variables so the custom
      // ones take precedence.
      if (('variables.less' === filename) && vars) css += generateCustomCSS(vars)
    })
fat's avatar
fat committed
220
221
222
223
224
225
226
227
228

    css = css.replace(/@import[^\n]*/gi, '') //strip any imports

    try {
      var parser = new less.Parser({
          paths: ['variables.less', 'mixins.less']
        , optimization: 0
        , filename: 'bootstrap.css'
      }).parse(css, function (err, tree) {
fat's avatar
fat committed
229
        if (err) {
230
          return showError('<strong>Ruh roh!</strong> Could not parse less files.', err)
fat's avatar
fat committed
231
        }
fat's avatar
fat committed
232
233
        result = {
          'bootstrap.css'     : cw + tree.toCSS(),
Chris Rebert's avatar
Chris Rebert committed
234
          'bootstrap.min.css' : cw + tree.toCSS({ compress: true }).replace(/\n/g, '') // FIXME: remove newline hack once less.js upgraded to v1.4
fat's avatar
fat committed
235
236
237
        }
      })
    } catch (err) {
238
      return showError('<strong>Ruh roh!</strong> Could not parse less files.', err)
fat's avatar
fat committed
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
    }

    return result
  }

  function generateJavascript() {
    var $checked = $('#plugin-section input:checked')
    if (!$checked.length) return false

    var js = $checked
      .map(function () { return __js[this.value] })
      .toArray()
      .join('\n')

    return {
      'bootstrap.js': js,
      'bootstrap.min.js': cw + uglify(js)
    }
  }

  var inputsComponent = $('#less-section input')
  var inputsPlugin    = $('#plugin-section input')
  var inputsVariables = $('#less-variables-section input')

  $('#less-section .toggle').on('click', function (e) {
    e.preventDefault()
    inputsComponent.prop('checked', !inputsComponent.is(':checked'))
  })

  $('#plugin-section .toggle').on('click', function (e) {
    e.preventDefault()
    inputsPlugin.prop('checked', !inputsPlugin.is(':checked'))
  })

  $('#less-variables-section .toggle').on('click', function (e) {
    e.preventDefault()
    inputsVariables.val('')
  })

fat's avatar
fat committed
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
  $('[data-dependencies]').on('click', function () {
    if (!$(this).is(':checked')) return
    var dependencies = this.getAttribute('data-dependencies')
    if (!dependencies) return
    dependencies = dependencies.split(',')
    for (var i = 0; i < dependencies.length; i++) {
      var dependency = $('[value="' + dependencies[i] + '"]')
      dependency && dependency.prop('checked', true)
    }
  })

  $('[data-dependents]').on('click', function () {
    if ($(this).is(':checked')) return
    var dependents = this.getAttribute('data-dependents')
    if (!dependents) return
    dependents = dependents.split(',')
    for (var i = 0; i < dependents.length; i++) {
      var dependent = $('[value="' + dependents[i] + '"]')
      dependent && dependent.prop('checked', false)
    }
  })

fat's avatar
fat committed
300
301
302
303
  var $compileBtn = $('#btn-compile')
  var $downloadBtn = $('#btn-download')

  $compileBtn.on('click', function (e) {
304
305
306
    var configData = getCustomizerData()
    var configJson = JSON.stringify(configData, null, 2)

fat's avatar
fat committed
307
308
309
310
    e.preventDefault()

    $compileBtn.attr('disabled', 'disabled')

311
    generateZip(generateCSS(), generateJavascript(), generateFonts(), configJson, function (blob) {
fat's avatar
fat committed
312
313
      $compileBtn.removeAttr('disabled')
      saveAs(blob, "bootstrap.zip")
314
      createGist(configJson)
fat's avatar
fat committed
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
    })
  })

  // browser support alerts
  if (!window.URL && navigator.userAgent.toLowerCase().indexOf('safari') != -1) {
    showCallout("Looks like you're using safari, which sadly doesn't have the best support\
                 for HTML5 blobs. Because of this your file will be downloaded with the name <code>\"untitled\"</code>.\
                 However, if you check your downloads folder, just rename this <code>\"untitled\"</code> file\
                 to <code>\"bootstrap.zip\"</code> and you should be good to go!")
  } else if (!window.URL && !window.webkitURL) {
    $('.bs-docs-section, .bs-sidebar').css('display', 'none')

    showCallout("Looks like your current browser doesn't support the Bootstrap Customizer. Please take a second\
                to <a href=\"https://www.google.com/intl/en/chrome/browser/\"> upgrade to a more modern browser</a>.", true)
  }

fat's avatar
fat committed
331
  parseUrl()
332
}