more tidying up

pull/2252/head
Richard Harris 7 years ago
parent 0bc78006e5
commit ba33f278be

@ -2,7 +2,7 @@ import MagicString, { Bundle } from 'magic-string';
import { walk, childKeys } from 'estree-walker'; import { walk, childKeys } from 'estree-walker';
import { getLocator } from 'locate-character'; import { getLocator } from 'locate-character';
import Stats from '../Stats'; import Stats from '../Stats';
import reservedNames from '../utils/reservedNames'; import { reserved } from '../utils/names';
import { namespaces, validNamespaces } from '../utils/namespaces'; import { namespaces, validNamespaces } from '../utils/namespaces';
import { removeNode } from '../utils/removeNode'; import { removeNode } from '../utils/removeNode';
import wrapModule from './wrapModule'; import wrapModule from './wrapModule';
@ -14,7 +14,7 @@ import internal_exports from './internal-exports';
import { Node, Ast, CompileOptions, Var, Warning } from '../interfaces'; import { Node, Ast, CompileOptions, Var, Warning } from '../interfaces';
import error from '../utils/error'; import error from '../utils/error';
import getCodeFrame from '../utils/getCodeFrame'; import getCodeFrame from '../utils/getCodeFrame';
import flattenReference from '../utils/flattenReference'; import flatten_reference from './utils/flatten_reference';
import is_reference from 'is-reference'; import is_reference from 'is-reference';
import TemplateScope from './nodes/shared/TemplateScope'; import TemplateScope from './nodes/shared/TemplateScope';
import fuzzymatch from '../utils/fuzzymatch'; import fuzzymatch from '../utils/fuzzymatch';
@ -322,7 +322,7 @@ export default class Component {
let alias = name; let alias = name;
for ( for (
let i = 1; let i = 1;
reservedNames.has(alias) || reserved.has(alias) ||
this.var_lookup.has(alias) || this.var_lookup.has(alias) ||
this.usedNames.has(alias); this.usedNames.has(alias);
alias = `${name}_${i++}` alias = `${name}_${i++}`
@ -338,7 +338,7 @@ export default class Component {
localUsedNames.add(name); localUsedNames.add(name);
} }
reservedNames.forEach(add); reserved.forEach(add);
this.var_lookup.forEach((value, key) => add(key)); this.var_lookup.forEach((value, key) => add(key));
return (name: string) => { return (name: string) => {
@ -947,7 +947,7 @@ export default class Component {
} }
if (is_reference(node, parent)) { if (is_reference(node, parent)) {
const { name } = flattenReference(node); const { name } = flatten_reference(node);
const owner = scope.find_owner(name); const owner = scope.find_owner(name);
if (name[0] === '$' && !owner) { if (name[0] === '$' && !owner) {

@ -1,7 +1,7 @@
import Node from './shared/Node'; import Node from './shared/Node';
import Binding from './Binding'; import Binding from './Binding';
import EventHandler from './EventHandler'; import EventHandler from './EventHandler';
import flattenReference from '../../utils/flattenReference'; import flatten_reference from '../utils/flatten_reference';
import fuzzymatch from '../../utils/fuzzymatch'; import fuzzymatch from '../../utils/fuzzymatch';
import list from '../../utils/list'; import list from '../../utils/list';
import Action from './Action'; import Action from './Action';
@ -32,7 +32,7 @@ export default class Window extends Node {
else if (node.type === 'Binding') { else if (node.type === 'Binding') {
if (node.expression.type !== 'Identifier') { if (node.expression.type !== 'Identifier') {
const { parts } = flattenReference(node.expression); const { parts } = flatten_reference(node.expression);
// TODO is this constraint necessary? // TODO is this constraint necessary?
component.error(node.expression, { component.error(node.expression, {

@ -1,7 +1,7 @@
import Component from '../../Component'; import Component from '../../Component';
import { walk } from 'estree-walker'; import { walk } from 'estree-walker';
import is_reference from 'is-reference'; import is_reference from 'is-reference';
import flattenReference from '../../../utils/flattenReference'; import flatten_reference from '../../utils/flatten_reference';
import { create_scopes, Scope, extract_names } from '../../utils/scope'; import { create_scopes, Scope, extract_names } from '../../utils/scope';
import { Node } from '../../../interfaces'; import { Node } from '../../../interfaces';
import globalWhitelist from '../../../utils/globalWhitelist'; import globalWhitelist from '../../../utils/globalWhitelist';
@ -119,7 +119,7 @@ export default class Expression {
} }
if (is_reference(node, parent)) { if (is_reference(node, parent)) {
const { name, nodes } = flattenReference(node); const { name, nodes } = flatten_reference(node);
if (scope.has(name)) return; if (scope.has(name)) return;
@ -254,7 +254,7 @@ export default class Expression {
} }
if (is_reference(node, parent)) { if (is_reference(node, parent)) {
const { name, nodes } = flattenReference(node); const { name, nodes } = flatten_reference(node);
if (scope.has(name)) return; if (scope.has(name)) return;
if (globalWhitelist.has(name) && !component.var_lookup.has(name)) return; if (globalWhitelist.has(name) && !component.var_lookup.has(name)) return;

@ -2,7 +2,7 @@ import Wrapper from './shared/Wrapper';
import Renderer from '../Renderer'; import Renderer from '../Renderer';
import Block from '../Block'; import Block from '../Block';
import AwaitBlock from '../../nodes/AwaitBlock'; import AwaitBlock from '../../nodes/AwaitBlock';
import createDebuggingComment from '../../../utils/createDebuggingComment'; import create_debugging_comment from './shared/create_debugging_comment';
import deindent from '../../utils/deindent'; import deindent from '../../utils/deindent';
import FragmentWrapper from './Fragment'; import FragmentWrapper from './Fragment';
import PendingBlock from '../../nodes/PendingBlock'; import PendingBlock from '../../nodes/PendingBlock';
@ -29,7 +29,7 @@ class AwaitBlockBranch extends Wrapper {
super(renderer, block, parent, node); super(renderer, block, parent, node);
this.block = block.child({ this.block = block.child({
comment: createDebuggingComment(node, this.renderer.component), comment: create_debugging_comment(node, this.renderer.component),
name: this.renderer.component.getUniqueName(`create_${status}_block`) name: this.renderer.component.getUniqueName(`create_${status}_block`)
}); });

@ -1,7 +1,7 @@
import Renderer from '../Renderer'; import Renderer from '../Renderer';
import Block from '../Block'; import Block from '../Block';
import Wrapper from './shared/Wrapper'; import Wrapper from './shared/Wrapper';
import createDebuggingComment from '../../../utils/createDebuggingComment'; import create_debugging_comment from './shared/create_debugging_comment';
import EachBlock from '../../nodes/EachBlock'; import EachBlock from '../../nodes/EachBlock';
import FragmentWrapper from './Fragment'; import FragmentWrapper from './Fragment';
import deindent from '../../utils/deindent'; import deindent from '../../utils/deindent';
@ -26,7 +26,7 @@ class ElseBlockWrapper extends Wrapper {
super(renderer, block, parent, node); super(renderer, block, parent, node);
this.block = block.child({ this.block = block.child({
comment: createDebuggingComment(node, this.renderer.component), comment: create_debugging_comment(node, this.renderer.component),
name: this.renderer.component.getUniqueName(`create_else_block`) name: this.renderer.component.getUniqueName(`create_else_block`)
}); });
@ -80,7 +80,7 @@ export default class EachBlockWrapper extends Wrapper {
block.addDependencies(dependencies); block.addDependencies(dependencies);
this.block = block.child({ this.block = block.child({
comment: createDebuggingComment(this.node, this.renderer.component), comment: create_debugging_comment(this.node, this.renderer.component),
name: renderer.component.getUniqueName('create_each_block'), name: renderer.component.getUniqueName('create_each_block'),
key: node.key as string, key: node.key as string,

@ -1,6 +1,6 @@
import Attribute from '../../../nodes/Attribute'; import Attribute from '../../../nodes/Attribute';
import Block from '../../Block'; import Block from '../../Block';
import fixAttributeCasing from '../../../../utils/fixAttributeCasing'; import fix_attribute_casing from './fix_attribute_casing';
import ElementWrapper from './index'; import ElementWrapper from './index';
import { stringify } from '../../../../utils/stringify'; import { stringify } from '../../../../utils/stringify';
import deindent from '../../../utils/deindent'; import deindent from '../../../utils/deindent';
@ -36,7 +36,7 @@ export default class AttributeWrapper {
render(block: Block) { render(block: Block) {
const element = this.parent; const element = this.parent;
const name = fixAttributeCasing(this.node.name); const name = fix_attribute_casing(this.node.name);
let metadata = element.node.namespace ? null : attributeLookup[name]; let metadata = element.node.namespace ? null : attributeLookup[name];
if (metadata && metadata.appliesTo && !~metadata.appliesTo.indexOf(element.node.name)) if (metadata && metadata.appliesTo && !~metadata.appliesTo.indexOf(element.node.name))

@ -5,7 +5,7 @@ import getObject from '../../../../utils/getObject';
import Block from '../../Block'; import Block from '../../Block';
import Node from '../../../nodes/shared/Node'; import Node from '../../../nodes/shared/Node';
import Renderer from '../../Renderer'; import Renderer from '../../Renderer';
import flattenReference from '../../../../utils/flattenReference'; import flatten_reference from '../../../utils/flatten_reference';
import { get_tail } from '../../../../utils/get_tail_snippet'; import { get_tail } from '../../../../utils/get_tail_snippet';
import EachBlock from '../../../nodes/EachBlock'; import EachBlock from '../../../nodes/EachBlock';
@ -199,7 +199,7 @@ function getDomUpdater(
} }
function getBindingGroup(renderer: Renderer, value: Node) { function getBindingGroup(renderer: Renderer, value: Node) {
const { parts } = flattenReference(value); // TODO handle cases involving computed member expressions const { parts } = flatten_reference(value); // TODO handle cases involving computed member expressions
const keypath = parts.join('.'); const keypath = parts.join('.');
// TODO handle contextual bindings — `keypath` should include unique ID of // TODO handle contextual bindings — `keypath` should include unique ID of

@ -0,0 +1,12 @@
const svg_attributes = 'accent-height accumulate additive alignment-baseline allowReorder alphabetic amplitude arabic-form ascent attributeName attributeType autoReverse azimuth baseFrequency baseline-shift baseProfile bbox begin bias by calcMode cap-height class clip clipPathUnits clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering contentScriptType contentStyleType cursor cx cy d decelerate descent diffuseConstant direction display divisor dominant-baseline dur dx dy edgeMode elevation enable-background end exponent externalResourcesRequired fill fill-opacity fill-rule filter filterRes filterUnits flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight format from fr fx fy g1 g2 glyph-name glyph-orientation-horizontal glyph-orientation-vertical glyphRef gradientTransform gradientUnits hanging height href horiz-adv-x horiz-origin-x id ideographic image-rendering in in2 intercept k k1 k2 k3 k4 kernelMatrix kernelUnitLength kerning keyPoints keySplines keyTimes lang lengthAdjust letter-spacing lighting-color limitingConeAngle local marker-end marker-mid marker-start markerHeight markerUnits markerWidth mask maskContentUnits maskUnits mathematical max media method min mode name numOctaves offset onabort onactivate onbegin onclick onend onerror onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup onrepeat onresize onscroll onunload opacity operator order orient orientation origin overflow overline-position overline-thickness panose-1 paint-order pathLength patternContentUnits patternTransform patternUnits pointer-events points pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits r radius refX refY rendering-intent repeatCount repeatDur requiredExtensions requiredFeatures restart result rotate rx ry scale seed shape-rendering slope spacing specularConstant specularExponent speed spreadMethod startOffset stdDeviation stemh stemv stitchTiles stop-color stop-opacity strikethrough-position strikethrough-thickness string stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style surfaceScale systemLanguage tabindex tableValues target targetX targetY text-anchor text-decoration text-rendering textLength to transform type u1 u2 underline-position underline-thickness unicode unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical values version vert-adv-y vert-origin-x vert-origin-y viewBox viewTarget visibility width widths word-spacing writing-mode x x-height x1 x2 xChannelSelector xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space y y1 y2 yChannelSelector z zoomAndPan'.split(' ');
const svg_attribute_lookup = new Map();
svg_attributes.forEach(name => {
svg_attribute_lookup.set(name.toLowerCase(), name);
});
export default function fix_attribute_casing(name) {
name = name.toLowerCase();
return svg_attribute_lookup.get(name) || name;
}

@ -3,12 +3,12 @@ import Element from '../../../nodes/Element';
import Wrapper from '../shared/Wrapper'; import Wrapper from '../shared/Wrapper';
import Block from '../../Block'; import Block from '../../Block';
import Node from '../../../nodes/shared/Node'; import Node from '../../../nodes/shared/Node';
import { quotePropIfNecessary, quoteNameIfNecessary } from '../../../../utils/quoteIfNecessary'; import { quote_prop_if_necessary, quote_name_if_necessary } from '../../../../utils/names';
import isVoidElementName from '../../../../utils/isVoidElementName'; import isVoidElementName from '../../../../utils/isVoidElementName';
import FragmentWrapper from '../Fragment'; import FragmentWrapper from '../Fragment';
import { stringify, escapeHTML, escape } from '../../../../utils/stringify'; import { stringify, escapeHTML, escape } from '../../../../utils/stringify';
import TextWrapper from '../Text'; import TextWrapper from '../Text';
import fixAttributeCasing from '../../../../utils/fixAttributeCasing'; import fix_attribute_casing from './fix_attribute_casing';
import deindent from '../../../utils/deindent'; import deindent from '../../../utils/deindent';
import { namespaces } from '../../../../utils/namespaces'; import { namespaces } from '../../../../utils/namespaces';
import AttributeWrapper from './Attribute'; import AttributeWrapper from './Attribute';
@ -19,7 +19,7 @@ import InlineComponentWrapper from '../InlineComponent';
import add_to_set from '../../../utils/add_to_set'; import add_to_set from '../../../utils/add_to_set';
import addEventHandlers from '../shared/addEventHandlers'; import addEventHandlers from '../shared/addEventHandlers';
import addActions from '../shared/addActions'; import addActions from '../shared/addActions';
import createDebuggingComment from '../../../../utils/createDebuggingComment'; import create_debugging_comment from '../shared/create_debugging_comment';
import sanitize from '../../../../utils/sanitize'; import sanitize from '../../../../utils/sanitize';
import { get_context_merger } from '../shared/get_context_merger'; import { get_context_merger } from '../shared/get_context_merger';
@ -133,7 +133,7 @@ export default class ElementWrapper extends Wrapper {
if (!(owner as InlineComponentWrapper).slots.has(name)) { if (!(owner as InlineComponentWrapper).slots.has(name)) {
const child_block = block.child({ const child_block = block.child({
comment: createDebuggingComment(node, this.renderer.component), comment: create_debugging_comment(node, this.renderer.component),
name: this.renderer.component.getUniqueName(`create_${sanitize(name)}_slot`) name: this.renderer.component.getUniqueName(`create_${sanitize(name)}_slot`)
}); });
@ -336,7 +336,7 @@ export default class ElementWrapper extends Wrapper {
let open = `<${wrapper.node.name}`; let open = `<${wrapper.node.name}`;
(wrapper as ElementWrapper).attributes.forEach((attr: AttributeWrapper) => { (wrapper as ElementWrapper).attributes.forEach((attr: AttributeWrapper) => {
open += ` ${fixAttributeCasing(attr.node.name)}${attr.stringify()}` open += ` ${fix_attribute_casing(attr.node.name)}${attr.stringify()}`
}); });
if (isVoidElementName(wrapper.node.name)) return open + '>'; if (isVoidElementName(wrapper.node.name)) return open + '>';
@ -369,7 +369,7 @@ export default class ElementWrapper extends Wrapper {
getClaimStatement(nodes: string) { getClaimStatement(nodes: string) {
const attributes = this.node.attributes const attributes = this.node.attributes
.filter((attr: Node) => attr.type === 'Attribute') .filter((attr: Node) => attr.type === 'Attribute')
.map((attr: Node) => `${quoteNameIfNecessary(attr.name)}: true`) .map((attr: Node) => `${quote_name_if_necessary(attr.name)}: true`)
.join(', '); .join(', ');
const name = this.node.namespace const name = this.node.namespace
@ -579,7 +579,7 @@ export default class ElementWrapper extends Wrapper {
updates.push(condition ? `${condition} && ${snippet}` : snippet); updates.push(condition ? `${condition} && ${snippet}` : snippet);
} else { } else {
const snippet = `{ ${quoteNameIfNecessary(attr.name)}: ${attr.getValue(block)} }`; const snippet = `{ ${quote_name_if_necessary(attr.name)}: ${attr.getValue(block)} }`;
initialProps.push(snippet); initialProps.push(snippet);
updates.push(condition ? `${condition} && ${snippet}` : snippet); updates.push(condition ? `${condition} && ${snippet}` : snippet);
@ -786,7 +786,7 @@ export default class ElementWrapper extends Wrapper {
snippet = expression.render(block); snippet = expression.render(block);
dependencies = expression.dependencies; dependencies = expression.dependencies;
} else { } else {
snippet = `${quotePropIfNecessary(name)}`; snippet = `${quote_prop_if_necessary(name)}`;
dependencies = new Set([name]); dependencies = new Set([name]);
} }
const updater = `@toggleClass(${this.var}, "${name}", ${snippet});`; const updater = `@toggleClass(${this.var}, "${name}", ${snippet});`;
@ -795,7 +795,7 @@ export default class ElementWrapper extends Wrapper {
if ((dependencies && dependencies.size > 0) || this.classDependencies.length) { if ((dependencies && dependencies.size > 0) || this.classDependencies.length) {
const allDeps = this.classDependencies.concat(...dependencies); const allDeps = this.classDependencies.concat(...dependencies);
const deps = allDeps.map(dependency => `changed${quotePropIfNecessary(dependency)}`).join(' || '); const deps = allDeps.map(dependency => `changed${quote_prop_if_necessary(dependency)}`).join(' || ');
const condition = allDeps.length > 1 ? `(${deps})` : deps; const condition = allDeps.length > 1 ? `(${deps})` : deps;
block.builders.update.add_conditional( block.builders.update.add_conditional(

@ -3,7 +3,7 @@ import Renderer from '../Renderer';
import Block from '../Block'; import Block from '../Block';
import EachBlock from '../../nodes/EachBlock'; import EachBlock from '../../nodes/EachBlock';
import IfBlock from '../../nodes/IfBlock'; import IfBlock from '../../nodes/IfBlock';
import createDebuggingComment from '../../../utils/createDebuggingComment'; import create_debugging_comment from './shared/create_debugging_comment';
import ElseBlock from '../../nodes/ElseBlock'; import ElseBlock from '../../nodes/ElseBlock';
import FragmentWrapper from './Fragment'; import FragmentWrapper from './Fragment';
import deindent from '../../utils/deindent'; import deindent from '../../utils/deindent';
@ -35,7 +35,7 @@ class IfBlockBranch extends Wrapper {
this.condition = (node as IfBlock).expression && (node as IfBlock).expression.render(block); this.condition = (node as IfBlock).expression && (node as IfBlock).expression.render(block);
this.block = block.child({ this.block = block.child({
comment: createDebuggingComment(node, parent.renderer.component), comment: create_debugging_comment(node, parent.renderer.component),
name: parent.renderer.component.getUniqueName( name: parent.renderer.component.getUniqueName(
(node as IfBlock).expression ? `create_if_block` : `create_else_block` (node as IfBlock).expression ? `create_if_block` : `create_else_block`
) )

@ -3,14 +3,14 @@ import Renderer from '../../Renderer';
import Block from '../../Block'; import Block from '../../Block';
import InlineComponent from '../../../nodes/InlineComponent'; import InlineComponent from '../../../nodes/InlineComponent';
import FragmentWrapper from '../Fragment'; import FragmentWrapper from '../Fragment';
import { quoteNameIfNecessary, quotePropIfNecessary } from '../../../../utils/quoteIfNecessary'; import { quote_name_if_necessary, quote_prop_if_necessary } from '../../../../utils/names';
import { stringify_props } from '../../../utils/stringify_props'; import { stringify_props } from '../../../utils/stringify_props';
import add_to_set from '../../../utils/add_to_set'; import add_to_set from '../../../utils/add_to_set';
import deindent from '../../../utils/deindent'; import deindent from '../../../utils/deindent';
import Attribute from '../../../nodes/Attribute'; import Attribute from '../../../nodes/Attribute';
import getObject from '../../../../utils/getObject'; import getObject from '../../../../utils/getObject';
import flattenReference from '../../../../utils/flattenReference'; import flatten_reference from '../../../utils/flatten_reference';
import createDebuggingComment from '../../../../utils/createDebuggingComment'; import create_debugging_comment from '../shared/create_debugging_comment';
import sanitize from '../../../../utils/sanitize'; import sanitize from '../../../../utils/sanitize';
import { get_context_merger } from '../shared/get_context_merger'; import { get_context_merger } from '../shared/get_context_merger';
import EachBlock from '../../../nodes/EachBlock'; import EachBlock from '../../../nodes/EachBlock';
@ -69,7 +69,7 @@ export default class InlineComponentWrapper extends Wrapper {
if (this.node.children.length) { if (this.node.children.length) {
const default_slot = block.child({ const default_slot = block.child({
comment: createDebuggingComment(node, renderer.component), comment: create_debugging_comment(node, renderer.component),
name: renderer.component.getUniqueName(`create_default_slot`) name: renderer.component.getUniqueName(`create_default_slot`)
}); });
@ -126,7 +126,7 @@ export default class InlineComponentWrapper extends Wrapper {
const attributeObject = usesSpread const attributeObject = usesSpread
? stringify_props(slot_props) ? stringify_props(slot_props)
: stringify_props( : stringify_props(
this.node.attributes.map(attr => `${quoteNameIfNecessary(attr.name)}: ${attr.getValue(block)}`).concat(slot_props) this.node.attributes.map(attr => `${quote_name_if_necessary(attr.name)}: ${attr.getValue(block)}`).concat(slot_props)
); );
if (this.node.attributes.length || this.node.bindings.length || slot_props.length) { if (this.node.attributes.length || this.node.bindings.length || slot_props.length) {
@ -200,7 +200,7 @@ export default class InlineComponentWrapper extends Wrapper {
changes.push(condition ? `${condition} && ${value}` : value); changes.push(condition ? `${condition} && ${value}` : value);
} else { } else {
const obj = `{ ${quoteNameIfNecessary(name)}: ${attr.getValue(block)} }`; const obj = `{ ${quote_name_if_necessary(name)}: ${attr.getValue(block)} }`;
initialProps.push(obj); initialProps.push(obj);
changes.push(condition ? `${condition} && ${obj}` : obj); changes.push(condition ? `${condition} && ${obj}` : obj);
@ -234,7 +234,7 @@ export default class InlineComponentWrapper extends Wrapper {
updates.push(deindent` updates.push(deindent`
if (${[...attribute.dependencies] if (${[...attribute.dependencies]
.map(dependency => `changed.${dependency}`) .map(dependency => `changed.${dependency}`)
.join(' || ')}) ${name_changes}${quotePropIfNecessary(attribute.name)} = ${attribute.getValue(block)}; .join(' || ')}) ${name_changes}${quote_prop_if_necessary(attribute.name)} = ${attribute.getValue(block)};
`); `);
} }
}); });
@ -269,7 +269,7 @@ export default class InlineComponentWrapper extends Wrapper {
// TODO we need to invalidate... something // TODO we need to invalidate... something
} else { } else {
object = flattenReference(binding.expression.node).name; object = flatten_reference(binding.expression.node).name;
lhs = component.source.slice(binding.expression.node.start, binding.expression.node.end).trim(); lhs = component.source.slice(binding.expression.node.start, binding.expression.node.end).trim();
} }
@ -299,13 +299,13 @@ export default class InlineComponentWrapper extends Wrapper {
statements.push(deindent` statements.push(deindent`
if (${snippet} !== void 0) { if (${snippet} !== void 0) {
${props}${quotePropIfNecessary(binding.name)} = ${snippet}; ${props}${quote_prop_if_necessary(binding.name)} = ${snippet};
}` }`
); );
updates.push(deindent` updates.push(deindent`
if (!${updating} && ${[...binding.expression.dependencies].map((dependency: string) => `changed.${dependency}`).join(' || ')}) { if (!${updating} && ${[...binding.expression.dependencies].map((dependency: string) => `changed.${dependency}`).join(' || ')}) {
${name_changes}${quotePropIfNecessary(binding.name)} = ${snippet}; ${name_changes}${quote_prop_if_necessary(binding.name)} = ${snippet};
} }
`); `);

@ -1,7 +1,7 @@
import Component from '../compile/Component'; import Component from '../../../Component';
import { Node } from '../interfaces'; import { Node } from '../../../../interfaces';
export default function createDebuggingComment( export default function create_debugging_comment(
node: Node, node: Node,
component: Component component: Component
) { ) {

@ -1,4 +1,4 @@
import { quotePropIfNecessary, quoteNameIfNecessary } from '../../../utils/quoteIfNecessary'; import { quote_prop_if_necessary, quote_name_if_necessary } from '../../../utils/names';
import isVoidElementName from '../../../utils/isVoidElementName'; import isVoidElementName from '../../../utils/isVoidElementName';
import Attribute from '../../nodes/Attribute'; import Attribute from '../../nodes/Attribute';
import Node from '../../nodes/shared/Node'; import Node from '../../nodes/shared/Node';
@ -64,7 +64,7 @@ export default function(node, renderer, options) {
const classExpr = node.classes.map((classDir: Class) => { const classExpr = node.classes.map((classDir: Class) => {
const { expression, name } = classDir; const { expression, name } = classDir;
const snippet = expression ? snip(expression) : `ctx${quotePropIfNecessary(name)}`; const snippet = expression ? snip(expression) : `ctx${quote_prop_if_necessary(name)}`;
return `${snippet} ? "${name}" : ""`; return `${snippet} ? "${name}" : ""`;
}).join(', '); }).join(', ');
@ -80,16 +80,16 @@ export default function(node, renderer, options) {
if (attribute.name === 'value' && node.name === 'textarea') { if (attribute.name === 'value' && node.name === 'textarea') {
textareaContents = stringify_attribute(attribute, true); textareaContents = stringify_attribute(attribute, true);
} else if (attribute.isTrue) { } else if (attribute.isTrue) {
args.push(`{ ${quoteNameIfNecessary(attribute.name)}: true }`); args.push(`{ ${quote_name_if_necessary(attribute.name)}: true }`);
} else if ( } else if (
boolean_attributes.has(attribute.name) && boolean_attributes.has(attribute.name) &&
attribute.chunks.length === 1 && attribute.chunks.length === 1 &&
attribute.chunks[0].type !== 'Text' attribute.chunks[0].type !== 'Text'
) { ) {
// a boolean attribute with one non-Text chunk // a boolean attribute with one non-Text chunk
args.push(`{ ${quoteNameIfNecessary(attribute.name)}: ${snip(attribute.chunks[0])} }`); args.push(`{ ${quote_name_if_necessary(attribute.name)}: ${snip(attribute.chunks[0])} }`);
} else { } else {
args.push(`{ ${quoteNameIfNecessary(attribute.name)}: \`${stringify_attribute(attribute, true)}\` }`); args.push(`{ ${quote_name_if_necessary(attribute.name)}: \`${stringify_attribute(attribute, true)}\` }`);
} }
} }
}); });

@ -1,5 +1,5 @@
import { escape, escapeTemplate, stringify } from '../../../utils/stringify'; import { escape, escapeTemplate, stringify } from '../../../utils/stringify';
import { quoteNameIfNecessary } from '../../../utils/quoteIfNecessary'; import { quote_name_if_necessary } from '../../../utils/names';
import { snip } from '../../../utils/snip'; import { snip } from '../../../utils/snip';
import Renderer from '../Renderer'; import Renderer from '../Renderer';
import { stringify_props } from '../../utils/stringify_props'; import { stringify_props } from '../../utils/stringify_props';
@ -101,7 +101,7 @@ export default function(node, renderer: Renderer, options) {
const slot_scope = slot_scopes.get(name); const slot_scope = slot_scopes.get(name);
slot_fns.push( slot_fns.push(
`${quoteNameIfNecessary(name)}: (${slot_scope}) => \`${target.slots[name]}\`` `${quote_name_if_necessary(name)}: (${slot_scope}) => \`${target.slots[name]}\``
); );
}); });

@ -1,11 +1,11 @@
import { quotePropIfNecessary } from '../../../utils/quoteIfNecessary'; import { quote_prop_if_necessary } from '../../../utils/names';
import get_slot_data from '../../../utils/get_slot_data'; import get_slot_data from '../../../utils/get_slot_data';
export default function(node, renderer, options) { export default function(node, renderer, options) {
const name = node.attributes.find(attribute => attribute.name === 'name'); const name = node.attributes.find(attribute => attribute.name === 'name');
const slot_name = name && name.chunks[0].data || 'default'; const slot_name = name && name.chunks[0].data || 'default';
const prop = quotePropIfNecessary(slot_name); const prop = quote_prop_if_necessary(slot_name);
const slot_data = get_slot_data(node.attributes, true); const slot_data = get_slot_data(node.attributes, true);

@ -1,6 +1,6 @@
import { Node } from '../interfaces'; import { Node } from '../../interfaces';
export default function flattenReference(node: Node) { export default function flatten_reference(node: Node) {
if (node.type === 'Expression') throw new Error('bad'); if (node.type === 'Expression') throw new Error('bad');
const nodes = []; const nodes = [];
const parts = []; const parts = [];

@ -1,8 +1,8 @@
import { isIdentifierStart, isIdentifierChar } from 'acorn'; import { isIdentifierStart, isIdentifierChar } from 'acorn';
import fragment from './state/fragment'; import fragment from './state/fragment';
import { whitespace } from '../utils/patterns'; import { whitespace } from '../utils/patterns';
import reservedNames from '../utils/reservedNames'; import { reserved } from '../utils/names';
import fullCharCodeAt from '../utils/fullCharCodeAt'; import full_char_code_at from '../utils/full_char_code_at';
import { Node, Ast } from '../interfaces'; import { Node, Ast } from '../interfaces';
import error from '../utils/error'; import error from '../utils/error';
@ -156,13 +156,13 @@ export class Parser {
let i = this.index; let i = this.index;
const code = fullCharCodeAt(this.template, i); const code = full_char_code_at(this.template, i);
if (!isIdentifierStart(code, true)) return null; if (!isIdentifierStart(code, true)) return null;
i += code <= 0xffff ? 1 : 2; i += code <= 0xffff ? 1 : 2;
while (i < this.template.length) { while (i < this.template.length) {
const code = fullCharCodeAt(this.template, i); const code = full_char_code_at(this.template, i);
if (!isIdentifierChar(code, true)) break; if (!isIdentifierChar(code, true)) break;
i += code <= 0xffff ? 1 : 2; i += code <= 0xffff ? 1 : 2;
@ -170,7 +170,7 @@ export class Parser {
const identifier = this.template.slice(this.index, this.index = i); const identifier = this.template.slice(this.index, this.index = i);
if (reservedNames.has(identifier)) { if (reserved.has(identifier)) {
this.error({ this.error({
code: `unexpected-reserved-word`, code: `unexpected-reserved-word`,
message: `'${identifier}' is a reserved word in JavaScript and cannot be used here` message: `'${identifier}' is a reserved word in JavaScript and cannot be used here`

@ -1,12 +0,0 @@
const svgAttributes = 'accent-height accumulate additive alignment-baseline allowReorder alphabetic amplitude arabic-form ascent attributeName attributeType autoReverse azimuth baseFrequency baseline-shift baseProfile bbox begin bias by calcMode cap-height class clip clipPathUnits clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering contentScriptType contentStyleType cursor cx cy d decelerate descent diffuseConstant direction display divisor dominant-baseline dur dx dy edgeMode elevation enable-background end exponent externalResourcesRequired fill fill-opacity fill-rule filter filterRes filterUnits flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight format from fr fx fy g1 g2 glyph-name glyph-orientation-horizontal glyph-orientation-vertical glyphRef gradientTransform gradientUnits hanging height href horiz-adv-x horiz-origin-x id ideographic image-rendering in in2 intercept k k1 k2 k3 k4 kernelMatrix kernelUnitLength kerning keyPoints keySplines keyTimes lang lengthAdjust letter-spacing lighting-color limitingConeAngle local marker-end marker-mid marker-start markerHeight markerUnits markerWidth mask maskContentUnits maskUnits mathematical max media method min mode name numOctaves offset onabort onactivate onbegin onclick onend onerror onfocusin onfocusout onload onmousedown onmousemove onmouseout onmouseover onmouseup onrepeat onresize onscroll onunload opacity operator order orient orientation origin overflow overline-position overline-thickness panose-1 paint-order pathLength patternContentUnits patternTransform patternUnits pointer-events points pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits r radius refX refY rendering-intent repeatCount repeatDur requiredExtensions requiredFeatures restart result rotate rx ry scale seed shape-rendering slope spacing specularConstant specularExponent speed spreadMethod startOffset stdDeviation stemh stemv stitchTiles stop-color stop-opacity strikethrough-position strikethrough-thickness string stroke stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width style surfaceScale systemLanguage tabindex tableValues target targetX targetY text-anchor text-decoration text-rendering textLength to transform type u1 u2 underline-position underline-thickness unicode unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical values version vert-adv-y vert-origin-x vert-origin-y viewBox viewTarget visibility width widths word-spacing writing-mode x x-height x1 x2 xChannelSelector xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type xml:base xml:lang xml:space y y1 y2 yChannelSelector z zoomAndPan'.split(' ');
const svgAttributeLookup = new Map();
svgAttributes.forEach(name => {
svgAttributeLookup.set(name.toLowerCase(), name);
});
export default function fixAttributeCasing(name) {
name = name.toLowerCase();
return svgAttributeLookup.get(name) || name;
}

@ -1,7 +1,7 @@
// Adapted from https://github.com/acornjs/acorn/blob/6584815dca7440e00de841d1dad152302fdd7ca5/src/tokenize.js // Adapted from https://github.com/acornjs/acorn/blob/6584815dca7440e00de841d1dad152302fdd7ca5/src/tokenize.js
// Reproduced under MIT License https://github.com/acornjs/acorn/blob/master/LICENSE // Reproduced under MIT License https://github.com/acornjs/acorn/blob/master/LICENSE
export default function fullCharCodeAt(str: string, i: number): number { export default function full_char_code_at(str: string, i: number): number {
let code = str.charCodeAt(i) let code = str.charCodeAt(i)
if (code <= 0xd7ff || code >= 0xe000) return code; if (code <= 0xd7ff || code >= 0xe000) return code;

@ -1,15 +0,0 @@
import { isIdentifierStart, isIdentifierChar } from 'acorn';
import fullCharCodeAt from './fullCharCodeAt';
export default function isValidIdentifier(str: string): boolean {
let i = 0;
while (i < str.length) {
const code = fullCharCodeAt(str, i);
if (!(i === 0 ? isIdentifierStart : isIdentifierChar)(code, true)) return false;
i += code <= 0xffff ? 1 : 2;
}
return true;
}

@ -0,0 +1,76 @@
import { isIdentifierStart, isIdentifierChar } from 'acorn';
import full_char_code_at from './full_char_code_at';
function is_valid(str: string): boolean {
let i = 0;
while (i < str.length) {
const code = full_char_code_at(str, i);
if (!(i === 0 ? isIdentifierStart : isIdentifierChar)(code, true)) return false;
i += code <= 0xffff ? 1 : 2;
}
return true;
}
export const reserved = new Set([
'arguments',
'await',
'break',
'case',
'catch',
'class',
'const',
'continue',
'debugger',
'default',
'delete',
'do',
'else',
'enum',
'eval',
'export',
'extends',
'false',
'finally',
'for',
'function',
'if',
'implements',
'import',
'in',
'instanceof',
'interface',
'let',
'new',
'null',
'package',
'private',
'protected',
'public',
'return',
'static',
'super',
'switch',
'this',
'throw',
'true',
'try',
'typeof',
'var',
'void',
'while',
'with',
'yield',
]);
export function quote_name_if_necessary(name) {
if (!is_valid(name)) return `"${name}"`;
return name;
}
export function quote_prop_if_necessary(name) {
if (!is_valid(name)) return `["${name}"]`;
return `.${name}`;
}

@ -1,12 +0,0 @@
import isValidIdentifier from './isValidIdentifier';
import reservedNames from './reservedNames';
export function quoteNameIfNecessary(name) {
if (!isValidIdentifier(name)) return `"${name}"`;
return name;
}
export function quotePropIfNecessary(name) {
if (!isValidIdentifier(name)) return `["${name}"]`;
return `.${name}`;
}

@ -1,52 +0,0 @@
const reservedNames = new Set([
'arguments',
'await',
'break',
'case',
'catch',
'class',
'const',
'continue',
'debugger',
'default',
'delete',
'do',
'else',
'enum',
'eval',
'export',
'extends',
'false',
'finally',
'for',
'function',
'if',
'implements',
'import',
'in',
'instanceof',
'interface',
'let',
'new',
'null',
'package',
'private',
'protected',
'public',
'return',
'static',
'super',
'switch',
'this',
'throw',
'true',
'try',
'typeof',
'var',
'void',
'while',
'with',
'yield',
]);
export default reservedNames;
Loading…
Cancel
Save