use @foo for generator.alias("foo")

pull/673/head
Rich Harris 8 years ago
parent c8e396730b
commit 9feee3a0bf

@ -16,7 +16,6 @@ const helperPattern = new RegExp(`@(${Object.keys(shared).join('|')})\\b`, 'g');
export class DomGenerator extends Generator { export class DomGenerator extends Generator {
blocks: Block[]; blocks: Block[];
uses: Set<string>;
readonly: Set<string>; readonly: Set<string>;
metaBindings: string[]; metaBindings: string[];
@ -34,7 +33,6 @@ export class DomGenerator extends Generator {
) { ) {
super(parsed, source, name, options); super(parsed, source, name, options);
this.blocks = []; this.blocks = [];
this.uses = new Set();
this.readonly = new Set(); this.readonly = new Set();
@ -43,16 +41,6 @@ export class DomGenerator extends Generator {
// initial values for e.g. window.innerWidth, if there's a <:Window> meta tag // initial values for e.g. window.innerWidth, if there's a <:Window> meta tag
this.metaBindings = []; this.metaBindings = [];
} }
helper(name: string) {
if (this.options.dev && `${name}Dev` in shared) {
name = `${name}Dev`;
}
this.uses.add(name);
return this.alias(name);
}
} }
export default function dom( export default function dom(
@ -99,17 +87,13 @@ export default function dom(
`( '${dep}' in newState && @differs( state.${dep}, oldState.${dep} ) )` `( '${dep}' in newState && @differs( state.${dep}, oldState.${dep} ) )`
) )
.join(' || ')}`; .join(' || ')}`;
const statement = `state.${key} = newState.${key} = ${generator.alias( const statement = `state.${key} = newState.${key} = @template.computed.${key}( ${deps.map(dep => `state.${dep}`).join(', ')} );`;
'template'
)}.computed.${key}( ${deps.map(dep => `state.${dep}`).join(', ')} );`;
computationBuilder.addConditionalLine(condition, statement); computationBuilder.addConditionalLine(condition, statement);
}); });
builder.addBlock(deindent` builder.addBlock(deindent`
function ${generator.alias( function @recompute ( state, newState, oldState, isInitial ) {
'recompute'
)} ( state, newState, oldState, isInitial ) {
${computationBuilder} ${computationBuilder}
} }
`); `);
@ -130,10 +114,7 @@ export default function dom(
var oldState = this._state; var oldState = this._state;
this._state = @assign( {}, oldState, newState ); this._state = @assign( {}, oldState, newState );
${computations.length && ${computations.length && `@recompute( this._state, newState, oldState, false )`}
`${generator.alias(
'recompute'
)}( this._state, newState, oldState, false )`}
@dispatchObservers( this, this._observers.pre, newState, oldState ); @dispatchObservers( this, this._observers.pre, newState, oldState );
${block.hasUpdateMethod && `this._fragment.update( newState, this._state );`} ${block.hasUpdateMethod && `this._fragment.update( newState, this._state );`}
@dispatchObservers( this, this._observers.post, newState, oldState ); @dispatchObservers( this, this._observers.post, newState, oldState );
@ -151,9 +132,9 @@ export default function dom(
if (generator.css && options.css !== false) { if (generator.css && options.css !== false) {
builder.addBlock(deindent` builder.addBlock(deindent`
function ${generator.alias('add_css')} () { function @add_css () {
var style = @createElement( 'style' ); var style = @createElement( 'style' );
style.id = ${JSON.stringify(generator.cssId + '-style')}; style.id = '${generator.cssId}-style';
style.textContent = ${JSON.stringify(generator.css)}; style.textContent = ${JSON.stringify(generator.css)};
@appendNode( style, document.head ); @appendNode( style, document.head );
} }
@ -171,14 +152,14 @@ export default function dom(
const prototypeBase = const prototypeBase =
`${name}.prototype` + `${name}.prototype` +
(templateProperties.methods (templateProperties.methods
? `, ${generator.alias('template')}.methods` ? `, @template.methods`
: ''); : '');
const proto = sharedPath const proto = sharedPath
? `@proto ` ? `@proto `
: deindent` : deindent`
{ {
${['get', 'fire', 'observe', 'on', 'set', '_flush'] ${['get', 'fire', 'observe', 'on', 'set', '_flush']
.map(n => `${n}: ${generator.helper(n)}`) .map(n => `${n}: @${n}`)
.join(',\n')} .join(',\n')}
}`; }`;
@ -190,15 +171,11 @@ export default function dom(
`if ( !options.target && !options._root ) throw new Error( "'target' is a required option" );`} `if ( !options.target && !options._root ) throw new Error( "'target' is a required option" );`}
${generator.usesRefs && `this.refs = {};`} ${generator.usesRefs && `this.refs = {};`}
this._state = ${templateProperties.data this._state = ${templateProperties.data
? `@assign( ${generator.alias( ? `@assign( @template.data(), options.data )`
'template'
)}.data(), options.data )`
: `options.data || {}`}; : `options.data || {}`};
${generator.metaBindings} ${generator.metaBindings}
${computations.length && ${computations.length &&
`${generator.alias( `@recompute( this._state, this._state, {}, true );`}
'recompute'
)}( this._state, this._state, {}, true );`}
${options.dev && ${options.dev &&
Array.from(generator.expectedProperties).map( Array.from(generator.expectedProperties).map(
prop => prop =>
@ -224,14 +201,12 @@ export default function dom(
options.css !== false && options.css !== false &&
`if ( !document.getElementById( ${JSON.stringify( `if ( !document.getElementById( ${JSON.stringify(
generator.cssId + '-style' generator.cssId + '-style'
)} ) ) ${generator.alias('add_css')}();`} )} ) ) @add_css();`}
${(generator.hasComponents || generator.hasIntroTransitions) && ${(generator.hasComponents || generator.hasIntroTransitions) &&
`this._renderHooks = [];`} `this._renderHooks = [];`}
${generator.hasComplexBindings && `this._bindings = [];`} ${generator.hasComplexBindings && `this._bindings = [];`}
this._fragment = ${generator.alias( this._fragment = @create_main_fragment( this._state, this );
'create_main_fragment'
)}( this._state, this );
if ( options.target ) { if ( options.target ) {
${generator.hydratable ? ${generator.hydratable ?
@ -254,11 +229,9 @@ export default function dom(
${templateProperties.oncreate && ${templateProperties.oncreate &&
deindent` deindent`
if ( options._root ) { if ( options._root ) {
options._root._renderHooks.push( ${generator.alias( options._root._renderHooks.push( @template.oncreate.bind( this ) );
'template'
)}.oncreate.bind( this ) );
} else { } else {
${generator.alias('template')}.oncreate.call( this ); @template.oncreate.call( this );
} }
`} `}
} }
@ -272,7 +245,7 @@ export default function dom(
${name}.prototype.teardown = ${name}.prototype.destroy = function destroy ( detach ) { ${name}.prototype.teardown = ${name}.prototype.destroy = function destroy ( detach ) {
this.fire( 'destroy' ); this.fire( 'destroy' );
${templateProperties.ondestroy && ${templateProperties.ondestroy &&
`${generator.alias('template')}.ondestroy.call( this );`} `@template.ondestroy.call( this );`}
if ( detach !== false ) this._fragment.unmount(); if ( detach !== false ) this._fragment.unmount();
this._fragment.destroy(); this._fragment.destroy();
@ -283,8 +256,16 @@ export default function dom(
}; };
`); `);
const usedHelpers = new Set();
let result = builder.toString() let result = builder.toString()
.replace(helperPattern, (match: string, name: string) => generator.helper(name)); .replace(/@(\w+)\b/g, (match: string, name: string) => {
if (name in shared) {
if (options.dev && `${name}Dev` in shared) name = `${name}Dev`;
usedHelpers.add(name);
}
return generator.alias(name);
});
if (sharedPath) { if (sharedPath) {
if (format !== 'es') { if (format !== 'es') {
@ -293,7 +274,7 @@ export default function dom(
); );
} }
const names = Array.from(generator.uses).sort().map(name => { const names = Array.from(usedHelpers).sort().map(name => {
return name !== generator.alias(name) return name !== generator.alias(name)
? `${name} as ${generator.alias(name)}` ? `${name} as ${generator.alias(name)}`
: name; : name;
@ -301,7 +282,7 @@ export default function dom(
result = `import { ${names.join(', ')} } from ${JSON.stringify(sharedPath)};\n\n` + result; result = `import { ${names.join(', ')} } from ${JSON.stringify(sharedPath)};\n\n` + result;
} else { } else {
generator.uses.forEach(key => { usedHelpers.forEach(key => {
const str = shared[key]; const str = shared[key];
const code = new MagicString(str); const code = new MagicString(str);
const expression = parseExpressionAt(str, 0); const expression = parseExpressionAt(str, 0);
@ -320,7 +301,7 @@ export default function dom(
if (node.name in shared) { if (node.name in shared) {
// this helper function depends on another one // this helper function depends on another one
const dependency = node.name; const dependency = node.name;
generator.uses.add(dependency); usedHelpers.add(dependency);
const alias = generator.alias(dependency); const alias = generator.alias(dependency);
if (alias !== node.name) if (alias !== node.name)

@ -382,7 +382,7 @@ export default function preprocess(
) { ) {
const block = new Block({ const block = new Block({
generator, generator,
name: generator.alias('create_main_fragment'), name: '@create_main_fragment',
key: null, key: null,
contexts: new Map(), contexts: new Map(),

@ -184,7 +184,7 @@ export default function visitComponent(
const expression = node.name === ':Self' const expression = node.name === ':Self'
? generator.name ? generator.name
: generator.importedComponents.get(node.name) || : generator.importedComponents.get(node.name) ||
`${generator.alias('template')}.components.${node.name}`; `@template.components.${node.name}`;
local.create.addBlockAtStart(deindent` local.create.addBlockAtStart(deindent`
${statements.join('\n')} ${statements.join('\n')}

@ -72,9 +72,7 @@ export default function visitEventHandler(
block.addVariable(handlerName); block.addVariable(handlerName);
block.builders.hydrate.addBlock(deindent` block.builders.hydrate.addBlock(deindent`
${handlerName} = ${generator.alias( ${handlerName} = @template.events.${name}.call( ${block.component}, ${state.parentNode}, function ( event ) {
'template'
)}.events.${name}.call( ${block.component}, ${state.parentNode}, function ( event ) {
${handlerBody} ${handlerBody}
}); });
`); `);

@ -20,7 +20,7 @@ export default function addTransitions(
block.addVariable(name); block.addVariable(name);
const fn = `${generator.alias('template')}.transitions.${intro.name}`; const fn = `@template.transitions.${intro.name}`;
block.builders.intro.addBlock(deindent` block.builders.intro.addBlock(deindent`
${block.component}._renderHooks.push( function () { ${block.component}._renderHooks.push( function () {
@ -48,7 +48,7 @@ export default function addTransitions(
? block.contextualise(intro.expression).snippet ? block.contextualise(intro.expression).snippet
: '{}'; : '{}';
const fn = `${generator.alias('template')}.transitions.${intro.name}`; // TODO add built-in transitions? const fn = `@template.transitions.${intro.name}`; // TODO add built-in transitions?
if (outro) { if (outro) {
block.builders.intro.addBlock(deindent` block.builders.intro.addBlock(deindent`
@ -73,7 +73,7 @@ export default function addTransitions(
? block.contextualise(outro.expression).snippet ? block.contextualise(outro.expression).snippet
: '{}'; : '{}';
const fn = `${generator.alias('template')}.transitions.${outro.name}`; const fn = `@template.transitions.${outro.name}`;
// TODO hide elements that have outro'd (unless they belong to a still-outroing // TODO hide elements that have outro'd (unless they belong to a still-outroing
// group) prior to their removal from the DOM // group) prior to their removal from the DOM

@ -59,22 +59,18 @@ export default function ssr(
${name}.data = function () { ${name}.data = function () {
return ${templateProperties.data return ${templateProperties.data
? `${generator.alias('template')}.data()` ? `@template.data()`
: `{}`}; : `{}`};
}; };
${name}.render = function ( state, options ) { ${name}.render = function ( state, options ) {
${templateProperties.data ${templateProperties.data
? `state = Object.assign( ${generator.alias( ? `state = Object.assign( @template.data(), state || {} );`
'template'
)}.data(), state || {} );`
: `state = state || {};`} : `state = state || {};`}
${computations.map( ${computations.map(
({ key, deps }) => ({ key, deps }) =>
`state.${key} = ${generator.alias( `state.${key} = @template.computed.${key}( ${deps.map(dep => `state.${dep}`).join(', ')} );`
'template'
)}.computed.${key}( ${deps.map(dep => `state.${dep}`).join(', ')} );`
)} )}
${generator.bindings.length && ${generator.bindings.length &&
@ -121,7 +117,7 @@ export default function ssr(
const { name } = prop.key; const { name } = prop.key;
const expression = const expression =
generator.importedComponents.get(name) || generator.importedComponents.get(name) ||
`${generator.alias('template')}.components.${name}`; `@template.components.${name}`;
return `addComponent( ${expression} );`; return `addComponent( ${expression} );`;
})} })}
`} `}
@ -144,7 +140,7 @@ export default function ssr(
function __escape ( html ) { function __escape ( html ) {
return String( html ).replace( /["'&<>]/g, match => escaped[ match ] ); return String( html ).replace( /["'&<>]/g, match => escaped[ match ] );
} }
`; `.replace(/@(\w+)/g, (match, name) => generator.alias(name));
return generator.generate(result, options, { name, format }); return generator.generate(result, options, { name, format });
} }

@ -68,7 +68,7 @@ export default function visitComponent(
const expression = node.name === ':Self' const expression = node.name === ':Self'
? generator.name ? generator.name
: generator.importedComponents.get(node.name) || : generator.importedComponents.get(node.name) ||
`${generator.alias('template')}.components.${node.name}`; `@template.components.${node.name}`;
bindings.forEach(binding => { bindings.forEach(binding => {
block.addBinding(binding, expression); block.addBinding(binding, expression);

@ -145,7 +145,7 @@ var template = (function () {
function add_css () { function add_css () {
var style = createElement( 'style' ); var style = createElement( 'style' );
style.id = "svelte-3842350206-style"; style.id = 'svelte-3842350206-style';
style.textContent = "\n\tp[svelte-3842350206], [svelte-3842350206] p {\n\t\tcolor: red;\n\t}\n"; style.textContent = "\n\tp[svelte-3842350206], [svelte-3842350206] p {\n\t\tcolor: red;\n\t}\n";
appendNode( style, document.head ); appendNode( style, document.head );
} }

@ -10,7 +10,7 @@ var template = (function () {
function add_css () { function add_css () {
var style = createElement( 'style' ); var style = createElement( 'style' );
style.id = "svelte-3842350206-style"; style.id = 'svelte-3842350206-style';
style.textContent = "\n\tp[svelte-3842350206], [svelte-3842350206] p {\n\t\tcolor: red;\n\t}\n"; style.textContent = "\n\tp[svelte-3842350206], [svelte-3842350206] p {\n\t\tcolor: red;\n\t}\n";
appendNode( style, document.head ); appendNode( style, document.head );
} }

Loading…
Cancel
Save