Skip to content

Commit

Permalink
feat(prettier): first pass
Browse files Browse the repository at this point in the history
  • Loading branch information
Nate Moore committed Apr 16, 2021
1 parent b6b1f37 commit d3db440
Showing 1 changed file with 60 additions and 5 deletions.
65 changes: 60 additions & 5 deletions prettier-plugin-astro/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const { doc: { builders: { concat, hardline } } } = require("prettier");

/** @type {Partial<import('prettier').SupportLanguage>[]} */
module.exports.languages = [
{
Expand All @@ -11,13 +13,55 @@ module.exports.languages = [
/** @type {Record<string, import('prettier').Parser>} */
module.exports.parsers = {
astro: {
parse: (text, parsers) => {
parse: (text, parsers, options) => {
const children = [];
let frontmatter = text;
let content = text;

if (frontmatter.indexOf('---') > -1) {
const delimiterStart = frontmatter.indexOf('---') + 3;
frontmatter = frontmatter.slice(delimiterStart);
const delimiterEnd = frontmatter.indexOf('---');
content = frontmatter.slice(0).slice(delimiterEnd + 3);
frontmatter = frontmatter.slice(0, delimiterEnd);

children.push({
type: 'AstroFrontmatter',
children: [
{ type: 'DelimiterStart', value: '---' },
{
type: 'AstroEmbed',
parser: 'babel-ts',
value: frontmatter
},
{ type: 'DelimiterEnd', value: '---' }
]
})
}

children.push({
type: 'AstroContent',
children: [
{
type: 'AstroEmbed',
// TODO: handle JSX-like expressions
parser: 'html',
value: content
}
]
});

return {
type: 'AstroRoot',
children
};
},
locEnd(node) {
// TODO: actually track this
return node.locEnd
},
locStart(node) {
// TODO: actually track this
return node.locStart
},
astFormat: 'astro-ast',
Expand All @@ -27,10 +71,21 @@ module.exports.parsers = {
/** @type {Record<string, import('prettier').Printer>} */
module.exports.printers = {
'astro-ast': {
print() {
/** @type {any} */
const doc = {};
return doc;
print(path, opts, print) {
const node = path.getValue();
if (Array.isArray(node)) return concat(path.map(print));
if (node.type === 'AstroEmbed') return concat([node]);
if (Array.isArray(node.children)) return concat(path.map(print, 'children'));

if (node.type === 'DelimiterStart') return concat([node.value, hardline]);
if (node.type === 'DelimiterEnd') return concat([node.value, hardline, hardline]);
return concat([node.value]);
},
embed(path, print, textToDoc, options) {
const node = path.getValue();
if (node.type !== 'AstroEmbed') return null;

return textToDoc(node.value, { ...options, parser: node.parser });
}
},
};

0 comments on commit d3db440

Please sign in to comment.