-
Notifications
You must be signed in to change notification settings - Fork 0
/
compiler.js
373 lines (280 loc) · 9.57 KB
/
compiler.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
;(function(is_server) {
var BOOL_ATTR = ('allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,default,'+
'defaultchecked,defaultmuted,defaultselected,defer,disabled,draggable,enabled,formnovalidate,hidden,'+
'indeterminate,inert,ismap,itemscope,loop,multiple,muted,nohref,noresize,noshade,novalidate,nowrap,open,'+
'pauseonexit,readonly,required,reversed,scoped,seamless,selected,sortable,spellcheck,translate,truespeed,'+
'typemustmatch,visible').split(',')
// these cannot be auto-closed
var VOID_TAGS = 'area,base,br,col,command,embed,hr,img,input,keygen,link,meta,param,source,track,wbr'.split(',')
/*
Following attributes give error when parsed on browser with { exrp_values }
'd' describes the SVG <path>, Chrome gives error if the value is not valid format
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/d
*/
var PREFIX_ATTR = ['style', 'src', 'd']
var HTML_PARSERS = {
jade: jade
}
var JS_PARSERS = {
coffeescript: coffee,
none: plainjs,
cs: coffee,
es6: es6,
typescript: typescript,
livescript: livescript,
ls: livescript
}
var LINE_TAG = /^<([\w\-]+)>(.*)<\/\1>/gim,
QUOTE = /=({[^}]+})([\s\/\>])/g,
SET_ATTR = /([\w\-]+)=(["'])([^\2]+?)\2/g,
EXPR = /{\s*([^}]+)\s*}/g,
// (tagname) (html) (javascript) endtag
CUSTOM_TAG = /^<([\w\-]+)>([^\x00]*[\w\/}]>$)?([^\x00]*?)^<\/\1>/gim,
SCRIPT = /<script(\s+type=['"]?([^>'"]+)['"]?)?>([^\x00]*?)<\/script>/gm,
STYLE = /<style(\s+type=['"]?([^>'"]+)['"]?|\s+scoped)?>([^\x00]*?)<\/style>/gm,
CSS_SELECTOR = /(^|\}|\{)\s*([^\{\}]+)\s*(?=\{)/g,
CSS_COMMENT = /\/\*[^\x00]*?\*\//gm,
HTML_COMMENT = /<!--.*?-->/g,
CLOSED_TAG = /<([\w\-]+)([^>]*)\/\s*>/g,
LINE_COMMENT = /^\s*\/\/.*$/gm,
JS_COMMENT = /\/\*[^\x00]*?\*\//gm
function compileHTML(html, opts, type) {
var brackets = riot.util.brackets
// whitespace
html = opts.whitespace ? html.replace(/\n/g, '\\n') : html.replace(/\s+/g, ' ')
// strip comments
html = html.trim().replace(HTML_COMMENT, '')
// foo={ bar } --> foo="{ bar }"
html = html.replace(brackets(QUOTE), '="$1"$2')
// alter special attribute names
html = html.replace(SET_ATTR, function(full, name, _, expr) {
if (expr.indexOf(brackets(0)) >= 0) {
name = name.toLowerCase()
if (PREFIX_ATTR.indexOf(name) >= 0) name = 'riot-' + name
// IE8 looses boolean attr values: `checked={ expr }` --> `__checked={ expr }`
else if (BOOL_ATTR.indexOf(name) >= 0) name = '__' + name
}
return name + '="' + expr + '"'
})
// run expressions trough parser
if (opts.expr) {
html = html.replace(brackets(EXPR), function(_, expr) {
var ret = compileJS(expr, opts, type).trim().replace(/\r?\n|\r/g, '').trim()
if (ret.slice(-1) == ';') ret = ret.slice(0, -1)
return brackets(0) + ret + brackets(1)
})
}
// <foo/> -> <foo></foo>
html = html.replace(CLOSED_TAG, function(_, name, attr) {
var tag = '<' + name + (attr ? ' ' + attr.trim() : '') + '>'
// Do not self-close HTML5 void tags
if (VOID_TAGS.indexOf(name.toLowerCase()) == -1) tag += '</' + name + '>'
return tag
})
// escape single quotes
html = html.replace(/'/g, "\\'")
// \{ jotain \} --> \\{ jotain \\}
html = html.replace(brackets(/\\{|\\}/g), '\\$&')
// compact: no whitespace between tags
if (opts.compact) html = html.replace(/> </g, '><')
return html
}
function coffee(js) {
return require('coffee-script').compile(js, { bare: true })
}
function es6(js) {
return require('babel').transform(js, { blacklist: ['useStrict'] }).code
}
function typescript(js) {
return require('typescript-simple')(js)
}
function livescript(js) {
return require('LiveScript').compile(js, { bare: true, header: false })
}
function plainjs(js) {
return js
}
function jade(html) {
return require('jade').render(html, {pretty: true})
}
function riotjs(js) {
// strip comments
js = js.replace(LINE_COMMENT, '').replace(JS_COMMENT, '')
// ES6 method signatures
var lines = js.split('\n'),
es6_ident = ''
lines.forEach(function(line, i) {
var l = line.trim()
// method start
if (l[0] != '}' && l.indexOf('(') > 0 && l.indexOf('function') == -1) {
var end = /[{}]/.exec(l.slice(-1)),
m = end && /(\s+)([\w]+)\s*\(([\w,\s]*)\)\s*\{/.exec(line)
if (m && !/^(if|while|switch|for)$/.test(m[2])) {
lines[i] = m[1] + 'this.' + m[2] + ' = function(' + m[3] + ') {'
// foo() { }
if (end[0] == '}') {
lines[i] += ' ' + l.slice(m[0].length - 1, -1) + '}.bind(this)'
} else {
es6_ident = m[1]
}
}
}
// method end
if (line.slice(0, es6_ident.length + 1) == es6_ident + '}') {
lines[i] = es6_ident + '}.bind(this);'
es6_ident = ''
}
})
return lines.join('\n')
}
function scopedCSS (tag, style) {
return style.replace(CSS_COMMENT, '').replace(CSS_SELECTOR, function (m, p1, p2) {
return p1 + ' ' + p2.split(/\s*,\s*/g).map(function(sel) {
return sel[0] == '@' ? sel : tag + ' ' + sel.replace(/:scope\s*/, '')
}).join(',')
}).trim()
}
function compileJS(js, opts, type) {
var parser = opts.parser || (type ? JS_PARSERS[type] : riotjs)
if (!parser) throw new Error('Parser not found "' + type + '"')
return parser(js, opts)
}
function compileTemplate(lang, html) {
var parser = HTML_PARSERS[lang]
if (!parser) throw new Error('Template parser not found "' + lang + '"')
return parser(html)
}
function compileCSS(style, tag, type) {
if (type == 'scoped-css') style = scopedCSS(tag, style)
return style.replace(/\s+/g, ' ').replace(/\\/g, '\\\\').replace(/'/g, "\\'").trim()
}
function mktag(name, html, css, js) {
return 'riot.tag(\''
+ name + '\', \''
+ html + '\''
+ (css ? ', \'' + css + '\'' : '')
+ ', function(opts) {' + js + '\n});'
}
function compile(src, opts) {
opts = opts || {}
if (opts.brackets) riot.settings.brackets = opts.brackets
if (opts.template) src = compileTemplate(opts.template, src)
src = src.replace(LINE_TAG, function(_, tagName, html) {
return mktag(tagName, compileHTML(html, opts), '', '')
})
return src.replace(CUSTOM_TAG, function(_, tagName, html, js) {
html = html || ''
// js wrapped inside <script> tag
var type = opts.type
if (!js.trim()) {
html = html.replace(SCRIPT, function(_, fullType, _type, script) {
if (_type) type = _type.replace('text/', '')
js = script
return ''
})
}
// styles in <style> tag
var style = ''
var styleType = 'css'
html = html.replace(STYLE, function(_, fullType, _type, _style) {
if (fullType && 'scoped' == fullType.trim()) styleType = 'scoped-css'
else if (_type) styleType = _type.replace('text/', '')
style = _style
return ''
})
return mktag(
tagName,
compileHTML(html, opts, type),
compileCSS(style, tagName, styleType),
compileJS(js, opts, type)
)
})
}
// io.js (node)
if (is_server) {
this.riot = require(process.env.RIOT || '../riot')
return module.exports = {
html: compileHTML,
compile: compile,
style: compileCSS
}
}
// browsers
var doc = document,
promise,
ready
function GET(url, fn) {
var req = new XMLHttpRequest()
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) fn(req.responseText)
}
req.open('GET', url, true)
req.send('')
}
function unindent(src) {
var ident = /[ \t]+/.exec(src)
if (ident) src = src.replace(new RegExp('^' + ident[0], 'gm'), '')
return src
}
function globalEval(js) {
var node = doc.createElement('script'),
root = doc.documentElement
node.text = compile(js)
root.appendChild(node)
root.removeChild(node)
}
function compileScripts(fn) {
var scripts = doc.querySelectorAll('script[type="riot/tag"]')
;[].map.call(scripts, function(script, i) {
var url = script.getAttribute('src')
function compileTag(source) {
globalEval(source)
if (i + 1 == scripts.length) {
promise.trigger('ready')
ready = true
fn && fn()
}
}
return url ? GET(url, compileTag) : compileTag(unindent(script.innerHTML))
})
}
riot.compile = function(arg, fn) {
// string
if (typeof arg == 'string') {
// compile & return
if (arg.trim()[0] == '<') {
var js = unindent(compile(arg))
if (!fn) globalEval(js)
return js
// URL
} else {
return GET(arg, function(str) {
var js = unindent(compile(str))
globalEval(js)
fn && fn(js, str)
})
}
}
// must be a function
if (typeof arg != 'function') arg = undefined
// all compiled
if (ready) return arg && arg()
// add to queue
if (promise) {
arg && promise.on('ready', arg)
// grab riot/tag elements + load & execute them
} else {
promise = riot.observable()
compileScripts(arg)
}
}
// reassign mount methods
var mount = riot.mount
riot.mount = function(a, b, c) {
var ret
riot.compile(function() { ret = mount(a, b, c) })
return ret
}
// @deprecated
riot.mountTo = riot.mount
})(!this.top)