Skip to content

Commit

Permalink
Move transform to class syntax and simplify the code a bit (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
Serabe authored Mar 8, 2019
1 parent 5062310 commit cb2f3df
Showing 1 changed file with 51 additions and 46 deletions.
97 changes: 51 additions & 46 deletions lib/bind-transform.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,72 +25,77 @@
```
*/

function BindTransform() {
this.syntax = null;
}

BindTransform.prototype.transform = function(ast) {
var b = this.syntax.builders;

this.syntax.traverse(ast, {
SubExpression(node) {
transform(node);
},
MustacheStatement(node) {
transform(node);
}
});
module.exports = class BindTransform {
constructor() {
this.syntax = null;
}

get builders() {
return this.syntax.builders;
}

function transform(call) {
if (call.path.original === "bind" && call.params.length > 0) {
let hasTarget = call.hash.pairs.some(p => p.key === "target");
transform(ast) {
let transform = node => this.transformNode(node);
this.syntax.traverse(ast, {
SubExpression: transform,
MustacheStatement: transform
});

return ast;
}

transformNode(node) {
this.addTarget(node);
}

addTarget(node) {
if (node.path.original === "bind" && node.params.length > 0) {
let hasTarget = node.hash.pairs.some(p => p.key === "target");

if (!hasTarget) {
let target = getDefaultTarget(call.params[0]);
let target = this.getDefaultTarget(node.params[0]);

call.hash.pairs.push(b.pair("target", target));
node.hash.pairs.push(this.builders.pair("target", target));
}
}
}

function getDefaultTarget(fn) {
if (fn.type === "PathExpression") {
if (fn.parts.length === 0) {
return b.null();
} else if (fn.parts.length === 1) {
return b.path("this");
} else {
let parts = fn.parts.slice(0);
parts.pop(); // Remove function part
getDefaultTarget(fn) {
let { builders } = this;

let lastPart = parts[parts.length - 1];
if (fn.type !== "PathExpression") {
return builders.null();
}

if (lastPart !== "actions") {
return pathFor(parts.join('.'), fn.data);
}
switch (fn.parts.length) {
case 0:
return builders.null();
case 1:
return builders.path("this");
default: {
let parts = fn.parts.slice(0, -1); // Remove function part

parts.pop(); // Remove actions part
let lastPart = parts[parts.length - 1];

if (parts.length === 0) {
return b.path("this");
}
// Remove actions part
if (lastPart === "actions") {
parts.pop();
}

return pathFor(parts.join("."), fn.data);
if (parts.length === 0) {
return builders.path("this");
}
} else {
return b.null();

return this.pathFor(parts.join("."), fn.data);
}
}
}

function pathFor(completePath, isData = false /* named argument */) {
let path = b.path(completePath);
pathFor(completePath, isData = false /* named argument */) {
let path = this.builders.path(completePath);

path.data = isData;

return path;
}

return ast;
};

module.exports = BindTransform;

0 comments on commit cb2f3df

Please sign in to comment.