Skip to content
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

Improve inline js formatting #109

Merged
merged 3 commits into from
Jan 3, 2019
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
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 12 additions & 7 deletions packages/migrate/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,20 @@ export default async function(options = {}) {
files.map(async file => {
const basename = path.basename(file);
if (basename.endsWith(".marko")) {
const prettyPrintOptions = {
syntax: options.syntax,
maxLen: options.maxLen,
noSemi: options.noSemi,
singleQuote: options.singleQuote,
filename: file
};
const migrateHelper = new MigrateHelper(options.prompt);
const add = migrateOptions =>
addMigration(migrateHelper, migrateOptions);
const source = await fs.readFile(file, "utf-8");
const ast = markoCompiler.parse(source, file, {
onContext(ctx) {
prettyPrintOptions.context = ctx;
ctx.addMigration = add;
addDefaultMigrations(ctx, updatedFiles, movedFiles);
},
Expand All @@ -73,13 +81,10 @@ export default async function(options = {}) {

await runAutoMigrations(migrateHelper);

updatedFiles[file] = markoPrettyprint.prettyPrintAST(ast, {
syntax: options.syntax,
maxLen: options.maxLen,
noSemi: options.noSemi,
singleQuote: options.singleQuote,
filename: file
});
updatedFiles[file] = markoPrettyprint.prettyPrintAST(
ast,
prettyPrintOptions
);
}
})
);
Expand Down
20 changes: 13 additions & 7 deletions packages/prettyprint/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/prettyprint/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"argly": "^1.2.0",
"editorconfig": "^0.15.2",
"lasso-package-root": "^1.0.1",
"marko": "^4.14.3",
"marko": "^4.14.12",
"minimatch": "^3.0.4",
"prettier": "^1.15.3",
"redent": "^2.0.0",
Expand Down
1 change: 1 addition & 0 deletions packages/prettyprint/src/PrintContext.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class PrintContext {
this.singleQuote = options.singleQuote;
this.markoCompiler = options.markoCompiler;
this.CodeWriter = options.CodeWriter;
this.taglibLookup = options.taglibLookup;
}

get isConciseSyntax() {
Expand Down
4 changes: 4 additions & 0 deletions packages/prettyprint/src/prettyPrintAST.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ module.exports = function prettyPrintAST(ast, options) {
options.syntax = SYNTAX_HTML;
}

if (options.context) {
options.taglibLookup = options.context.taglibLookup;
}

var dirname = path.dirname(filename);
options.dirname = dirname;

Expand Down
7 changes: 6 additions & 1 deletion packages/prettyprint/src/prettyPrintSource.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ module.exports = function prettyPrintSource(src, options) {
options.CodeWriter =
options.CodeWriter || requireMarkoFile(dirname, "compiler/CodeWriter");

var ast = markoCompiler.parse(src, filename, { raw: true });
var ast = markoCompiler.parse(src, filename, {
raw: true,
onContext(context) {
options.context = context;
}
});
return prettyPrintAST(ast, options);
};
55 changes: 26 additions & 29 deletions packages/prettyprint/src/printHtmlElement.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"use strict";

const redent = require("redent");
const hasUnenclosedWhitespace = require("./util/hasUnenclosedWhitespace");
const getBodyText = require("./util/getBodyText");
const hasLineBreaks = require("./util/hasLineBreaks");
Expand All @@ -8,8 +9,8 @@ const Writer = require("./util/Writer");
const formattingTags = require("./formatting-tags");

const formatJS = require("./util/formatJS");
const formatArgument = require("./util/formatArgument");
const formatStyles = require("./util/formatStyles");
const toCode = require("./util/toCode");

const codeTags = {
class: {
Expand Down Expand Up @@ -102,7 +103,7 @@ module.exports = function printHtmlElement(node, printContext, writer) {
}

var tagNameString = tagNameExpression
? `\${${formatJS(tagNameExpression, printContext, undefined, true)}}`
? `\${${formatJS(tagNameExpression, printContext, true)}}`
: node.tagName;

writer.write(tagNameString);
Expand All @@ -116,15 +117,13 @@ module.exports = function printHtmlElement(node, printContext, writer) {
if (typeof className === "string") {
writer.write("." + className);
} else {
writer.write(
".${" + toCode(className, printContext, undefined, true) + "}"
);
writer.write(".${" + formatJS(className, printContext, true) + "}");
}
});
}

if (node.argument != null) {
writer.write("(" + node.argument + ")");
writer.write(formatArgument(node, printContext));
}

var attrsWriter = new Writer(writer.col);
Expand All @@ -150,12 +149,7 @@ module.exports = function printHtmlElement(node, printContext, writer) {
// append them to the output while avoiding putting too many attributes on one line.
attrs.forEach(attr => {
var attrStr = "";
var attrValueStr = toCode(
attr.value,
printContext,
printContext.depth + 1,
true
);
var attrValueStr = formatJS(attr.value, printContext, true);

if (attr.name) {
attrStr += attr.name;
Expand All @@ -166,10 +160,7 @@ module.exports = function printHtmlElement(node, printContext, writer) {
attrStr += "=" + attrValueStr;
}
} else if (attr.argument != null) {
attrStr +=
"(" +
toCode(attr.argument, printContext, printContext.depth + 1, true) +
")";
attrStr += formatArgument(attr, printContext);
}
} else if (attr.spread) {
if (hasUnenclosedWhitespace(attr.value)) {
Expand Down Expand Up @@ -214,7 +205,10 @@ module.exports = function printHtmlElement(node, printContext, writer) {
attrsString = " " + attrStringsArray.join(" ");
}

if (writer.col + attrsString.length < maxLen) {
if (
writer.col + attrsString.length < maxLen ||
attrStringsArray.length === 1
) {
writer.write(attrsString);
} else {
if (useCommas) {
Expand All @@ -223,27 +217,30 @@ module.exports = function printHtmlElement(node, printContext, writer) {

attrStringsArray.forEach((attrString, i) => {
if (i !== 0) {
writer.write(printContext.currentIndentString);
writer.write(printContext.indentString);
attrString = redent(
attrString,
printContext.depth + 1,
printContext.indentString
);
}

if (i === lastIndex) {
writer.write(attrString + ";" + printContext.eol);
} else {
writer.write(attrString + "," + printContext.eol);
}
writer.write(attrString + (i === lastIndex ? ";" : ","));
writer.write(printContext.eol);
});
} else {
writer.write(" [" + printContext.eol);
attrStringsArray.forEach(attrString => {
writer.write(printContext.currentIndentString);
writer.write(printContext.indentString);
writer.write(printContext.indentString);
writer.write(attrString + printContext.eol);
writer.write(
redent(
attrString,
printContext.depth + 1,
printContext.indentString
)
);
writer.write(printContext.eol);
});

writer.write(printContext.currentIndentString);
writer.write(printContext.indentString);
writer.write("]");
}
}
Expand Down
35 changes: 18 additions & 17 deletions packages/prettyprint/src/printScriptlet.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,33 +7,34 @@ module.exports = function printScriptlet(node, printContext, writer) {
const currentIndentString = printContext.currentIndentString;
const indentString = printContext.indentString;
const code = node.code;
let isBlock = node.block;

if (node.tag) {
writer.write("<%");
writer.write(code);
writer.write("%>");
} else {
const output = formatJS(code, printContext, printContext.depth);
const output = formatJS(code, printContext);
const newLineCount = countNewLines(output);
const isInline =
newLineCount === 0 ||
(!node.block && newLineCount === countNewLines(code));

if (!isBlock && /[\r\n]/g.test(output)) {
isBlock = true;
}

if (isBlock) {
if (isInline) {
writer.write(`$ ${output}`);
} else {
// Multi-line scriptlet

writer.write(
currentIndentString +
"$ {\n" +
redent(output, printContext.depth + 1, indentString) +
"\n" +
currentIndentString +
"}"
`$ {\n${redent(
output,
printContext.depth + 1,
indentString
)}\n${currentIndentString}}`
);
} else {
writer.write("$ ");
writer.write(output);
}
}
};

function countNewLines(str) {
const match = str.match(/[\r\n]/g);
return (match && match.length) || 0;
}
65 changes: 65 additions & 0 deletions packages/prettyprint/src/util/formatArgument.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
const formatJS = require("./formatJS");
const toCode = require("./toCode");
const STATEMENTS = ["for", "while", "if"];

module.exports = function(node, printContext) {
let code = node.argument;

if (!code) {
return "()";
}

code = `(${toCode(code, printContext)})`;

let statement;
let isParams = false;

if (node.type === "HTMLAttribute") {
statement = getStatementName(node.name);
} else {
const taglibLookup = printContext.taglibLookup;
const tagName = node.tagName;

if (taglibLookup && tagName) {
const tagDef = taglibLookup.getTag(tagName);

if (tagDef) {
const featureFlags = tagDef.featureFlags;
isParams = featureFlags && featureFlags.includes("params");
}
}

statement = getStatementName(tagName);
}

try {
if (STATEMENTS.includes(statement)) {
return formatJS(`${statement + code};`, printContext).slice(
statement.length + 1,
-1
);
}

if (isParams) {
return formatJS(`${code}=>{}`, printContext, true).slice(0, -4);
}

return formatJS(`_${code}`, printContext, true).slice(1);
} catch (_) {
return code;
}
};

function getStatementName(name) {
switch (name) {
case "if":
case "for":
case "while":
return name;
case "else-if":
case "until":
return "if";
default:
return;
}
}
Loading