-
Notifications
You must be signed in to change notification settings - Fork 57
/
browserify-transform.js
358 lines (328 loc) · 12.2 KB
/
browserify-transform.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
'use strict'
var isMemberExpression = require('estree-is-member-expression')
var convertSourceMap = require('convert-source-map')
var transformAst = require('transform-ast')
var through = require('through2')
var hyperx = require('hyperx')
var acorn = require('acorn-node')
var path = require('path')
var SVG_TAGS = require('./svg-tags')
var SUPPORTED_VIEWS = require('./supported-views')
var DELIM = '~!@|@|@!~'
var VARNAME = 'nanohtml'
var SVGNS = 'http://www.w3.org/2000/svg'
var XLINKNS = '"http://www.w3.org/1999/xlink"'
var BOOL_PROPS = require('./bool-props').reduce(function (o, key) {
o[key] = 1
return o
}, {})
// Props that need to be set directly rather than with el.setAttribute()
var DIRECT_PROPS = require('./direct-props').reduce(function (o, key) {
o[key] = 1
return o
}, {})
module.exports = function yoYoify (file, opts) {
if (/\.json$/.test(file)) return through()
var bufs = []
var viewVariables = []
var babelTemplateObjects = Object.create(null)
var bubleTemplateObjects = Object.create(null)
return through(write, end)
function write (buf, enc, next) {
bufs.push(buf)
next()
}
function end (cb) {
var src = Buffer.concat(bufs).toString('utf8')
var flags = (opts && opts._flags) || {}
var basedir = flags.basedir || process.cwd()
var filename = path.relative(basedir, file)
var res
try {
res = transformAst(src, { parser: acorn, inputFilename: filename }, walk)
if (flags.debug) {
var sm = convertSourceMap.fromObject(res.map).toComment()
res = res.toString() + '\n' + sm + '\n'
} else {
res = res.toString()
}
} catch (err) {
return cb(err)
}
this.push(res)
this.push(null)
}
function walk (node) {
if (isSupportedView(node)) {
if (node.arguments[0].value === 'bel' ||
node.arguments[0].value === 'choo/html' ||
node.arguments[0].value === 'nanohtml') {
// html and choo/html have no other exports that may be used
node.edit.update('{}')
}
if (node.parent.type === 'VariableDeclarator') {
viewVariables.push(node.parent.id.name)
// Typescript Synthetic Default Imports
} else if (node.parent.type === 'CallExpression' && node.parent.callee.name === '__importDefault' && node.parent.parent.type === 'VariableDeclarator') {
viewVariables.push(node.parent.parent.id.name)
}
}
if (node.type === 'VariableDeclarator' && node.init && isBabelTemplateDefinition(node.init)) {
// Babel generates helper calls like
// _taggedTemplateLiteral(["<div","/>"], ["<div","/>"])
// The first parameter is the `cooked` template literal parts, and the second parameter is the `raw`
// template literal parts.
// We just pick the cooked parts.
babelTemplateObjects[node.id.name] = node.init.arguments[0]
}
if (node.type === 'VariableDeclarator' && node.init && isBubleTemplateDefinition(node.init)) {
// Buble generates helper calls like
// Object.freeze([":host .class { color: hotpink; }"])
bubleTemplateObjects[node.id.name] = node.init.arguments[0]
}
if (node.type === 'TemplateLiteral' && node.parent.tag) {
var name = node.parent.tag.name || (node.parent.tag.object && node.parent.tag.object.name)
if (viewVariables.indexOf(name) !== -1) {
processNode(node.parent, [ node.quasis.map(cooked) ].concat(node.expressions.map(expr)))
}
}
if (node.type === 'CallExpression' && node.callee.type === 'Identifier' && viewVariables.indexOf(node.callee.name) !== -1) {
var template, expressions
if (node.arguments[0] && node.arguments[0].type === 'ArrayExpression') {
// Detect transpiled template strings like:
// html(["<div","/>"], {id: "test"})
// Emitted by Buble < 0.19.
template = node.arguments[0].elements.map(function (part) { return part.value })
expressions = node.arguments.slice(1).map(expr)
processNode(node, [ template ].concat(expressions))
} else if (node.arguments[0] && node.arguments[0].type === 'Identifier') {
// Detect transpiled template strings like:
// html(_templateObject, {id: "test"})
// Emitted by Babel and buble.
var arg = node.arguments[0].name
var templateObject = babelTemplateObjects[arg] || bubleTemplateObjects[arg]
if (!templateObject) {
return // Does something else I guess. probably a manual call and not a tagged template string
}
template = templateObject.elements.map(function (part) { return part.value })
expressions = node.arguments.slice(1).map(expr)
processNode(node, [ template ].concat(expressions))
// Remove the _taggedTemplateLiteral helper call
templateObject.parent.edit.update('0')
}
}
}
}
function processNode (node, args) {
var resultArgs = []
var argCount = 0
var tagCount = 0
var needsAc = false
var needsSa = false
function createElement (tag, props, children) {
var res = []
var elname = VARNAME + tagCount
tagCount++
if (tag === '!--') {
return DELIM + [elname, 'var ' + elname + ' = document.createComment(' + JSON.stringify(props.comment) + ')', null].join(DELIM) + DELIM
}
if (tag === 'nanohtml-fragment') {
res.push('var ' + elname + ' = document.createDocumentFragment()')
} else {
// Whether this element needs a namespace
var namespace = props.namespace
if (!namespace && SVG_TAGS.indexOf(tag) !== -1) {
namespace = SVGNS
}
// Whether this element is extended
var isCustomElement = props.is
delete props.is
// Create the element
if (namespace) {
if (isCustomElement) {
res.push('var ' + elname + ' = document.createElementNS(' + JSON.stringify(namespace) + ', ' + JSON.stringify(tag) + ', { is: ' + JSON.stringify(isCustomElement) + ' })')
} else {
res.push('var ' + elname + ' = document.createElementNS(' + JSON.stringify(namespace) + ', ' + JSON.stringify(tag) + ')')
}
} else if (isCustomElement) {
res.push('var ' + elname + ' = document.createElement(' + JSON.stringify(tag) + ', { is: ' + JSON.stringify(isCustomElement) + ' })')
} else {
res.push('var ' + elname + ' = document.createElement(' + JSON.stringify(tag) + ')')
}
}
function addAttr (to, key, val) {
// Normalize className
if (key.toLowerCase() === '"classname"') {
key = '"class"'
}
// The for attribute gets transformed to htmlFor, but we just set as for
if (key === '"htmlFor"') {
key = '"for"'
}
// If a property is boolean, set itself to the key
if (BOOL_PROPS[key.slice(1, -1)]) {
if (val.slice(0, 9) === 'arguments') {
if (namespace) {
res.push('if (' + val + ' && ' + key + ') ' + to + '.setAttributeNS(null, ' + key + ', ' + key + ')')
} else if (DIRECT_PROPS[key.slice(1, -1)]) {
res.push('if (' + val + ' && ' + key + ') ' + to + '[' + key + '] = true')
} else {
res.push('if (' + val + ' && ' + key + ') ' + to + '.setAttribute(' + key + ', ' + key + ')')
}
return
} else {
if (val === 'true') val = key
else if (val === 'false') return
}
}
if (key.slice(1, 3) === 'on' || DIRECT_PROPS[key.slice(1, -1)]) {
res.push(to + '[' + key + '] = ' + val)
} else {
if (key === '"xlink:href"') {
res.push(to + '.setAttributeNS(' + XLINKNS + ', ' + key + ', ' + val + ')')
} else if (namespace && key.slice(0, 1) === '"') {
if (!/^xmlns($|:)/i.test(key.slice(1, -1))) {
// skip xmlns definitions
res.push(to + '.setAttributeNS(null, ' + key + ', ' + val + ')')
}
} else if (namespace) {
res.push('if (' + key + ') ' + to + '.setAttributeNS(null, ' + key + ', ' + val + ')')
} else if (key.slice(0, 1) === '"') {
res.push(to + '.setAttribute(' + key + ', ' + val + ')')
} else {
needsSa = true
res.push('sa(' + to + ', ' + key + ', ' + val + ')')
}
}
}
// Add properties to element
Object.keys(props).forEach(function (key) {
var prop = props[key]
var ksrcs = getSourceParts(key)
var srcs = getSourceParts(prop)
var k, val
if (srcs) {
val = ''
srcs.forEach(function (src, index) {
if (src.arg) {
if (index > 0) val += ' + '
if (src.before) val += JSON.stringify(src.before) + ' + '
val += 'arguments[' + argCount + ']'
if (src.after) val += ' + ' + JSON.stringify(src.after)
resultArgs.push(src.arg)
argCount++
}
})
} else {
val = JSON.stringify(prop)
}
if (ksrcs) {
k = ''
ksrcs.forEach(function (src, index) {
if (src.arg) {
if (index > 0) val += ' + '
if (src.before) val += JSON.stringify(src.before) + ' + '
k += 'arguments[' + argCount + ']'
if (src.after) k += ' + ' + JSON.stringify(src.after)
resultArgs.push(src.arg)
argCount++
}
})
} else {
k = JSON.stringify(key)
}
addAttr(elname, k, val)
})
if (Array.isArray(children)) {
var childs = []
children.forEach(function (child) {
var srcs = getSourceParts(child)
if (srcs) {
var src = srcs[0]
if (src.src) {
res.push(src.src)
}
if (src.name) {
childs.push(src.name)
}
if (src.arg) {
var argname = 'arguments[' + argCount + ']'
resultArgs.push(src.arg)
argCount++
childs.push(argname)
}
} else {
childs.push(JSON.stringify(child))
}
})
if (childs.length > 0) {
needsAc = true
res.push('ac(' + elname + ', [' + childs.join(',') + '])')
}
}
// Return delim'd parts as a child
// return [elname, res]
return DELIM + [elname, res.join('\n'), null].join(DELIM) + DELIM
}
var hx = hyperx(createElement, {
comments: true,
createFragment: function (nodes) {
return createElement('nanohtml-fragment', {}, nodes)
}
})
// Run through hyperx
var res = hx.apply(null, args)
// Pull out the final parts and wrap in a closure with arguments
var src = getSourceParts(res)
if (src && src[0].src) {
var params = resultArgs.join(',')
node.edit.update('(function () {' +
(needsAc ? '\n var ac = require(\'' + path.resolve(__dirname, 'append-child.js').replace(/\\/g, '\\\\') + '\')' : '') +
(needsSa ? '\n var sa = require(\'' + path.resolve(__dirname, 'set-attribute.js').replace(/\\/g, '\\\\') + '\')' : '') +
'\n ' + src[0].src + '\n return ' + src[0].name + '\n }(' + params + '))')
}
}
function isSupportedView (node) {
return (node.type === 'CallExpression' &&
node.callee && node.callee.name === 'require' &&
node.arguments.length === 1 &&
SUPPORTED_VIEWS.indexOf(node.arguments[0].value) !== -1)
}
function isBabelTemplateDefinition (node) {
return node.type === 'CallExpression' &&
node.callee.type === 'Identifier' && node.callee.name === '_taggedTemplateLiteral'
}
function isBubleTemplateDefinition (node) {
return node.type === 'CallExpression' &&
isMemberExpression(node.callee, 'Object.freeze') &&
node.arguments[0] && node.arguments[0].type === 'ArrayExpression' &&
node.arguments[0].elements.every(function (el) { return el.type === 'Literal' })
}
function cooked (node) { return node.value.cooked }
function expr (ex, idx) {
return DELIM + [null, null, ex.source()].join(DELIM) + DELIM
}
function getSourceParts (str) {
if (typeof str !== 'string') return false
if (str.indexOf(DELIM) === -1) return false
var parts = str.split(DELIM)
var chunk = parts.splice(0, 5)
var arr = [{
before: chunk[0],
name: chunk[1],
src: chunk[2],
arg: chunk[3],
after: chunk[4]
}]
while (parts.length > 0) {
chunk = parts.splice(0, 4)
arr.push({
before: '',
name: chunk[0],
src: chunk[1],
arg: chunk[2],
after: chunk[3]
})
}
return arr
}