nested each blocks

pull/31/head
Rich Harris 8 years ago
parent ba9238b864
commit 8f892bf65b

@ -1,332 +1,274 @@
import { getLocator } from 'locate-character';
import deindent from './utils/deindent.js';
import walkHtml from './utils/walkHtml.js';
import flattenReference from './utils/flattenReference.js';
const ROOT = 'options.target';
function createRenderer ( fragment ) {
return deindent`
function ${fragment.name} ( target${fragment.useAnchor ? ', anchor' : ''} ) {
${fragment.initStatements.join( '\n\n' )}
return {
update: function ( ${fragment.contextChain.join( ', ' )} ) {
${fragment.updateStatements.join( '\n\n' )}
},
teardown: function () {
${fragment.teardownStatements.join( '\n\n' )}
}
}
}
`;
}
export default function generate ( parsed, template ) {
const locator = getLocator( template );
const renderers = [];
const counters = {
fragment: 0,
element: 0,
text: 0,
anchor: 0,
if: 0,
each: 0,
loop: 0
each: 0
};
const initStatements = [];
const setStatements = [ deindent`
const oldState = state;
state = Object.assign( {}, oldState, newState );
` ];
const teardownStatements = [];
// TODO add contents of <script> tag, with `export default` replaced with `var template =`
// TODO css
const locator = getLocator( template );
let current = {
useAnchor: false,
name: 'renderMainFragment',
target: 'target',
parsed.html.children.forEach( child => {
const declarations = [];
initStatements: [],
updateStatements: [],
teardownStatements: [],
let current = {
target: ROOT,
conditions: [],
children: [],
renderBlocks: [],
removeBlocks: [],
anchor: null,
renderImmediately: true
};
contexts: {},
contextChain: [ 'context' ],
const stack = [ current ];
counters: {
element: 0,
text: 0,
anchor: 0
},
parent: null
};
function flattenExpression ( node, contexts ) {
const flattened = flattenReference( node );
if ( flattened ) {
if ( flattened.name in contexts ) return flattened.keypath;
// TODO handle globals, e.g. {{Math.round(foo)}}
return `context.${flattened.keypath}`;
}
throw new Error( 'TODO expressions' );
}
parsed.html.children.forEach( child => {
walkHtml( child, {
Element: {
enter ( node ) {
const target = `element_${counters.element++}`;
stack.push( current );
declarations.push( `var ${target};` );
const name = `element_${current.counters.element++}`;
if ( current.renderImmediately ) {
current.renderBlocks.push( deindent`
${target} = document.createElement( '${node.name}' );
${current.target}.appendChild( ${target} );
` );
} else {
current.renderBlocks.push( deindent`
${target} = document.createElement( '${node.name}' );
${current.anchor}.parentNode.insertBefore( ${target}, ${current.anchor} );
` );
}
current.initStatements.push( deindent`
var ${name} = document.createElement( '${node.name}' );
` );
current.removeBlocks.push( deindent`
${target}.parentNode.removeChild( ${target} );
current.teardownStatements.push( deindent`
${name}.parentNode.removeChild( ${name} );
` );
current = {
target,
conditions: current.conditions,
children: current.children,
renderBlocks: current.renderBlocks,
removeBlocks: current.removeBlocks,
anchor: current.anchor,
renderImmediately: false
};
current = Object.assign( {}, current, {
target: name,
parent: current
});
},
leave () {
stack.pop();
current = stack[ stack.length - 1 ];
}
},
const name = current.target;
Text: {
enter ( node ) {
if ( current.target === ROOT ) {
const identifier = `text_${counters.text++}`;
declarations.push( `var ${identifier};` );
current = current.parent;
current.renderBlocks.push( deindent`
${identifier} = document.createTextNode( ${JSON.stringify( node.data )} );
${current.target}.appendChild( ${identifier} );
if ( current.useAnchor && current.target === 'target' ) {
current.initStatements.push( deindent`
target.insertBefore( ${name}, anchor );
` );
current.removeBlocks.push( deindent`
${identifier}.parentNode.removeChild( ${identifier} );
${identifier} = null;
} else {
current.initStatements.push( deindent`
${current.target}.appendChild( ${name} );
` );
}
}
},
else {
current.renderBlocks.push( deindent`
${current.target}.appendChild( document.createTextNode( ${JSON.stringify( node.data )} ) );
` );
}
Text: {
enter ( node ) {
current.initStatements.push( deindent`
${current.target}.appendChild( document.createTextNode( ${JSON.stringify( node.data ) }) );
` );
}
},
MustacheTag: {
enter ( node ) {
const identifier = `text_${counters.text++}`;
const expression = node.expression.type === 'Identifier' ? node.expression.name : 'TODO'; // TODO handle block-local state
const name = `text_${current.counters.text++}`;
const expression = flattenExpression( node.expression, current.contexts );
declarations.push( `var ${identifier};` );
current.renderBlocks.push( deindent`
${identifier} = document.createTextNode( '' );
${current.target}.appendChild( ${identifier} );
current.initStatements.push( deindent`
var ${name} = document.createTextNode( '' );
var ${name}_value = '';
${current.target}.appendChild( ${name} );
` );
setStatements.push( deindent`
if ( state.${expression} !== oldState.${expression} ) { // TODO and conditions
${identifier}.data = state.${expression};
current.updateStatements.push( deindent`
if ( ${expression} !== ${name}_value ) {
${name}_value = ${expression};
${name}.data = ${name}_value;
}
` );
current.removeBlocks.push( deindent`
${identifier}.parentNode.removeChild( ${identifier} );
${identifier} = null;
` );
}
},
IfBlock: {
enter ( node ) {
const anchor = `anchor_${counters.anchor++}`;
const suffix = `if_${counters.if++}`;
const i = counters.if++;
const name = `ifBlock_${i}`;
const renderer = `renderIfBlock_${i}`;
declarations.push( `var ${anchor};` );
const expression = flattenExpression( node.expression, current.contexts );
const expression = node.expression.type === 'Identifier' ? node.expression.name : 'TODO'; // TODO handle block-local state
current.renderBlocks.push( deindent`
${anchor} = document.createComment( '#if ${template.slice( node.expression.start, node.expression.end)}' );
${current.target}.appendChild( ${anchor} );
current.initStatements.push( deindent`
var ${name}_anchor = document.createComment( '#if ${template.slice( node.expression.start, node.expression.end )}' );
${current.target}.appendChild( ${name}_anchor );
var ${name} = null;
` );
current.removeBlocks.push( deindent`
${anchor}.parentNode.removeChild( ${anchor} );
${anchor} = null;
` );
current.updateStatements.push( deindent`
if ( ${expression} && !${name} ) {
${name} = ${renderer}( ${current.target}, ${name}_anchor );
}
current = {
renderName: `render_${suffix}`,
removeName: `remove_${suffix}`,
target: current.target,
conditions: current.conditions.concat( expression ),
renderBlocks: [],
removeBlocks: [],
anchor,
renderImmediately: false
};
else if ( !${expression} && ${name} ) {
${name}.teardown();
${name} = null;
}
setStatements.push( deindent`
// TODO account for conditions (nested ifs)
if ( state.${expression} && !oldState.${expression} ) ${current.renderName}();
else if ( !state.${expression} && oldState.${expression} ) ${current.removeName}();
if ( ${name} ) {
${name}.update( context );
}
` );
teardownStatements.push( deindent`
// TODO account for conditions (nested ifs)
if ( state.${expression} ) ${current.removeName}();
current.teardownStatements.push( deindent`
if ( ${name} ) ${name}.teardown();
` );
stack.push( current );
},
current = {
useAnchor: true,
name: renderer,
target: 'target',
leave ( node ) {
const { line, column } = locator( node.start );
contextChain: current.contextChain,
initStatements.push( deindent`
// (${line}:${column}) {{#if ${template.slice( node.expression.start, node.expression.end )}}}...{{/if}}
function ${current.renderName} () {
${current.renderBlocks.join( '\n\n' )}
}
initStatements: [],
updateStatements: [],
teardownStatements: [],
function ${current.removeName} () {
${current.removeBlocks.join( '\n\n' )}
}
` );
counters: {
element: 0,
text: 0,
anchor: 0
},
parent: current
};
},
stack.pop();
current = stack[ stack.length - 1 ];
leave () {
renderers.push( createRenderer( current ) );
current = current.parent;
}
},
EachBlock: {
enter ( node ) {
const loopIndex = counters.loop++;
const anchor = `anchor_${counters.anchor++}`;
declarations.push( `var fragment_${loopIndex} = document.createDocumentFragment();` );
declarations.push( `var ${anchor};` );
const expression = node.expression.type === 'Identifier' ? node.expression.name : 'TODO'; // TODO handle block-local state
current.renderBlocks.push( deindent`
${anchor} = document.createComment( '#each ${template.slice( node.expression.start, node.expression.end)}' );
${current.target}.appendChild( ${anchor} );
` );
const i = counters.each++;
const name = `eachBlock_${i}`;
const renderer = `renderEachBlock_${i}`;
current.removeBlocks.push( deindent`
${anchor}.parentNode.removeChild( ${anchor} );
${anchor} = null;
` );
current = {
target: `fragment_${loopIndex}`,
expression,
conditions: current.conditions,
renderBlocks: [],
removeBlocks: [],
anchor,
loopIndex,
renderImmediately: true
};
const expression = flattenExpression( node.expression, current.contexts );
setStatements.push( deindent`
// TODO account for conditions (nested ifs)
if ( '${expression}' in state ) each_${loopIndex}.update();
current.initStatements.push( deindent`
var ${name}_anchor = document.createComment( '#each ${template.slice( node.expression.start, node.expression.end )}' );
${current.target}.appendChild( ${name}_anchor );
var ${name}_iterations = [];
const ${name}_fragment = document.createDocumentFragment();
` );
// need to add teardown logic if this is at the
// top level (TODO or if there are event handlers attached?)
if ( current.target === ROOT ) {
teardownStatements.push( deindent`
if ( true ) { // <!-- TODO conditions
for ( let i = 0; i < state.${expression}.length; i += 1 ) {
each_${loopIndex}.removeIteration( i );
}
current.updateStatements.push( deindent`
for ( var i = 0; i < ${expression}.length; i += 1 ) {
if ( !${name}_iterations[i] ) {
${name}_iterations[i] = ${renderer}( ${name}_fragment );
}
` );
}
stack.push( current );
},
leave ( node ) {
const { line, column } = locator( node.start );
const loopIndex = current.loopIndex;
initStatements.push( deindent`
// (${line}:${column}) {{#each ${template.slice( node.expression.start, node.expression.end )}}}...{{/each}}
${current.renderBlocks.join( '\n\n' )}
var each_${loopIndex} = {
iterations: [],
update: function () {
var target = document.createDocumentFragment();
var i;
for ( i = 0; i < state.${current.expression}.length; i += 1 ) {
if ( !this.iterations[i] ) {
this.iterations[i] = this.renderIteration( target );
}
const iteration = ${name}_iterations[i];
${name}_iterations[i].update( ${current.contextChain.join( ', ' )}, ${expression}[i] );
}
const iteration = this.iterations[i];
this.updateIteration( this.iterations[i], state.${current.expression}[i] );
}
for ( var i = ${expression}.length; i < ${name}_iterations.length; i += 1 ) {
${name}_iterations[i].teardown();
}
for ( ; i < this.iterations.length; i += 1 ) {
this.removeIteration( i );
}
${name}_anchor.parentNode.insertBefore( ${name}_fragment, ${name}_anchor );
${name}_iterations.length = ${expression}.length;
` );
${current.anchor}.parentNode.insertBefore( target, ${current.anchor} );
each_${loopIndex}.length = state.${current.expression}.length;
},
current.teardownStatements.push( deindent`
for ( let i = 0; i < ${name}_iterations.length; i += 1 ) {
${name}_iterations[i].teardown();
}
` );
renderIteration: function ( target ) {
var fragment = fragment_0.cloneNode( true );
const contexts = Object.assign( {}, current.contexts );
contexts[ node.context ] = true;
var element_0 = fragment.childNodes[0];
var text_0 = element_0.childNodes[0];
current = {
useAnchor: false,
name: renderer,
target: 'target',
var iteration = {
element_0: element_0,
text_0: text_0
};
contexts,
contextChain: current.contextChain.concat( node.context ),
target.appendChild( fragment );
return iteration;
},
initStatements: [],
updateStatements: [],
teardownStatements: [],
updateIteration: function ( iteration, context ) {
iteration.text_0.data = context;
},
counters: {
element: 0,
text: 0,
anchor: 0
},
removeIteration: function ( i ) {
var iteration = this.iterations[i];
iteration.element_0.parentNode.removeChild( iteration.element_0 );
}
};
` );
parent: current
};
},
teardownStatements.push( ...current.removeBlocks );
leave () {
renderers.push( createRenderer( current ) );
stack.pop();
current = stack[ stack.length - 1 ];
current = current.parent;
}
}
});
initStatements.push( ...current.renderBlocks );
initStatements.unshift( declarations.join( '\n' ) );
teardownStatements.push( ...current.removeBlocks );
});
teardownStatements.push( 'state = {};' );
renderers.push( createRenderer( current ) );
const code = deindent`
${renderers.reverse().join( '\n\n' )}
export default function createComponent ( options ) {
var component = {};
var state = {};
@ -373,16 +315,18 @@ export default function generate ( parsed, template ) {
// component-specific methods
component.set = function set ( newState ) {
${setStatements.join( '\n\n' )}
Object.assign( state, newState );
mainFragment.update( state );
};
component.teardown = function teardown () {
${teardownStatements.join( '\n\n' )}
};
mainFragment.teardown();
mainFragment = null;
// initialisation
${initStatements.join( '\n\n' )}
state = {};
};
let mainFragment = renderMainFragment( options.target );
component.set( options.data );
return component;

@ -0,0 +1,16 @@
export default function flatten ( node ) {
const parts = [];
while ( node.type === 'MemberExpression' ) {
if ( node.computed ) return null;
parts.unshift( node.property.name );
node = node.object;
}
if ( node.type !== 'Identifier' ) return null;
const name = node.name;
parts.unshift( name );
return { name, keypath: parts.join( '.' ) };
}

@ -0,0 +1,28 @@
export default function isReference ( node, parent ) {
if ( node.type === 'MemberExpression' ) {
return !node.computed && isReference( node.object, node );
}
if ( node.type === 'Identifier' ) {
// the only time we could have an identifier node without a parent is
// if it's the entire body of a function without a block statement
// i.e. an arrow function expression like `a => a`
if ( !parent ) return true;
// TODO is this right?
if ( parent.type === 'MemberExpression' || parent.type === 'MethodDefinition' ) {
return parent.computed || node === parent.object;
}
// disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
if ( parent.type === 'Property' ) return parent.computed || node === parent.value;
// disregard the `bar` in `class Foo { bar () {...} }`
if ( parent.type === 'MethodDefinition' ) return false;
// disregard the `bar` in `export { foo as bar }`
if ( parent.type === 'ExportSpecifier' && node !== parent.local ) return;
return true;
}
}

@ -2,9 +2,9 @@ export default {
description: 'nested {{#each}} blocks',
data: {
columns: [ 'a', 'b', 'c' ],
row: [ 1, 2, 3 ]
rows: [ 1, 2, 3 ]
},
html: `<div>a, 1</div><div>b, 1</div><div>c, 1</div><div>a, 2</div><div>b, 2</div><div>c, 2</div><div>a, 3</div><div>b, 3</div><div>c, 3</div>`,
html: `<div>a, 1</div><div>a, 2</div><div>a, 3</div><!--#each rows--><div>b, 1</div><div>b, 2</div><div>b, 3</div><!--#each rows--><div>c, 1</div><div>c, 2</div><div>c, 3</div><!--#each rows--><!--#each columns-->`,
test ( component, target ) {
// TODO
}

@ -64,7 +64,7 @@ describe( 'svelte', () => {
i = String( i + 1 );
while ( i.length < 3 ) i = ` ${i}`;
return `${i}: ${line}`;
return `${i}: ${line.replace( /^\t+/, match => match.split( '\t' ).join( ' ' ) )}`;
}).join( '\n' );
cache[ path.resolve( `test/samples/${dir}/main.svelte` ) ] = code;

Loading…
Cancel
Save