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

(feat) format pug #248

Merged
merged 1 commit into from
Aug 26, 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
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# prettier-plugin-svelte changelog

## Unreleased
## 2.4.0 (Unreleased)

* (feat) add support for formatting pug inside `<template>` tags, if the corresponding plugin is available ([#248](https://github.com/sveltejs/prettier-plugin-svelte/pull/248))
* (fix) Adjust "is inside other tag"-checks when snipping tags ([#244](https://github.com/sveltejs/prettier-plugin-svelte/issues/244))

## 2.3.1
Expand Down
109 changes: 106 additions & 3 deletions package-lock.json

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

7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,16 @@
},
"homepage": "https://github.com/sveltejs/prettier-plugin-svelte#readme",
"devDependencies": {
"@prettier/plugin-pug": "^1.16.0",
"@rollup/plugin-commonjs": "14.0.0",
"@rollup/plugin-node-resolve": "11.0.1",
"@types/node": "^10.12.18",
"@types/prettier": "^2.1.6",
"ava": "3.15.0",
"prettier": "^2.3.0",
"rollup": "2.36.0",
"@rollup/plugin-commonjs": "14.0.0",
"@rollup/plugin-node-resolve": "11.0.1",
"rollup-plugin-typescript": "1.0.1",
"svelte": "^3.35.0",
"svelte": "^3.38.2",
"ts-node": "^9.1.1",
"tslib": "^2.0.3",
"typescript": "4.1.3"
Expand Down
70 changes: 51 additions & 19 deletions src/embed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ import {
getLeadingComment,
isIgnoreDirective,
isNodeSupportedLanguage,
isPugTemplate,
isTypeScript,
printRaw,
} from './print/node-helpers';
import { Node } from './print/nodes';
import { ElementNode, Node } from './print/nodes';

const {
builders: { concat, hardline, group, indent, literalline },
Expand Down Expand Up @@ -42,16 +44,18 @@ export function embed(
}

const embedType = (
tag: string,
parser: 'typescript' | 'babel-ts' | 'css',
tag: 'script' | 'style' | 'template',
parser: 'typescript' | 'babel-ts' | 'css' | 'pug',
isTopLevel: boolean,
) =>
embedTag(
tag,
options.originalText,
path,
(content) => formatBodyContent(content, parser, textToDoc, options),
print,
isTopLevel,
options,
);

const embedScript = (isTopLevel: boolean) =>
Expand All @@ -65,6 +69,7 @@ export function embed(
isTopLevel,
);
const embedStyle = (isTopLevel: boolean) => embedType('style', 'css', isTopLevel);
const embedPug = () => embedType('template', 'pug', false);

switch (node.type) {
case 'Script':
Expand All @@ -76,6 +81,8 @@ export function embed(
return embedScript(false);
} else if (node.name === 'style') {
return embedStyle(false);
} else if (isPugTemplate(node)) {
return embedPug();
}
}
}
Expand Down Expand Up @@ -116,16 +123,32 @@ function getSnippedContent(node: Node) {

function formatBodyContent(
content: string,
parser: 'typescript' | 'babel-ts' | 'css',
parser: 'typescript' | 'babel-ts' | 'css' | 'pug',
textToDoc: (text: string, options: object) => Doc,
options: ParserOptions,
options: ParserOptions & { pugTabWidth?: number },
) {
const indentContent = options.svelteIndentScriptAndStyle;

try {
const indentIfDesired = (doc: Doc) => (indentContent ? indent(doc) : doc);

const body = textToDoc(content, { parser });

if (parser === 'pug' && typeof body === 'string') {
// Pug returns no docs but a final string.
// Therefore prepend the line offsets
const whitespace = options.useTabs
? '\t'
: ' '.repeat(
options.pugTabWidth && options.pugTabWidth > 0
? options.pugTabWidth
: options.tabWidth,
);
const pugBody = body
.split('\n')
.map((line) => (line ? whitespace + line : line))
.join('\n');
return concat([hardline, pugBody]);
}

const indentIfDesired = (doc: Doc) =>
options.svelteIndentScriptAndStyle ? indent(doc) : doc;
trimRight([body], isLine);
return concat([indentIfDesired(concat([hardline, body])), hardline]);
} catch (error) {
Expand All @@ -144,24 +167,33 @@ function formatBodyContent(
}

function embedTag(
tag: string,
tag: 'script' | 'style' | 'template',
text: string,
path: FastPath,
formatBodyContent: (content: string) => Doc,
print: PrintFn,
isTopLevel: boolean,
options: ParserOptions,
) {
const node: Node = path.getNode();
const content = getSnippedContent(node);
const content =
tag === 'template' ? printRaw(node as ElementNode, text) : getSnippedContent(node);
const previousComment = getLeadingComment(path);

const body: Doc =
isNodeSupportedLanguage(node) && !isIgnoreDirective(previousComment)
? content.trim() !== ''
? formatBodyContent(content)
: content === ''
? ''
: hardline
: preformattedBody(content);
const canFormat =
isNodeSupportedLanguage(node) &&
!isIgnoreDirective(previousComment) &&
(tag !== 'template' ||
options.plugins.some(
(plugin) => typeof plugin !== 'string' && plugin.parsers && plugin.parsers.pug,
));
const body: Doc = canFormat
? content.trim() !== ''
? formatBodyContent(content)
: content === ''
? ''
: hardline
: preformattedBody(content);

const attributes = concat(
path.map(
Expand Down
6 changes: 5 additions & 1 deletion src/print/node-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { blockElements, TagName } from '../lib/elements';
import { FastPath, ParserOptions } from 'prettier';
import { findLastIndex, isASTNode, isPreTagContent } from './helpers';

const unsupportedLanguages = ['coffee', 'coffeescript', 'pug', 'styl', 'stylus', 'sass'];
const unsupportedLanguages = ['coffee', 'coffeescript', 'styl', 'stylus', 'sass'];

export function isInlineElement(path: FastPath, options: ParserOptions, node: Node) {
return (
Expand Down Expand Up @@ -265,6 +265,10 @@ export function isTypeScript(node: Node) {
return ['typescript', 'ts'].includes(lang);
}

export function isPugTemplate(node: Node): boolean {
return node.type === 'Element' && node.name === 'template' && getLangAttribute(node) === 'pug';
}

export function isLoneMustacheTag(node: true | Node[]): node is [MustacheTagNode] {
return node !== true && node.length === 1 && node[0].type === 'MustacheTag';
}
Expand Down
Loading