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

Prettier support for .astro files #106

Merged
merged 22 commits into from
Apr 21, 2021
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 .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module.exports = {
extends: ['plugin:@typescript-eslint/recommended', 'prettier'],
plugins: ['@typescript-eslint', 'prettier'],
rules: {
'@typescript-eslint/ban-ts-comment': 'warn',
'@typescript-eslint/ban-ts-comment': 'off',
'@typescript-eslint/camelcase': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-empty-function': 'off',
Expand Down
5 changes: 4 additions & 1 deletion .github/workflows/nodejs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,11 @@ jobs:

npm ci
npm run build

cd prettier-plugin-astro
npm ci

cd examples/kitchen-sink
cd ../examples/kitchen-sink
npm ci
npm run build
cd ../..
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
node_modules/
lib/
parser/
dist/
*.tsbuildinfo
.DS_Store
Expand Down
18 changes: 9 additions & 9 deletions examples/snowpack/package-lock.json

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

10 changes: 7 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"exports": {
".": "./astro.mjs",
"./snowpack-plugin": "./snowpack-plugin.cjs",
"./parser": "./parser.cjs",
"./components/*.astro": "./components/*.astro"
},
"bin": {
Expand All @@ -20,7 +21,10 @@
"astro.mjs"
],
"scripts": {
"build": "tsc",
"build": "npm run build:core && npm run build:parser",
"build:core": "tsc -p tsconfig.json",
"build:parser": "tsc -p tsconfig.parser.json",
"postbuild:parser": "echo '{ \"type\": \"commonjs\" }' > parser/package.json",
"dev": "tsc --watch",
"lint": "eslint 'src/**/*.{js,ts}'",
"format": "prettier -w '{src,test}/**/*.{js,ts}'",
Expand Down Expand Up @@ -99,7 +103,7 @@
"uvu": "^0.5.1"
},
"engines": {
"node": "~14.0.0",
"npm": ">=6.14.0 <7.0.0"
"node": ">=14.0.0",
"npm": ">=6.14.0"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Glad you made this change. Was thinking the same

}
}
1 change: 1 addition & 0 deletions parser.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('./parser/index.js');
154 changes: 154 additions & 0 deletions prettier-plugin-astro/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
const {
doc: {
builders: { concat, hardline },
},
} = require('prettier');
const { parse } = require('astro/parser');

/** @type {Partial<import('prettier').SupportLanguage>[]} */
module.exports.languages = [
{
name: 'astro',
parsers: ['astro'],
extensions: ['.astro'],
vscodeLanguageIds: ['astro'],
},
];

/** @type {Record<string, import('prettier').Parser>} */
module.exports.parsers = {
astro: {
parse: (text) => {
let { html, css, module: frontmatter } = parse(text);
html = html ? { ...html, text: text.slice(html.start, html.end), isRoot: true } : null;
return [frontmatter, html, css].filter((v) => v);
},
locStart(node) {
return node.start;
},
locEnd(node) {
return node.end;
},
astFormat: 'astro-ast',
},
'astro-expression': {
parse: (text, parsers) => {
return { text };
},
locStart(node) {
return node.start;
},
locEnd(node) {
return node.end;
},
astFormat: 'astro-expression',
}
};

const findExpressionsInAST = (node, collect = []) => {
if (node.type === 'MustacheTag') {
return collect.concat(node);
}
if (node.children) {
collect.push(...[].concat(...node.children.map(child => findExpressionsInAST(child))));
}
return collect;
}

const formatExpression = ({ expression: { codeStart, codeEnd, children }}, text, options) => {
if (children.length === 0) {
if ([`'`, `"`].includes(codeStart[0])) {
return `<script $ lang="ts">${codeStart}${codeEnd}</script>`
}
return `{${codeStart}${codeEnd}}`;
}

return `<script $ lang="ts">${text}</script>`;
}

const isAstroScript = (node) => node.type === 'concat' && node.parts[0] === '<script' && node.parts[1].type === 'indent' && node.parts[1].contents.parts.find(v => v === '$');

const walkDoc = (doc) => {
let inAstroScript = false;
const recurse = (node, { parent }) => {
if (node.type === 'concat') {
if (isAstroScript(node)) {
inAstroScript = true;
parent.contents = { type: 'concat', parts: ['{'] };
}
return node.parts.map(part => recurse(part, { parent: node }));
}
if (inAstroScript) {
if (node.type === 'break-parent') {
parent.parts = parent.parts.filter(part => !['break-parent', 'line'].includes(part.type));
}
if (node.type === 'indent') {
parent.parts = parent.parts.map(part => {
if (part.type !== 'indent') return part;
return {
type: 'concat',
parts: [part.contents]
}
})
}
if (typeof node === 'string' && node.endsWith(';')) {
parent.parts = parent.parts.map(part => {
if (typeof part === 'string' && part.endsWith(';')) return part.slice(0, -1);
return part;
});
}
if (node === '</script>') {
parent.parts = parent.parts.map(part => part === '</script>' ? '}' : part);
inAstroScript = false;
}
}
if (['group', 'indent'].includes(node.type)) {
return recurse(node.contents, { parent: node });
}
}
recurse(doc, { parent: null });
}

/** @type {Record<string, import('prettier').Printer>} */
module.exports.printers = {
'astro-ast': {
print(path, opts, print) {
const node = path.getValue();

if (Array.isArray(node)) return concat(path.map(print));
if (node.type === 'Fragment') return concat(path.map(print, 'children'));

return node;
},
embed(path, print, textToDoc, options) {
const node = path.getValue();
if (node.type === 'Script' && node.context === 'setup') {
return concat(['---', hardline, textToDoc(node.content, { ...options, parser: 'typescript' }), '---', hardline, hardline]);
}
if (node.type === 'Fragment' && node.isRoot) {
const expressions = findExpressionsInAST(node);
if (expressions.length > 0) {
const parts = [].concat(...expressions.map((expr, i, all) => {
const prev = all[i - 1];
const start = node.text.slice((prev?.end ?? node.start) - node.start, expr.start - node.start);
const exprText = formatExpression(expr, node.text.slice(expr.start - node.start + 1, expr.end - node.start - 1), options);

if (i === all.length - 1) {
const end = node.text.slice(expr.end - node.start);
return [start, exprText, end]
}

return [start, exprText]
}));
const html = parts.join('\n');
const doc = textToDoc(html, { parser: 'html' });
walkDoc(doc);
return doc;
}
return textToDoc(node.text, { parser: 'html' });
}

return null;
},
},
};
Loading