Skip to content

[WIP] Make things a bit classier #1359

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions src/generators/Generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ export default class Generator {
this.templateProperties = {};

this.walkJs(dom);
this.name = this.alias(name);
this.name = this.getUniqueName(name);

if (options.customElement === true) {
this.customElement = {
Expand Down Expand Up @@ -610,8 +610,10 @@ export default class Generator {
}

if (templateProperties.methods && dom) {
addDeclaration('methods', templateProperties.methods.value);

const indentationLevel = getIndentationLevel(source, templateProperties.methods.start);
if (indentationLevel) {
removeIndentation(code, templateProperties.methods.start, templateProperties.methods.end, indentationLevel, indentExclusionRanges);
}
templateProperties.methods.value.properties.forEach(prop => {
this.methods.add(prop.key.name);
});
Expand Down
258 changes: 142 additions & 116 deletions src/generators/dom/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import MagicString from 'magic-string';
import isReference from 'is-reference';
import { parseExpressionAt } from 'acorn';
import annotateWithScopes from '../../utils/annotateWithScopes';
import { walk } from 'estree-walker';
import { walk, childKeys } from 'estree-walker';
import deindent from '../../utils/deindent';
import { stringify, escape } from '../../utils/stringify';
import CodeBuilder from '../../utils/CodeBuilder';
Expand Down Expand Up @@ -133,17 +133,6 @@ export default function dom(
? 'svelte/shared.js'
: options.shared || '';

let prototypeBase = `${name}.prototype`;

const proto = sharedPath
? `@proto`
: deindent`
{
${['destroy', 'get', 'fire', 'on', 'set', '_set', '_mount', '_unmount', '_differs']
.map(n => `${n}: @${n}`)
.join(',\n')}
}`;

const debugName = `<${generator.customElement ? generator.tag : name}>`;

// generate initial state object
Expand Down Expand Up @@ -172,11 +161,7 @@ export default function dom(

const constructorBody = deindent`
${options.dev && `this._debugName = '${debugName}';`}
${options.dev && !generator.customElement &&
`if (!options || (!options.target && !options.root)) throw new Error("'target' is a required option");`}
@init(this, options);
${templateProperties.store && `this.store = %store();`}
${generator.usesRefs && `this.refs = {};`}
this._state = ${initialState.reduce((state, piece) => `@assign(${state}, ${piece})`)};
${storeProps.length > 0 && `this.store._add(this, [${storeProps.map(prop => `"${prop.slice(1)}"`)}]);`}
${generator.metaBindings}
Expand Down Expand Up @@ -207,72 +192,101 @@ export default function dom(
}];`
)}

${generator.slots.size && `this._slotted = options.slots || {};`}

${generator.customElement ?
deindent`
this.attachShadow({ mode: 'open' });
${css.code && `this.shadowRoot.innerHTML = \`<style>${escape(css.code, { onlyEscapeAtSymbol: true }).replace(/\\/g, '\\\\')}${options.dev ? `\n/*# sourceMappingURL=${css.map.toUrl()} */` : ''}</style>\`;`}
${generator.customElement ? deindent`
${css.code && `this.shadowRoot.innerHTML = \`<style>${escape(css.code, { onlyEscapeAtSymbol: true }).replace(/\\/g, '\\\\')}${options.dev ? `\n/*# sourceMappingURL=${css.map.toUrl()} */` : ''}</style>\`;`}
` :
(generator.stylesheet.hasStyles && options.css !== false &&
`if (!document.getElementById("${generator.stylesheet.id}-style")) @add_css();`)
}
`if (!document.getElementById("${generator.stylesheet.id}-style")) @add_css();`)}

this._fragment = @create_main_fragment(this, this._state);

${hasInitHooks && deindent`
var self = this;
var _oncreate = function() {
var changed = { ${expectedProperties.map(p => `${p}: 1`).join(', ')} };
${templateProperties.onstate && `%onstate.call(self, { changed: changed, current: self._state });`}
${templateProperties.oncreate && `%oncreate.call(self);`}
self.fire("update", { changed: changed, current: self._state });
};
`}
this.root._oncreate.push(() => {
const changed = { ${expectedProperties.map(p => `${p}: 1`).join(', ')} };
${templateProperties.onstate && `%onstate.call(this, { changed, current: this._state });`}
${templateProperties.oncreate && `%oncreate.call(this);`}
this.fire("update", { changed, current: this._state });
});`}

${(hasInitHooks || generator.hasComponents || generator.hasComplexBindings || generator.hasIntroTransitions) && deindent`
if (!options.root) {
this._oncreate = [];
${(generator.hasComponents || generator.hasComplexBindings) && `this._beforecreate = [];`}
${(generator.hasComponents || generator.hasIntroTransitions) && `this._aftercreate = [];`}
}
`}
${generator.customElement ?
deindent`
this._fragment.c();
this._fragment.${block.hasIntroMethod ? 'i' : 'm'}(this.shadowRoot, null);

${generator.slots.size && `this.slots = {};`}
if (options.target) this._mount(options.target, options.anchor);
` :
deindent`
if (options.target) {
${generator.hydratable
? deindent`
var nodes = @children(options.target);
options.hydrate ? this._fragment.l(nodes) : this._fragment.c();
nodes.forEach(@detachNode);
` :
deindent`
${options.dev && `if (options.hydrate) throw new Error("options.hydrate only works if the component was compiled with the \`hydratable: true\` option");`}
this._fragment.c();
`}
this._mount(options.target, options.anchor);

${(generator.hasComponents || generator.hasComplexBindings || hasInitHooks || generator.hasIntroTransitions) && deindent`
${generator.hasComponents && `this._lock = true;`}
${(generator.hasComponents || generator.hasComplexBindings) && `@callAll(this._beforecreate);`}
${(generator.hasComponents || hasInitHooks) && `@callAll(this._oncreate);`}
${(generator.hasComponents || generator.hasIntroTransitions) && `@callAll(this._aftercreate);`}
${generator.hasComponents && `this._lock = false;`}
`}
}`}
`;

this._fragment = @create_main_fragment(this, this._state);
const classMethods = [];
const extraMethods = [];

${hasInitHooks && deindent`
this.root._oncreate.push(_oncreate);
`}
if (templateProperties.methods) {
templateProperties.methods.value.properties.forEach(prop => {
if (/FunctionExpression/.test(prop.value.type)) {
const { type, params, body, async, generator: isGenerator, start, end } = prop.value;

${generator.customElement ? deindent`
this._fragment.c();
this._fragment.${block.hasIntroMethod ? 'i' : 'm'}(this.shadowRoot, null);

if (options.target) this._mount(options.target, options.anchor);
` : deindent`
if (options.target) {
${generator.hydratable
? deindent`
var nodes = @children(options.target);
options.hydrate ? this._fragment.l(nodes) : this._fragment.c();
nodes.forEach(@detachNode);
` :
deindent`
${options.dev && `if (options.hydrate) throw new Error("options.hydrate only works if the component was compiled with the \`hydratable: true\` option");`}
this._fragment.c();
`}
this._mount(options.target, options.anchor);
const prefix = async ? `async ` : isGenerator ? `*` : ``;
const key = `${prefix}[✂${prop.key.start}-${prop.key.end}✂]`;

${(generator.hasComponents || generator.hasComplexBindings || hasInitHooks || generator.hasIntroTransitions) && deindent`
${generator.hasComponents && `this._lock = true;`}
${(generator.hasComponents || generator.hasComplexBindings) && `@callAll(this._beforecreate);`}
${(generator.hasComponents || hasInitHooks) && `@callAll(this._oncreate);`}
${(generator.hasComponents || generator.hasIntroTransitions) && `@callAll(this._aftercreate);`}
${generator.hasComponents && `this._lock = false;`}
`}
if (type === 'ArrowFunctionExpression') {
const paramsSnippet = params.length > 0
? `[✂${params[0].start}-${params[params.length - 1].end}✂]`
: '';

let bodySnippet = `[✂${body.start}-${body.end}✂]`;
if (body.type !== 'BlockStatement') bodySnippet = `{ return ${bodySnippet}; }`;

classMethods.push(`${key}(${paramsSnippet}) ${bodySnippet}`)
} else if (type === 'FunctionExpression') {
let c = start;
while (generator.source[c] !== '(') c += 1;
classMethods.push(`${key}[✂${c}-${end}✂]`);
}
} else {
extraMethods.push(`[✂${prop.start}-${prop.end}✂]`)
}
`}
`;
});
}

if (computations.length) {
classMethods.push(deindent`
_recompute(changed, state) {
${computationBuilder}
}`);
}

if (options.dev) {
const readonly = Array.from(generator.readonly);
if (readonly.length > 0) {
classMethods.push(deindent`
_checkReadOnly(newState) {
if (this._updatingReadonlyProperty) return;
${readonly.map(prop => `if ('${prop}' in newState) throw new Error("${debugName}: Cannot set read-only property '${prop}'");`)}
}`);
}
}

if (generator.customElement) {
const props = generator.props || Array.from(generator.expectedProperties);
Expand All @@ -281,6 +295,9 @@ export default function dom(
class ${name} extends HTMLElement {
constructor(options = {}) {
super();
this._handlers = {};
this._init.call(this, options);
this.attachShadow({ mode: 'open' });
${constructorBody}
}

Expand All @@ -289,39 +306,45 @@ export default function dom(
}

${props.map(prop => deindent`
get ${prop}() {
return this.get().${prop};
}
get ${prop}() {
return this.get().${prop};
}

set ${prop}(value) {
this.set({ ${prop}: value });
}
`).join('\n\n')}
set ${prop}(value) {
this.set({ ${prop}: value });
}`).join('\n\n')}

${generator.slots.size && deindent`
connectedCallback() {
Object.keys(this._slotted).forEach(key => {
this.appendChild(this._slotted[key]);
});
}`}
${classMethods.length && classMethods.join('\n\n')}

attributeChangedCallback(attr, oldValue, newValue) {
this.set({ [attr]: newValue });
}

${(generator.hasComponents || generator.hasComplexBindings || templateProperties.oncreate || generator.hasIntroTransitions) && deindent`
connectedCallback() {
${generator.hasComponents && `this._lock = true;`}
${(generator.hasComponents || generator.hasComplexBindings) && `@callAll(this._beforecreate);`}
${(generator.hasComponents || templateProperties.oncreate) && `@callAll(this._oncreate);`}
${(generator.hasComponents || generator.hasIntroTransitions) && `@callAll(this._aftercreate);`}
${generator.hasComponents && `this._lock = false;`}
}
${(generator.slots.size || generator.hasComponents || generator.hasComplexBindings || templateProperties.oncreate || generator.hasIntroTransitions) && deindent`
connectedCallback() {
${generator.slots.size && deindent`
Object.keys(this._slotted).forEach(key => {
this.appendChild(this._slotted[key]);
});`}
${generator.hasComponents && `this._lock = true;`}
${(generator.hasComponents || generator.hasComplexBindings) && `@callAll(this._beforecreate);`}
${(generator.hasComponents || templateProperties.oncreate) && `@callAll(this._oncreate);`}
${(generator.hasComponents || generator.hasIntroTransitions) && `@callAll(this._aftercreate);`}
${generator.hasComponents && `this._lock = false;`}
}
`}
}

customElements.define("${generator.tag}", ${name});
@assign(@assign(${prototypeBase}, ${proto}), {
Object.getOwnPropertyNames(${generator.options.dev ? `Object.getPrototypeOf(@Component.prototype)` : `@Component.prototype`}).forEach(name => {
${name}.prototype[name] = @Component.prototype[name];
});

@assign(${name}.prototype, {
fire: @Base.prototype.fire,
get: @Base.prototype.get,
on: @Base.prototype.on,
_differs: @Base.prototype._differs,

_mount(target, anchor) {
target.insertBefore(this, anchor);
},
Expand All @@ -330,36 +353,31 @@ export default function dom(
this.parentNode.removeChild(this);
}
});

customElements.define("${generator.tag}", ${name});
`);
} else {
builder.addBlock(deindent`
function ${name}(options) {
${constructorBody}
}
class ${name} extends @Component {
constructor(options) {
super(options);
${constructorBody}
}

@assign(${prototypeBase}, ${proto});
${templateProperties.methods && `@assign(${prototypeBase}, %methods);`}
${classMethods.length && classMethods.join('\n\n')}
}
`);
}

const immutable = templateProperties.immutable ? templateProperties.immutable.value.value : options.immutable;

builder.addBlock(deindent`
${options.dev && deindent`
${name}.prototype._checkReadOnly = function _checkReadOnly(newState) {
${Array.from(generator.readonly).map(
prop =>
`if ('${prop}' in newState && !this._updatingReadonlyProperty) throw new Error("${debugName}: Cannot set read-only property '${prop}'");`
)}
};
${extraMethods.length > 0 && deindent`
@assign(${name}.prototype, {
${extraMethods.join(',\n\n')}
});
`}

${computations.length ? deindent`
${name}.prototype._recompute = function _recompute(changed, state) {
${computationBuilder}
}
` : (!sharedPath && `${name}.prototype._recompute = @noop;`)}

${templateProperties.setup && `%setup(${name});`}

${templateProperties.preload && `${name}.preload = %preload;`}
Expand Down Expand Up @@ -402,6 +420,12 @@ export default function dom(
} else {
let inlineHelpers = '';

// super gross hack to ensure Component isn't declared before Base
usedHelpers.delete('Component');
usedHelpers.delete('ComponentDev');
usedHelpers.add('Base').add('Component');
if (generator.options.dev) usedHelpers.add('ComponentDev');

usedHelpers.forEach(key => {
const str = shared[key];
const code = new MagicString(str);
Expand All @@ -424,8 +448,9 @@ export default function dom(
usedHelpers.add(dependency);

const alias = generator.alias(dependency);
if (alias !== node.name)
if (alias !== node.name) {
code.overwrite(node.start, node.end, alias);
}
}
}
},
Expand All @@ -439,17 +464,18 @@ export default function dom(
// special case
const global = `_svelteTransitionManager`;

inlineHelpers += `\n\nvar ${generator.alias('transitionManager')} = window.${global} || (window.${global} = ${code});\n\n`;
inlineHelpers += `var ${generator.alias('transitionManager')} = window.${global} || (window.${global} = ${code});\n\n`;
} else {
const alias = generator.alias(expression.id.name);

if (alias !== expression.id.name)
code.overwrite(expression.id.start, expression.id.end, alias);

inlineHelpers += `\n\n${code}`;
inlineHelpers += `${code}\n\n`;
}
});

result += inlineHelpers;
result = inlineHelpers + result;
}

const filename = options.filename && (
Expand Down
Loading