-
-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
index.js
623 lines (486 loc) · 16.7 KB
/
index.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
import MagicString, { Bundle } from 'magic-string';
import { walk } from 'estree-walker';
import deindent from '../utils/deindent.js';
import isReference from '../utils/isReference.js';
import counter from './utils/counter.js';
import flattenReference from '../utils/flattenReference.js';
import namespaces from '../utils/namespaces.js';
import getIntro from './utils/getIntro.js';
import getOutro from './utils/getOutro.js';
import visitors from './visitors/index.js';
import processCss from './css/process.js';
export default function generate ( parsed, source, options, names ) {
const format = options.format || 'es';
const renderers = [];
const generator = {
addElement ( name, renderStatement, needsIdentifier = false ) {
const isToplevel = generator.current.localElementDepth === 0;
if ( needsIdentifier || isToplevel ) {
generator.current.initStatements.push( deindent`
var ${name} = ${renderStatement};
` );
generator.createMountStatement( name );
} else {
generator.current.initStatements.push( deindent`
${generator.current.target}.appendChild( ${renderStatement} );
` );
}
if ( isToplevel ) {
generator.current.detachStatements.push( deindent`
${name}.parentNode.removeChild( ${name} );
` );
}
},
createMountStatement ( name ) {
if ( generator.current.target === 'target' ) {
generator.current.mountStatements.push( deindent`
target.insertBefore( ${name}, anchor );
` );
} else {
generator.current.initStatements.push( deindent`
${generator.current.target}.appendChild( ${name} );
` );
}
},
createAnchor ( _name, description = '' ) {
const name = `${_name}_anchor`;
const statement = `document.createComment( ${JSON.stringify( description )} )`;
generator.addElement( name, statement, true );
return name;
},
generateBlock ( node, name ) {
generator.push({
name,
target: 'target',
localElementDepth: 0,
initStatements: [],
mountStatements: [],
updateStatements: [],
detachStatements: [],
teardownStatements: [],
getUniqueName: generator.getUniqueNameMaker()
});
// walk the children here
node.children.forEach( generator.visit );
generator.addRenderer( generator.current );
generator.pop();
// unset the children, to avoid them being visited again
node.children = [];
},
addRenderer ( fragment ) {
if ( fragment.autofocus ) {
fragment.initStatements.push( `${fragment.autofocus}.focus();` );
}
const detachStatements = fragment.detachStatements.join( '\n\n' );
const teardownStatements = fragment.teardownStatements.join( '\n\n' );
const detachBlock = deindent`
if ( detach ) {
${detachStatements}
}
`;
const teardownBlock = deindent`
${teardownStatements}${detachStatements ? `\n\n${detachBlock}` : ``}
`;
renderers.push( deindent`
function ${fragment.name} ( ${fragment.params}, component ) {
${fragment.initStatements.join( '\n\n' )}
return {
mount: function ( target, anchor ) {
${fragment.mountStatements.join( '\n\n' )}
},
update: function ( changed, ${fragment.params} ) {
${fragment.updateStatements.join( '\n\n' )}
},
teardown: function ( detach ) {
${teardownBlock}
}
};
}
` );
},
addSourcemapLocations ( node ) {
walk( node, {
enter ( node ) {
generator.code.addSourcemapLocation( node.start );
generator.code.addSourcemapLocation( node.end );
}
});
},
code: new MagicString( source ),
components: {},
contextualise ( expression, isEventHandler ) {
const usedContexts = [];
const dependencies = [];
const { contextDependencies, contexts, indexes } = generator.current;
walk( expression, {
enter ( node, parent ) {
if ( isReference( node, parent ) ) {
const { name } = flattenReference( node );
if ( parent && parent.type === 'CallExpression' && node === parent.callee && generator.helpers[ name ] ) {
generator.code.prependRight( node.start, `template.helpers.` );
return;
}
if ( name === 'event' && isEventHandler ) {
return;
}
if ( contexts[ name ] ) {
dependencies.push( ...contextDependencies[ name ] );
if ( !~usedContexts.indexOf( name ) ) usedContexts.push( name );
} else if ( indexes[ name ] ) {
const context = indexes[ name ];
if ( !~usedContexts.indexOf( context ) ) usedContexts.push( context );
} else {
dependencies.push( name );
generator.code.prependRight( node.start, `root.` );
if ( !~usedContexts.indexOf( 'root' ) ) usedContexts.push( 'root' );
}
this.skip();
}
}
});
return {
dependencies,
contexts: usedContexts,
snippet: `[✂${expression.start}-${expression.end}✂]`,
string: generator.code.slice( expression.start, expression.end )
};
},
events: {},
getUniqueName: counter( names ),
getUniqueNameMaker () {
return counter( names );
},
cssId: parsed.css ? `svelte-${parsed.hash}` : '',
helpers: {},
pop () {
const tail = generator.current;
generator.current = tail.parent;
return tail;
},
push ( fragment ) {
const newFragment = Object.assign( {}, generator.current, fragment, {
parent: generator.current
});
generator.current = newFragment;
},
usesRefs: false,
source,
visit ( node ) {
const visitor = visitors[ node.type ];
if ( !visitor ) throw new Error( `Not implemented: ${node.type}` );
if ( visitor.enter ) visitor.enter( generator, node );
if ( node.children ) {
node.children.forEach( child => {
generator.visit( child );
});
}
if ( visitor.leave ) visitor.leave( generator, node );
}
};
const templateProperties = {};
const imports = [];
if ( parsed.js ) {
generator.addSourcemapLocations( parsed.js.content );
// imports need to be hoisted out of the IIFE
for ( let i = 0; i < parsed.js.content.body.length; i += 1 ) {
const node = parsed.js.content.body[i];
if ( node.type === 'ImportDeclaration' ) {
let a = node.start;
let b = node.end;
while ( /[ \t]/.test( source[ a - 1 ] ) ) a -= 1;
while ( source[b] === '\n' ) b += 1;
//imports.push( source.slice( a, b ).replace( /^\s/, '' ) );
imports.push( node );
generator.code.remove( a, b );
}
}
const defaultExport = parsed.js.content.body.find( node => node.type === 'ExportDefaultDeclaration' );
if ( defaultExport ) {
const finalNode = parsed.js.content.body[ parsed.js.content.body.length - 1 ];
if ( defaultExport === finalNode ) {
// export is last property, we can just return it
generator.code.overwrite( defaultExport.start, defaultExport.declaration.start, `return ` );
} else {
// TODO ensure `template` isn't already declared
generator.code.overwrite( defaultExport.start, defaultExport.declaration.start, `var template = ` );
let i = defaultExport.start;
while ( /\s/.test( source[ i - 1 ] ) ) i--;
const indentation = source.slice( i, defaultExport.start );
generator.code.appendLeft( finalNode.end, `\n\n${indentation}return template;` );
}
defaultExport.declaration.properties.forEach( prop => {
templateProperties[ prop.key.name ] = prop.value;
});
generator.code.prependRight( parsed.js.content.start, 'var template = (function () {' );
} else {
generator.code.prependRight( parsed.js.content.start, '(function () {' );
}
generator.code.appendLeft( parsed.js.content.end, '}());' );
[ 'helpers', 'events', 'components' ].forEach( key => {
if ( templateProperties[ key ] ) {
templateProperties[ key ].properties.forEach( prop => {
generator[ key ][ prop.key.name ] = prop.value;
});
}
});
}
let namespace = null;
if ( templateProperties.namespace ) {
const ns = templateProperties.namespace.value;
namespace = namespaces[ ns ] || ns;
// TODO remove the namespace property from the generated code, it's unused past this point
}
generator.push({
name: 'renderMainFragment',
namespace,
target: 'target',
elementDepth: 0,
localElementDepth: 0,
initStatements: [],
mountStatements: [],
updateStatements: [],
detachStatements: [],
teardownStatements: [],
contexts: {},
indexes: {},
params: 'root',
indexNames: {},
listNames: {},
getUniqueName: generator.getUniqueNameMaker()
});
parsed.html.children.forEach( generator.visit );
generator.addRenderer( generator.pop() );
const topLevelStatements = [];
const setStatements = [ deindent`
var oldState = state;
state = Object.assign( {}, oldState, newState );
` ];
if ( templateProperties.computed ) {
const statements = [];
const dependencies = new Map();
templateProperties.computed.properties.forEach( prop => {
const key = prop.key.name;
const value = prop.value;
const deps = value.params.map( param => param.name );
dependencies.set( key, deps );
});
const visited = new Set();
function visit ( key ) {
if ( !dependencies.has( key ) ) return; // not a computation
if ( visited.has( key ) ) return;
visited.add( key );
const deps = dependencies.get( key );
deps.forEach( visit );
statements.push( deindent`
if ( ${deps.map( dep => `( '${dep}' in newState && typeof state.${dep} === 'object' || state.${dep} !== oldState.${dep} )` ).join( ' || ' )} ) {
state.${key} = newState.${key} = template.computed.${key}( ${deps.map( dep => `state.${dep}` ).join( ', ' )} );
}
` );
}
templateProperties.computed.properties.forEach( prop => visit( prop.key.name ) );
topLevelStatements.push( deindent`
function applyComputations ( state, newState, oldState ) {
${statements.join( '\n\n' )}
}
` );
setStatements.push( `applyComputations( state, newState, oldState )` );
}
setStatements.push( deindent`
dispatchObservers( observers.immediate, newState, oldState );
if ( mainFragment ) mainFragment.update( newState, state );
dispatchObservers( observers.deferred, newState, oldState );
` );
const importBlock = imports
.map( ( declaration, i ) => {
if ( format === 'es' ) {
return source.slice( declaration.start, declaration.end );
}
const defaultImport = declaration.specifiers.find( x => x.type === 'ImportDefaultSpecifier' || x.type === 'ImportSpecifier' && x.imported.name === 'default' );
const namespaceImport = declaration.specifiers.find( x => x.type === 'ImportNamespaceSpecifier' );
const namedImports = declaration.specifiers.filter( x => x.type === 'ImportSpecifier' && x.imported.name !== 'default' );
const name = ( defaultImport || namespaceImport ) ? ( defaultImport || namespaceImport ).local.name : `__import${i}`;
declaration.name = name; // hacky but makes life a bit easier later
const statements = namedImports.map( specifier => {
return `var ${specifier.local.name} = ${name}.${specifier.imported.name}`;
});
if ( defaultImport ) {
statements.push( `${name} = ( ${name} && ${name}.__esModule ) ? ${name}['default'] : ${name};` );
}
return statements.join( '\n' );
})
.filter( Boolean )
.join( '\n' );
if ( parsed.js ) {
if ( imports.length ) {
topLevelStatements.push( importBlock );
}
topLevelStatements.push( `[✂${parsed.js.content.start}-${parsed.js.content.end}✂]` );
}
if ( parsed.css && options.css !== false ) {
topLevelStatements.push( deindent`
let addedCss = false;
function addCss () {
var style = document.createElement( 'style' );
style.textContent = ${JSON.stringify( processCss( parsed ) )};
document.head.appendChild( style );
addedCss = true;
}
` );
}
topLevelStatements.push( ...renderers.reverse() );
const constructorName = options.name || 'SvelteComponent';
const initStatements = [];
if ( parsed.css && options.css !== false ) {
initStatements.push( `if ( !addedCss ) addCss();` );
}
if ( generator.hasComponents ) {
initStatements.push( deindent`
this.__renderHooks = [];
` );
}
if ( generator.hasComplexBindings ) {
initStatements.push( deindent`
this.__bindings = [];
var mainFragment = renderMainFragment( state, this );
if ( options.target ) this._mount( options.target );
while ( this.__bindings.length ) this.__bindings.pop()();
` );
setStatements.push( `while ( this.__bindings.length ) this.__bindings.pop()();` );
} else {
initStatements.push( deindent`
var mainFragment = renderMainFragment( state, this );
if ( options.target ) this._mount( options.target );
` );
}
if ( generator.hasComponents ) {
const statement = deindent`
while ( this.__renderHooks.length ) {
var hook = this.__renderHooks.pop();
hook.fn.call( hook.context );
}
`;
initStatements.push( statement );
setStatements.push( statement );
}
if ( templateProperties.onrender ) {
initStatements.push( deindent`
if ( options.root ) {
options.root.__renderHooks.push({ fn: template.onrender, context: this });
} else {
template.onrender.call( this );
}
` );
}
const initialState = templateProperties.data ? `Object.assign( template.data(), options.data )` : `options.data || {}`;
topLevelStatements.push( deindent`
function ${constructorName} ( options ) {
options = options || {};
var component = this;${generator.usesRefs ? `\nthis.refs = {}` : ``}
var state = ${initialState};${templateProperties.computed ? `\napplyComputations( state, state, {} );` : ``}
var observers = {
immediate: Object.create( null ),
deferred: Object.create( null )
};
var callbacks = Object.create( null );
function dispatchObservers ( group, newState, oldState ) {
for ( var key in group ) {
if ( !( key in newState ) ) continue;
var newValue = newState[ key ];
var oldValue = oldState[ key ];
if ( newValue === oldValue && typeof newValue !== 'object' ) continue;
var callbacks = group[ key ];
if ( !callbacks ) continue;
for ( var i = 0; i < callbacks.length; i += 1 ) {
var callback = callbacks[i];
if ( callback.__calling ) continue;
callback.__calling = true;
callback.call( component, newValue, oldValue );
callback.__calling = false;
}
}
}
this.fire = function fire ( eventName, data ) {
var handlers = eventName in callbacks && callbacks[ eventName ].slice();
if ( !handlers ) return;
for ( var i = 0; i < handlers.length; i += 1 ) {
handlers[i].call( this, data );
}
};
this.get = function get ( key ) {
return key ? state[ key ] : state;
};
this.set = function set ( newState ) {
${setStatements.join( '\n\n' )}
};
this._mount = function mount ( target, anchor ) {
mainFragment.mount( target, anchor );
}
this.observe = function ( key, callback, options ) {
var group = ( options && options.defer ) ? observers.deferred : observers.immediate;
( group[ key ] || ( group[ key ] = [] ) ).push( callback );
if ( !options || options.init !== false ) {
callback.__calling = true;
callback.call( component, state[ key ] );
callback.__calling = false;
}
return {
cancel: function () {
var index = group[ key ].indexOf( callback );
if ( ~index ) group[ key ].splice( index, 1 );
}
};
};
this.on = function on ( eventName, handler ) {
var handlers = callbacks[ eventName ] || ( callbacks[ eventName ] = [] );
handlers.push( handler );
return {
cancel: function () {
var index = handlers.indexOf( handler );
if ( ~index ) handlers.splice( index, 1 );
}
};
};
this.teardown = function teardown ( detach ) {
this.fire( 'teardown' );${templateProperties.onteardown ? `\ntemplate.onteardown.call( this );` : ``}
mainFragment.teardown( detach !== false );
mainFragment = null;
state = {};
};
this.root = options.root;
this.yield = options.yield;
${initStatements.join( '\n\n' )}
}
` );
if ( templateProperties.methods ) {
topLevelStatements.push( `${constructorName}.prototype = template.methods;` );
}
const result = topLevelStatements.join( '\n\n' );
const pattern = /\[✂(\d+)-(\d+)$/;
const parts = result.split( '✂]' );
const finalChunk = parts.pop();
const compiled = new Bundle({ separator: '' });
function addString ( str ) {
compiled.addSource({
content: new MagicString( str )
});
}
const intro = getIntro( format, options, imports );
if ( intro ) addString( intro );
const { filename } = options;
parts.forEach( str => {
const chunk = str.replace( pattern, '' );
if ( chunk ) addString( chunk );
const match = pattern.exec( str );
const snippet = generator.code.snip( +match[1], +match[2] );
compiled.addSource({
filename,
content: snippet
});
});
addString( finalChunk );
addString( '\n\n' + getOutro( format, constructorName, options, imports ) );
return {
code: compiled.toString(),
map: compiled.generateMap({ includeContent: true })
};
}