Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export class ComponentDefinitionData {
html: Expression;
watches: Array<ComponentWatch> = [];
dynamicElements: Expression[] = [];
baseComponent: Expression | undefined;
baseComponent?: Expression;
lookups: Map<number, ArrowFunctionExpression> = new Map();
refs: string[] = [];
parts: Array<Part> = [];
Expand Down
3 changes: 2 additions & 1 deletion packages/babel-plugin-wallace/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ export enum IMPORTABLES {
onEvent = "onEvent",
SequentialRepeater = "SequentialRepeater",
KeyedRepeater = "KeyedRepeater",
toDateString = "toDateString"
toDateString = "toDateString",
watch = "watch"
}

/**
Expand Down
1 change: 1 addition & 0 deletions packages/babel-plugin-wallace/src/contexts/parameters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ function extractFinalPropsName(path: NodePath<Function>): PropsMap {
return propVariableMap;
}

// TODO: this really needs to be done on a per-directive basis as it can vary.
function mapAndRenameXargs(path: NodePath<Function>, component: Component) {
const renameMapping: { [key: string]: string } = {};
renameMapping[XARGS.event] = XARGS.event;
Expand Down
65 changes: 44 additions & 21 deletions packages/babel-plugin-wallace/src/directives.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,16 @@ class ApplyDirective extends Directive {
}
}

class AssignDirective extends Directive {
static attributeName = "assign";
static valueMode: ValueMode = ValueMode.EitherRequired;
static qualifierMode: QualifierMode = QualifierMode.SetsValue;
static mustBeOnRoot = true;
apply(node: TagNode, value: NodeValue, qualifier: Qualifier, _base: string) {
node.component.assignTo = value.expression || value.value;
}
}

class BindDirective extends Directive {
static attributeName = "bind";
static valueMode: ValueMode = ValueMode.ExpressionRequired;
Expand Down Expand Up @@ -87,25 +97,6 @@ class CtrlDirective extends Directive {
}
}

/**
* This is a hack to enable a Proxy of a Date to be passed to `valueAsDate`.
* It is not a documented directive.
*/
class ValueAsDateDirective extends Directive {
static attributeName = "valueAsDate";
apply(node: TagNode, value: NodeValue, _qualifier: Qualifier, _base: string) {
if (value.type === "expression") {
node.requiredImport(IMPORTABLES.toDateString);
node.watchAttribute(
"value",
t.callExpression(t.identifier(IMPORTABLES.toDateString), [value.expression])
);
} else if (value.type === "string") {
node.addFixedAttribute("valueAsDate", value.value);
}
}
}

class EventDirective extends Directive {
static attributeName = "event";
static valueMode: ValueMode = ValueMode.StringRequired;
Expand Down Expand Up @@ -267,18 +258,48 @@ class UniqueDirective extends Directive {
static attributeName = "unique";
static valueMode: ValueMode = ValueMode.NotAllowed;
static qualifierMode: QualifierMode = QualifierMode.NotAllowed;
static mustBeOnRoot = true;
apply(node: TagNode, _value: NodeValue, _qualifier: Qualifier, _base: string) {
node.component.unique = true;
}
}

/**
* This is a hack to enable a Proxy of a Date to be passed to `valueAsDate`.
* It is not a documented directive.
*/
class ValueAsDateDirective extends Directive {
static attributeName = "valueAsDate";
apply(node: TagNode, value: NodeValue, _qualifier: Qualifier, _base: string) {
if (value.type === "expression") {
node.requiredImport(IMPORTABLES.toDateString);
node.watchAttribute(
"value",
t.callExpression(t.identifier(IMPORTABLES.toDateString), [value.expression])
);
} else if (value.type === "string") {
node.addFixedAttribute("valueAsDate", value.value);
}
}
}

class WatchDirective extends Directive {
static attributeName = "watch";
static valueMode: ValueMode = ValueMode.ExpressionOptional;
static qualifierMode: QualifierMode = QualifierMode.NotAllowed;
static mustBeOnRoot = true;
apply(node: TagNode, value: NodeValue, _qualifier: Qualifier, _base: string) {
node.component.watchProps = { callback: value.expression };
}
}

export const builtinDirectives = [
ApplyDirective,
AssignDirective,
BindDirective,
ClassDirective,
CssDirective,
CtrlDirective,
ValueAsDateDirective,
EventDirective,
FixedDirective,
HideDirective,
Expand All @@ -292,5 +313,7 @@ export const builtinDirectives = [
ShowDirective,
StyleDirective,
ToggleDirective,
UniqueDirective
UniqueDirective,
ValueAsDateDirective,
WatchDirective
];
3 changes: 3 additions & 0 deletions packages/babel-plugin-wallace/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ export const ERROR_MESSAGES = {
DIRECTIVE_NO_VALUE_ALLOWED: (directive: string) => {
return `The \`${directive}\` directive does not allow a value.`;
},
DIRECTIVE_MUST_BE_ON_ROOT_ELEMENT: (directive: string) => {
return `The \`${directive}\` directive may only be used on the root element.`;
},
EVENT_USED_WITHOUT_BIND:
"The `event` directive must be used with the `bind` directive.",
FLAG_REQUIRED: (flag: string) => {
Expand Down
9 changes: 7 additions & 2 deletions packages/babel-plugin-wallace/src/models/component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type {
JSXText,
Expression
} from "@babel/types";
import { stringLiteral } from "@babel/types";
import { stringLiteral, LVal } from "@babel/types";
import type { Scope } from "@babel/traverse";
import { HTML_SPLITTER } from "../constants";
import { buildConcat, getPlaceholderExpression } from "../ast-helpers";
Expand Down Expand Up @@ -45,14 +45,16 @@ export class Component {
#currentNodeAddress: Array<number> = [];
module: Module;
scope: Scope;
baseComponent: Expression | undefined;
baseComponent?: Expression;
rootElement: HTMLElement;
extractedNodes: ExtractedNode[] = [];
propsIdentifier: Identifier;
componentIdentifier: Identifier;
xargMapping: { [key: string]: string } = {};
htmlExpressions: Expression[] = [];
unique: boolean = false;
assignTo?: LVal | string;
watchProps?: { callback?: Expression };
constructor(
module: Module,
scope: Scope,
Expand Down Expand Up @@ -103,6 +105,9 @@ export class Component {
this.#addElement(node.getElement(), path, tracker);
this.extractedNodes.push(node);
}
needsCustomSetMethod() {
return this.assignTo || this.watchProps;
}
processJSXElement(
path: NodePath<JSXElement>,
tracker: WalkTracker,
Expand Down
14 changes: 10 additions & 4 deletions packages/babel-plugin-wallace/src/models/directive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,13 @@ export class Directive {
static allowOnNested = false;
static allowOnRepeated = false;
static allowOnNormalElement = true;
static mustBeOnRoot = false;
static mayAccessComponent = true;
static mayAccessElement = false;
static mayAccessEvent = false;
apply(node: TagNode, value: NodeValue, qualifier: Qualifier, base: string) {}
apply(node: TagNode, value: NodeValue, qualifier: Qualifier, base: string) {
throw new Error("apply not implemented on directive");
}
validate(
node: TagNode,
value: NodeValue,
Expand All @@ -59,7 +62,7 @@ export class Directive {
) {
const constructor = this.constructor as typeof Directive;
this.validateTypeAndQualifier(node, value, qualifier, constructor);
this.validateNestedAndRepeat(node, constructor);
this.validateLocation(node, constructor);
this.validateScopeVariablAccess(node, value, constructor, component);
}
validateTypeAndQualifier(
Expand Down Expand Up @@ -156,8 +159,8 @@ export class Directive {
break;
}
}
validateNestedAndRepeat(node: TagNode, constructor: typeof Directive) {
const { attributeName, allowOnRepeated, allowOnNested } = constructor;
validateLocation(node: TagNode, constructor: typeof Directive) {
const { attributeName, allowOnRepeated, allowOnNested, mustBeOnRoot } = constructor;
if (!allowOnRepeated && node.isRepeatedComponent) {
error(
node.path,
Expand All @@ -170,6 +173,9 @@ export class Directive {
ERROR_MESSAGES.DIRECTIVE_NOT_ALLOWED_ON_NESTED_ELEMENT(attributeName)
);
}
if (mustBeOnRoot && node.parent) {
error(node.path, ERROR_MESSAGES.DIRECTIVE_MUST_BE_ON_ROOT_ELEMENT(attributeName));
}
}
/*
Ensures the expression only accesses the scope variables it is allowed to.
Expand Down
65 changes: 63 additions & 2 deletions packages/babel-plugin-wallace/src/writers/defineComponent.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as t from "@babel/types";
import type { CallExpression } from "@babel/types";
import { Component } from "../models";
import type { CallExpression, ExpressionStatement, LVal } from "@babel/types";
import { Component, Module } from "../models";
import { wallaceConfig } from "../config";
import { COMPONENT_PROPERTIES, IMPORTABLES } from "../constants";
import type {
Expand Down Expand Up @@ -165,6 +165,62 @@ function buildConstructor(
);
}

function assignExpression(left: LVal, right: Expression): ExpressionStatement {
return t.expressionStatement(t.assignmentExpression("=", left, right));
}

function buildWatchCall(module: Module, name: string, watch?: { callback?: Expression }) {
module.requireImport(IMPORTABLES.watch);
const callback =
watch.callback ||
t.arrowFunctionExpression(
[],
t.callExpression(t.memberExpression(t.thisExpression(), t.identifier("update")), [])
);
return t.callExpression(t.identifier(IMPORTABLES.watch), [
t.identifier(name),
callback
]);
}

function getComponentPropertyAssignment(
module: Module,
name: string,
watch?: { callback?: Expression }
) {
const left = t.memberExpression(t.thisExpression(), t.identifier(name));
const right = watch ? buildWatchCall(module, name, watch) : t.identifier(name);
return assignExpression(left, right);
}

// TOOD: revisit once we rename per directive.
function buildSetFunction(componentDefinition: ComponentDefinitionData) {
const component = componentDefinition.component;
const { assignTo, watchProps, module } = component;

const statements: any[] = [
t.variableDeclaration("const", [
t.variableDeclarator(component.componentIdentifier, t.identifier("this")),
t.variableDeclarator(component.propsIdentifier, t.identifier("props"))
]),
getComponentPropertyAssignment(module, "props", watchProps)
];
if (assignTo) {
let actualValue: LVal;
if (typeof assignTo === "string") {
actualValue = t.memberExpression(component.propsIdentifier, t.identifier(assignTo));
} else {
actualValue = assignTo;
}
statements.push(assignExpression(actualValue, t.identifier("this")));
}
return t.functionExpression(
null,
[t.identifier("props"), t.identifier("ctrl")],
t.blockStatement(statements)
);
}

function buildDismountKeys(componentDefinition: ComponentDefinitionData) {
return t.arrayExpression(
componentDefinition.dismountKeys.map(key => t.numericLiteral(key))
Expand All @@ -173,12 +229,17 @@ function buildDismountKeys(componentDefinition: ComponentDefinitionData) {

export function buildDefineComponentCall(component: Component): CallExpression {
const componentDefinition = consolidateComponent(component);

const args: any[] = [
componentDefinition.html,
buildWatchesArg(componentDefinition),
buildLookupsArg(componentDefinition),
buildConstructor(componentDefinition)
];
const setFunctionArg = componentDefinition.component.needsCustomSetMethod()
? buildSetFunction(componentDefinition)
: t.numericLiteral(0);
args.push(setFunctionArg);
if (wallaceConfig.flags.allowDismount) {
args.push(buildDismountKeys(componentDefinition));
}
Expand Down
10 changes: 8 additions & 2 deletions packages/wallace/lib/component.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
const throwAway = document.createElement("template");
const NO_LOOKUP = "__";

const defaultSetFunction = function (props, /* #INCLUDE-IF: allowCtrl */ ctrl) {
this.props = props;
/* #INCLUDE-IF: allowCtrl */ this.ctrl = ctrl;
};

const ComponentPrototype = {
render: function (props, /* #INCLUDE-IF: allowCtrl */ ctrl) {
this.props = props;
/* #INCLUDE-IF: allowCtrl */ this.ctrl = ctrl;
this.set(props, /* #INCLUDE-IF: allowCtrl */ ctrl);
this.update();
},

Expand Down Expand Up @@ -152,12 +156,14 @@ export const defineComponent = (
watches,
queries,
contructor,
setFunction,
/* #INCLUDE-IF: allowDismount */ dismountKeys,
inheritFrom
) => {
const ComponentDefinition = initConstructor(contructor, inheritFrom || ComponentBase);
const proto = ComponentDefinition.prototype;
throwAway.innerHTML = html;
proto.set = setFunction || defaultSetFunction;
proto._w = watches;
proto._q = queries;
proto._t = throwAway.content.firstChild;
Expand Down
Loading
Loading