repo
stringclasses
15 values
pull_number
int64
147
18.3k
instance_id
stringlengths
14
31
issue_numbers
sequencelengths
1
3
base_commit
stringlengths
40
40
patch
stringlengths
289
585k
test_patch
stringlengths
355
6.82M
problem_statement
stringlengths
25
49.4k
hints_text
stringlengths
0
58.9k
created_at
unknowndate
2014-08-08 22:09:38
2024-06-28 03:13:12
version
stringclasses
110 values
PASS_TO_PASS
sequencelengths
0
4.82k
FAIL_TO_PASS
sequencelengths
1
1.06k
language
stringclasses
4 values
image_urls
sequencelengths
0
4
website links
sequencelengths
0
4
prettier/prettier
14,279
prettier__prettier-14279
[ "14275" ]
f602be5a478a5bcdca870b31936dc873ecae1120
diff --git a/src/language-js/needs-parens.js b/src/language-js/needs-parens.js --- a/src/language-js/needs-parens.js +++ b/src/language-js/needs-parens.js @@ -466,22 +466,30 @@ function needsParens(path, options) { } case "TSConditionalType": - if (name === "extendsType" && parent.type === "TSConditionalType") { - return true; - } - // fallthrough case "TSFunctionType": case "TSConstructorType": if (name === "extendsType" && parent.type === "TSConditionalType") { - const returnTypeAnnotation = (node.returnType || node.typeAnnotation) - .typeAnnotation; + if (node.type === "TSConditionalType") { + return true; + } + + let { typeAnnotation } = node.returnType || node.typeAnnotation; + + if ( + typeAnnotation.type === "TSTypePredicate" && + typeAnnotation.typeAnnotation + ) { + typeAnnotation = typeAnnotation.typeAnnotation.typeAnnotation; + } + if ( - returnTypeAnnotation.type === "TSInferType" && - returnTypeAnnotation.typeParameter.constraint + typeAnnotation.type === "TSInferType" && + typeAnnotation.typeParameter.constraint ) { return true; } } + if (name === "checkType" && parent.type === "TSConditionalType") { return true; }
diff --git a/tests/format/typescript/conditional-types/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/conditional-types/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/typescript/conditional-types/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/typescript/conditional-types/__snapshots__/jsfmt.spec.js.snap @@ -278,20 +278,6 @@ type Unpacked<T> = T extends (infer U)[] ================================================================================ `; -exports[`issue-13275.ts format 1`] = ` -====================================options===================================== -parsers: ["typescript"] -printWidth: 80 - | printWidth -=====================================input====================================== -type Foo<T> = T extends ((...a: any[]) => infer R extends string) ? R : never; - -=====================================output===================================== -type Foo<T> = T extends ((...a: any[]) => infer R extends string) ? R : never; - -================================================================================ -`; - exports[`nested-in-condition.ts format 1`] = ` ====================================options===================================== parsers: ["typescript"] @@ -431,3 +417,57 @@ type Unpacked<T> = T extends (infer U)[] ================================================================================ `; + +exports[`parentheses.ts format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +// #13275 +type Foo<T> = T extends ((...a: any[]) => infer R extends string) ? R : never; +type Foo<T> = T extends (new (...a: any[]) => infer R extends string) ? R : never; + +// #14275 +type Test<T> = T extends (( + token: TSESTree.Token +) => token is infer U extends TSESTree.Token) + ? U + : TSESTree.Token; +type Test<T> = T extends (( + token: TSESTree.Token +) => asserts token is infer U extends TSESTree.Token) + ? U + : TSESTree.Token; +type Test<T> = T extends (new ( + token: TSESTree.Token +) => token is infer U extends TSESTree.Token) + ? U + : TSESTree.Token; + +=====================================output===================================== +// #13275 +type Foo<T> = T extends ((...a: any[]) => infer R extends string) ? R : never; +type Foo<T> = T extends (new (...a: any[]) => infer R extends string) + ? R + : never; + +// #14275 +type Test<T> = T extends (( + token: TSESTree.Token +) => token is infer U extends TSESTree.Token) + ? U + : TSESTree.Token; +type Test<T> = T extends (( + token: TSESTree.Token +) => asserts token is infer U extends TSESTree.Token) + ? U + : TSESTree.Token; +type Test<T> = T extends (new ( + token: TSESTree.Token +) => token is infer U extends TSESTree.Token) + ? U + : TSESTree.Token; + +================================================================================ +`; diff --git a/tests/format/typescript/conditional-types/issue-13275.ts b/tests/format/typescript/conditional-types/issue-13275.ts deleted file mode 100644 --- a/tests/format/typescript/conditional-types/issue-13275.ts +++ /dev/null @@ -1 +0,0 @@ -type Foo<T> = T extends ((...a: any[]) => infer R extends string) ? R : never; diff --git a/tests/format/typescript/conditional-types/parentheses.ts b/tests/format/typescript/conditional-types/parentheses.ts new file mode 100644 --- /dev/null +++ b/tests/format/typescript/conditional-types/parentheses.ts @@ -0,0 +1,20 @@ +// #13275 +type Foo<T> = T extends ((...a: any[]) => infer R extends string) ? R : never; +type Foo<T> = T extends (new (...a: any[]) => infer R extends string) ? R : never; + +// #14275 +type Test<T> = T extends (( + token: TSESTree.Token +) => token is infer U extends TSESTree.Token) + ? U + : TSESTree.Token; +type Test<T> = T extends (( + token: TSESTree.Token +) => asserts token is infer U extends TSESTree.Token) + ? U + : TSESTree.Token; +type Test<T> = T extends (new ( + token: TSESTree.Token +) => token is infer U extends TSESTree.Token) + ? U + : TSESTree.Token;
Incorrect removal of parentheses when using an `infer` with a constraint in a function predicate **Prettier 2.8.3** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEMCeAHOACAKnAZxgB5cA+bAXj2zgA94oATA7ACjYB0ptsYIA1giR4AygFFRuAE5w4AOlyCE3AJRUK-ITwCWrHVABmcadgCqtBghZjJMuYuVRV3XgH5zr7CNwSpshSVtAG5uEAAaEAgMGB1oAmRQAENpaQgAdwAFFIQElCSAG3SktATIgCNpJLAhGFEkgFs4ABkDOGRDQoI4CqqauDqMaoMAc2QYaQBXHpA4BvK4JiZF5qSoEcmkkbgAMQhpBqSYWPXkECTJ-giQAAsYBoKAdRudeAIhsDhRXNedADdXmgzmACGUQAZutIYJkqiNDh0ujMAFYEOiiUYFOAARUmEHgCIK3UiQ2kkLO6CwBDA0h0MWuGBpsEeOiYMBuyAAHAAGYlpbqPKoYM4MwgmP7tSIAR1x8Bh0Ty5wIAFooHJlkxrrJpTpZDCtvCkJ1CTNug0dOMpiaMXAAILHGnlS5wTImVqqglEkAEa04vHtQ2IyIwJLlZms9lIABMQaqOgKowAwhAGgbZgQAKzXSbdXAhvJGz1-aYASWYCDq1NpMBtzFE6ExHrgAF8m0A) <!-- prettier-ignore --> ```sh --parser typescript ``` **Input:** <!-- prettier-ignore --> ```tsx type Test<T> = T extends (( token: TSESTree.Token ) => token is infer U extends TSESTree.Token) ? U : TSESTree.Token; ``` **Output:** <!-- prettier-ignore --> ```tsx type Test<T> = T extends ( token: TSESTree.Token ) => token is infer U extends TSESTree.Token ? U : TSESTree.Token; ``` **Expected behavior:** The parentheses should be retained as they are required. Without the parentheses it causes a syntax error: ``` SyntaxError: '?' expected. (5:19) 3 | ) => token is infer U extends TSESTree.Token 4 | ? U > 5 | : TSESTree.Token; | ^ 6 | ```
"2023-01-31T09:28:25Z"
2.9
[]
[ "tests/format/typescript/conditional-types/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEMCeAHOACAKnAZxgB5cA+bAXj2zgA94oATA7ACjYB0ptsYIA1giR4AygFFRuAE5w4AOlyCE3AJRUK-ITwCWrHVABmcadgCqtBghZjJMuYuVRV3XgH5zr7CNwSpshSVtAG5uEAAaEAgMGB1oAmRQAENpaQgAdwAFFIQElCSAG3SktATIgCNpJLAhGFEkgFs4ABkDOGRDQoI4CqqauDqMaoMAc2QYaQBXHpA4BvK4JiZF5qSoEcmkkbgAMQhpBqSYWPXkECTJ-giQAAsYBoKAdRudeAIhsDhRXNedADdXmgzmACGUQAZutIYJkqiNDh0ujMAFYEOiiUYFOAARUmEHgCIK3UiQ2kkLO6CwBDA0h0MWuGBpsEeOiYMBuyAAHAAGYlpbqPKoYM4MwgmP7tSIAR1x8Bh0Ty5wIAFooHJlkxrrJpTpZDCtvCkJ1CTNug0dOMpiaMXAAILHGnlS5wTImVqqglEkAEa04vHtQ2IyIwJLlZms9lIABMQaqOgKowAwhAGgbZgQAKzXSbdXAhvJGz1-aYASWYCDq1NpMBtzFE6ExHrgAF8m0A" ]
prettier/prettier
14,314
prettier__prettier-14314
[ "8204" ]
62827ab4d5daf858af7599143846e6bc942c4942
diff --git a/src/language-js/parse/babel.js b/src/language-js/parse/babel.js --- a/src/language-js/parse/babel.js +++ b/src/language-js/parse/babel.js @@ -218,8 +218,9 @@ const allowedMessageCodes = new Set([ "DuplicateExport", ]); +const babelParserOptionsCombinations = [appendPlugins(["jsx"])]; const babel = createBabelParser({ - optionsCombinations: [appendPlugins(["jsx", "flow"])], + optionsCombinations: babelParserOptionsCombinations, }); const babelTs = createBabelParser({ optionsCombinations: [ @@ -235,7 +236,6 @@ const babelTSExpression = createBabelParser({ isExpression: true, optionsCombinations: [appendPlugins(["typescript"])], }); - const babelFlow = createBabelParser({ optionsCombinations: [ appendPlugins([ @@ -246,7 +246,9 @@ const babelFlow = createBabelParser({ ], }); const babelEstree = createBabelParser({ - optionsCombinations: [appendPlugins(["jsx", "flow", "estree"])], + optionsCombinations: babelParserOptionsCombinations.map((options) => + appendPlugins(["estree"], options) + ), }); // Export as a plugin so we can reuse the same bundle for UMD loading
diff --git a/tests/config/format-test.js b/tests/config/format-test.js --- a/tests/config/format-test.js +++ b/tests/config/format-test.js @@ -218,19 +218,6 @@ function runSpec(fixtures, parsers, options) { const allParsers = [...parsers]; if (!IS_ERROR_TESTS) { - if ( - parsers.includes("typescript") && - !parsers.includes("babel-ts") && - !IS_TYPESCRIPT_ONLY_TEST && - !babelTsDisabledTest.has(dirname) - ) { - allParsers.push("babel-ts"); - } - - if (parsers.includes("flow") && !parsers.includes("babel-flow")) { - allParsers.push("babel-flow"); - } - if ( parsers.includes("babel") && (isTestDirectory(dirname, "js") || isTestDirectory(dirname, "jsx")) @@ -246,6 +233,19 @@ function runSpec(fixtures, parsers, options) { } } + if ( + parsers.includes("typescript") && + !parsers.includes("babel-ts") && + !IS_TYPESCRIPT_ONLY_TEST && + !babelTsDisabledTest.has(dirname) + ) { + allParsers.push("babel-ts"); + } + + if (parsers.includes("flow") && !parsers.includes("babel-flow")) { + allParsers.push("babel-flow"); + } + if (parsers.includes("babel") && !parsers.includes("__babel_estree")) { allParsers.push("__babel_estree"); } diff --git a/tests/format/flow/decorator/__snapshots__/jsfmt.spec.js.snap b/tests/format/flow/decorator/__snapshots__/jsfmt.spec.js.snap new file mode 100644 --- /dev/null +++ b/tests/format/flow/decorator/__snapshots__/jsfmt.spec.js.snap @@ -0,0 +1,117 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`comments.js format 1`] = ` +====================================options===================================== +parsers: ["babel-flow"] +printWidth: 80 + | printWidth +=====================================input====================================== +class Something { + @Annotateme() + // comment + static property: Array<string>; +} + +=====================================output===================================== +class Something { + @Annotateme() + // comment + static property: Array<string>; +} + +================================================================================ +`; + +exports[`mobx.js format 1`] = ` +====================================options===================================== +parsers: ["babel-flow"] +printWidth: 80 + | printWidth +=====================================input====================================== +import {observable} from "mobx"; + +@observer class OrderLine { + @observable price:number = 0; + @observable amount:number = 1; + + constructor(price) { + this.price = price; + } + + @computed get total() { + return this.price * this.amount; + } + + @action.bound setPrice(price) { + this.price = price; + } + + @computed + get total() { + return this.price * this.amount; + } + + @action.bound + setPrice(price) { + this.price = price; + } + + @computed @computed @computed @computed @computed @computed @computed get total() { + return this.price * this.amount; + } + + @action handleDecrease = (event: React.ChangeEvent<HTMLInputElement>) => this.count--; + + @action handleSomething = (event: React.ChangeEvent<HTMLInputElement>) => doSomething(); +} + +=====================================output===================================== +import { observable } from "mobx"; + +@observer +class OrderLine { + @observable price: number = 0; + @observable amount: number = 1; + + constructor(price) { + this.price = price; + } + + @computed get total() { + return this.price * this.amount; + } + + @action.bound setPrice(price) { + this.price = price; + } + + @computed + get total() { + return this.price * this.amount; + } + + @action.bound + setPrice(price) { + this.price = price; + } + + @computed + @computed + @computed + @computed + @computed + @computed + @computed + get total() { + return this.price * this.amount; + } + + @action handleDecrease = (event: React.ChangeEvent<HTMLInputElement>) => + this.count--; + + @action handleSomething = (event: React.ChangeEvent<HTMLInputElement>) => + doSomething(); +} + +================================================================================ +`; diff --git a/tests/format/js/decorator-comments/comments.js b/tests/format/flow/decorator/comments.js similarity index 100% rename from tests/format/js/decorator-comments/comments.js rename to tests/format/flow/decorator/comments.js diff --git a/tests/format/flow/decorator/jsfmt.spec.js b/tests/format/flow/decorator/jsfmt.spec.js new file mode 100644 --- /dev/null +++ b/tests/format/flow/decorator/jsfmt.spec.js @@ -0,0 +1,2 @@ +// TODO: Run tests with `flow` parser https://github.com/facebook/flow/issues/9003 +run_spec(import.meta, ["babel-flow"]); diff --git a/tests/format/flow/decorator/mobx.js b/tests/format/flow/decorator/mobx.js new file mode 100644 --- /dev/null +++ b/tests/format/flow/decorator/mobx.js @@ -0,0 +1,36 @@ +import {observable} from "mobx"; + +@observer class OrderLine { + @observable price:number = 0; + @observable amount:number = 1; + + constructor(price) { + this.price = price; + } + + @computed get total() { + return this.price * this.amount; + } + + @action.bound setPrice(price) { + this.price = price; + } + + @computed + get total() { + return this.price * this.amount; + } + + @action.bound + setPrice(price) { + this.price = price; + } + + @computed @computed @computed @computed @computed @computed @computed get total() { + return this.price * this.amount; + } + + @action handleDecrease = (event: React.ChangeEvent<HTMLInputElement>) => this.count--; + + @action handleSomething = (event: React.ChangeEvent<HTMLInputElement>) => doSomething(); +} diff --git a/tests/format/js/babel-plugins/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/babel-plugins/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/js/babel-plugins/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/babel-plugins/__snapshots__/jsfmt.spec.js.snap @@ -937,8 +937,8 @@ export * as ns from "mod"; ================================================================================ `; -exports[`flow.js [acorn] format 1`] = ` -"Unexpected token (3:17) +exports[`flow.js [__babel_estree] format 1`] = ` +"Unexpected token, expected "," (3:17) 1 | // https://babeljs.io/docs/en/babel-preset-flow 2 | > 3 | function foo(one: any, two: number, three?): string {} @@ -946,8 +946,8 @@ exports[`flow.js [acorn] format 1`] = ` 4 |" `; -exports[`flow.js [espree] format 1`] = ` -"Unexpected token : (3:17) +exports[`flow.js [acorn] format 1`] = ` +"Unexpected token (3:17) 1 | // https://babeljs.io/docs/en/babel-preset-flow 2 | > 3 | function foo(one: any, two: number, three?): string {} @@ -955,8 +955,8 @@ exports[`flow.js [espree] format 1`] = ` 4 |" `; -exports[`flow.js [meriyah] format 1`] = ` -"Expected ')' (3:17) +exports[`flow.js [babel] format 1`] = ` +"Unexpected token, expected "," (3:17) 1 | // https://babeljs.io/docs/en/babel-preset-flow 2 | > 3 | function foo(one: any, two: number, three?): string {} @@ -964,7 +964,7 @@ exports[`flow.js [meriyah] format 1`] = ` 4 |" `; -exports[`flow.js format 1`] = ` +exports[`flow.js [babel-flow] format 1`] = ` ====================================options===================================== parsers: ["babel", "babel-ts", "babel-flow"] printWidth: 80 @@ -982,6 +982,42 @@ function foo(one: any, two: number, three?): string {} ================================================================================ `; +exports[`flow.js [babel-ts] format 1`] = ` +====================================options===================================== +parsers: ["babel", "babel-ts", "babel-flow"] +printWidth: 80 + | printWidth +=====================================input====================================== +// https://babeljs.io/docs/en/babel-preset-flow + +function foo(one: any, two: number, three?): string {} + +=====================================output===================================== +// https://babeljs.io/docs/en/babel-preset-flow + +function foo(one: any, two: number, three?): string {} + +================================================================================ +`; + +exports[`flow.js [espree] format 1`] = ` +"Unexpected token : (3:17) + 1 | // https://babeljs.io/docs/en/babel-preset-flow + 2 | +> 3 | function foo(one: any, two: number, three?): string {} + | ^ + 4 |" +`; + +exports[`flow.js [meriyah] format 1`] = ` +"Expected ')' (3:17) + 1 | // https://babeljs.io/docs/en/babel-preset-flow + 2 | +> 3 | function foo(one: any, two: number, three?): string {} + | ^ + 4 |" +`; + exports[`function-bind.js [acorn] format 1`] = ` "Unexpected token (3:5) 1 | // https://babeljs.io/docs/en/babel-plugin-proposal-function-bind @@ -2381,7 +2417,7 @@ function test(param = throw new Error("required!")) { ================================================================================ `; -exports[`typescript.js [acorn] format 1`] = ` +exports[`typescript.js [__babel_estree] format 1`] = ` "Unexpected token (3:8) 1 | // https://babeljs.io/docs/en/babel-preset-typescript 2 | @@ -2390,8 +2426,8 @@ exports[`typescript.js [acorn] format 1`] = ` 4 |" `; -exports[`typescript.js [espree] format 1`] = ` -"Unexpected token : (3:8) +exports[`typescript.js [acorn] format 1`] = ` +"Unexpected token (3:8) 1 | // https://babeljs.io/docs/en/babel-preset-typescript 2 | > 3 | const x: number = 0; @@ -2399,8 +2435,8 @@ exports[`typescript.js [espree] format 1`] = ` 4 |" `; -exports[`typescript.js [meriyah] format 1`] = ` -"Missing initializer in const declaration (3:8) +exports[`typescript.js [babel] format 1`] = ` +"Unexpected token (3:8) 1 | // https://babeljs.io/docs/en/babel-preset-typescript 2 | > 3 | const x: number = 0; @@ -2408,7 +2444,7 @@ exports[`typescript.js [meriyah] format 1`] = ` 4 |" `; -exports[`typescript.js format 1`] = ` +exports[`typescript.js [babel-flow] format 1`] = ` ====================================options===================================== parsers: ["babel", "babel-ts", "babel-flow"] printWidth: 80 @@ -2426,6 +2462,42 @@ const x: number = 0; ================================================================================ `; +exports[`typescript.js [babel-ts] format 1`] = ` +====================================options===================================== +parsers: ["babel", "babel-ts", "babel-flow"] +printWidth: 80 + | printWidth +=====================================input====================================== +// https://babeljs.io/docs/en/babel-preset-typescript + +const x: number = 0; + +=====================================output===================================== +// https://babeljs.io/docs/en/babel-preset-typescript + +const x: number = 0; + +================================================================================ +`; + +exports[`typescript.js [espree] format 1`] = ` +"Unexpected token : (3:8) + 1 | // https://babeljs.io/docs/en/babel-preset-typescript + 2 | +> 3 | const x: number = 0; + | ^ + 4 |" +`; + +exports[`typescript.js [meriyah] format 1`] = ` +"Missing initializer in const declaration (3:8) + 1 | // https://babeljs.io/docs/en/babel-preset-typescript + 2 | +> 3 | const x: number = 0; + | ^ + 4 |" +`; + exports[`v8intrinsic.js [acorn] format 1`] = ` "Unexpected token (3:1) 1 | // https://github.com/babel/babel/pull/10148 diff --git a/tests/format/js/babel-plugins/jsfmt.spec.js b/tests/format/js/babel-plugins/jsfmt.spec.js --- a/tests/format/js/babel-plugins/jsfmt.spec.js +++ b/tests/format/js/babel-plugins/jsfmt.spec.js @@ -85,5 +85,7 @@ run_spec(import.meta, ["babel", "babel-ts", "babel-flow"], { "import-reflection.js", "explicit-resource-management.js", ], + babel: ["flow.js", "typescript.js"], + __babel_estree: ["flow.js", "typescript.js"], }, }); diff --git a/tests/format/js/decorator-comments/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/decorator-comments/__snapshots__/jsfmt.spec.js.snap deleted file mode 100644 --- a/tests/format/js/decorator-comments/__snapshots__/jsfmt.spec.js.snap +++ /dev/null @@ -1,53 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`comments.js [acorn] format 1`] = ` -"Unexpected character '@' (2:5) - 1 | class Something { -> 2 | @Annotateme() - | ^ - 3 | // comment - 4 | static property: Array<string>; - 5 | }" -`; - -exports[`comments.js [espree] format 1`] = ` -"Unexpected character '@' (2:5) - 1 | class Something { -> 2 | @Annotateme() - | ^ - 3 | // comment - 4 | static property: Array<string>; - 5 | }" -`; - -exports[`comments.js [meriyah] format 1`] = ` -"Unexpected token: ':' (4:20) - 2 | @Annotateme() - 3 | // comment -> 4 | static property: Array<string>; - | ^ - 5 | } - 6 |" -`; - -exports[`comments.js format 1`] = ` -====================================options===================================== -parsers: ["babel", "typescript"] -printWidth: 80 - | printWidth -=====================================input====================================== -class Something { - @Annotateme() - // comment - static property: Array<string>; -} - -=====================================output===================================== -class Something { - @Annotateme() - // comment - static property: Array<string>; -} - -================================================================================ -`; diff --git a/tests/format/js/decorator-comments/jsfmt.spec.js b/tests/format/js/decorator-comments/jsfmt.spec.js deleted file mode 100644 --- a/tests/format/js/decorator-comments/jsfmt.spec.js +++ /dev/null @@ -1,3 +0,0 @@ -run_spec(import.meta, ["babel", "typescript"], { - errors: { acorn: true, espree: true, meriyah: true }, -}); diff --git a/tests/format/js/decorators/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/decorators/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/js/decorators/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/decorators/__snapshots__/jsfmt.spec.js.snap @@ -129,6 +129,11 @@ export class AppModule {} // C export class Bar{} +class Something { + @Annotateme() + property; +} + =====================================output===================================== var x = 100; @@ -159,6 +164,11 @@ export class AppModule {} // C export class Bar {} +class Something { + @Annotateme() + property; +} + ================================================================================ `; @@ -270,8 +280,8 @@ exports[`mobx.js [acorn] format 1`] = ` 2 | > 3 | @observer class OrderLine { | ^ - 4 | @observable price:number = 0; - 5 | @observable amount:number = 1; + 4 | @observable price = 0; + 5 | @observable amount = 1; 6 |" `; @@ -281,22 +291,11 @@ exports[`mobx.js [espree] format 1`] = ` 2 | > 3 | @observer class OrderLine { | ^ - 4 | @observable price:number = 0; - 5 | @observable amount:number = 1; + 4 | @observable price = 0; + 5 | @observable amount = 1; 6 |" `; -exports[`mobx.js [meriyah] format 1`] = ` -"Unexpected token: ':' (4:20) - 2 | - 3 | @observer class OrderLine { -> 4 | @observable price:number = 0; - | ^ - 5 | @observable amount:number = 1; - 6 | - 7 | constructor(price) {" -`; - exports[`mobx.js format 1`] = ` ====================================options===================================== parsers: ["babel"] @@ -306,8 +305,8 @@ printWidth: 80 import {observable} from "mobx"; @observer class OrderLine { - @observable price:number = 0; - @observable amount:number = 1; + @observable price = 0; + @observable amount = 1; constructor(price) { this.price = price; @@ -330,14 +329,14 @@ import {observable} from "mobx"; setPrice(price) { this.price = price; } - + @computed @computed @computed @computed @computed @computed @computed get total() { return this.price * this.amount; } - @action handleDecrease = (event: React.ChangeEvent<HTMLInputElement>) => this.count--; - - @action handleSomething = (event: React.ChangeEvent<HTMLInputElement>) => doSomething(); + @action handleDecrease = (event) => this.count--; + + @action handleSomething = (event) => doSomething(); } =====================================output===================================== @@ -345,8 +344,8 @@ import { observable } from "mobx"; @observer class OrderLine { - @observable price: number = 0; - @observable amount: number = 1; + @observable price = 0; + @observable amount = 1; constructor(price) { this.price = price; @@ -381,11 +380,9 @@ class OrderLine { return this.price * this.amount; } - @action handleDecrease = (event: React.ChangeEvent<HTMLInputElement>) => - this.count--; + @action handleDecrease = (event) => this.count--; - @action handleSomething = (event: React.ChangeEvent<HTMLInputElement>) => - doSomething(); + @action handleSomething = (event) => doSomething(); } ================================================================================ diff --git a/tests/format/js/decorators/comments.js b/tests/format/js/decorators/comments.js --- a/tests/format/js/decorators/comments.js +++ b/tests/format/js/decorators/comments.js @@ -29,3 +29,8 @@ export class AppModule {} @Bar() // C export class Bar{} + +class Something { + @Annotateme() + property; +} diff --git a/tests/format/js/decorators/jsfmt.spec.js b/tests/format/js/decorators/jsfmt.spec.js --- a/tests/format/js/decorators/jsfmt.spec.js +++ b/tests/format/js/decorators/jsfmt.spec.js @@ -1,3 +1,3 @@ run_spec(import.meta, ["babel"], { - errors: { acorn: true, espree: true, meriyah: ["multiple.js", "mobx.js"] }, + errors: { acorn: true, espree: true, meriyah: ["multiple.js"] }, }); diff --git a/tests/format/js/decorators/mobx.js b/tests/format/js/decorators/mobx.js --- a/tests/format/js/decorators/mobx.js +++ b/tests/format/js/decorators/mobx.js @@ -1,8 +1,8 @@ import {observable} from "mobx"; @observer class OrderLine { - @observable price:number = 0; - @observable amount:number = 1; + @observable price = 0; + @observable amount = 1; constructor(price) { this.price = price; @@ -25,12 +25,12 @@ import {observable} from "mobx"; setPrice(price) { this.price = price; } - + @computed @computed @computed @computed @computed @computed @computed get total() { return this.price * this.amount; } - @action handleDecrease = (event: React.ChangeEvent<HTMLInputElement>) => this.count--; - - @action handleSomething = (event: React.ChangeEvent<HTMLInputElement>) => doSomething(); + @action handleDecrease = (event) => this.count--; + + @action handleSomething = (event) => doSomething(); } diff --git a/tests/format/js/rest/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/rest/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/js/rest/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/rest/__snapshots__/jsfmt.spec.js.snap @@ -1,44 +1,17 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`trailing-commas.js - {"trailingComma":"all"} [acorn] format 1`] = ` -"Unexpected token (1:9) -> 1 | declare class C { - | ^ - 2 | f( - 3 | superSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperLong, - 4 | ...args" -`; - -exports[`trailing-commas.js - {"trailingComma":"all"} [espree] format 1`] = ` -"Unexpected token class (1:9) -> 1 | declare class C { - | ^ - 2 | f( - 3 | superSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperLong, - 4 | ...args" -`; - -exports[`trailing-commas.js - {"trailingComma":"all"} [meriyah] format 1`] = ` -"Unexpected token: 'class' (1:13) -> 1 | declare class C { - | ^ - 2 | f( - 3 | superSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperLong, - 4 | ...args" -`; - exports[`trailing-commas.js - {"trailingComma":"all"} format 1`] = ` ====================================options===================================== -parsers: ["babel", "flow"] +parsers: ["babel", "flow", "typescript"] printWidth: 80 trailingComma: "all" | printWidth =====================================input====================================== -declare class C { +class C { f( superSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperLong, ...args - ): void, + ) {} } function f( @@ -46,7 +19,7 @@ function f( ...args ) {} -declare class C { f(...superSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperLong): void; } +class D { f(...superSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperLong) {}; } [superSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperLong,,]; @@ -55,11 +28,11 @@ var {veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLon =====================================output===================================== -declare class C { +class C { f( superSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperLong, ...args - ): void; + ) {} } function f( @@ -67,10 +40,10 @@ function f( ...args ) {} -declare class C { +class D { f( ...superSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperLong - ): void; + ) {} } [ diff --git a/tests/format/js/rest/jsfmt.spec.js b/tests/format/js/rest/jsfmt.spec.js --- a/tests/format/js/rest/jsfmt.spec.js +++ b/tests/format/js/rest/jsfmt.spec.js @@ -1,4 +1,3 @@ -run_spec(import.meta, ["babel", "flow"], { +run_spec(import.meta, ["babel", "flow", "typescript"], { trailingComma: "all", - errors: { acorn: true, espree: true, meriyah: true }, }); diff --git a/tests/format/js/rest/trailing-commas.js b/tests/format/js/rest/trailing-commas.js --- a/tests/format/js/rest/trailing-commas.js +++ b/tests/format/js/rest/trailing-commas.js @@ -1,8 +1,8 @@ -declare class C { +class C { f( superSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperLong, ...args - ): void, + ) {} } function f( @@ -10,7 +10,7 @@ function f( ...args ) {} -declare class C { f(...superSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperLong): void; } +class D { f(...superSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperLong) {}; } [superSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperLong,,]; diff --git a/tests/format/js/trailing-whitespace/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/trailing-whitespace/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/js/trailing-whitespace/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/trailing-whitespace/__snapshots__/jsfmt.spec.js.snap @@ -1,41 +1,11 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`trailing.js [acorn] format 1`] = ` -"Unexpected token (1:8) -> 1 | export type Result<T, V> = | { kind: "not-test-editor1" } | { kind: "not-test-editor2" }; - | ^ - 2 | - 3 | // Note: there are trailing whitespace in this file - 4 | \`" -`; - -exports[`trailing.js [espree] format 1`] = ` -"Unexpected token type (1:8) -> 1 | export type Result<T, V> = | { kind: "not-test-editor1" } | { kind: "not-test-editor2" }; - | ^ - 2 | - 3 | // Note: there are trailing whitespace in this file - 4 | \`" -`; - -exports[`trailing.js [meriyah] format 1`] = ` -"Unexpected token: 'identifier' (1:11) -> 1 | export type Result<T, V> = | { kind: "not-test-editor1" } | { kind: "not-test-editor2" }; - | ^ - 2 | - 3 | // Note: there are trailing whitespace in this file - 4 | \`" -`; - -exports[`trailing.js format 1`] = ` +exports[`snippet: #0 format 1`] = ` ====================================options===================================== parsers: ["babel", "flow", "typescript"] printWidth: 80 | printWidth =====================================input====================================== -export type Result<T, V> = | { kind: "not-test-editor1" } | { kind: "not-test-editor2" }; - -// Note: there are trailing whitespace in this file \` @@ -43,13 +13,7 @@ export type Result<T, V> = | { kind: "not-test-editor1" } | { kind: "not-test-ed \`; - =====================================output===================================== -export type Result<T, V> = - | { kind: "not-test-editor1" } - | { kind: "not-test-editor2" }; - -// Note: there are trailing whitespace in this file \` diff --git a/tests/format/js/trailing-whitespace/jsfmt.spec.js b/tests/format/js/trailing-whitespace/jsfmt.spec.js --- a/tests/format/js/trailing-whitespace/jsfmt.spec.js +++ b/tests/format/js/trailing-whitespace/jsfmt.spec.js @@ -1,3 +1,7 @@ -run_spec(import.meta, ["babel", "flow", "typescript"], { - errors: { acorn: true, espree: true, meriyah: true }, -}); +run_spec( + { + importMeta: import.meta, + snippets: ["`\n \n \n` + `\n \n \n`;"], + }, + ["babel", "flow", "typescript"] +); diff --git a/tests/format/js/trailing-whitespace/trailing.js b/tests/format/js/trailing-whitespace/trailing.js deleted file mode 100644 --- a/tests/format/js/trailing-whitespace/trailing.js +++ /dev/null @@ -1,10 +0,0 @@ -export type Result<T, V> = | { kind: "not-test-editor1" } | { kind: "not-test-editor2" }; - -// Note: there are trailing whitespace in this file -` - - -` + ` - - -`; diff --git a/tests/format/jsx/expression-with-types/__snapshots__/jsfmt.spec.js.snap b/tests/format/jsx/expression-with-types/__snapshots__/jsfmt.spec.js.snap new file mode 100644 --- /dev/null +++ b/tests/format/jsx/expression-with-types/__snapshots__/jsfmt.spec.js.snap @@ -0,0 +1,225 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`expression.js - {"singleQuote":false,"jsxSingleQuote":false} format 1`] = ` +====================================options===================================== +jsxSingleQuote: false +parsers: ["flow", "typescript"] +printWidth: 80 +singleQuote: false + | printWidth +=====================================input====================================== +<Component + onChange={( + key: "possible_key_1" | "possible_key_2" | "possible_key_3", + value: string | Immutable.List<string>, + ) => { + this.setState({ + updatedTask: this.state.updatedTask.set(key, value) + }); + }} +/>; + +<Component> + {( + key: "possible_key_1" | "possible_key_2" | "possible_key_3", + value: string | Immutable.List<string>, + ) => { + this.setState({ + updatedTask: this.state.updatedTask.set(key, value) + }); + }} +</Component>; + +=====================================output===================================== +<Component + onChange={( + key: "possible_key_1" | "possible_key_2" | "possible_key_3", + value: string | Immutable.List<string>, + ) => { + this.setState({ + updatedTask: this.state.updatedTask.set(key, value), + }); + }} +/>; + +<Component> + {( + key: "possible_key_1" | "possible_key_2" | "possible_key_3", + value: string | Immutable.List<string>, + ) => { + this.setState({ + updatedTask: this.state.updatedTask.set(key, value), + }); + }} +</Component>; + +================================================================================ +`; + +exports[`expression.js - {"singleQuote":false,"jsxSingleQuote":true} format 1`] = ` +====================================options===================================== +jsxSingleQuote: true +parsers: ["flow", "typescript"] +printWidth: 80 +singleQuote: false + | printWidth +=====================================input====================================== +<Component + onChange={( + key: "possible_key_1" | "possible_key_2" | "possible_key_3", + value: string | Immutable.List<string>, + ) => { + this.setState({ + updatedTask: this.state.updatedTask.set(key, value) + }); + }} +/>; + +<Component> + {( + key: "possible_key_1" | "possible_key_2" | "possible_key_3", + value: string | Immutable.List<string>, + ) => { + this.setState({ + updatedTask: this.state.updatedTask.set(key, value) + }); + }} +</Component>; + +=====================================output===================================== +<Component + onChange={( + key: "possible_key_1" | "possible_key_2" | "possible_key_3", + value: string | Immutable.List<string>, + ) => { + this.setState({ + updatedTask: this.state.updatedTask.set(key, value), + }); + }} +/>; + +<Component> + {( + key: "possible_key_1" | "possible_key_2" | "possible_key_3", + value: string | Immutable.List<string>, + ) => { + this.setState({ + updatedTask: this.state.updatedTask.set(key, value), + }); + }} +</Component>; + +================================================================================ +`; + +exports[`expression.js - {"singleQuote":true,"jsxSingleQuote":false} format 1`] = ` +====================================options===================================== +jsxSingleQuote: false +parsers: ["flow", "typescript"] +printWidth: 80 +singleQuote: true + | printWidth +=====================================input====================================== +<Component + onChange={( + key: "possible_key_1" | "possible_key_2" | "possible_key_3", + value: string | Immutable.List<string>, + ) => { + this.setState({ + updatedTask: this.state.updatedTask.set(key, value) + }); + }} +/>; + +<Component> + {( + key: "possible_key_1" | "possible_key_2" | "possible_key_3", + value: string | Immutable.List<string>, + ) => { + this.setState({ + updatedTask: this.state.updatedTask.set(key, value) + }); + }} +</Component>; + +=====================================output===================================== +<Component + onChange={( + key: 'possible_key_1' | 'possible_key_2' | 'possible_key_3', + value: string | Immutable.List<string>, + ) => { + this.setState({ + updatedTask: this.state.updatedTask.set(key, value), + }); + }} +/>; + +<Component> + {( + key: 'possible_key_1' | 'possible_key_2' | 'possible_key_3', + value: string | Immutable.List<string>, + ) => { + this.setState({ + updatedTask: this.state.updatedTask.set(key, value), + }); + }} +</Component>; + +================================================================================ +`; + +exports[`expression.js - {"singleQuote":true,"jsxSingleQuote":true} format 1`] = ` +====================================options===================================== +jsxSingleQuote: true +parsers: ["flow", "typescript"] +printWidth: 80 +singleQuote: true + | printWidth +=====================================input====================================== +<Component + onChange={( + key: "possible_key_1" | "possible_key_2" | "possible_key_3", + value: string | Immutable.List<string>, + ) => { + this.setState({ + updatedTask: this.state.updatedTask.set(key, value) + }); + }} +/>; + +<Component> + {( + key: "possible_key_1" | "possible_key_2" | "possible_key_3", + value: string | Immutable.List<string>, + ) => { + this.setState({ + updatedTask: this.state.updatedTask.set(key, value) + }); + }} +</Component>; + +=====================================output===================================== +<Component + onChange={( + key: 'possible_key_1' | 'possible_key_2' | 'possible_key_3', + value: string | Immutable.List<string>, + ) => { + this.setState({ + updatedTask: this.state.updatedTask.set(key, value), + }); + }} +/>; + +<Component> + {( + key: 'possible_key_1' | 'possible_key_2' | 'possible_key_3', + value: string | Immutable.List<string>, + ) => { + this.setState({ + updatedTask: this.state.updatedTask.set(key, value), + }); + }} +</Component>; + +================================================================================ +`; diff --git a/tests/format/jsx/expression-with-types/expression.js b/tests/format/jsx/expression-with-types/expression.js new file mode 100644 --- /dev/null +++ b/tests/format/jsx/expression-with-types/expression.js @@ -0,0 +1,21 @@ +<Component + onChange={( + key: "possible_key_1" | "possible_key_2" | "possible_key_3", + value: string | Immutable.List<string>, + ) => { + this.setState({ + updatedTask: this.state.updatedTask.set(key, value) + }); + }} +/>; + +<Component> + {( + key: "possible_key_1" | "possible_key_2" | "possible_key_3", + value: string | Immutable.List<string>, + ) => { + this.setState({ + updatedTask: this.state.updatedTask.set(key, value) + }); + }} +</Component>; diff --git a/tests/format/jsx/expression-with-types/jsfmt.spec.js b/tests/format/jsx/expression-with-types/jsfmt.spec.js new file mode 100644 --- /dev/null +++ b/tests/format/jsx/expression-with-types/jsfmt.spec.js @@ -0,0 +1,16 @@ +run_spec(import.meta, ["flow", "typescript"], { + singleQuote: false, + jsxSingleQuote: false, +}); +run_spec(import.meta, ["flow", "typescript"], { + singleQuote: false, + jsxSingleQuote: true, +}); +run_spec(import.meta, ["flow", "typescript"], { + singleQuote: true, + jsxSingleQuote: false, +}); +run_spec(import.meta, ["flow", "typescript"], { + singleQuote: true, + jsxSingleQuote: true, +}); diff --git a/tests/format/jsx/jsx/__snapshots__/jsfmt.spec.js.snap b/tests/format/jsx/jsx/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/jsx/jsx/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/jsx/jsx/__snapshots__/jsfmt.spec.js.snap @@ -2276,39 +2276,6 @@ foo ? ( ================================================================================ `; -exports[`expression.js - {"singleQuote":false,"jsxSingleQuote":false} [acorn] format 1`] = ` -"Unexpected token (87:8) - 85 | <Component - 86 | onChange={( -> 87 | key: "possible_key_1" | "possible_key_2" | "possible_key_3", - | ^ - 88 | value: string | Immutable.List<string>, - 89 | ) => { - 90 | this.setState({" -`; - -exports[`expression.js - {"singleQuote":false,"jsxSingleQuote":false} [espree] format 1`] = ` -"Unexpected token : (87:8) - 85 | <Component - 86 | onChange={( -> 87 | key: "possible_key_1" | "possible_key_2" | "possible_key_3", - | ^ - 88 | value: string | Immutable.List<string>, - 89 | ) => { - 90 | this.setState({" -`; - -exports[`expression.js - {"singleQuote":false,"jsxSingleQuote":false} [meriyah] format 1`] = ` -"Expected ')' (87:8) - 85 | <Component - 86 | onChange={( -> 87 | key: "possible_key_1" | "possible_key_2" | "possible_key_3", - | ^ - 88 | value: string | Immutable.List<string>, - 89 | ) => { - 90 | this.setState({" -`; - exports[`expression.js - {"singleQuote":false,"jsxSingleQuote":false} format 1`] = ` ====================================options===================================== jsxSingleQuote: false @@ -2401,17 +2368,6 @@ singleQuote: false }} />; -<Component - onChange={( - key: "possible_key_1" | "possible_key_2" | "possible_key_3", - value: string | Immutable.List<string>, - ) => { - this.setState({ - updatedTask: this.state.updatedTask.set(key, value) - }); - }} -/>; - <BookingIntroPanel> {data => doLogClick("short", "short", data)} </BookingIntroPanel>; @@ -2428,17 +2384,6 @@ singleQuote: false }} </BookingIntroPanel>; -<Component> - {( - key: "possible_key_1" | "possible_key_2" | "possible_key_3", - value: string | Immutable.List<string>, - ) => { - this.setState({ - updatedTask: this.state.updatedTask.set(key, value) - }); - }} -</Component>; - <SuspendyTree> <div style={{ height: 200, overflow: "scroll" }}> {Array(20) @@ -2538,17 +2483,6 @@ singleQuote: false }} />; -<Component - onChange={( - key: "possible_key_1" | "possible_key_2" | "possible_key_3", - value: string | Immutable.List<string>, - ) => { - this.setState({ - updatedTask: this.state.updatedTask.set(key, value), - }); - }} -/>; - <BookingIntroPanel> {(data) => doLogClick("short", "short", data)} </BookingIntroPanel>; @@ -2573,17 +2507,6 @@ singleQuote: false }} </BookingIntroPanel>; -<Component> - {( - key: "possible_key_1" | "possible_key_2" | "possible_key_3", - value: string | Immutable.List<string>, - ) => { - this.setState({ - updatedTask: this.state.updatedTask.set(key, value), - }); - }} -</Component>; - <SuspendyTree> <div style={{ height: 200, overflow: "scroll" }}> {Array(20) @@ -2597,39 +2520,6 @@ singleQuote: false ================================================================================ `; -exports[`expression.js - {"singleQuote":false,"jsxSingleQuote":true} [acorn] format 1`] = ` -"Unexpected token (87:8) - 85 | <Component - 86 | onChange={( -> 87 | key: "possible_key_1" | "possible_key_2" | "possible_key_3", - | ^ - 88 | value: string | Immutable.List<string>, - 89 | ) => { - 90 | this.setState({" -`; - -exports[`expression.js - {"singleQuote":false,"jsxSingleQuote":true} [espree] format 1`] = ` -"Unexpected token : (87:8) - 85 | <Component - 86 | onChange={( -> 87 | key: "possible_key_1" | "possible_key_2" | "possible_key_3", - | ^ - 88 | value: string | Immutable.List<string>, - 89 | ) => { - 90 | this.setState({" -`; - -exports[`expression.js - {"singleQuote":false,"jsxSingleQuote":true} [meriyah] format 1`] = ` -"Expected ')' (87:8) - 85 | <Component - 86 | onChange={( -> 87 | key: "possible_key_1" | "possible_key_2" | "possible_key_3", - | ^ - 88 | value: string | Immutable.List<string>, - 89 | ) => { - 90 | this.setState({" -`; - exports[`expression.js - {"singleQuote":false,"jsxSingleQuote":true} format 1`] = ` ====================================options===================================== jsxSingleQuote: true @@ -2722,17 +2612,6 @@ singleQuote: false }} />; -<Component - onChange={( - key: "possible_key_1" | "possible_key_2" | "possible_key_3", - value: string | Immutable.List<string>, - ) => { - this.setState({ - updatedTask: this.state.updatedTask.set(key, value) - }); - }} -/>; - <BookingIntroPanel> {data => doLogClick("short", "short", data)} </BookingIntroPanel>; @@ -2749,17 +2628,6 @@ singleQuote: false }} </BookingIntroPanel>; -<Component> - {( - key: "possible_key_1" | "possible_key_2" | "possible_key_3", - value: string | Immutable.List<string>, - ) => { - this.setState({ - updatedTask: this.state.updatedTask.set(key, value) - }); - }} -</Component>; - <SuspendyTree> <div style={{ height: 200, overflow: "scroll" }}> {Array(20) @@ -2859,17 +2727,6 @@ singleQuote: false }} />; -<Component - onChange={( - key: "possible_key_1" | "possible_key_2" | "possible_key_3", - value: string | Immutable.List<string>, - ) => { - this.setState({ - updatedTask: this.state.updatedTask.set(key, value), - }); - }} -/>; - <BookingIntroPanel> {(data) => doLogClick("short", "short", data)} </BookingIntroPanel>; @@ -2894,17 +2751,6 @@ singleQuote: false }} </BookingIntroPanel>; -<Component> - {( - key: "possible_key_1" | "possible_key_2" | "possible_key_3", - value: string | Immutable.List<string>, - ) => { - this.setState({ - updatedTask: this.state.updatedTask.set(key, value), - }); - }} -</Component>; - <SuspendyTree> <div style={{ height: 200, overflow: "scroll" }}> {Array(20) @@ -2918,39 +2764,6 @@ singleQuote: false ================================================================================ `; -exports[`expression.js - {"singleQuote":true,"jsxSingleQuote":false} [acorn] format 1`] = ` -"Unexpected token (87:8) - 85 | <Component - 86 | onChange={( -> 87 | key: "possible_key_1" | "possible_key_2" | "possible_key_3", - | ^ - 88 | value: string | Immutable.List<string>, - 89 | ) => { - 90 | this.setState({" -`; - -exports[`expression.js - {"singleQuote":true,"jsxSingleQuote":false} [espree] format 1`] = ` -"Unexpected token : (87:8) - 85 | <Component - 86 | onChange={( -> 87 | key: "possible_key_1" | "possible_key_2" | "possible_key_3", - | ^ - 88 | value: string | Immutable.List<string>, - 89 | ) => { - 90 | this.setState({" -`; - -exports[`expression.js - {"singleQuote":true,"jsxSingleQuote":false} [meriyah] format 1`] = ` -"Expected ')' (87:8) - 85 | <Component - 86 | onChange={( -> 87 | key: "possible_key_1" | "possible_key_2" | "possible_key_3", - | ^ - 88 | value: string | Immutable.List<string>, - 89 | ) => { - 90 | this.setState({" -`; - exports[`expression.js - {"singleQuote":true,"jsxSingleQuote":false} format 1`] = ` ====================================options===================================== jsxSingleQuote: false @@ -3043,17 +2856,6 @@ singleQuote: true }} />; -<Component - onChange={( - key: "possible_key_1" | "possible_key_2" | "possible_key_3", - value: string | Immutable.List<string>, - ) => { - this.setState({ - updatedTask: this.state.updatedTask.set(key, value) - }); - }} -/>; - <BookingIntroPanel> {data => doLogClick("short", "short", data)} </BookingIntroPanel>; @@ -3070,17 +2872,6 @@ singleQuote: true }} </BookingIntroPanel>; -<Component> - {( - key: "possible_key_1" | "possible_key_2" | "possible_key_3", - value: string | Immutable.List<string>, - ) => { - this.setState({ - updatedTask: this.state.updatedTask.set(key, value) - }); - }} -</Component>; - <SuspendyTree> <div style={{ height: 200, overflow: "scroll" }}> {Array(20) @@ -3180,17 +2971,6 @@ singleQuote: true }} />; -<Component - onChange={( - key: 'possible_key_1' | 'possible_key_2' | 'possible_key_3', - value: string | Immutable.List<string>, - ) => { - this.setState({ - updatedTask: this.state.updatedTask.set(key, value), - }); - }} -/>; - <BookingIntroPanel> {(data) => doLogClick('short', 'short', data)} </BookingIntroPanel>; @@ -3215,17 +2995,6 @@ singleQuote: true }} </BookingIntroPanel>; -<Component> - {( - key: 'possible_key_1' | 'possible_key_2' | 'possible_key_3', - value: string | Immutable.List<string>, - ) => { - this.setState({ - updatedTask: this.state.updatedTask.set(key, value), - }); - }} -</Component>; - <SuspendyTree> <div style={{ height: 200, overflow: 'scroll' }}> {Array(20) @@ -3239,39 +3008,6 @@ singleQuote: true ================================================================================ `; -exports[`expression.js - {"singleQuote":true,"jsxSingleQuote":true} [acorn] format 1`] = ` -"Unexpected token (87:8) - 85 | <Component - 86 | onChange={( -> 87 | key: "possible_key_1" | "possible_key_2" | "possible_key_3", - | ^ - 88 | value: string | Immutable.List<string>, - 89 | ) => { - 90 | this.setState({" -`; - -exports[`expression.js - {"singleQuote":true,"jsxSingleQuote":true} [espree] format 1`] = ` -"Unexpected token : (87:8) - 85 | <Component - 86 | onChange={( -> 87 | key: "possible_key_1" | "possible_key_2" | "possible_key_3", - | ^ - 88 | value: string | Immutable.List<string>, - 89 | ) => { - 90 | this.setState({" -`; - -exports[`expression.js - {"singleQuote":true,"jsxSingleQuote":true} [meriyah] format 1`] = ` -"Expected ')' (87:8) - 85 | <Component - 86 | onChange={( -> 87 | key: "possible_key_1" | "possible_key_2" | "possible_key_3", - | ^ - 88 | value: string | Immutable.List<string>, - 89 | ) => { - 90 | this.setState({" -`; - exports[`expression.js - {"singleQuote":true,"jsxSingleQuote":true} format 1`] = ` ====================================options===================================== jsxSingleQuote: true @@ -3364,17 +3100,6 @@ singleQuote: true }} />; -<Component - onChange={( - key: "possible_key_1" | "possible_key_2" | "possible_key_3", - value: string | Immutable.List<string>, - ) => { - this.setState({ - updatedTask: this.state.updatedTask.set(key, value) - }); - }} -/>; - <BookingIntroPanel> {data => doLogClick("short", "short", data)} </BookingIntroPanel>; @@ -3391,17 +3116,6 @@ singleQuote: true }} </BookingIntroPanel>; -<Component> - {( - key: "possible_key_1" | "possible_key_2" | "possible_key_3", - value: string | Immutable.List<string>, - ) => { - this.setState({ - updatedTask: this.state.updatedTask.set(key, value) - }); - }} -</Component>; - <SuspendyTree> <div style={{ height: 200, overflow: "scroll" }}> {Array(20) @@ -3501,17 +3215,6 @@ singleQuote: true }} />; -<Component - onChange={( - key: 'possible_key_1' | 'possible_key_2' | 'possible_key_3', - value: string | Immutable.List<string>, - ) => { - this.setState({ - updatedTask: this.state.updatedTask.set(key, value), - }); - }} -/>; - <BookingIntroPanel> {(data) => doLogClick('short', 'short', data)} </BookingIntroPanel>; @@ -3536,17 +3239,6 @@ singleQuote: true }} </BookingIntroPanel>; -<Component> - {( - key: 'possible_key_1' | 'possible_key_2' | 'possible_key_3', - value: string | Immutable.List<string>, - ) => { - this.setState({ - updatedTask: this.state.updatedTask.set(key, value), - }); - }} -</Component>; - <SuspendyTree> <div style={{ height: 200, overflow: 'scroll' }}> {Array(20) diff --git a/tests/format/jsx/jsx/expression.js b/tests/format/jsx/jsx/expression.js --- a/tests/format/jsx/jsx/expression.js +++ b/tests/format/jsx/jsx/expression.js @@ -82,17 +82,6 @@ }} />; -<Component - onChange={( - key: "possible_key_1" | "possible_key_2" | "possible_key_3", - value: string | Immutable.List<string>, - ) => { - this.setState({ - updatedTask: this.state.updatedTask.set(key, value) - }); - }} -/>; - <BookingIntroPanel> {data => doLogClick("short", "short", data)} </BookingIntroPanel>; @@ -109,17 +98,6 @@ }} </BookingIntroPanel>; -<Component> - {( - key: "possible_key_1" | "possible_key_2" | "possible_key_3", - value: string | Immutable.List<string>, - ) => { - this.setState({ - updatedTask: this.state.updatedTask.set(key, value) - }); - }} -</Component>; - <SuspendyTree> <div style={{ height: 200, overflow: "scroll" }}> {Array(20) diff --git a/tests/format/jsx/jsx/jsfmt.spec.js b/tests/format/jsx/jsx/jsfmt.spec.js --- a/tests/format/jsx/jsx/jsfmt.spec.js +++ b/tests/format/jsx/jsx/jsfmt.spec.js @@ -1,26 +1,16 @@ -const errors = { - acorn: ["expression.js"], - espree: ["expression.js"], - meriyah: ["expression.js"], -}; - run_spec(import.meta, ["flow", "babel", "typescript"], { singleQuote: false, jsxSingleQuote: false, - errors, }); run_spec(import.meta, ["flow", "babel", "typescript"], { singleQuote: false, jsxSingleQuote: true, - errors, }); run_spec(import.meta, ["flow", "babel", "typescript"], { singleQuote: true, jsxSingleQuote: false, - errors, }); run_spec(import.meta, ["flow", "babel", "typescript"], { singleQuote: true, jsxSingleQuote: true, - errors, }); diff --git a/tests/format/misc/errors/babel-flow/__snapshots__/jsfmt.spec.js.snap b/tests/format/misc/errors/babel-flow/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/misc/errors/babel-flow/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/misc/errors/babel-flow/__snapshots__/jsfmt.spec.js.snap @@ -1,11 +1,11 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`async-arrow-invalid.js [babel] format 1`] = ` -"Type parameters must come after the async keyword, e.g. instead of \`<T> async (3:1) +"Unterminated JSX contents. (3:19) 1 | // https://github.com/babel/babel/pull/11979 2 | > 3 | <T> async () => {} - | ^ + | ^ 4 |" `; diff --git a/tests/format/misc/errors/js/import-assertions/__snapshots__/jsfmt.spec.js.snap b/tests/format/misc/errors/js/import-assertions/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/misc/errors/js/import-assertions/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/misc/errors/js/import-assertions/__snapshots__/jsfmt.spec.js.snap @@ -22,30 +22,30 @@ exports[`invalid-export-from.mjs [babel] format 1`] = ` `; exports[`invalid-flow-type-import-1.mjs [babel] format 1`] = ` -"Unexpected token, expected "from" (1:20) +"Unexpected token, expected "from" (1:13) > 1 | import type module foo from "./module.wasm"; - | ^ + | ^ 2 |" `; exports[`invalid-flow-type-import-2.mjs [babel] format 1`] = ` -"An \`import module\` declaration can not use \`type\` or \`typeof\` keyword. (1:20) +"Unexpected token, expected "from" (1:20) > 1 | import module type foo from "./module.wasm"; | ^ 2 |" `; exports[`invalid-flow-typeof-import-1.mjs [babel] format 1`] = ` -"Unexpected token, expected "from" (1:22) +"Unexpected token, expected "{" (1:8) > 1 | import typeof module foo from "./module.wasm"; - | ^ + | ^ 2 |" `; exports[`invalid-flow-typeof-import-2.mjs [babel] format 1`] = ` -"An \`import module\` declaration can not use \`type\` or \`typeof\` keyword. (1:22) +"Unexpected token, expected "{" (1:15) > 1 | import module typeof foo from "./module.wasm"; - | ^ + | ^ 2 |" `; @@ -85,14 +85,14 @@ exports[`invalid-namespace-import.mjs [babel] format 1`] = ` `; exports[`invalid-ts-type-import-1.mts [babel] format 1`] = ` -"Unexpected token, expected "from" (1:20) +"Unexpected token, expected "from" (1:13) > 1 | import type module foo from "./module.wasm"; - | ^ + | ^ 2 |" `; exports[`invalid-ts-type-import-2.mts [babel] format 1`] = ` -"An \`import module\` declaration can not use \`type\` or \`typeof\` keyword. (1:20) +"Unexpected token, expected "from" (1:20) > 1 | import module type foo from "./module.wasm"; | ^ 2 |" diff --git a/tests/format/misc/flow-babel-only/__snapshots__/jsfmt.spec.js.snap b/tests/format/misc/flow-babel-only/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/misc/flow-babel-only/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/misc/flow-babel-only/__snapshots__/jsfmt.spec.js.snap @@ -2,7 +2,7 @@ exports[`class_with_generics.js format 1`] = ` ====================================options===================================== -parsers: ["babel"] +parsers: ["babel-flow"] printWidth: 80 | printWidth =====================================input====================================== @@ -21,21 +21,19 @@ class Component extends React.Component/*:: <Props, State> */ { =====================================output===================================== import React from "react"; -/*:: type Props = { +type Props = { foo?: ?string, bar: number, -}; */ - -/*:: type State = { baz: number }; */ - -class Component extends React.Component /*:: <Props, State> */ {} +}; +type State = { baz: number }; +class Component extends React.Component<Props, State> {} ================================================================================ `; exports[`constructor-field-override.js format 1`] = ` ====================================options===================================== -parsers: ["babel"] +parsers: ["babel-flow"] printWidth: 80 | printWidth =====================================input====================================== @@ -55,7 +53,7 @@ class Foo { exports[`functions.js format 1`] = ` ====================================options===================================== -parsers: ["babel"] +parsers: ["babel-flow"] printWidth: 80 | printWidth =====================================input====================================== @@ -67,8 +65,8 @@ export function updateStoreFromURL( =====================================output===================================== export function updateStoreFromURL( - store /*: Store*/, - { search, hash } /*: {search: string, hash: string}*/, + store: Store, + { search, hash }: { search: string, hash: string }, ) {} ================================================================================ diff --git a/tests/format/misc/flow-babel-only/jsfmt.spec.js b/tests/format/misc/flow-babel-only/jsfmt.spec.js --- a/tests/format/misc/flow-babel-only/jsfmt.spec.js +++ b/tests/format/misc/flow-babel-only/jsfmt.spec.js @@ -1 +1 @@ -run_spec(import.meta, ["babel"]); +run_spec(import.meta, ["babel-flow"]); diff --git a/tests/format/typescript/decorators/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/decorators/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/typescript/decorators/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/typescript/decorators/__snapshots__/jsfmt.spec.js.snap @@ -37,6 +37,28 @@ class Foo { ================================================================================ `; +exports[`comments.ts format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +class Something { + @Annotateme() + // comment + static property: Array<string>; +} + +=====================================output===================================== +class Something { + @Annotateme() + // comment + static property: Array<string>; +} + +================================================================================ +`; + exports[`decorator-type-assertion.ts format 1`] = ` ====================================options===================================== parsers: ["typescript"] @@ -419,3 +441,97 @@ class MyContainerComponent { ================================================================================ `; + +exports[`mobx.ts format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +import {observable} from "mobx"; + +@observer class OrderLine { + @observable price:number = 0; + @observable amount:number = 1; + + constructor(price) { + this.price = price; + } + + @computed get total() { + return this.price * this.amount; + } + + @action.bound setPrice(price) { + this.price = price; + } + + @computed + get total() { + return this.price * this.amount; + } + + @action.bound + setPrice(price) { + this.price = price; + } + + @computed @computed @computed @computed @computed @computed @computed get total() { + return this.price * this.amount; + } + + @action handleDecrease = (event: React.ChangeEvent<HTMLInputElement>) => this.count--; + + @action handleSomething = (event: React.ChangeEvent<HTMLInputElement>) => doSomething(); +} + +=====================================output===================================== +import { observable } from "mobx"; + +@observer +class OrderLine { + @observable price: number = 0; + @observable amount: number = 1; + + constructor(price) { + this.price = price; + } + + @computed get total() { + return this.price * this.amount; + } + + @action.bound setPrice(price) { + this.price = price; + } + + @computed + get total() { + return this.price * this.amount; + } + + @action.bound + setPrice(price) { + this.price = price; + } + + @computed + @computed + @computed + @computed + @computed + @computed + @computed + get total() { + return this.price * this.amount; + } + + @action handleDecrease = (event: React.ChangeEvent<HTMLInputElement>) => + this.count--; + + @action handleSomething = (event: React.ChangeEvent<HTMLInputElement>) => + doSomething(); +} + +================================================================================ +`; diff --git a/tests/format/typescript/decorators/comments.ts b/tests/format/typescript/decorators/comments.ts new file mode 100644 --- /dev/null +++ b/tests/format/typescript/decorators/comments.ts @@ -0,0 +1,5 @@ +class Something { + @Annotateme() + // comment + static property: Array<string>; +} diff --git a/tests/format/typescript/decorators/mobx.ts b/tests/format/typescript/decorators/mobx.ts new file mode 100644 --- /dev/null +++ b/tests/format/typescript/decorators/mobx.ts @@ -0,0 +1,36 @@ +import {observable} from "mobx"; + +@observer class OrderLine { + @observable price:number = 0; + @observable amount:number = 1; + + constructor(price) { + this.price = price; + } + + @computed get total() { + return this.price * this.amount; + } + + @action.bound setPrice(price) { + this.price = price; + } + + @computed + get total() { + return this.price * this.amount; + } + + @action.bound + setPrice(price) { + this.price = price; + } + + @computed @computed @computed @computed @computed @computed @computed get total() { + return this.price * this.amount; + } + + @action handleDecrease = (event: React.ChangeEvent<HTMLInputElement>) => this.count--; + + @action handleSomething = (event: React.ChangeEvent<HTMLInputElement>) => doSomething(); +}
Remove `flow` support from `parser: babel` I was trying to improve parse performance on large files, and found it will cost almost half time on some file by removing plugins. Something interesting come up, we have `flow` and `babel-flow` parser, but we also enabled `flow` syntax in `babel` plugins https://github.com/prettier/prettier/blob/master/src/language-js/parser-babel.js#L101 Shouldn't we encourage people use `flow` or `babel-flow`? People use `typescript` and `babel-ts` for `.ts`, not `babel`. Can we remove it? --- Refs: Motivation for `babel-flow` https://github.com/prettier/prettier/issues/5460#issuecomment-441298551 and https://github.com/prettier/prettier/issues/5460#issuecomment-441360123 PR introduce `babel-flow` https://github.com/prettier/prettier/pull/5685
> found it will cost almost half time on some file by removing plugins. Could you show some benchmark results? > Can we remove it? I guess we can if we make Prettier switch to `babel-flow` automatically when the `@flow` pragma is found. > Could you show some benchmark results? Will do. > I guess we can if we make Prettier switch to babel-flow automatically when the @flow pragma is found. My intention is not support flow at all, but check `@flow` is a good idea, so we don't break anything. Run against `src/**/*` <details> <summary>Test script</summary> <pre><code> const fs = require('fs') const oldParse = require('./src/language-js/parser-babel-master').parsers.babel.parse const newParse = require('./src/language-js/parser-babel').parsers.babel.parse const files = require('fast-glob').sync('src/**/*').map(file => fs.readFileSync(file, 'utf8')) console.log('first run') console.time('new') for (const code of files) { newParse(code) } console.timeEnd('new') console.time('old') for (const code of files) { oldParse(code) } console.timeEnd('old') console.log() console.log('second run') console.time('old') for (const code of files) { oldParse(code) } console.timeEnd('old') console.time('new') for (const code of files) { newParse(code) } console.timeEnd('new') </code></pre> </details> ```text first run new: 517.260ms old: 594.656ms second run old: 332.977ms new: 186.684ms ``` ----- Run against this 18M js file from [here](https://github.com/prettier/prettier/issues/5004#issuecomment-459876800) <details> <summary>Test script</summary> <pre><code> const fs = require('fs') const oldParse = require('./src/language-js/parser-babel-master').parsers.babel.parse const newParse = require('./src/language-js/parser-babel').parsers.babel.parse const code = fs.readFileSync('./AngryBots.js', 'utf8') console.log('first run') console.time('new') newParse(code) console.timeEnd('new') console.time('old') oldParse(code) console.timeEnd('old') console.log() console.log('second run') console.time('old') oldParse(code) console.timeEnd('old') console.time('new') newParse(code) console.timeEnd('new') </code></pre> </details> Actual Babel options (`jsx` `flow` and some other plugins are not enabled) ```text [ { sourceType: 'module', allowAwaitOutsideFunction: true, allowImportExportEverywhere: true, allowReturnOutsideFunction: true, allowSuperOutsideMethod: true, allowUndeclaredExports: true, errorRecovery: true, createParenthesizedExpressions: true, plugins: [ 'asyncGenerators', 'bigInt', 'doExpressions', 'exportDefaultFrom', 'functionBind', 'functionSent', 'importMeta', 'numericSeparator', 'objectRestSpread', 'optionalCatchBinding', 'partialApplication', 'throwExpressions', 'v8intrinsic' ] } ] ``` Result ```text first run new: 26619.009ms old: 47839.521ms second run old: 46681.359ms new: 27487.509ms ``` ---- The prototype can be found [here](https://github.com/fisker/prettier/pull/378/commits/9bf8f0a9bb168f019fdb5140ea25015761132f3a). @thorn0 I've done removing `flow` (also simple tests for each babel plugin) from `babel` parser https://github.com/fisker/prettier/pull/378 , it indeed makes the parse faster on pure js projects, but this is a breaking change. Before,we can parse `flow` syntax by default. After, users need use `@flow` or switch to `babel-flow` parser, should I send the PR? Do people write Flow code in files with `.js` extension and without `@flow`? I don't use flow , but some tests in `tests/flow/` don't has `@flow` We can't proceed with this if people do that. > Shouldn't we encourage people use `flow` or `babel-flow`? About this, what do you think? Prettier should "just work", even without config files. But if people write Flow code in `.js` files, they'll have to know to create a config file to specify `parser`. Copying my comment from #8508: > That's fine. The babel parser isn't safe for Flow anyway: https://prettier.io/blog/2019/01/20/1.16.0.html#flow I agree that it's a mess. BTW, probably this means that if we proceed with #8204 (parse Flow syntax only if the pragma is present), it won't really be a breaking change as we'd break something that is already broken.
"2023-02-08T10:23:27Z"
3.0
[ "tests/format/jsx/jsx/jsfmt.spec.js", "tests/format/jsx/expression-with-types/jsfmt.spec.js", "tests/format/js/trailing-whitespace/jsfmt.spec.js", "tests/format/flow/decorator/jsfmt.spec.js", "tests/format/js/decorators/jsfmt.spec.js", "tests/format/js/rest/jsfmt.spec.js", "tests/format/typescript/decorators/jsfmt.spec.js", "tests/format/misc/flow-babel-only/jsfmt.spec.js" ]
[ "tests/format/js/babel-plugins/jsfmt.spec.js", "tests/format/misc/errors/babel-flow/jsfmt.spec.js", "tests/format/misc/errors/js/import-assertions/jsfmt.spec.js" ]
JavaScript
[]
[]
prettier/prettier
14,393
prettier__prettier-14393
[ "14309" ]
2a5b391cc05e0ed8e00285c0a8afb71bb776147c
diff --git a/src/language-js/needs-parens.js b/src/language-js/needs-parens.js --- a/src/language-js/needs-parens.js +++ b/src/language-js/needs-parens.js @@ -187,6 +187,10 @@ function needsParens(path, options) { } case "Decorator": { if (name === "expression") { + if (isMemberExpression(node) && node.computed) { + return true; + } + let hasCallExpression = false; let hasMemberExpression = false; let current = node;
diff --git a/tests/config/format-test.js b/tests/config/format-test.js --- a/tests/config/format-test.js +++ b/tests/config/format-test.js @@ -82,6 +82,8 @@ const meriyahDisabledTests = new Set([ __dirname, "../format/js/babel-plugins/decorator-auto-accessors.js" ), + // Parsing to different ASTs + path.join(__dirname, "../format/js/decorators/member-expression.js"), ]); const isUnstable = (filename, options) => { diff --git a/tests/format/js/decorators/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/decorators/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/js/decorators/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/decorators/__snapshots__/jsfmt.spec.js.snap @@ -162,6 +162,144 @@ export class Bar {} ================================================================================ `; +exports[`member-expression.js [acorn] format 1`] = ` +"Unexpected character '@' (3:5) + 1 | [ + 2 | class { +> 3 | @(decorators[0]) + | ^ + 4 | method() {} + 5 | }, + 6 | class {" +`; + +exports[`member-expression.js [espree] format 1`] = ` +"Unexpected character '@' (3:5) + 1 | [ + 2 | class { +> 3 | @(decorators[0]) + | ^ + 4 | method() {} + 5 | }, + 6 | class {" +`; + +exports[`member-expression.js format 1`] = ` +====================================options===================================== +parsers: ["babel"] +printWidth: 80 + | printWidth +=====================================input====================================== +[ + class { + @(decorators[0]) + method() {} + }, + class { + @decorators[0] + method() {} + }, + class { + @(decorators?.[0]) + method() {} + }, + class { + @(decorators.at(0)) + method() {} + }, + class { + @(decorators?.at(0)) + method() {} + }, + class { + @(decorators.first) + method() {} + }, + class { + @(decorators?.first) + method() {} + }, + class { + @(decorators[first]) + method() {} + }, + class { + @decorators[first] + method() {} + }, + class { + @(decorators["first"]) + method() {} + }, + @(decorators[first]) + class { + method() {} + }, + @(decorators[0]) + class { + method() {} + }, +] + +=====================================output===================================== +[ + class { + @(decorators[0]) + method() {} + }, + class { + @decorators [0]; + method() {} + }, + class { + @(decorators?.[0]) + method() {} + }, + class { + @decorators.at(0) + method() {} + }, + class { + @(decorators?.at(0)) + method() {} + }, + class { + @decorators.first + method() {} + }, + class { + @(decorators?.first) + method() {} + }, + class { + @(decorators[first]) + method() {} + }, + class { + @decorators [first]; + method() {} + }, + class { + @(decorators["first"]) + method() {} + }, + ( + @(decorators[first]) + class { + method() {} + } + ), + ( + @(decorators[0]) + class { + method() {} + } + ), +]; + +================================================================================ +`; + exports[`methods.js [acorn] format 1`] = ` "Unexpected character '@' (3:3) 1 | diff --git a/tests/format/js/decorators/member-expression.js b/tests/format/js/decorators/member-expression.js new file mode 100644 --- /dev/null +++ b/tests/format/js/decorators/member-expression.js @@ -0,0 +1,50 @@ +[ + class { + @(decorators[0]) + method() {} + }, + class { + @decorators[0] + method() {} + }, + class { + @(decorators?.[0]) + method() {} + }, + class { + @(decorators.at(0)) + method() {} + }, + class { + @(decorators?.at(0)) + method() {} + }, + class { + @(decorators.first) + method() {} + }, + class { + @(decorators?.first) + method() {} + }, + class { + @(decorators[first]) + method() {} + }, + class { + @decorators[first] + method() {} + }, + class { + @(decorators["first"]) + method() {} + }, + @(decorators[first]) + class { + method() {} + }, + @(decorators[0]) + class { + method() {} + }, +]
Using member access expressions (`@(array[0])`) in decorators produces incorrect output **Prettier 2.8.3** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAucAbAhgZ0wAgApwBOm0OwAOlDjgAIAUAtgJ4Aickh6MEhAgoZyYBtAAwBdAJSVqAc0Jw4MOhLIBfSuqggANCAgAHGAEtomZKHQCIAdzyWEZlOlTX0TM7oBGnMAGtFAMroDHAAMkZQcMgAZs6YcF4+-jAB+uhgETLIMIQArgkgcAyecAAmpWWh6FAyuegycABiPAxcxjXIIOi53DogABYwDKgA6v1G8JhpYHABDhNGAG4TTJ1g2H0R8YQweJwyrTFxBQBWmAAeAZmocACKuRDwR6jxumnERJ0wTPpwmGCEIyGPr6QGwEZGUowfrIAAcIjehAg8RGnH0nVBfyIiyiugAjg94HsDI4upgALSRMplPryAlGeR7eqHJCxF4FeIMIzZPIc65wXgwHJGTw9OAEQjhSLPV4gTD8+6PKKs466GDoTwQqEwpAAJjVnCMqEyAGEIAwWYVMABWPq5eIAFQ1jjZssW+QAklAKrAAgCgTBeN6At8bjK4KpVEA) <!-- prettier-ignore --> ```sh --parser typescript ``` **Input:** <!-- prettier-ignore --> ```tsx class Person { @(myDecoratorArray[0]) greet() {} } ``` **Output:** <!-- prettier-ignore --> ```tsx class Person { @myDecoratorArray[0] greet() {} } ``` **Why is this wrong?** In the original script, the `Person` class has a single member: a `greet` method decorated with `myDecoratorArray[0]`. The output has very different code. The `Person` class now has two members: - a `greet` method with _zero_ decorators, and - a computed property (`0`) decorated with `myDecoratorArray`. **Expected behavior:** The output should be the same as the input, with the decorator properly enclosed in parentheses.
"2023-02-21T06:54:03Z"
2.9
[]
[ "tests/format/js/decorators/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAucAbAhgZ0wAgApwBOm0OwAOlDjgAIAUAtgJ4Aickh6MEhAgoZyYBtAAwBdAJSVqAc0Jw4MOhLIBfSuqggANCAgAHGAEtomZKHQCIAdzyWEZlOlTX0TM7oBGnMAGtFAMroDHAAMkZQcMgAZs6YcF4+-jAB+uhgETLIMIQArgkgcAyecAAmpWWh6FAyuegycABiPAxcxjXIIOi53DogABYwDKgA6v1G8JhpYHABDhNGAG4TTJ1g2H0R8YQweJwyrTFxBQBWmAAeAZmocACKuRDwR6jxumnERJ0wTPpwmGCEIyGPr6QGwEZGUowfrIAAcIjehAg8RGnH0nVBfyIiyiugAjg94HsDI4upgALSRMplPryAlGeR7eqHJCxF4FeIMIzZPIc65wXgwHJGTw9OAEQjhSLPV4gTD8+6PKKs466GDoTwQqEwpAAJjVnCMqEyAGEIAwWYVMABWPq5eIAFQ1jjZssW+QAklAKrAAgCgTBeN6At8bjK4KpVEA" ]
prettier/prettier
14,400
prettier__prettier-14400
[ "13197" ]
6905b39ec7bc6ed38732e26ceced5b57677e2600
diff --git a/src/language-html/utils/index.js b/src/language-html/utils/index.js --- a/src/language-html/utils/index.js +++ b/src/language-html/utils/index.js @@ -109,6 +109,7 @@ function isScriptLikeTag(node) { (node.fullName === "script" || node.fullName === "style" || node.fullName === "svg:style" || + node.fullName === "svg:script" || (isUnknownNamespace(node) && (node.name === "script" || node.name === "style"))) );
diff --git a/tests/config/utils/check-parsers.js b/tests/config/utils/check-parsers.js --- a/tests/config/utils/check-parsers.js +++ b/tests/config/utils/check-parsers.js @@ -46,7 +46,10 @@ const categoryParsers = new Map([ "handlebars", { parsers: ["glimmer"], verifyParsers: [], extensions: [".hbs"] }, ], - ["html", { parsers: ["html"], verifyParsers: [], extensions: [".html"] }], + [ + "html", + { parsers: ["html"], verifyParsers: [], extensions: [".html", ".svg"] }, + ], ["mjml", { parsers: ["html"], verifyParsers: [], extensions: [".mjml"] }], [ "js", diff --git a/tests/format/html/svg/__snapshots__/jsfmt.spec.js.snap b/tests/format/html/svg/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/html/svg/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/html/svg/__snapshots__/jsfmt.spec.js.snap @@ -19,16 +19,7 @@ printWidth: 80 </html> <svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> -<defs /> <style > - polygon { fill: black } - - div { - color: white; - font:18px serif; - height: 100%; - overflow: auto; - } - </style> +<defs /> <g> <g><polygon points="5,5 195,10 185,185 10,195" /> @@ -73,18 +64,6 @@ printWidth: 80 <svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> <defs /> - <style> - polygon { - fill: black; - } - - div { - color: white; - font: 18px serif; - height: 100%; - overflow: auto; - } - </style> <g> <g> diff --git a/tests/format/html/svg/embeded/__snapshots__/jsfmt.spec.js.snap b/tests/format/html/svg/embeded/__snapshots__/jsfmt.spec.js.snap new file mode 100644 --- /dev/null +++ b/tests/format/html/svg/embeded/__snapshots__/jsfmt.spec.js.snap @@ -0,0 +1,253 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`svg.html - {"embeddedLanguageFormatting":"off"} format 1`] = ` +====================================options===================================== +embeddedLanguageFormatting: "off" +parsers: ["html"] +printWidth: 80 + | printWidth +=====================================input====================================== +<!DOCTYPE html> +<html> + <head> + <title>SVG</title> + </head> + <body> +<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> +<script> +document.addEventListener( +'DOMContentLoaded', () => { + const element = document.getElementById('foo') + if (element) { +element.fillStyle = 'currentColor' +} +}); +</script> +<style > + polygon { fill: black } + + div { + color: white; + font:18px serif; + height: 100%; + overflow: auto; + } + </style> +</svg> + </body> +</html> + +=====================================output===================================== +<!doctype html> +<html> + <head> + <title>SVG</title> + </head> + <body> + <svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> + <script> + document.addEventListener( + 'DOMContentLoaded', () => { + const element = document.getElementById('foo') + if (element) { + element.fillStyle = 'currentColor' + } + }); + </script> + <style> + polygon { fill: black } + + div { + color: white; + font:18px serif; + height: 100%; + overflow: auto; + } + </style> + </svg> + </body> +</html> + +================================================================================ +`; + +exports[`svg.html format 1`] = ` +====================================options===================================== +parsers: ["html"] +printWidth: 80 + | printWidth +=====================================input====================================== +<!DOCTYPE html> +<html> + <head> + <title>SVG</title> + </head> + <body> +<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> +<script> +document.addEventListener( +'DOMContentLoaded', () => { + const element = document.getElementById('foo') + if (element) { +element.fillStyle = 'currentColor' +} +}); +</script> +<style > + polygon { fill: black } + + div { + color: white; + font:18px serif; + height: 100%; + overflow: auto; + } + </style> +</svg> + </body> +</html> + +=====================================output===================================== +<!doctype html> +<html> + <head> + <title>SVG</title> + </head> + <body> + <svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> + <script> + document.addEventListener("DOMContentLoaded", () => { + const element = document.getElementById("foo"); + if (element) { + element.fillStyle = "currentColor"; + } + }); + </script> + <style> + polygon { + fill: black; + } + + div { + color: white; + font: 18px serif; + height: 100%; + overflow: auto; + } + </style> + </svg> + </body> +</html> + +================================================================================ +`; + +exports[`svg.svg - {"embeddedLanguageFormatting":"off"} format 1`] = ` +====================================options===================================== +embeddedLanguageFormatting: "off" +parsers: ["html"] +printWidth: 80 + | printWidth +=====================================input====================================== +<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> +<script> +document.addEventListener( +'DOMContentLoaded', () => { + const element = document.getElementById('foo') + if (element) { +element.fillStyle = 'currentColor' +} +}); +</script> +<style > + polygon { fill: black } + + div { + color: white; + font:18px serif; + height: 100%; + overflow: auto; + } + </style> +</svg> + +=====================================output===================================== +<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> + <script> + document.addEventListener( + 'DOMContentLoaded', () => { + const element = document.getElementById('foo') + if (element) { + element.fillStyle = 'currentColor' + } + }); + </script> + <style> + polygon { fill: black } + + div { + color: white; + font:18px serif; + height: 100%; + overflow: auto; + } + </style> +</svg> + +================================================================================ +`; + +exports[`svg.svg format 1`] = ` +====================================options===================================== +parsers: ["html"] +printWidth: 80 + | printWidth +=====================================input====================================== +<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> +<script> +document.addEventListener( +'DOMContentLoaded', () => { + const element = document.getElementById('foo') + if (element) { +element.fillStyle = 'currentColor' +} +}); +</script> +<style > + polygon { fill: black } + + div { + color: white; + font:18px serif; + height: 100%; + overflow: auto; + } + </style> +</svg> + +=====================================output===================================== +<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> + <script> + document.addEventListener("DOMContentLoaded", () => { + const element = document.getElementById("foo"); + if (element) { + element.fillStyle = "currentColor"; + } + }); + </script> + <style> + polygon { + fill: black; + } + + div { + color: white; + font: 18px serif; + height: 100%; + overflow: auto; + } + </style> +</svg> + +================================================================================ +`; diff --git a/tests/format/html/svg/embeded/jsfmt.spec.js b/tests/format/html/svg/embeded/jsfmt.spec.js new file mode 100644 --- /dev/null +++ b/tests/format/html/svg/embeded/jsfmt.spec.js @@ -0,0 +1,2 @@ +run_spec(import.meta, ["html"]); +run_spec(import.meta, ["html"], { embeddedLanguageFormatting: "off" }); diff --git a/tests/format/html/svg/embeded/svg.html b/tests/format/html/svg/embeded/svg.html new file mode 100644 --- /dev/null +++ b/tests/format/html/svg/embeded/svg.html @@ -0,0 +1,29 @@ +<!DOCTYPE html> +<html> + <head> + <title>SVG</title> + </head> + <body> +<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> +<script> +document.addEventListener( +'DOMContentLoaded', () => { + const element = document.getElementById('foo') + if (element) { +element.fillStyle = 'currentColor' +} +}); +</script> +<style > + polygon { fill: black } + + div { + color: white; + font:18px serif; + height: 100%; + overflow: auto; + } + </style> +</svg> + </body> +</html> diff --git a/tests/format/html/svg/embeded/svg.svg b/tests/format/html/svg/embeded/svg.svg new file mode 100644 --- /dev/null +++ b/tests/format/html/svg/embeded/svg.svg @@ -0,0 +1,21 @@ +<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> +<script> +document.addEventListener( +'DOMContentLoaded', () => { + const element = document.getElementById('foo') + if (element) { +element.fillStyle = 'currentColor' +} +}); +</script> +<style > + polygon { fill: black } + + div { + color: white; + font:18px serif; + height: 100%; + overflow: auto; + } + </style> +</svg> diff --git a/tests/format/html/svg/svg.html b/tests/format/html/svg/svg.html --- a/tests/format/html/svg/svg.html +++ b/tests/format/html/svg/svg.html @@ -11,16 +11,7 @@ </html> <svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"> -<defs /> <style > - polygon { fill: black } - - div { - color: white; - font:18px serif; - height: 100%; - overflow: auto; - } - </style> +<defs /> <g> <g><polygon points="5,5 195,10 185,185 10,195" />
Script in SVG is incorrectly formatted when using HTML parser <!-- BEFORE SUBMITTING AN ISSUE: 1. Search for your issue on GitHub: https://github.com/prettier/prettier/issues A large number of opened issues are duplicates of existing issues. If someone has already opened an issue for what you are experiencing, you do not need to open a new issue — please add a 👍 reaction to the existing issue instead. 2. We get a lot of requests for adding options, but Prettier is built on the principle of being opinionated about code formatting. This means we add options only in the case of strict technical necessity. Find out more: https://prettier.io/docs/en/option-philosophy.html Don't fill the form below manually! Let a program create a report for you: 1. Go to https://prettier.io/playground 2. Paste your code and set options 3. Press the "Report issue" button in the lower right --> **Prettier 2.7.1** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAzgNwOYAIAeAtgDZToC8AOiABYwwAOSA9MwO4cB0bAzJxACdszAEwAGCcyzZquNgEsAJjBpUQIgCxjZNOPOx01m7SFyZ5cNgCEI+NWNwPNuTdQB8lKJRiow8gWDEcLhgdtQAjCKyYACeajxRpgJqAGyyAGbyxMRqYACuAgIIMADCEMSC7p7e3qgAhlDyhHXwuC0wAvIARnnwAHJ1hHC5MbKYdcR5cBTUCQDckbKKBfacKegZWTnU6UVwAF5wssweXj7MfgFBp7V4mdlqUNBHpugdEADWw9T5hcVlFQEsjeAk+cAAtMR5FA4GA6gw1KC8lBFMD3l9wQplKpqIlcCCweDFHV0DQ6oU6nFcWjQRjiaSIOl0ug4DAjFUzrUGC0aLhFGoALIOEw3GA1HwNJotYLtTo9fqDb4gVGmcaTaaCyK4cIATkw4QFuu1IhoBq1AFZMOCDebjTRrXNDSIXOF9QKROE7WbnTwrQaeHbrbIunBsNDVgB2DamZbJahiTgiaO4e7bEC7OAHF64E7VMX5+qNZqtWXdXpwAZDNQEukkmiM5mssYTKYzdRzEy4ENhqCR5Ox1ZJzYPHZ7Q7HUW1ZjclSTnwz3n86hCxwc8W1SXFmX0OXlytKlVmFsa5fhCPaiPEBO26+G8+X6+4cG3+-EZ+cW3v80C89nt+P69HXCAAOD9tVA80rzA28QLA80Pygz9b3g20UP-MCvwFFDwIQr9HA-YNQ3DeNOB1fsVhIodTFTNQMyzCc83FQspRLHcywVKtqBrCF6XrJkWTFVVjzbEQO0IntVjIpYKJABMqJTLZaLHbMlDUYgSRgABldFs1zTlzgXOdmK3AAVAQGnQdJBEINo2PlCtFTUDoLKsgRCFkGAYgYJVQRgaVm3VNsHC1SI5h4FJgudRZTG7YiQHUt5tNpOBOAQQ8B1mMRkyKbyWjKZE2WoaFFDgTJGngBizlQZhsFFDAwE6BgYDnRQIHyIZYE4OpFEUABRTBigAGXkN4EDgAQAAoAHIABEAHkBTKWAhogbq4EUKaABpcAmgBKXByDcXBgEY-NIDIGBcCeEqDr5Nq8g6mBOGwVleqCR6rBiABJRRpoSrSdKm3a5lO7x5HSHbrrgfaTv08Ugku6RbqhzhuSKWA+ggErUfJYpMextG8axuAQbh-NwZ2qbuTyFkAEEixaeRoHQKbcGhfEcBh0H828BHcHrAaBFu9IJhZUn1x5mA+YqNbFGF0WSe58UUe6vqBtgYbRphSaprS-rii2nb9sO46lclmWSrl8hcA6KZxcliWKYmgBCAXxq5smJe8aQcZpuB6ZYpmyD2+2vfzABfM3vHD4Go5gH3Vf1jWRvgbXpsICA-eKcbDb2g6jthsPxTdoXrdtxXPcln3kWpumGZgIP0BDuOY9Dh345wLqeqTmBNdT8b08zlkgjqAbc+Ngu4+8Ev5eIMWp4biGJot9aPaLqvO9r-368b5vK-FSP95gVuzcPiWz4j2OxSqqQGvkJrTmq6RThATaQAgJrG+QUByVBNgAAVcZkGQCACYbBKToFfiALo5kwBfC0oqYaMJkAiznnAN+MC6hwNZJpbkfgoDYGQOXN+cBCAhh6utQaDRsB5DqC9AAYtZdo0JCEoDqL0CAUC6AkAAOo0HkPAdAeC4CaQQOgAR8hzCeRAWAdAkC37QhZAIGA-9zLYGaCghWb8ABW6B8CaRYUEAAinkCA8BNFoLfmjJRIDuHECgQwTosAeFKBUMgYCYgrGghZDw8yDAQGOOmONAaUCACOpj4CqI-pAth6BwQwnWutKBRRwn+DgKouhGikCoJZG-FkhB5BEIEFMPJhi4AmLMXACxuSQB+S6C47EyARBv2clkFhZRCBZJANMc0UC-YmTqF0GJOT0EgEwFML6KJiiaTvk1emihtIxCCNUuA4dw5AA) ```sh # Options (if any): --parser html ``` **Input:** ```html <svg xmlns="http://www.w3.org/2000/svg" width="240" height="240" viewBox="0 0 24 24"> <script> document.addEventListener('DOMContentLoaded', () => { const node = document.getElementById('lastStroke'); if (node) { let svg = node.parentNode.parentNode.parentNode; if ('pauseAnimations' in svg) { let hover = false; let loaded = false; node.addEventListener('endEvent', () => { loaded = true; if (!hover) { svg.pauseAnimations(); } }); svg.addEventListener('mouseenter', () => { hover = true; svg.unpauseAnimations(); }); svg.addEventListener('mouseleave', () => { hover = false; if (loaded) { svg.pauseAnimations(); } }); } } }); </script> </svg> ``` **Output:** ```svg <svg xmlns="http://www.w3.org/2000/svg" width="240" height="240" viewBox="0 0 24 24" > <script> document.addEventListener('DOMContentLoaded', () => { const node = document.getElementById('lastStroke'); if (node) { let svg = node.parentNode.parentNode.parentNode; if ('pauseAnimations' in svg) { let hover = false; let loaded = false; node.addEventListener('endEvent', () => { loaded = true; if (!hover) { svg.pauseAnimations(); } }); svg.addEventListener('mouseenter', () => { hover = true; svg.unpauseAnimations(); }); svg.addEventListener('mouseleave', () => { hover = false; if (loaded) { svg.pauseAnimations(); } }); } } }); </script> </svg> ``` **Expected behavior:** Expected output to be readable. There is no special parser for SVG, so using HTML parser to format it. However, something weird happens when there is a script inside SVG and Prettier turns it into unreadable mess.
"2023-02-22T12:55:33Z"
3.0
[ "tests/format/html/svg/jsfmt.spec.js" ]
[ "tests/format/html/svg/embeded/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAzgNwOYAIAeAtgDZToC8AOiABYwwAOSA9MwO4cB0bAzJxACdszAEwAGCcyzZquNgEsAJjBpUQIgCxjZNOPOx01m7SFyZ5cNgCEI+NWNwPNuTdQB8lKJRiow8gWDEcLhgdtQAjCKyYACeajxRpgJqAGyyAGbyxMRqYACuAgIIMADCEMSC7p7e3qgAhlDyhHXwuC0wAvIARnnwAHJ1hHC5MbKYdcR5cBTUCQDckbKKBfacKegZWTnU6UVwAF5wssweXj7MfgFBp7V4mdlqUNBHpugdEADWw9T5hcVlFQEsjeAk+cAAtMR5FA4GA6gw1KC8lBFMD3l9wQplKpqIlcCCweDFHV0DQ6oU6nFcWjQRjiaSIOl0ug4DAjFUzrUGC0aLhFGoALIOEw3GA1HwNJotYLtTo9fqDb4gVGmcaTaaCyK4cIATkw4QFuu1IhoBq1AFZMOCDebjTRrXNDSIXOF9QKROE7WbnTwrQaeHbrbIunBsNDVgB2DamZbJahiTgiaO4e7bEC7OAHF64E7VMX5+qNZqtWXdXpwAZDNQEukkmiM5mssYTKYzdRzEy4ENhqCR5Ox1ZJzYPHZ7Q7HUW1ZjclSTnwz3n86hCxwc8W1SXFmX0OXlytKlVmFsa5fhCPaiPEBO26+G8+X6+4cG3+-EZ+cW3v80C89nt+P69HXCAAOD9tVA80rzA28QLA80Pygz9b3g20UP-MCvwFFDwIQr9HA-YNQ3DeNOB1fsVhIodTFTNQMyzCc83FQspRLHcywVKtqBrCF6XrJkWTFVVjzbEQO0IntVjIpYKJABMqJTLZaLHbMlDUYgSRgABldFs1zTlzgXOdmK3AAVAQGnQdJBEINo2PlCtFTUDoLKsgRCFkGAYgYJVQRgaVm3VNsHC1SI5h4FJgudRZTG7YiQHUt5tNpOBOAQQ8B1mMRkyKbyWjKZE2WoaFFDgTJGngBizlQZhsFFDAwE6BgYDnRQIHyIZYE4OpFEUABRTBigAGXkN4EDgAQAAoAHIABEAHkBTKWAhogbq4EUKaABpcAmgBKXByDcXBgEY-NIDIGBcCeEqDr5Nq8g6mBOGwVleqCR6rBiABJRRpoSrSdKm3a5lO7x5HSHbrrgfaTv08Ugku6RbqhzhuSKWA+ggErUfJYpMextG8axuAQbh-NwZ2qbuTyFkAEEixaeRoHQKbcGhfEcBh0H828BHcHrAaBFu9IJhZUn1x5mA+YqNbFGF0WSe58UUe6vqBtgYbRphSaprS-rii2nb9sO46lclmWSrl8hcA6KZxcliWKYmgBCAXxq5smJe8aQcZpuB6ZYpmyD2+2vfzABfM3vHD4Go5gH3Vf1jWRvgbXpsICA-eKcbDb2g6jthsPxTdoXrdtxXPcln3kWpumGZgIP0BDuOY9Dh345wLqeqTmBNdT8b08zlkgjqAbc+Ngu4+8Ev5eIMWp4biGJot9aPaLqvO9r-368b5vK-FSP95gVuzcPiWz4j2OxSqqQGvkJrTmq6RThATaQAgJrG+QUByVBNgAAVcZkGQCACYbBKToFfiALo5kwBfC0oqYaMJkAiznnAN+MC6hwNZJpbkfgoDYGQOXN+cBCAhh6utQaDRsB5DqC9AAYtZdo0JCEoDqL0CAUC6AkAAOo0HkPAdAeC4CaQQOgAR8hzCeRAWAdAkC37QhZAIGA-9zLYGaCghWb8ABW6B8CaRYUEAAinkCA8BNFoLfmjJRIDuHECgQwTosAeFKBUMgYCYgrGghZDw8yDAQGOOmONAaUCACOpj4CqI-pAth6BwQwnWutKBRRwn+DgKouhGikCoJZG-FkhB5BEIEFMPJhi4AmLMXACxuSQB+S6C47EyARBv2clkFhZRCBZJANMc0UC-YmTqF0GJOT0EgEwFML6KJiiaTvk1emihtIxCCNUuA4dw5AA", "https://prettier.io/playground" ]
prettier/prettier
14,402
prettier__prettier-14402
[ "5666" ]
b5210fd392da98d099eeb978380e5452819a7c26
diff --git a/src/language-js/print/function-parameters.js b/src/language-js/print/function-parameters.js --- a/src/language-js/print/function-parameters.js +++ b/src/language-js/print/function-parameters.js @@ -279,8 +279,17 @@ function isDecoratedFunction(path) { ); } +function shouldBreakFunctionParameters(functionNode) { + const parameters = getFunctionParameters(functionNode); + return ( + parameters.length > 1 && + parameters.some((parameter) => parameter.type === "TSParameterProperty") + ); +} + export { printFunctionParameters, shouldHugTheOnlyFunctionParameter, shouldGroupFunctionParameters, + shouldBreakFunctionParameters, }; diff --git a/src/language-js/print/function.js b/src/language-js/print/function.js --- a/src/language-js/print/function.js +++ b/src/language-js/print/function.js @@ -41,6 +41,7 @@ import { locEnd } from "../loc.js"; import { printFunctionParameters, shouldGroupFunctionParameters, + shouldBreakFunctionParameters, } from "./function-parameters.js"; import { printPropertyKey } from "./property.js"; import { printFunctionTypeParameters, printDeclareToken } from "./misc.js"; @@ -171,6 +172,7 @@ function printMethodValue(path, options, print) { const { node } = path; const parametersDoc = printFunctionParameters(path, print, options); const returnTypeDoc = printReturnType(path, print); + const shouldBreakParameters = shouldBreakFunctionParameters(node); const shouldGroupParameters = shouldGroupFunctionParameters( node, returnTypeDoc @@ -178,7 +180,11 @@ function printMethodValue(path, options, print) { const parts = [ printFunctionTypeParameters(path, options, print), group([ - shouldGroupParameters ? group(parametersDoc) : parametersDoc, + shouldBreakParameters + ? group(parametersDoc, { shouldBreak: true }) + : shouldGroupParameters + ? group(parametersDoc) + : parametersDoc, returnTypeDoc, ]), ];
diff --git a/tests/format/misc/errors/typescript/modifiers/__snapshots__/jsfmt.spec.js.snap b/tests/format/misc/errors/typescript/modifiers/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/misc/errors/typescript/modifiers/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/misc/errors/typescript/modifiers/__snapshots__/jsfmt.spec.js.snap @@ -2213,174 +2213,222 @@ exports[`snippet: #163 [typescript] format 1`] = ` `; exports[`snippet: #164 [babel-ts] format 1`] = ` +"A parameter property is only allowed in a constructor implementation. (1:28) +> 1 | class Foo {["constructor"](private parameter) {}} + | ^" +`; + +exports[`snippet: #164 [typescript] format 1`] = ` +"A parameter property is only allowed in a constructor implementation. (1:28) +> 1 | class Foo {["constructor"](private parameter) {}} + | ^^^^^^^" +`; + +exports[`snippet: #165 [babel-ts] format 1`] = ` +"A parameter property is only allowed in a constructor implementation. (1:28) +> 1 | class Foo {['constructor'](private parameter) {}} + | ^" +`; + +exports[`snippet: #165 [typescript] format 1`] = ` +"A parameter property is only allowed in a constructor implementation. (1:28) +> 1 | class Foo {['constructor'](private parameter) {}} + | ^^^^^^^" +`; + +exports[`snippet: #166 [babel-ts] format 1`] = ` +"A parameter property is only allowed in a constructor implementation. (1:28) +> 1 | class Foo {[\`constructor\`](private parameter) {}} + | ^" +`; + +exports[`snippet: #166 [typescript] format 1`] = ` +"A parameter property is only allowed in a constructor implementation. (1:28) +> 1 | class Foo {[\`constructor\`](private parameter) {}} + | ^^^^^^^" +`; + +exports[`snippet: #167 [babel-ts] format 1`] = ` +"A parameter property is only allowed in a constructor implementation. (1:33) +> 1 | class Foo {['const' + 'ructor'](private parameter) {}} + | ^" +`; + +exports[`snippet: #167 [typescript] format 1`] = ` +"A parameter property is only allowed in a constructor implementation. (1:33) +> 1 | class Foo {['const' + 'ructor'](private parameter) {}} + | ^^^^^^^" +`; + +exports[`snippet: #168 [babel-ts] format 1`] = ` "'abstract' modifier cannot appear on a type member. (1:13) > 1 | type Foo = {abstract bar}; | ^" `; -exports[`snippet: #164 [typescript] format 1`] = ` +exports[`snippet: #168 [typescript] format 1`] = ` "'abstract' modifier cannot appear on a type member (1:13) > 1 | type Foo = {abstract bar}; | ^^^^^^^^" `; -exports[`snippet: #165 [babel-ts] format 1`] = ` +exports[`snippet: #169 [babel-ts] format 1`] = ` "Unexpected token, expected ";" (1:22) > 1 | type Foo = {accessor bar}; | ^" `; -exports[`snippet: #165 [typescript] format 1`] = ` +exports[`snippet: #169 [typescript] format 1`] = ` "'accessor' modifier cannot appear on a type member (1:13) > 1 | type Foo = {accessor bar}; | ^^^^^^^^" `; -exports[`snippet: #166 [babel-ts] format 1`] = ` +exports[`snippet: #170 [babel-ts] format 1`] = ` "Unexpected token, expected ";" (1:19) > 1 | type Foo = {async bar}; | ^" `; -exports[`snippet: #166 [typescript] format 1`] = ` +exports[`snippet: #170 [typescript] format 1`] = ` "'async' modifier cannot appear on a type member (1:13) > 1 | type Foo = {async bar}; | ^^^^^" `; -exports[`snippet: #167 [babel-ts] format 1`] = ` +exports[`snippet: #171 [babel-ts] format 1`] = ` "Unexpected token, expected ";" (1:19) > 1 | type Foo = {const bar}; | ^" `; -exports[`snippet: #167 [typescript] format 1`] = ` +exports[`snippet: #171 [typescript] format 1`] = ` "';' expected. (1:19) > 1 | type Foo = {const bar}; | ^" `; -exports[`snippet: #168 [babel-ts] format 1`] = ` +exports[`snippet: #172 [babel-ts] format 1`] = ` "'declare' modifier cannot appear on a type member. (1:13) > 1 | type Foo = {declare bar}; | ^" `; -exports[`snippet: #168 [typescript] format 1`] = ` +exports[`snippet: #172 [typescript] format 1`] = ` "'declare' modifier cannot appear on a type member (1:13) > 1 | type Foo = {declare bar}; | ^^^^^^^" `; -exports[`snippet: #169 [babel-ts] format 1`] = ` +exports[`snippet: #173 [babel-ts] format 1`] = ` "Unexpected token, expected ";" (1:21) > 1 | type Foo = {default bar}; | ^" `; -exports[`snippet: #169 [typescript] format 1`] = ` +exports[`snippet: #173 [typescript] format 1`] = ` "';' expected. (1:21) > 1 | type Foo = {default bar}; | ^" `; -exports[`snippet: #170 [babel-ts] format 1`] = ` +exports[`snippet: #174 [babel-ts] format 1`] = ` "Unexpected token, expected ";" (1:20) > 1 | type Foo = {export bar}; | ^" `; -exports[`snippet: #170 [typescript] format 1`] = ` +exports[`snippet: #174 [typescript] format 1`] = ` "'export' modifier cannot appear on a type member (1:13) > 1 | type Foo = {export bar}; | ^^^^^^" `; -exports[`snippet: #171 [babel-ts] format 1`] = ` +exports[`snippet: #175 [babel-ts] format 1`] = ` "Unexpected token, expected ";" (1:16) > 1 | type Foo = {in bar}; | ^" `; -exports[`snippet: #171 [typescript] format 1`] = ` +exports[`snippet: #175 [typescript] format 1`] = ` "'in' modifier cannot appear on a type member (1:13) > 1 | type Foo = {in bar}; | ^^" `; -exports[`snippet: #172 [babel-ts] format 1`] = ` +exports[`snippet: #176 [babel-ts] format 1`] = ` "Unexpected token, expected ";" (1:17) > 1 | type Foo = {out bar}; | ^" `; -exports[`snippet: #172 [typescript] format 1`] = ` +exports[`snippet: #176 [typescript] format 1`] = ` "'out' modifier cannot appear on a type member (1:13) > 1 | type Foo = {out bar}; | ^^^" `; -exports[`snippet: #173 [babel-ts] format 1`] = ` +exports[`snippet: #177 [babel-ts] format 1`] = ` "'override' modifier cannot appear on a type member. (1:13) > 1 | type Foo = {override bar}; | ^" `; -exports[`snippet: #173 [typescript] format 1`] = ` +exports[`snippet: #177 [typescript] format 1`] = ` "'override' modifier cannot appear on a type member (1:13) > 1 | type Foo = {override bar}; | ^^^^^^^^" `; -exports[`snippet: #174 [babel-ts] format 1`] = ` +exports[`snippet: #178 [babel-ts] format 1`] = ` "'private' modifier cannot appear on a type member. (1:13) > 1 | type Foo = {private bar}; | ^" `; -exports[`snippet: #174 [typescript] format 1`] = ` +exports[`snippet: #178 [typescript] format 1`] = ` "'private' modifier cannot appear on a type member (1:13) > 1 | type Foo = {private bar}; | ^^^^^^^" `; -exports[`snippet: #175 [babel-ts] format 1`] = ` +exports[`snippet: #179 [babel-ts] format 1`] = ` "'protected' modifier cannot appear on a type member. (1:13) > 1 | type Foo = {protected bar}; | ^" `; -exports[`snippet: #175 [typescript] format 1`] = ` +exports[`snippet: #179 [typescript] format 1`] = ` "'protected' modifier cannot appear on a type member (1:13) > 1 | type Foo = {protected bar}; | ^^^^^^^^^" `; -exports[`snippet: #176 [babel-ts] format 1`] = ` +exports[`snippet: #180 [babel-ts] format 1`] = ` "'public' modifier cannot appear on a type member. (1:13) > 1 | type Foo = {public bar}; | ^" `; -exports[`snippet: #176 [typescript] format 1`] = ` +exports[`snippet: #180 [typescript] format 1`] = ` "'public' modifier cannot appear on a type member (1:13) > 1 | type Foo = {public bar}; | ^^^^^^" `; -exports[`snippet: #177 [babel-ts] format 1`] = ` +exports[`snippet: #181 [babel-ts] format 1`] = ` "'static' modifier cannot appear on a type member. (1:13) > 1 | type Foo = {static bar}; | ^" `; -exports[`snippet: #177 [typescript] format 1`] = ` +exports[`snippet: #181 [typescript] format 1`] = ` "'static' modifier cannot appear on a type member (1:13) > 1 | type Foo = {static bar}; | ^^^^^^" `; -exports[`snippet: #178 [babel-ts] format 1`] = ` +exports[`snippet: #182 [babel-ts] format 1`] = ` "Index signatures cannot have the 'declare' modifier. (2:3) 1 | class Foo { > 2 | declare [index: string]: number @@ -2388,7 +2436,7 @@ exports[`snippet: #178 [babel-ts] format 1`] = ` 3 | }" `; -exports[`snippet: #178 [typescript] format 1`] = ` +exports[`snippet: #182 [typescript] format 1`] = ` "'declare' modifier cannot appear on an index signature (2:3) 1 | class Foo { > 2 | declare [index: string]: number diff --git a/tests/format/misc/errors/typescript/modifiers/jsfmt.spec.js b/tests/format/misc/errors/typescript/modifiers/jsfmt.spec.js --- a/tests/format/misc/errors/typescript/modifiers/jsfmt.spec.js +++ b/tests/format/misc/errors/typescript/modifiers/jsfmt.spec.js @@ -103,6 +103,11 @@ run_spec( ).map( (modifier) => `class Foo { constructor(${modifier} parameter) {} }` ), + 'class Foo {["constructor"](private parameter) {}}', + "class Foo {['constructor'](private parameter) {}}", + "class Foo {[`constructor`](private parameter) {}}", + // cspell:disable-next-line + "class Foo {['const' + 'ructor'](private parameter) {}}", // `TSPropertySignature` ...POSSIBLE_MODIFIERS.filter((modifier) => modifier !== "readonly").map( diff --git a/tests/format/typescript/class/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/class/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/typescript/class/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/typescript/class/__snapshots__/jsfmt.spec.js.snap @@ -450,6 +450,65 @@ class A { ================================================================================ `; +exports[`parameter-properties.ts format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +class MyClass { + constructor(protected x: number, private y: string) { + } +} + +[ + class { + "constructor"(protected x: number, private y: string) { + } + }, +] + +class Mixed { + constructor(public a: number, b: unknown) { + } +} + +class OneParameterProperty { + constructor(public foobar: boolean) { + } +} + +=====================================output===================================== +class MyClass { + constructor( + protected x: number, + private y: string, + ) {} +} + +[ + class { + constructor( + protected x: number, + private y: string, + ) {} + }, +]; + +class Mixed { + constructor( + public a: number, + b: unknown, + ) {} +} + +class OneParameterProperty { + constructor(public foobar: boolean) {} +} + +================================================================================ +`; + exports[`quoted-property.ts format 1`] = ` ====================================options===================================== parsers: ["typescript"] diff --git a/tests/format/typescript/class/parameter-properties.ts b/tests/format/typescript/class/parameter-properties.ts new file mode 100644 --- /dev/null +++ b/tests/format/typescript/class/parameter-properties.ts @@ -0,0 +1,21 @@ +class MyClass { + constructor(protected x: number, private y: string) { + } +} + +[ + class { + "constructor"(protected x: number, private y: string) { + } + }, +] + +class Mixed { + constructor(public a: number, b: unknown) { + } +} + +class OneParameterProperty { + constructor(public foobar: boolean) { + } +} diff --git a/tests/format/typescript/conformance/classes/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/conformance/classes/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/typescript/conformance/classes/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/typescript/conformance/classes/__snapshots__/jsfmt.spec.js.snap @@ -348,11 +348,18 @@ class Thing3 extends Thing2 { type Constructor<T> = new (...args: any[]) => T; class Base { - constructor(public x: number, public y: number) {} + constructor( + public x: number, + public y: number, + ) {} } class Derived extends Base { - constructor(x: number, y: number, public z: number) { + constructor( + x: number, + y: number, + public z: number, + ) { super(x, y); } } @@ -485,11 +492,18 @@ const Timestamped = <CT extends Constructor<object>>(Base: CT) => { type Constructor<T> = new (...args: any[]) => T; class Base { - constructor(public x: number, public y: number) {} + constructor( + public x: number, + public y: number, + ) {} } class Derived extends Base { - constructor(x: number, y: number, public z: number) { + constructor( + x: number, + y: number, + public z: number, + ) { super(x, y); } } diff --git a/tests/format/typescript/conformance/classes/constructorDeclarations/constructorParameters/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/conformance/classes/constructorDeclarations/constructorParameters/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/typescript/conformance/classes/constructorDeclarations/constructorParameters/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/typescript/conformance/classes/constructorDeclarations/constructorParameters/__snapshots__/jsfmt.spec.js.snap @@ -120,7 +120,10 @@ class C { class D<T, U> { constructor(x: T, y: U); - constructor(x: T = 1, public y: U = x) { + constructor( + x: T = 1, + public y: U = x, + ) { var z = x; } } @@ -235,7 +238,10 @@ var r4 = d.z; // error =====================================output===================================== class C { y: string; - constructor(private x: string, protected z: string) {} + constructor( + private x: string, + protected z: string, + ) {} } var c: C; @@ -245,7 +251,11 @@ var r3 = c.z; // error class D<T> { y: T; - constructor(a: T, private x: T, protected z: T) {} + constructor( + a: T, + private x: T, + protected z: T, + ) {} } var d: D<string>; diff --git a/tests/format/typescript/conformance/internalModules/importDeclarations/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/conformance/internalModules/importDeclarations/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/typescript/conformance/internalModules/importDeclarations/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/typescript/conformance/internalModules/importDeclarations/__snapshots__/jsfmt.spec.js.snap @@ -128,7 +128,10 @@ var p: M.D.Point; module A { export var x = "hello world"; export class Point { - constructor(public x: number, public y: number) {} + constructor( + public x: number, + public y: number, + ) {} } export module B { export interface Id { @@ -153,7 +156,10 @@ module X { export module Y { export class Point { - constructor(public x: number, public y: number) {} + constructor( + public x: number, + public y: number, + ) {} } } } @@ -261,7 +267,10 @@ var p: { x: number; y: number; }; =====================================output===================================== module moduleA { export class Point { - constructor(public x: number, public y: number) {} + constructor( + public x: number, + public y: number, + ) {} } }
TypeScript constructor assignment improvement. **Prettier 1.15.3** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEcAeAHCAnGACMAGwEMBnUvAFTlJgGETy9gAdKPA6W7AVzBhwAKNhw4ZsASwBuxeHmIYJSPAEFFAZTjYpEsHAA0I0eOmy4nKADMJAc2V1o1m5u264RgJTMAvm28h9EAgMGAkuZFBibGwIAHcABSiEUmQQYikICQATAJAAI2xiMABrOBh1DCKJKBtkGF4DEAALGABbQgB1Jol4Ukq9TShSHukegE9UsHJc6tItGHjCm1biZEtiQjnAgCtSNAAhQpKy9WJWuAAZarg1ja2QXbR1aptCOABFHgh4W83Gyuwc2wqRgYwwNDAkhCuRMsA62RgTWQAA4AAyBcQQOYdQoYVLiGhaKQ3QLYOAARx4EjJi2Iy1WSHWf0Cc1aEjqDRZLzen2+N0Zd0aMGIeXhWURyAATIF6sQJIQXg5WitUlBoCSQDw5pQRSkBX9vN4gA) ```sh --parser typescript ``` **Input:** ```tsx export class TestClass { constructor( private api: ApiService, private config: ConfigService ) {} } ``` **Output:** ```tsx export class TestClass { constructor(private api: ApiService, private config: ConfigService) {} } ``` **Expected behavior:** Consider breaking line despite `printWidth` value (as input). Since it visually should be close to: ```tsx export class TestClass { private api: ApiService; private config: ConfigService; } ``` and not: ```tsx export class TestClass { private api: ApiService; private config: ConfigService; } ```
Is there any direct relation between "class properties" and "constructor arguments" in TypeScript? I don't use TypeScript so I really don't know. I'm aware that sometimes in constructor you want to do: ```js constructor(foo, bar) { this.foo = foo; this.bar = bar; } ``` But if this works like JS, and there's no direct relation between the arguments and the class properties, then I see no reason why it should be visually close to class properties, and no reason we should special case `constructor`. It's a TypeScript-specific feature called [parameter property](https://www.typescriptlang.org/docs/handbook/classes.html#parameter-properties). I think we should not treat it differently since it can be used with normal parameter simultaneously: ```ts export class TestClass { constructor( private api: ApiService, something: any, private config: ConfigService ) {} } ``` Oh cool I didn't know.. in that case, we can discuss if it makes sense to add this, but I agree with @ikatyang we should not treat it differently. > I think we should not treat it differently since it can be used with normal parameter simultaneously Good point. I would love to see this added -- anytime a parameter property is used multi-line the whole ctor. This makes features like reference code lens in vscode better: ![image](https://user-images.githubusercontent.com/641685/52997435-82ba6f00-33ee-11e9-8faf-e88cd92b0245.png) Any way this could be re-opened? @eamodio Can you provide a screenshot showing the vscode lens thing not working? ![image](https://user-images.githubusercontent.com/641685/53004012-3d9e3900-33fe-11e9-8400-b7f2225a7885.png) They still work, but it is much clearer if they are each on their own line. @lydell is this something that can be reconsidered and re-opened? I’m familiar with the code that would have to change to do this and could work on this issue this weekend, but I’m not sure if there’s consensus to implement this yet? Personally, as an avid typescript user I think putting parameter properties on their own lines (even if there are non-property parameters in between) is a good idea. I would love to have this introduced, this would make the code much easier to read. This format that Prettier is applying now is making it very hard to understand that there are multiple class properties defined there, making this Typescript feature much less apealing: ``` export class TestClass { constructor(private api: ApiService, private config: ConfigService, autoConnect: boolean) {} } // vs export class TestClass { constructor( private api: ApiService, private config: ConfigService, autoConnect: boolean ) {} } ``` I suggest introducing this feature as a new option. ``` --typescript-parameter-prop-multi-line <never|allways|preserve> > never (default) - working as today > allways - apply multi line format every time there's at least one parameter property > preserve - keep existing format decision ``` Thanks! That's why prettier should have more options in configuration. This formatting rule is a deal-breaker to me, as an Angular developer. Having this in one file ```ts constructor(private form: NgForm, private ngbModal: NgbModal, private commonDialogsService: CommonDialogsService) {} ``` but this in another file ``` constructor( private title: Title, private form: NgForm, private ngbModal: NgbModal, private commonDialogsService: CommonDialogsService, ) {} ``` is just not acceptable. It's inconsistent, it's hard to scan, it makes the code harder to understand. I think that putting each constructor parameter on their own line if there are any parameter properties helps a lot with code readability. In addition to helping with code readability, it helps avoid merge conflicts and reduce diff sizes in line-based version control. I think it would be an improvement to Prettier to change this without adding an additional configuration option. ```typescript constructor(foo: string, private bar: number) {} ``` would change to ```typescript constructor( foo: string, private bar: number, ) {} ``` An alternative approach to a unilateral change or a new configuration variable is to honor whether someone has entered a trailing comma in their constructor parameter list, then people could opt-in to multi-line constructor parameters by writing ```typescript constructor(foo: string, private bar: number,) {} ``` I think that this should be a configuration option for typescript. We've decided internally to currently force it by putting in a trailing comment after the first parameter as below but preference would be just to have config we can turn on that would do this for us. ``` constructor( public foo: string, // private bar: number, ) {} ``` The most elegant solution to this, until there is a specific rule in place, is to add the `// prettier-ignore` trigger before the constructor. The empty comment, `//`, solution doesn't let other developers know what it's doing. I believe that there should be a constructor specific rule. In Angular and because of dependency injection, the constructor tends to have more than normal amounts of parameters. Bump - would love this to be resolved! It's definitely annoying as is. Let's do this when at least one parameter is a parameter property. Bumping this. It's not just annoying, it's a deal-breaker for working in any serious Angular project. Not only is it unclear to read, but it also create tons of avoidable merge conflicts. Any update on this? Or solution that it's not a patch like `//`? Thanks! For me it's unbelievable this issue is 4yrs old and no one did it. Hi! Me and two classmates was gonna work on this issue for our masters class at Uni. We have tried to replicate the problem and found that prettier puts the parameters on different lines based on characters per line and not the amount of parameters. If you have any helpful input or advice we are all ears, thanks!
"2023-02-22T14:16:24Z"
3.0
[ "tests/format/misc/errors/typescript/modifiers/jsfmt.spec.js" ]
[ "tests/format/typescript/conformance/classes/constructorDeclarations/constructorParameters/jsfmt.spec.js", "tests/format/typescript/class/jsfmt.spec.js", "tests/format/typescript/conformance/internalModules/importDeclarations/jsfmt.spec.js", "tests/format/typescript/conformance/classes/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEcAeAHCAnGACMAGwEMBnUvAFTlJgGETy9gAdKPA6W7AVzBhwAKNhw4ZsASwBuxeHmIYJSPAEFFAZTjYpEsHAA0I0eOmy4nKADMJAc2V1o1m5u264RgJTMAvm28h9EAgMGAkuZFBibGwIAHcABSiEUmQQYikICQATAJAAI2xiMABrOBh1DCKJKBtkGF4DEAALGABbQgB1Jol4Ukq9TShSHukegE9UsHJc6tItGHjCm1biZEtiQjnAgCtSNAAhQpKy9WJWuAAZarg1ja2QXbR1aptCOABFHgh4W83Gyuwc2wqRgYwwNDAkhCuRMsA62RgTWQAA4AAyBcQQOYdQoYVLiGhaKQ3QLYOAARx4EjJi2Iy1WSHWf0Cc1aEjqDRZLzen2+N0Zd0aMGIeXhWURyAATIF6sQJIQXg5WitUlBoCSQDw5pQRSkBX9vN4gA" ]
prettier/prettier
14,476
prettier__prettier-14476
[ "14237", "14237" ]
992ed5b572e9438cc4b45ea939b8931905ee46d6
diff --git a/src/language-css/parse/parse-value.js b/src/language-css/parse/parse-value.js --- a/src/language-css/parse/parse-value.js +++ b/src/language-css/parse/parse-value.js @@ -1,18 +1,12 @@ import PostcssValuesParser from "postcss-values-parser/lib/parser.js"; +import getFunctionArgumentsText from "../utils/get-function-arguments-text.js"; +import getValueRoot from "../utils/get-value-root.js"; import hasSCSSInterpolation from "../utils/has-scss-interpolation.js"; import hasStringOrFunction from "../utils/has-string-or-function.js"; import isSCSSVariable from "../utils/is-scss-variable.js"; -import stringifyNode from "../utils/stringify-node.js"; import parseSelector from "./parse-selector.js"; import { addTypePrefix } from "./utils.js"; -const getHighestAncestor = (node) => { - while (node.parent) { - node = node.parent; - } - return node; -}; - function parseValueNode(valueNode, options) { const { nodes } = valueNode; let parenGroup = { @@ -48,7 +42,7 @@ function parseValueNode(valueNode, options) { if (node.type === "func" && node.value === "selector") { node.group.groups = [ parseSelector( - getHighestAncestor(valueNode).text.slice( + getValueRoot(valueNode).text.slice( node.group.open.sourceIndex + 1, node.group.close.sourceIndex ) @@ -76,10 +70,7 @@ function parseValueNode(valueNode, options) { (!hasStringOrFunction(groupList) && !isSCSSVariable(groupList[0], options)) ) { - const stringifiedContent = stringifyNode({ - groups: node.group.groups, - }); - node.group.groups = [stringifiedContent.trim()]; + node.group.groups = [getFunctionArgumentsText(node)]; } } if (node.type === "paren" && node.value === "(") { @@ -162,7 +153,6 @@ function parseNestedValue(node, options) { } } } - delete node.parent; } return node; } diff --git a/src/language-css/utils/get-function-arguments-text.js b/src/language-css/utils/get-function-arguments-text.js new file mode 100644 --- /dev/null +++ b/src/language-css/utils/get-function-arguments-text.js @@ -0,0 +1,13 @@ +import getValueRoot from "./get-value-root.js"; + +/** + * @param {*} node + * @returns {string} + */ +function getFunctionArgumentsText(node) { + return getValueRoot(node) + .text.slice(node.group.open.sourceIndex + 1, node.group.close.sourceIndex) + .trim(); +} + +export default getFunctionArgumentsText; diff --git a/src/language-css/utils/get-value-root.js b/src/language-css/utils/get-value-root.js new file mode 100644 --- /dev/null +++ b/src/language-css/utils/get-value-root.js @@ -0,0 +1,9 @@ +const getValueRoot = (node) => { + while (node.parent) { + node = node.parent; + } + + return node; +}; + +export default getValueRoot; diff --git a/src/language-css/utils/has-string-or-function.js b/src/language-css/utils/has-string-or-function.js --- a/src/language-css/utils/has-string-or-function.js +++ b/src/language-css/utils/has-string-or-function.js @@ -1,6 +1,10 @@ function hasStringOrFunction(groupList) { return groupList.some( - (group) => group.type === "string" || group.type === "func" + (group) => + group.type === "string" || + (group.type === "func" && + // workaround false-positive func + !group.value.endsWith("\\")) ); }
diff --git a/tests/format/css/url/__snapshots__/jsfmt.spec.js.snap b/tests/format/css/url/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/css/url/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/css/url/__snapshots__/jsfmt.spec.js.snap @@ -11,11 +11,63 @@ div { background: -fb-url(/images/bg.png); } +@font-face { + src: url(RobotoFlex-VariableFont_GRAD,XTRA,YOPQ,YTAS,YTDE,YTFI,YTLC,YTUC,opsz,slnt,wdth,wght.ttf); + src: url(foo.ttf?query=foo,bar,); + src: url(foo.woff2?foo=rgb\\(255,255,0\\)); +} + +a { + content: url(https://example.com/\\)\\).jpg); + content: url(https://example.com/\\(\\(.jpg); + content: url(https://example.com/\\ \\ .jpg); + content: url( https://example.com/\\)\\).jpg ); + content: url( https://example.com/\\(\\(.jpg ); + content: url( https://example.com/\\ \\ .jpg ); + + background: + no-repeat url(https://example.com/\\)\\).jpg), + no-repeat url(https://example.com/\\(\\(.jpg), + no-repeat url(https://example.com/\\ \\ .jpg), + no-repeat url( https://example.com/\\)\\).jpg ), + no-repeat url( https://example.com/\\(\\(.jpg ), + no-repeat url( https://example.com/\\ \\ .jpg ), + no-repeat url(foo.ttf?query=foo,bar,), + no-repeat url(foo.woff2?foo=rgb\\(255,255,0\\)) + no-repeat url(RobotoFlex-VariableFont_GRAD,XTRA,YOPQ,YTAS,YTDE,YTFI,YTLC,YTUC,opsz,slnt,wdth,wght.ttf); + ; +} + =====================================output===================================== div { background: url(/images/bg.png); background: -fb-url(/images/bg.png); } +@font-face { + src: url(RobotoFlex-VariableFont_GRAD,XTRA,YOPQ,YTAS,YTDE,YTFI,YTLC,YTUC,opsz,slnt,wdth,wght.ttf); + src: url(foo.ttf?query=foo,bar,); + src: url(foo.woff2?foo=rgb\\(255,255,0\\)); +} + +a { + content: url(https://example.com/\\)\\).jpg); + content: url(https://example.com/\\(\\(.jpg); + content: url(https://example.com/\\ \\ .jpg); + content: url( https://example.com/\\)\\).jpg ); + content: url( https://example.com/\\(\\(.jpg ); + content: url(https://example.com/\\ \\ .jpg); + + background: no-repeat url(https://example.com/\\)\\).jpg), + no-repeat url(https://example.com/\\(\\(.jpg), + no-repeat url(https://example.com/\\ \\ .jpg), + no-repeat url( https://example.com/\\)\\).jpg ), + no-repeat url( https://example.com/\\(\\(.jpg ), + no-repeat url( https://example.com/\\ \\ .jpg ), + no-repeat url(foo.ttf?query=foo,bar,), + no-repeat url(foo.woff2?foo=rgb\\(255,255,0\\)) + no-repeat url(RobotoFlex-VariableFont_GRAD,XTRA,YOPQ,YTAS,YTDE,YTFI,YTLC,YTUC,opsz,slnt,wdth,wght.ttf); +} + ================================================================================ `; diff --git a/tests/format/css/url/url.css b/tests/format/css/url/url.css --- a/tests/format/css/url/url.css +++ b/tests/format/css/url/url.css @@ -2,3 +2,30 @@ div { background: url(/images/bg.png); background: -fb-url(/images/bg.png); } + +@font-face { + src: url(RobotoFlex-VariableFont_GRAD,XTRA,YOPQ,YTAS,YTDE,YTFI,YTLC,YTUC,opsz,slnt,wdth,wght.ttf); + src: url(foo.ttf?query=foo,bar,); + src: url(foo.woff2?foo=rgb\(255,255,0\)); +} + +a { + content: url(https://example.com/\)\).jpg); + content: url(https://example.com/\(\(.jpg); + content: url(https://example.com/\ \ .jpg); + content: url( https://example.com/\)\).jpg ); + content: url( https://example.com/\(\(.jpg ); + content: url( https://example.com/\ \ .jpg ); + + background: + no-repeat url(https://example.com/\)\).jpg), + no-repeat url(https://example.com/\(\(.jpg), + no-repeat url(https://example.com/\ \ .jpg), + no-repeat url( https://example.com/\)\).jpg ), + no-repeat url( https://example.com/\(\(.jpg ), + no-repeat url( https://example.com/\ \ .jpg ), + no-repeat url(foo.ttf?query=foo,bar,), + no-repeat url(foo.woff2?foo=rgb\(255,255,0\)) + no-repeat url(RobotoFlex-VariableFont_GRAD,XTRA,YOPQ,YTAS,YTDE,YTFI,YTLC,YTUC,opsz,slnt,wdth,wght.ttf); + ; +}
@font-face urls are incorrectly stripped of commas **Prettier 2.8.3** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAzjAngGzgPgB0oACEgAQDNoYBaSgQzDhOGLI4+tnoYFsAljixISAJwgAjANyc58hYqXKVqxewXoxYUQFcxOABQAlKRBgQAYngAetAGoMxAhpLyWaAfQDixgIIAIgA0ABoAKv5BAJoA8gAKAIrRYX4AyskBAKLJlgCSyQAyAMLJAKolEAAO6ABeQeg4sEEA7gAmMAAWLQDmHTAAdDAwlACU0hokAL5yxKgA9Ji4BBMkIEEgVTAC0OjIoE4SzXFOCLsoDDjNDFi765JiTADWcDCp-HAFAlBwyIw46HA7g8wM9XpUmF9usgYGJdICQHA+JI4K1WiiCgwoN1dAxunAPGI+AwhpDkCAGLoLGsQH0+DgAOodATwdDg5ipU7MgQAN2ZWDJYHQtxAXwBYhgcQe3SJvwuAPWACt0DZUpC8AldOYfkg-vKQOCxGKybScNTKs5YPSBO0OsgABwABnW5ogAPpD0qZPNcDF3J+6wAjpr4JKqmdyehaN8USjqWI4EGBPHJbiZTq5fCAYJobDM2q4H4hs5JJS4HE4GJPt9Zf881j1cHtbr4TBXFabcgAEzrGEMISQooQPhphHoACs1N0ALCrjOzfW3LhuSgaNgqTAzkqMD8K9S2DwNYBk0mQA) <!-- prettier-ignore --> ```sh --parser html ``` **Input:** <!-- prettier-ignore --> ```html <style> @font-face { font-family: rob; src: url(RobotoFlex-VariableFont_GRAD,XTRA,YOPQ,YTAS,YTDE,YTFI,YTLC,YTUC,opsz,slnt,wdth,wght.ttf); } </style> ``` **Output:** <!-- prettier-ignore --> ```html <style> @font-face { font-family: rob; src: url(RobotoFlex-VariableFont_GRADXTRAYOPQYTASYTDEYTFIYTLCYTUCopszslntwdthwght.ttf); } </style> ``` **Expected behavior:** Commas in filename should be kept - I don't see why they would be invalid inside a url() CSS function. @font-face urls are incorrectly stripped of commas **Prettier 2.8.3** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAzjAngGzgPgB0oACEgAQDNoYBaSgQzDhOGLI4+tnoYFsAljixISAJwgAjANyc58hYqXKVqxewXoxYUQFcxOABQAlKRBgQAYngAetAGoMxAhpLyWaAfQDixgIIAIgA0ABoAKv5BAJoA8gAKAIrRYX4AyskBAKLJlgCSyQAyAMLJAKolEAAO6ABeQeg4sEEA7gAmMAAWLQDmHTAAdDAwlACU0hokAL5yxKgA9Ji4BBMkIEEgVTAC0OjIoE4SzXFOCLsoDDjNDFi765JiTADWcDCp-HAFAlBwyIw46HA7g8wM9XpUmF9usgYGJdICQHA+JI4K1WiiCgwoN1dAxunAPGI+AwhpDkCAGLoLGsQH0+DgAOodATwdDg5ipU7MgQAN2ZWDJYHQtxAXwBYhgcQe3SJvwuAPWACt0DZUpC8AldOYfkg-vKQOCxGKybScNTKs5YPSBO0OsgABwABnW5ogAPpD0qZPNcDF3J+6wAjpr4JKqmdyehaN8USjqWI4EGBPHJbiZTq5fCAYJobDM2q4H4hs5JJS4HE4GJPt9Zf881j1cHtbr4TBXFabcgAEzrGEMISQooQPhphHoACs1N0ALCrjOzfW3LhuSgaNgqTAzkqMD8K9S2DwNYBk0mQA) <!-- prettier-ignore --> ```sh --parser html ``` **Input:** <!-- prettier-ignore --> ```html <style> @font-face { font-family: rob; src: url(RobotoFlex-VariableFont_GRAD,XTRA,YOPQ,YTAS,YTDE,YTFI,YTLC,YTUC,opsz,slnt,wdth,wght.ttf); } </style> ``` **Output:** <!-- prettier-ignore --> ```html <style> @font-face { font-family: rob; src: url(RobotoFlex-VariableFont_GRADXTRAYOPQYTASYTDEYTFIYTLCYTUCopszslntwdthwght.ttf); } </style> ``` **Expected behavior:** Commas in filename should be kept - I don't see why they would be invalid inside a url() CSS function.
Thank you for reporting this! This is a CSS formatting problem, not for HTML! **Prettier 2.8.3** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEACVABAZtGBaLAQzDlWAB0p1rqdYDCBbASwBsBPJVAJwgCMA3DWEjRY8RMlSxlMQGduYLgFdurABQAlfhBgQAYqzgAPPADVC3ZoT5H9uAPoBxTQEEAIgBoAGgBU3ngCaAPIACgCKQb6uAMpR7gCiUfoAklEAMgDCUQCq2RAADnIAXp5yrLCeAO4AJjAAFtUA5vUwAHQwMFgAlAKy6AC+wv3oIJ4ghTDM0HLIoJa8VaGWCLMohKxVhOyz43zcxADWcDAxTHDpzFBwyESscnB7B2DHpwXEV03IMNzKjyBwRh8OA1Gog9KEKBNZSEJpwezcRiETqfZAgQjKPRjECtRisADq9WY8Dk7xIMVWxOYADdiew0WA5LsQFcHtwYKEDk0kbcNg9xgArOTGGKfIzhZS6G5IO78kDvbhshlM7EFKywfHMOr1ZAADgADOM1RAHviDgU0Wq4GzqTdxgBHSXwTmFNbouR4a4gkHY7hwR3MP2c2E8mV8-4PFjfX4RsVwVydKx8TFwUJwbiXa68+6xqHip3S2X-GA2TXa5AAJnGP0IbE+mQgjFDALkAFZscoHr4bGsi+NqX8UlAwbAYmArAUYK5hzEYOwjNmHgMBkA) <!-- prettier-ignore --> ```sh --parser css ``` **Input:** <!-- prettier-ignore --> ```css @font-face { font-family: rob; src: url(RobotoFlex-VariableFont_GRAD,XTRA,YOPQ,YTAS,YTDE,YTFI,YTLC,YTUC,opsz,slnt,wdth,wght.ttf); } ``` **Output:** <!-- prettier-ignore --> ```css @font-face { font-family: rob; src: url(RobotoFlex-VariableFont_GRADXTRAYOPQYTASYTDEYTFIYTLCYTUCopszslntwdthwght.ttf); } ``` Thank you for reporting this! This is a CSS formatting problem, not for HTML! **Prettier 2.8.3** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEACVABAZtGBaLAQzDlWAB0p1rqdYDCBbASwBsBPJVAJwgCMA3DWEjRY8RMlSxlMQGduYLgFdurABQAlfhBgQAYqzgAPPADVC3ZoT5H9uAPoBxTQEEAIgBoAGgBU3ngCaAPIACgCKQb6uAMpR7gCiUfoAklEAMgDCUQCq2RAADnIAXp5yrLCeAO4AJjAAFtUA5vUwAHQwMFgAlAKy6AC+wv3oIJ4ghTDM0HLIoJa8VaGWCLMohKxVhOyz43zcxADWcDAxTHDpzFBwyESscnB7B2DHpwXEV03IMNzKjyBwRh8OA1Gog9KEKBNZSEJpwezcRiETqfZAgQjKPRjECtRisADq9WY8Dk7xIMVWxOYADdiew0WA5LsQFcHtwYKEDk0kbcNg9xgArOTGGKfIzhZS6G5IO78kDvbhshlM7EFKywfHMOr1ZAADgADOM1RAHviDgU0Wq4GzqTdxgBHSXwTmFNbouR4a4gkHY7hwR3MP2c2E8mV8-4PFjfX4RsVwVydKx8TFwUJwbiXa68+6xqHip3S2X-GA2TXa5AAJnGP0IbE+mQgjFDALkAFZscoHr4bGsi+NqX8UlAwbAYmArAUYK5hzEYOwjNmHgMBkA) <!-- prettier-ignore --> ```sh --parser css ``` **Input:** <!-- prettier-ignore --> ```css @font-face { font-family: rob; src: url(RobotoFlex-VariableFont_GRAD,XTRA,YOPQ,YTAS,YTDE,YTFI,YTLC,YTUC,opsz,slnt,wdth,wght.ttf); } ``` **Output:** <!-- prettier-ignore --> ```css @font-face { font-family: rob; src: url(RobotoFlex-VariableFont_GRADXTRAYOPQYTASYTDEYTFIYTLCYTUCopszslntwdthwght.ttf); } ```
"2023-03-09T21:20:26Z"
3.0
[]
[ "tests/format/css/url/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAzjAngGzgPgB0oACEgAQDNoYBaSgQzDhOGLI4+tnoYFsAljixISAJwgAjANyc58hYqXKVqxewXoxYUQFcxOABQAlKRBgQAYngAetAGoMxAhpLyWaAfQDixgIIAIgA0ABoAKv5BAJoA8gAKAIrRYX4AyskBAKLJlgCSyQAyAMLJAKolEAAO6ABeQeg4sEEA7gAmMAAWLQDmHTAAdDAwlACU0hokAL5yxKgA9Ji4BBMkIEEgVTAC0OjIoE4SzXFOCLsoDDjNDFi765JiTADWcDCp-HAFAlBwyIw46HA7g8wM9XpUmF9usgYGJdICQHA+JI4K1WiiCgwoN1dAxunAPGI+AwhpDkCAGLoLGsQH0+DgAOodATwdDg5ipU7MgQAN2ZWDJYHQtxAXwBYhgcQe3SJvwuAPWACt0DZUpC8AldOYfkg-vKQOCxGKybScNTKs5YPSBO0OsgABwABnW5ogAPpD0qZPNcDF3J+6wAjpr4JKqmdyehaN8USjqWI4EGBPHJbiZTq5fCAYJobDM2q4H4hs5JJS4HE4GJPt9Zf881j1cHtbr4TBXFabcgAEzrGEMISQooQPhphHoACs1N0ALCrjOzfW3LhuSgaNgqTAzkqMD8K9S2DwNYBk0mQA" ]
prettier/prettier
14,548
prettier__prettier-14548
[ "14547" ]
ddf3b43c33e2e98f6413b5232ad623876d96738e
diff --git a/src/language-js/parse/postprocess/typescript.js b/src/language-js/parse/postprocess/typescript.js --- a/src/language-js/parse/postprocess/typescript.js +++ b/src/language-js/parse/postprocess/typescript.js @@ -30,6 +30,20 @@ function throwErrorOnTsNode(node, message) { throwSyntaxError({ loc: { start, end } }, message); } +function nodeCanBeDecorated(node) { + const ts = require("typescript"); + + return [true, false].some((useLegacyDecorators) => + // @ts-expect-error -- internal? + ts.nodeCanBeDecorated( + useLegacyDecorators, + node, + node.parent, + node.parent.parent + ) + ); +} + // Invalid decorators are removed since `@typescript-eslint/typescript-estree` v4 // https://github.com/typescript-eslint/typescript-eslint/pull/2375 // There is a `checkGrammarDecorators` in `typescript` package, consider use it directly in future @@ -44,16 +58,7 @@ function throwErrorForInvalidDecorator(node) { const { SyntaxKind } = ts; for (const modifier of modifiers) { if (ts.isDecorator(modifier)) { - const legacyDecorators = true; - if ( - // @ts-expect-error -- internal? - !ts.nodeCanBeDecorated( - legacyDecorators, - node, - node.parent, - node.parent.parent - ) - ) { + if (!nodeCanBeDecorated(node)) { if ( node.kind === SyntaxKind.MethodDeclaration && // @ts-expect-error -- internal? @@ -67,9 +72,8 @@ function throwErrorForInvalidDecorator(node) { throwErrorOnTsNode(modifier, "Decorators are not valid here."); } } else if ( - legacyDecorators && - (node.kind === SyntaxKind.GetAccessor || - node.kind === SyntaxKind.SetAccessor) + node.kind === SyntaxKind.GetAccessor || + node.kind === SyntaxKind.SetAccessor ) { // @ts-expect-error -- internal? const accessors = ts.getAllAccessorDeclarations(
diff --git a/tests/format/js/decorators/class-expression/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/decorators/class-expression/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/js/decorators/class-expression/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/decorators/class-expression/__snapshots__/jsfmt.spec.js.snap @@ -24,14 +24,6 @@ exports[`arguments.js [flow] format 1`] = ` 3 |" `; -exports[`arguments.js [typescript] format 1`] = ` -"Decorators are not valid here. (1:13) -> 1 | console.log(@deco class Foo {}) - | ^^^^^ - 2 | console.log(@deco class {}) - 3 |" -`; - exports[`arguments.js - {"semi":false} [acorn] format 1`] = ` "Unexpected character '@' (1:13) > 1 | console.log(@deco class Foo {}) @@ -56,14 +48,6 @@ exports[`arguments.js - {"semi":false} [flow] format 1`] = ` 3 |" `; -exports[`arguments.js - {"semi":false} [typescript] format 1`] = ` -"Decorators are not valid here. (1:13) -> 1 | console.log(@deco class Foo {}) - | ^^^^^ - 2 | console.log(@deco class {}) - 3 |" -`; - exports[`arguments.js - {"semi":false} format 1`] = ` ====================================options===================================== parsers: ["babel", "flow", "typescript"] @@ -144,15 +128,6 @@ exports[`class-expression.js [flow] format 1`] = ` 4 | (@deco class Foo {});" `; -exports[`class-expression.js [typescript] format 1`] = ` -"Decorators are not valid here. (1:13) -> 1 | const a1 = (@deco class Foo {}); - | ^^^^^ - 2 | const a2 = (@deco class {}); - 3 | - 4 | (@deco class Foo {});" -`; - exports[`class-expression.js - {"semi":false} [acorn] format 1`] = ` "Unexpected character '@' (1:13) > 1 | const a1 = (@deco class Foo {}); @@ -180,15 +155,6 @@ exports[`class-expression.js - {"semi":false} [flow] format 1`] = ` 4 | (@deco class Foo {});" `; -exports[`class-expression.js - {"semi":false} [typescript] format 1`] = ` -"Decorators are not valid here. (1:13) -> 1 | const a1 = (@deco class Foo {}); - | ^^^^^ - 2 | const a2 = (@deco class {}); - 3 | - 4 | (@deco class Foo {});" -`; - exports[`class-expression.js - {"semi":false} format 1`] = ` ====================================options===================================== parsers: ["babel", "flow", "typescript"] @@ -336,14 +302,6 @@ exports[`member-expression.js [flow] format 1`] = ` 3 |" `; -exports[`member-expression.js [typescript] format 1`] = ` -"Decorators are not valid here. (1:2) -> 1 | (@deco class Foo {}).name; - | ^^^^^ - 2 | (@deco class {}).name; - 3 |" -`; - exports[`member-expression.js - {"semi":false} [acorn] format 1`] = ` "Unexpected character '@' (1:2) > 1 | (@deco class Foo {}).name; @@ -368,14 +326,6 @@ exports[`member-expression.js - {"semi":false} [flow] format 1`] = ` 3 |" `; -exports[`member-expression.js - {"semi":false} [typescript] format 1`] = ` -"Decorators are not valid here. (1:2) -> 1 | (@deco class Foo {}).name; - | ^^^^^ - 2 | (@deco class {}).name; - 3 |" -`; - exports[`member-expression.js - {"semi":false} format 1`] = ` ====================================options===================================== parsers: ["babel", "flow", "typescript"] @@ -448,15 +398,6 @@ exports[`super-class.js [flow] format 1`] = ` 4 |" `; -exports[`super-class.js [typescript] format 1`] = ` -"Decorators are not valid here. (1:20) -> 1 | class Foo extends (@deco class Foo {}){} - | ^^^^^ - 2 | - 3 | class Foo extends (@deco class {}){} - 4 |" -`; - exports[`super-class.js - {"semi":false} [acorn] format 1`] = ` "Unexpected character '@' (1:20) > 1 | class Foo extends (@deco class Foo {}){} @@ -484,15 +425,6 @@ exports[`super-class.js - {"semi":false} [flow] format 1`] = ` 4 |" `; -exports[`super-class.js - {"semi":false} [typescript] format 1`] = ` -"Decorators are not valid here. (1:20) -> 1 | class Foo extends (@deco class Foo {}){} - | ^^^^^ - 2 | - 3 | class Foo extends (@deco class {}){} - 4 |" -`; - exports[`super-class.js - {"semi":false} format 1`] = ` ====================================options===================================== parsers: ["babel", "flow", "typescript"] diff --git a/tests/format/js/decorators/class-expression/jsfmt.spec.js b/tests/format/js/decorators/class-expression/jsfmt.spec.js --- a/tests/format/js/decorators/class-expression/jsfmt.spec.js +++ b/tests/format/js/decorators/class-expression/jsfmt.spec.js @@ -1,6 +1,5 @@ const errors = { flow: true, - typescript: true, acorn: true, espree: true, }; diff --git a/tests/format/typescript/decorators/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/decorators/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/typescript/decorators/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/typescript/decorators/__snapshots__/jsfmt.spec.js.snap @@ -497,6 +497,48 @@ class MyContainerComponent { ================================================================================ `; +exports[`legacy.ts format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +[ + @decorator() class {}, + @decorator() class A {}, +]; + +class A { + @decorator() accessor #field; +} + +class B { + @decorator() #field () {} +} + +=====================================output===================================== +[ + ( + @decorator() + class {} + ), + ( + @decorator() + class A {} + ), +]; + +class A { + @decorator() accessor #field; +} + +class B { + @decorator() #field() {} +} + +================================================================================ +`; + exports[`mobx.ts format 1`] = ` ====================================options===================================== parsers: ["typescript"] diff --git a/tests/format/typescript/decorators/legacy.ts b/tests/format/typescript/decorators/legacy.ts new file mode 100644 --- /dev/null +++ b/tests/format/typescript/decorators/legacy.ts @@ -0,0 +1,12 @@ +[ + @decorator() class {}, + @decorator() class A {}, +]; + +class A { + @decorator() accessor #field; +} + +class B { + @decorator() #field () {} +} diff --git a/tests/format/typescript/type-arguments-bit-shift-left-like/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/type-arguments-bit-shift-left-like/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/typescript/type-arguments-bit-shift-left-like/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/typescript/type-arguments-bit-shift-left-like/__snapshots__/jsfmt.spec.js.snap @@ -49,7 +49,7 @@ exports[`3.ts [typescript] format 1`] = ` 2 |" `; -exports[`4.ts [babel-ts] format 1`] = ` +exports[`4.ts format 1`] = ` ====================================options===================================== parsers: ["typescript"] printWidth: 80 @@ -66,13 +66,6 @@ printWidth: 80 ================================================================================ `; -exports[`4.ts [typescript] format 1`] = ` -"Decorators are not valid here. (1:2) -> 1 | (@f<<T>(v: T) => void>() class {}); - | ^^^^^^^^^^^^^^^^^^^^^^^ - 2 |" -`; - exports[`5.tsx [babel-ts] format 1`] = ` ====================================options===================================== parsers: ["typescript"] diff --git a/tests/format/typescript/type-arguments-bit-shift-left-like/jsfmt.spec.js b/tests/format/typescript/type-arguments-bit-shift-left-like/jsfmt.spec.js --- a/tests/format/typescript/type-arguments-bit-shift-left-like/jsfmt.spec.js +++ b/tests/format/typescript/type-arguments-bit-shift-left-like/jsfmt.spec.js @@ -1,3 +1,3 @@ run_spec(__dirname, ["typescript"], { - errors: { typescript: ["3.ts", "4.ts", "5.tsx"] }, + errors: { typescript: ["3.ts", "5.tsx"] }, });
Decorators on accessor private fields report SyntaxError **Prettier 2.8.5** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAucAbAhgZ0wAgII7AA6UOOAAgCZxgAUAlDumGHNhAE44DEAZgJZxUlANwkAviAA0ICAAcY-aJmSh0HDhADuABXUIVKdKi3oAnipkAjDswDWcGAGV0AWzgAZflDjJexzDhrWzAHZzlmbwBzZBgOAFcgkDhXKzhKakoPdCgo+PQouAAxTld0GEVc5BB0eJgIaRAACxhXVAB1Jv54TAjWJwNu-gA3brNqsGxG70COGB1bKLK-AKSAK0wADydo1DgARXiIeBXUQJkIjlnqmDM5NjAOfgVGuSfYdv5KGCbkAA4AAwXTSBdq2OTVN5sOAcYa+GQARyO8AW8kMNUwAFofOl0o0OHAkfwCQsCsskP4zklAq5+LEEtTdnA8BUnlY6nAdDCvD5TucQJgmYdjr4KasZDB0FZPt9fkgAEwS2z8VDRADCEFc5OSmAArI14oEACpSwyU-nDRIASSg1FgTkezxgeFtTluez5cHE4iAA) <!-- prettier-ignore --> ```sh --parser typescript ``` **Input:** <!-- prettier-ignore --> ```tsx class A { @dec() accessor #field; } ``` **Output:** <!-- prettier-ignore --> ```tsx SyntaxError: Decorators are not valid here. (2:3) 1 | class A { > 2 | @dec() accessor #field; | ^^^^^^ 3 | } ``` **Expected behavior:** No SyntaxError. Change the parser from "typescript" to "babel-ts" will make it work. Prettier 2.8.4 works fine, seems 2.8.5 introduced this.
TypeScript seems don't allow it [playground](https://www.typescriptlang.org/play?#code/MYGwhgzhAECC0G8BQ1oAEAmBTYAKAlNGMMFlAPYBO0AxAGYCWWIGA3EgL5A) You should unset the `experimentalDecorators` option. While it's enabled, it uses stage 2 decorator proposal, not the latest stage 3 proposal
"2023-03-21T07:41:07Z"
2.9
[]
[ "tests/format/js/decorators/class-expression/jsfmt.spec.js", "tests/format/typescript/decorators/jsfmt.spec.js", "tests/format/typescript/type-arguments-bit-shift-left-like/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAucAbAhgZ0wAgII7AA6UOOAAgCZxgAUAlDumGHNhAE44DEAZgJZxUlANwkAviAA0ICAAcY-aJmSh0HDhADuABXUIVKdKi3oAnipkAjDswDWcGAGV0AWzgAZflDjJexzDhrWzAHZzlmbwBzZBgOAFcgkDhXKzhKakoPdCgo+PQouAAxTld0GEVc5BB0eJgIaRAACxhXVAB1Jv54TAjWJwNu-gA3brNqsGxG70COGB1bKLK-AKSAK0wADydo1DgARXiIeBXUQJkIjlnqmDM5NjAOfgVGuSfYdv5KGCbkAA4AAwXTSBdq2OTVN5sOAcYa+GQARyO8AW8kMNUwAFofOl0o0OHAkfwCQsCsskP4zklAq5+LEEtTdnA8BUnlY6nAdDCvD5TucQJgmYdjr4KasZDB0FZPt9fkgAEwS2z8VDRADCEFc5OSmAArI14oEACpSwyU-nDRIASSg1FgTkezxgeFtTluez5cHE4iAA" ]
prettier/prettier
14,557
prettier__prettier-14557
[ "9060" ]
6650770c04cda06f1233f66b175e89b3ffa98424
diff --git a/src/language-js/print/expression-statement.js b/src/language-js/print/expression-statement.js new file mode 100644 --- /dev/null +++ b/src/language-js/print/expression-statement.js @@ -0,0 +1,44 @@ +import { printDanglingComments } from "../../main/comments/print.js"; +import { + markerForIfWithoutBlockAndSameLineComment, + hasComment, + CommentCheckFlags, +} from "../utils/index.js"; +import { + isSingleJsxExpressionStatementInMarkdown, + isSingleVueEventBindingExpressionStatement, + isVueEventBindingExpression, +} from "./semicolon.js"; + +function printExpressionStatement(path, options, print) { + const parts = [print("expression")]; + + if (isSingleVueEventBindingExpressionStatement(path, options)) { + if (isVueEventBindingExpression(path.node.expression)) { + parts.push(";"); + } + } else if (isSingleJsxExpressionStatementInMarkdown(path, options)) { + // Do not append semicolon after the only JSX element in a program + } else if (options.semi) { + parts.push(";"); + } + + if ( + hasComment( + path.node, + CommentCheckFlags.Dangling, + ({ marker }) => marker === markerForIfWithoutBlockAndSameLineComment + ) + ) { + parts.push( + " ", + printDanglingComments(path, options, { + marker: markerForIfWithoutBlockAndSameLineComment, + }) + ); + } + + return parts; +} + +export { printExpressionStatement }; diff --git a/src/language-js/print/html-binding.js b/src/language-js/print/html-binding.js --- a/src/language-js/print/html-binding.js +++ b/src/language-js/print/html-binding.js @@ -32,22 +32,4 @@ function printHtmlBinding(path, options, print) { } } -// based on https://github.com/prettier/prettier/blob/main/src/language-html/syntax-vue.js isVueEventBindingExpression() -function isVueEventBindingExpression(node) { - switch (node.type) { - case "MemberExpression": - switch (node.property.type) { - case "Identifier": - case "NumericLiteral": - case "StringLiteral": - return isVueEventBindingExpression(node.object); - } - return false; - case "Identifier": - return true; - default: - return false; - } -} - -export { isVueEventBindingExpression, printHtmlBinding }; +export { printHtmlBinding }; diff --git a/src/language-js/print/semicolon.js b/src/language-js/print/semicolon.js --- a/src/language-js/print/semicolon.js +++ b/src/language-js/print/semicolon.js @@ -3,12 +3,15 @@ import { getLeftSidePathName, hasNakedLeftSide, isJsxElement, - isTheOnlyJsxElementInMarkdown, } from "../utils/index.js"; import { shouldPrintParamsWithoutParens } from "./function.js"; function shouldPrintLeadingSemicolon(path, options) { - if (options.semi || isTheOnlyJsxElementInMarkdown(options, path)) { + if ( + options.semi || + isSingleJsxExpressionStatementInMarkdown(path, options) || + isSingleVueEventBindingExpressionStatement(path, options) + ) { return false; } @@ -86,4 +89,47 @@ function expressionNeedsASIProtection(path, options) { ); } -export { shouldPrintLeadingSemicolon }; +function isSingleJsxExpressionStatementInMarkdown({ node, parent }, options) { + return ( + (options.parentParser === "markdown" || options.parentParser === "mdx") && + node.type === "ExpressionStatement" && + isJsxElement(node.expression) && + parent.type === "Program" && + parent.body.length === 1 + ); +} + +// based on /src/language-html/syntax-vue.js isVueEventBindingExpression() +function isVueEventBindingExpression(node) { + switch (node.type) { + case "MemberExpression": + switch (node.property.type) { + case "Identifier": + case "NumericLiteral": + case "StringLiteral": + return isVueEventBindingExpression(node.object); + } + return false; + case "Identifier": + return true; + default: + return false; + } +} + +function isSingleVueEventBindingExpressionStatement({ node, parent }, options) { + return ( + (options.parser === "__vue_event_binding" || + options.parser === "__vue_ts_event_binding") && + node.type === "ExpressionStatement" && + parent.type === "Program" && + parent.body.length === 1 + ); +} + +export { + shouldPrintLeadingSemicolon, + isSingleJsxExpressionStatementInMarkdown, + isSingleVueEventBindingExpressionStatement, + isVueEventBindingExpression, +}; diff --git a/src/language-js/printer-estree.js b/src/language-js/printer-estree.js --- a/src/language-js/printer-estree.js +++ b/src/language-js/printer-estree.js @@ -18,12 +18,10 @@ import pathNeedsParens from "./needs-parens.js"; import { hasComment, CommentCheckFlags, - isTheOnlyJsxElementInMarkdown, isNextLineEmpty, needsHardlineAfterDanglingComment, isCallExpression, isMemberExpression, - markerForIfWithoutBlockAndSameLineComment, isArrayOrTupleExpression, isObjectOrRecordExpression, startsWithNoLookaheadToken, @@ -33,10 +31,7 @@ import { locStart, locEnd } from "./loc.js"; import isBlockComment from "./utils/is-block-comment.js"; import isIgnored from "./utils/is-ignored.js"; -import { - printHtmlBinding, - isVueEventBindingExpression, -} from "./print/html-binding.js"; +import { printHtmlBinding } from "./print/html-binding.js"; import { printAngular } from "./print/angular.js"; import { printJsx } from "./print/jsx.js"; import { printFlow } from "./print/flow.js"; @@ -88,6 +83,7 @@ import { printLiteral } from "./print/literal.js"; import { printDecorators } from "./print/decorators.js"; import { printTypeAnnotationProperty } from "./print/type-annotation.js"; import { shouldPrintLeadingSemicolon } from "./print/semicolon.js"; +import { printExpressionStatement } from "./print/expression-statement.js"; /** * @typedef {import("../common/ast-path.js").default} AstPath @@ -197,35 +193,8 @@ function printPathNoParens(path, options, print, args) { // Babel extension. case "EmptyStatement": return ""; - case "ExpressionStatement": { - if ( - options.parser === "__vue_event_binding" || - options.parser === "__vue_ts_event_binding" - ) { - const { parent } = path; - if ( - parent.type === "Program" && - parent.body.length === 1 && - parent.body[0] === node - ) { - return [ - print("expression"), - isVueEventBindingExpression(node.expression) ? ";" : "", - ]; - } - } - - const danglingComment = printDanglingComments(path, options, { - marker: markerForIfWithoutBlockAndSameLineComment, - }); - - // Do not append semicolon after the only JSX element in a program - return [ - print("expression"), - isTheOnlyJsxElementInMarkdown(options, path) ? "" : semi, - danglingComment ? [" ", danglingComment] : "", - ]; - } + case "ExpressionStatement": + return printExpressionStatement(path, options, print); case "ChainExpression": return print("expression"); diff --git a/src/language-js/utils/index.js b/src/language-js/utils/index.js --- a/src/language-js/utils/index.js +++ b/src/language-js/utils/index.js @@ -244,22 +244,6 @@ function isAngularTestWrapper(node) { */ const isJsxElement = createTypeCheckFunction(["JSXElement", "JSXFragment"]); -function isTheOnlyJsxElementInMarkdown(options, path) { - if (options.parentParser !== "markdown" && options.parentParser !== "mdx") { - return false; - } - - const { node } = path; - - if (!node.expression || !isJsxElement(node.expression)) { - return false; - } - - const { parent } = path; - - return parent.type === "Program" && parent.body.length === 1; -} - function isGetterOrSetter(node) { return node.kind === "get" || node.kind === "set"; } @@ -1181,7 +1165,6 @@ export { isStringPropSafeToUnquote, isTemplateOnItsOwnLine, isTestCall, - isTheOnlyJsxElementInMarkdown, isTSXFile, isTypeAnnotationAFunction, isNextLineEmpty,
diff --git a/tests/format/vue/ts-event-binding/__snapshots__/jsfmt.spec.js.snap b/tests/format/vue/event-binding/__snapshots__/jsfmt.spec.js.snap similarity index 95% rename from tests/format/vue/ts-event-binding/__snapshots__/jsfmt.spec.js.snap rename to tests/format/vue/event-binding/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/vue/ts-event-binding/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/vue/event-binding/__snapshots__/jsfmt.spec.js.snap @@ -1,6 +1,6 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`basic.vue format 1`] = ` +exports[`basic-ts.vue format 1`] = ` ====================================options===================================== parsers: ["vue"] printWidth: 80 @@ -42,7 +42,7 @@ function log(...args) { ================================================================================ `; -exports[`function-expression.vue format 1`] = ` +exports[`function-expression-ts.vue format 1`] = ` ====================================options===================================== parsers: ["vue"] printWidth: 80 diff --git a/tests/format/vue/ts-event-binding/basic.vue b/tests/format/vue/event-binding/basic-ts.vue similarity index 100% rename from tests/format/vue/ts-event-binding/basic.vue rename to tests/format/vue/event-binding/basic-ts.vue diff --git a/tests/format/vue/ts-event-binding/function-expression.vue b/tests/format/vue/event-binding/function-expression-ts.vue similarity index 100% rename from tests/format/vue/ts-event-binding/function-expression.vue rename to tests/format/vue/event-binding/function-expression-ts.vue diff --git a/tests/format/vue/ts-event-binding/jsfmt.spec.js b/tests/format/vue/event-binding/jsfmt.spec.js similarity index 100% rename from tests/format/vue/ts-event-binding/jsfmt.spec.js rename to tests/format/vue/event-binding/jsfmt.spec.js diff --git a/tests/format/vue/event-binding/no-semi/__snapshots__/jsfmt.spec.js.snap b/tests/format/vue/event-binding/no-semi/__snapshots__/jsfmt.spec.js.snap new file mode 100644 --- /dev/null +++ b/tests/format/vue/event-binding/no-semi/__snapshots__/jsfmt.spec.js.snap @@ -0,0 +1,26 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`single-expression.vue - {"semi":false} format 1`] = ` +====================================options===================================== +parsers: ["vue"] +printWidth: 80 +semi: false + | printWidth +=====================================input====================================== +<template> + <foo-bar + @click="[foo, bar].forEach(fn => void fn())" + @loaded="(map = $event) && initMap()" + ></foo-bar> +</template> + +=====================================output===================================== +<template> + <foo-bar + @click="[foo, bar].forEach((fn) => void fn())" + @loaded="(map = $event) && initMap()" + ></foo-bar> +</template> + +================================================================================ +`; diff --git a/tests/format/vue/event-binding/no-semi/jsfmt.spec.js b/tests/format/vue/event-binding/no-semi/jsfmt.spec.js new file mode 100644 --- /dev/null +++ b/tests/format/vue/event-binding/no-semi/jsfmt.spec.js @@ -0,0 +1 @@ +run_spec(import.meta, ["vue"], { semi: false }); diff --git a/tests/format/vue/event-binding/no-semi/single-expression.vue b/tests/format/vue/event-binding/no-semi/single-expression.vue new file mode 100644 --- /dev/null +++ b/tests/format/vue/event-binding/no-semi/single-expression.vue @@ -0,0 +1,6 @@ +<template> + <foo-bar + @click="[foo, bar].forEach(fn => void fn())" + @loaded="(map = $event) && initMap()" + ></foo-bar> +</template>
Unnecessary leading semi **Prettier 2.1.0** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeeBbADgGwIbwB8AOlAARmoBuAtBnlmQAI4R4Amc7AvMSABT1G3MgBI4VBDACUZAGRyyASyhKYAWQb9pfQqgD0tISSgHMuAnBMgANCAhYYS6AGdkoPACdPEAO4AFLwQ3FDwqCCV2WxAAI088MABrOBgAZSwElQBzZBhPAFc4OzgMGK5OdgAZPCgs-LwsuAAxCE96GCda5BA8fJgIaIALGAwcAHVBtTgXDLA4VOC1JSo1AE9usBc3OxUXOE8Yf3is+mQAMzwcPbsAKxcADwAheKSU1LwMOEqVOHPL65Ad3uqWyODgAEV8hB4H8rkUQBlPHtPN0qIVolhPCoYGNIjBBsgABwABjsmIgezG8Sw3Ux032kmiAEcofAjg4Qj0XDQoHAuFxop44CylEKjg1TkgLnC7HsMEpYQCXKCIazflL-vCYHgYrj2PjkAAmOx5PBKHDZADCEAwkpAUGgvzs+T2ABUdSFpQC0XAAJJQTiwVJgLGOACCAdSMFWYMVcAAvvGgA) ```sh --arrow-parens avoid --parser vue --no-semi --trailing-comma none ``` **Input:** ```vue <template> <v-map @loaded="(map = $event) && initMap()"></v-map> </template> ``` **Output:** ```vue <template> <v-map @loaded=";(map = $event) && initMap()"></v-map> </template> ``` **Expected behavior:** ```vue <template> <v-map @loaded="(map = $event) && initMap()"></v-map> </template> ```
This is expected and we format js like this, when `--no-semi`, but looks weird in this case. Yes, when code like `;(() => {...})()` is placed at start of js file, the leading semi is unnecessary too, can this behavior be adjusted? We won't change current behavior in js files, but this one may worth discuss. __updated:__ Here is another interesting case: <details> <summary>ASI after if statement</summary> **Prettier 2.1.0** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBLAZgAgBQEMCUmwAOlJpgEbb6kC+ppeAzgJ5RjWYC8AfEaeVwB3XKhiZc1ARJFjKUqLXzUQAGhAQADjFTQmyULgBORiEIAKxhPpS4ANiJb71FI7jABrODADKm96hQAObIMEYArnDqcAC2FHAAJgmJADK4weG4QXAAYhBGMbgwOsHIILjhMBBqIAAWMDF2AOq1YnBM-mBwPtZiqABuYixlYEzOaFBMcEYw5m5Bhcjo9lPqAFZMAB4AQm6e3j64MXApgXBLK1EgG5s+gUF2cACK4RDwF3arIP5GU0ZlFFw8TsNU0RkCMCaqASMFqyAAHAAGdRgiBTJpuTRlMHtab9c7qACOr3gcy0NnKTAAtFA4IlEjUjHBiagmXMsoskMtPlcpjFUB8vkx7o8Xm9zlzLuoYECoTC4UgAEzStyoOz3ADCEBinJA7QArDVwlMACpAmzcr79SIASSgyVgPjA4O0AEF7T4YCxHoK4LRaEA) ```sh --parser babel --no-semi ``` **Input:** ```jsx if (a) { b() } (async() => { await a() await b() })() ``` **Output:** ```jsx if (a) { b() } ;(async () => { await a() await b() })() ``` </details> but yes, I think no change, see my comment below. > maybe we need to protect against the programmer adding code before the expression statement in the future Yes, we won't change it in js files. The behavior for js file is out scope of this issue. > We won't change current behavior in js files Here is the rationale, linked from the `--no-semi` option: https://prettier.io/docs/en/rationale.html#semicolons (My apologies for the other comment. Yes this may be off-topic now, but I think the link is relevant to answer the question in <https://github.com/prettier/prettier/issues/9060#issuecomment-680431266>.) > this one may worth discuss It would definitely be nice to be consistent with Angular & HTML parsers, which would format that template unchanged. --no-semi Input: ``` [1, 2].forEach((item) => console.log(item)) [1, 2].forEach((item) => console.log(item)) ``` Output: ``` ;[1, 2] .forEach((item) => console.log(item)) [(1, 2)].forEach((item) => console.log(item)) ``` The first line, I can understand. The second line, I'm shocked. Run ```js console.log( [1, 2].forEach((item) => console.log(item)) [1, 2].forEach((item) => console.log(item)) ) ``` and ```js [1, 2].map((item) => item) [0, 1].toFixed(10) ``` to understand it. > Run > > ```js > console.log( > [1, 2].forEach((item) => console.log(item)) > > [1, 2].forEach((item) => console.log(item)) > ) > ``` > > and > > ```js > [1, 2].map((item) => item) > > [0, 1].toFixed(10) > ``` > > to understand it. Why is it wrong If you still can't get it, parser your code on https://astexplorer.net/, and check the AST. Please reconsider, leading semicolon is invalid in Alpine.js. Currently need to ignore every such node. 已收到。谢谢,我会尽快回复你。
"2023-03-22T09:14:22Z"
3.0
[ "tests/format/vue/event-binding/jsfmt.spec.js" ]
[ "tests/format/vue/event-binding/no-semi/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeeBbADgGwIbwB8AOlAARmoBuAtBnlmQAI4R4Amc7AvMSABT1G3MgBI4VBDACUZAGRyyASyhKYAWQb9pfQqgD0tISSgHMuAnBMgANCAhYYS6AGdkoPACdPEAO4AFLwQ3FDwqCCV2WxAAI088MABrOBgAZSwElQBzZBhPAFc4OzgMGK5OdgAZPCgs-LwsuAAxCE96GCda5BA8fJgIaIALGAwcAHVBtTgXDLA4VOC1JSo1AE9usBc3OxUXOE8Yf3is+mQAMzwcPbsAKxcADwAheKSU1LwMOEqVOHPL65Ad3uqWyODgAEV8hB4H8rkUQBlPHtPN0qIVolhPCoYGNIjBBsgABwABjsmIgezG8Sw3Ux032kmiAEcofAjg4Qj0XDQoHAuFxop44CylEKjg1TkgLnC7HsMEpYQCXKCIazflL-vCYHgYrj2PjkAAmOx5PBKHDZADCEAwkpAUGgvzs+T2ABUdSFpQC0XAAJJQTiwVJgLGOACCAdSMFWYMVcAAvvGgA" ]
prettier/prettier
14,587
prettier__prettier-14587
[ "14575" ]
dd779dae55133f3065817608636e26d6b81a9e62
diff --git a/src/language-html/print-preprocess.js b/src/language-html/print-preprocess.js --- a/src/language-html/print-preprocess.js +++ b/src/language-html/print-preprocess.js @@ -411,18 +411,13 @@ function addIsSpaceSensitive(ast, options) { } function markTsScript(ast, options) { - if (options.parser === "vue") { - const vueScriptTag = ast.children.find((child) => - isVueScriptTag(child, options) + options.__should_parse_vue_template_with_ts = + options.parser === "vue" && + ast.children.some( + (child) => + isVueScriptTag(child, options) && + ["ts", "typescript"].includes(child.attrMap.lang) ); - if (!vueScriptTag) { - return; - } - const { lang } = vueScriptTag.attrMap; - if (lang === "ts" || lang === "typescript") { - options.__should_parse_vue_template_with_ts = true; - } - } } module.exports = preprocess;
diff --git a/tests/format/vue/multiparser/__snapshots__/jsfmt.spec.js.snap b/tests/format/vue/multiparser/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/vue/multiparser/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/vue/multiparser/__snapshots__/jsfmt.spec.js.snap @@ -70,6 +70,60 @@ export default { ================================================================================ `; +exports[`lang-ts-multiple-script-tags.vue format 1`] = ` +====================================options===================================== +parsers: ["vue"] +printWidth: 80 + | printWidth +=====================================input====================================== +<script></script> +<script></script> +<script></script> +<script></script> +<script></script> +<script></script> +<script setup lang="ts"> +let x: string | number = 1 +</script> +<script></script> +<script></script> +<script></script> +<template> + <span + v-if=" (x as string).length > 0" + v-for="a in [1,2, 3,4,5].map( (x : number) => x * x)" + :foo=" (x as number).toFixed( 2) " + > + {{ (x as number).toFixed(2) }} + </span> +</template> + +=====================================output===================================== +<script></script> +<script></script> +<script></script> +<script></script> +<script></script> +<script></script> +<script setup lang="ts"> +let x: string | number = 1; +</script> +<script></script> +<script></script> +<script></script> +<template> + <span + v-if=" (x as string).length > 0" + v-for="a in [1,2, 3,4,5].map( (x : number) => x * x)" + :foo=" (x as number).toFixed( 2) " + > + {{ (x as number).toFixed(2) }} + </span> +</template> + +================================================================================ +`; + exports[`lang-tsx.vue format 1`] = ` ====================================options===================================== parsers: ["vue"] diff --git a/tests/format/vue/multiparser/lang-ts-multiple-script-tags.vue b/tests/format/vue/multiparser/lang-ts-multiple-script-tags.vue new file mode 100644 --- /dev/null +++ b/tests/format/vue/multiparser/lang-ts-multiple-script-tags.vue @@ -0,0 +1,21 @@ +<script></script> +<script></script> +<script></script> +<script></script> +<script></script> +<script></script> +<script setup lang="ts"> +let x: string | number = 1 +</script> +<script></script> +<script></script> +<script></script> +<template> + <span + v-if=" (x as string).length > 0" + v-for="a in [1,2, 3,4,5].map( (x : number) => x * x)" + :foo=" (x as number).toFixed( 2) " + > + {{ (x as number).toFixed(2) }} + </span> +</template>
Vue not formatting TS expression if `script[lang=ts]` is second `<script>` **Prettier 2.8.6** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAzmATgSwA4wB8qA9JrgYQDpQbb4wAE6cMArnowDYCGUA5gF4qIGOhHUoXVowAeSZjFwDGAH0ZQ2AWwBGcLI0GMAjDVLkGk1PC15e8SY0bBgjABSynXxj3Tenmrr6AJQAdDAQAGI4snAAJm4ATMGMAL6pZiQ2djwOIAA0IBAEONDoyKA8WFgQAO4AClUI5Sg8XLU8AJ7lhTpYPGAA1qwAyjxacAAyOFBwyABmbSy9-UOjeAMz-MhKbHCFcEFxcfGTfPxsPPxwkRBYWrkwW8ggPGwRBSAAFjBaXADqXxw8HQGzAcBGzWBOAAbsDOi8wOgeiAZiwsDB6v1+A8Fkt9iAAFboWQjLbSACKbAg8DxXGWIA2WHRLxhe0+eGUMH+ODiMC+yAAHAAGQqciAsf79PAvTlwdEwuaFACO1PgWOKLVe6AAtLN4vFPlg4KqcMasVdcUhFvSCSwtDgdlg9oV0OS4ABBGBKHA6d5wer6aazOkMt0CSlqubW-GFGA8HQ8vkCpCJOP9HBcLYAYQgWitIHlAFZPmwWAAVBMtG0MtlwACSUBOsBG9AIHqbIxgnWkobg6SAA) <!-- prettier-ignore --> ```sh --parser vue ``` **Input:** <!-- prettier-ignore --> ```vue <script></script> <script setup lang="ts"> let x: string | number = 1 </script> <template> {{ (x as number).toFixed(2) }} </template> ``` **Output:** <!-- prettier-ignore --> ```vue <script></script> <script setup lang="ts"> let x: string | number = 1; </script> <template> {{ (x as number).toFixed(2) }} </template> ``` **Expected behavior:** Should parse as TS. [Vue playground](https://sfc.vuejs.org/#eNp9j81qwzAQhF9l0SmBWKI9mqTQS59CFyfZugrWD7vr1OD63btKTAktVBeNZjUfO7N5LcVeRzSt2fOJQpGXvVuFT6sFjDIWGLrUH7wR9kZnAwpMLbBQSD18QRrjEQkO8KS5B4RgLEMnqBpgnmEzwe10fL/vua2V/BYmPG+et7AsFfETNDsTYskkTeyKvXBOuu1ccX4d6EYt3JzqaZ369uZDpHDrHL+fascL20y9U2VpTBIiWuTYHCl/MpKCvdk9MJyaV6SGMJ2RkP5j/vr6h1uxWmoxyzeu3H5+) Problem is here https://github.com/prettier/prettier/blob/c6e026ea28a4832ff51c7485091cf19135451650/src/language-html/print-preprocess.js#L413-L426 Should check any `<script>` instead of only checking the first `<script>`
"2023-03-25T13:27:33Z"
2.9
[]
[ "tests/format/vue/multiparser/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAzmATgSwA4wB8qA9JrgYQDpQbb4wAE6cMArnowDYCGUA5gF4qIGOhHUoXVowAeSZjFwDGAH0ZQ2AWwBGcLI0GMAjDVLkGk1PC15e8SY0bBgjABSynXxj3Tenmrr6AJQAdDAQAGI4snAAJm4ATMGMAL6pZiQ2djwOIAA0IBAEONDoyKA8WFgQAO4AClUI5Sg8XLU8AJ7lhTpYPGAA1qwAyjxacAAyOFBwyABmbSy9-UOjeAMz-MhKbHCFcEFxcfGTfPxsPPxwkRBYWrkwW8ggPGwRBSAAFjBaXADqXxw8HQGzAcBGzWBOAAbsDOi8wOgeiAZiwsDB6v1+A8Fkt9iAAFboWQjLbSACKbAg8DxXGWIA2WHRLxhe0+eGUMH+ODiMC+yAAHAAGQqciAsf79PAvTlwdEwuaFACO1PgWOKLVe6AAtLN4vFPlg4KqcMasVdcUhFvSCSwtDgdlg9oV0OS4ABBGBKHA6d5wer6aazOkMt0CSlqubW-GFGA8HQ8vkCpCJOP9HBcLYAYQgWitIHlAFZPmwWAAVBMtG0MtlwACSUBOsBG9AIHqbIxgnWkobg6SAA" ]
prettier/prettier
14,672
prettier__prettier-14672
[ "14666" ]
cddb59d211ff408c5b0b283a6dc2619889f725a3
diff --git a/src/language-js/print/type-parameters.js b/src/language-js/print/type-parameters.js --- a/src/language-js/print/type-parameters.js +++ b/src/language-js/print/type-parameters.js @@ -112,6 +112,10 @@ function printDanglingCommentsForInline(path, options) { function printTypeParameter(path, options, print) { const { node, parent } = path; + + /** + * @type {import("../../document/builders.js").Doc[]} + */ const parts = [node.type === "TSTypeParameter" && node.const ? "const " : ""]; const name = node.type === "TSTypeParameter" ? print("name") : node.name; @@ -160,14 +164,14 @@ function printTypeParameter(path, options, print) { } if (node.constraint) { - parts.push(" extends ", print("constraint")); + parts.push(" extends", indent([line, print("constraint")])); } if (node.default) { parts.push(" = ", print("default")); } - return parts; + return group(parts); } export { printTypeParameter, printTypeParameters, getTypeParametersGroupId };
diff --git a/tests/format/typescript/typeparams/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/typeparams/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/typescript/typeparams/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/typescript/typeparams/__snapshots__/jsfmt.spec.js.snap @@ -362,6 +362,54 @@ class _ { ================================================================================ `; +exports[`line-breaking-after-extends.ts format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +export type OuterType1< + LongerLongerLongerLongerInnerType extends LongerLongerLongerLongerOtherType<OneMoreType> +> = { a: 1 }; + +export type OuterType2< + LongerLongerLongerLongerInnerType extends LongerLongerLongerLongerLongerLongerLongerLongerOtherType +> = { a: 1 }; + +export type OuterType3< + LongerLongerLongerLongerInnerType extends LongerLongerLongerLongerLongerLo.ngerLongerLongerOtherType +> = { a: 1 }; + +export type OuterType4< + LongerLongerLongerLongerInnerType extends + | LongerLongerLongerLongerLongerLo + | ngerLongerLongerOtherType +> = { a: 1 }; + +=====================================output===================================== +export type OuterType1< + LongerLongerLongerLongerInnerType extends + LongerLongerLongerLongerOtherType<OneMoreType>, +> = { a: 1 }; + +export type OuterType2< + LongerLongerLongerLongerInnerType extends + LongerLongerLongerLongerLongerLongerLongerLongerOtherType, +> = { a: 1 }; + +export type OuterType3< + LongerLongerLongerLongerInnerType extends + LongerLongerLongerLongerLongerLo.ngerLongerLongerOtherType, +> = { a: 1 }; + +export type OuterType4< + LongerLongerLongerLongerInnerType extends + LongerLongerLongerLongerLongerLo | ngerLongerLongerOtherType, +> = { a: 1 }; + +================================================================================ +`; + exports[`long-function-arg.ts format 1`] = ` ====================================options===================================== parsers: ["typescript"] diff --git a/tests/format/typescript/typeparams/line-breaking-after-extends.ts b/tests/format/typescript/typeparams/line-breaking-after-extends.ts new file mode 100644 --- /dev/null +++ b/tests/format/typescript/typeparams/line-breaking-after-extends.ts @@ -0,0 +1,17 @@ +export type OuterType1< + LongerLongerLongerLongerInnerType extends LongerLongerLongerLongerOtherType<OneMoreType> +> = { a: 1 }; + +export type OuterType2< + LongerLongerLongerLongerInnerType extends LongerLongerLongerLongerLongerLongerLongerLongerOtherType +> = { a: 1 }; + +export type OuterType3< + LongerLongerLongerLongerInnerType extends LongerLongerLongerLongerLongerLo.ngerLongerLongerOtherType +> = { a: 1 }; + +export type OuterType4< + LongerLongerLongerLongerInnerType extends + | LongerLongerLongerLongerLongerLo + | ngerLongerLongerOtherType +> = { a: 1 };
Nested TypeScript generics are not well line-wrapped (even if input is) Found a bug. Thank you for your consideration! **Prettier 2.8.7** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEcAeAHCAnGACGATwzjwHkBXebAFWLgB4AdKPPAGWgHM5tOoefbr36CAklCi86JPOnhQAJgGcOwoQJHrRvMjAAW0+s1ZtyUgLI44MuCzYA+Fg7wBePMACGSPAEYAvgDcLAD0IXgACthwMDAAlrx4EFQYVHhxqgA26gT6nqwAHAAMeGB52J5g1MogADQgEBjx0DVIoJ7Y2BAA7hEdCK0gnpndnoQ19QBGFWAA1jEAyp4AtnDscVLIAGbDynBTM-MwCxiVG1zIMNgU+6jLk3CKio-s+VwUnjwAYjjLnrHnZBDKgQOogfQwZaZADq+ji8GUpzAcAWA3hcQAbvDCECwMoJiANntcFFPn9trtbgArZRoBbnTJwACKFAg8ApmT29VO2GJQKIJGUYGwcSaYIwItg0LiigMyGK3K6e2hFQwQIlcGJGLgYIAjqz4FFGoNPMoALRSR6PMHRfVxaKkrjkpA7Tm3PbLOKXa7uhlwACCsRFkyocAiIg2OpdlPqyj9LLZUddXJAME8k2lsv0yAATPUrp44plzgBhCDLZ2oZQAVjBFD2NHTrWTtwxNwkz1gC2Fopg-qUCyIjI5e38-iAA) <!-- prettier-ignore --> ```sh --parser typescript ``` **Input:** <!-- prettier-ignore --> ```tsx export type OuterType< LongerLongerLongerLongerInnerType extends LongerLongerLongerLongerOtherType< OneMoreType > > = {a: 1}; // Prettier output is longer than 80 characters ``` **Output:** <!-- prettier-ignore --> ```tsx export type OuterType< LongerLongerLongerLongerInnerType extends LongerLongerLongerLongerOtherType<OneMoreType> > = { a: 1 }; // Prettier output is longer than 80 characters ``` **Expected behavior:** I expect the Prettier output to fit within the 80 character line length (especially since the input does)
(I tried commenting things like #11923 but that didn't work. Having to resort to `// prettier-ignore` for now) I prefer breaking line after `extends` for this case: ```ts export type OuterType< LongerLongerLongerLongerInnerType extends   LongerLongerLongerLongerOtherType<OneMoreType> > = {a: 1}; ```
"2023-04-08T16:31:50Z"
3.0
[]
[ "tests/format/typescript/typeparams/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEcAeAHCAnGACGATwzjwHkBXebAFWLgB4AdKPPAGWgHM5tOoefbr36CAklCi86JPOnhQAJgGcOwoQJHrRvMjAAW0+s1ZtyUgLI44MuCzYA+Fg7wBePMACGSPAEYAvgDcLAD0IXgACthwMDAAlrx4EFQYVHhxqgA26gT6nqwAHAAMeGB52J5g1MogADQgEBjx0DVIoJ7Y2BAA7hEdCK0gnpndnoQ19QBGFWAA1jEAyp4AtnDscVLIAGbDynBTM-MwCxiVG1zIMNgU+6jLk3CKio-s+VwUnjwAYjjLnrHnZBDKgQOogfQwZaZADq+ji8GUpzAcAWA3hcQAbvDCECwMoJiANntcFFPn9trtbgArZRoBbnTJwACKFAg8ApmT29VO2GJQKIJGUYGwcSaYIwItg0LiigMyGK3K6e2hFQwQIlcGJGLgYIAjqz4FFGoNPMoALRSR6PMHRfVxaKkrjkpA7Tm3PbLOKXa7uhlwACCsRFkyocAiIg2OpdlPqyj9LLZUddXJAME8k2lsv0yAATPUrp44plzgBhCDLZ2oZQAVjBFD2NHTrWTtwxNwkz1gC2Fopg-qUCyIjI5e38-iAA" ]
prettier/prettier
14,701
prettier__prettier-14701
[ "14625" ]
fb948bb15f31ade3b35e66b720f8d44260de45f8
diff --git a/src/language-js/needs-parens.js b/src/language-js/needs-parens.js --- a/src/language-js/needs-parens.js +++ b/src/language-js/needs-parens.js @@ -890,6 +890,9 @@ function needsParens(path, options) { parent.type !== "VariableDeclarator" && parent.type !== "YieldExpression") ); + + case "TSInstantiationExpression": + return key === "object" && isMemberExpression(parent); } return false;
diff --git a/tests/format/typescript/instantiation-expression/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/instantiation-expression/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/typescript/instantiation-expression/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/typescript/instantiation-expression/__snapshots__/jsfmt.spec.js.snap @@ -103,6 +103,46 @@ new A<T>(); ================================================================================ `; +exports[`property-access.ts format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +(Array<string>).name; +(fn1<string>).bind(obj); +(fn2<string, number>).bind(obj); +a[(Array<string>)]; +a[(Array<string>).name]; +(Array<string>).a; +(Array<string>)?.a; +(Array<string>)[a]; +(Array<string>)?.[a]; +(Array<string>)["a"]; +(Array<string>)?.["a"]; +(Array<string>)[\`a\`]; +(Array<string>)?.[\`a\`]; +(Array<string>)[(Array<string>)]; + +=====================================output===================================== +(Array<string>).name; +(fn1<string>).bind(obj); +(fn2<string, number>).bind(obj); +a[Array<string>]; +a[(Array<string>).name]; +(Array<string>).a; +(Array<string>)?.a; +(Array<string>)[a]; +(Array<string>)?.[a]; +(Array<string>)["a"]; +(Array<string>)?.["a"]; +(Array<string>)[\`a\`]; +(Array<string>)?.[\`a\`]; +(Array<string>)[Array<string>]; + +================================================================================ +`; + exports[`typeof.ts format 1`] = ` ====================================options===================================== parsers: ["typescript"] diff --git a/tests/format/typescript/instantiation-expression/property-access.ts b/tests/format/typescript/instantiation-expression/property-access.ts new file mode 100644 --- /dev/null +++ b/tests/format/typescript/instantiation-expression/property-access.ts @@ -0,0 +1,14 @@ +(Array<string>).name; +(fn1<string>).bind(obj); +(fn2<string, number>).bind(obj); +a[(Array<string>)]; +a[(Array<string>).name]; +(Array<string>).a; +(Array<string>)?.a; +(Array<string>)[a]; +(Array<string>)?.[a]; +(Array<string>)["a"]; +(Array<string>)?.["a"]; +(Array<string>)[`a`]; +(Array<string>)?.[`a`]; +(Array<string>)[(Array<string>)];
Prettier removes parenthesis around Typescript instantiation expression that is used as part of a bind call **Prettier 2.8.7** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuc0DOMAEBbAngeQCMArOMLAXk2AB0pNMBBJTARgBo6GAhFgJk71MAYRYBmOgF9MAQzSZIUDAG46dGLgAOcTAFkCJMjABqMgDYBXOABUtOqgAoN2iADMcB0uQCUAbQDWcLhumM5wIXhEXjAAuqpQdK4WUOQAltCYqWimZqkAJjlWADzGmHAAHvBQefJQFtiEcABOAHwOXJgQJCwASmQQTXlFGE2pUADm7JjGLVMdAG7mVix1Dc103iyLljpZ09QdTXAwFk30UUYAdNtWaA5dxN6XY2CWeXB3Nzpy097xkmooEkUjB0vRxsccvlCnASmVKggaphVo1Wu0hA9ev1BsMYKMJlMZoIGF8WCMxuNMAAfZH1VHU2lmMwM5LvVxjOB5DYsUo01lwdlQTkHISpdwOL6YCjSxnMqk0yXSqj8wWc7wihgMI4nM6YFUcrlCaRwMxoHS0IQMRQYWlrJowqWYABydOaEqWcD+HS1x1O9CyUIKHvuJCmKOaMPVAH5baiHSx9UK8vEGACoGm6NasBCTOZ8voLuQHY4c4GYUUC4Yix7bNoWk9CGM8g46kyppEqzA-iB2CAIJpQehkKAZE0mhAAO4ABVHCDQyBA5gnMlw897hCaMjAgRgAGUZNg4AAZDnIVzmM3rzfb467zRbinIPFWXtwNZ5d55I8yCYWGQQgAxAZsBkGBQQmBcZAsGAIB7EAAAsYGwMwAHV4NSeA0HvMA4F3OcMNSeYMNwBcwDQNcQDGM0mhgKdN3GECzwvOBe2INByl3CkzDgABFCwIHgJjTRYkB7yaaiFzCNAwFGAc4M0fEYBQ-IYHg5AAA4AAZewUiAzRQzdNAXBSPmaeY4DggBHfj4Do-t5xQOQAFohU5Tk4KOazUiOOj-0YpBz2E3szWwVInyaF8QDQLi4EYMDRkIaC4CnZoTyFITLyimK+IEiyAuY3sYBkQhlLyVTkAEEA8RkVJcgmYQIGwfyQA+ABWOCLDNaxiocwLMvmKwAElqgQPcZNSAdGGqXcNG4jK4EkSQgA) <!-- prettier-ignore --> ```sh --parser typescript ``` **Input:** <!-- prettier-ignore --> ```tsx const myObject = { A: 1, B: 2, C: 3 } as const; type MyObjectValueType = (typeof myObject)[keyof typeof myObject]; function isValidValue<V extends number>( obj: Record<string, V>, value: number ): value is V { return Object.values(obj).includes(value as V); } function getValidValue<V extends number>( obj: Record<string, V>, value: string | number | null | undefined ): V | undefined { if (value === null || value === undefined) { return undefined } else { const numberValue = Number(value); return isValidValue(obj, numberValue) ? numberValue : undefined; } } const getValidMyObjectValue = (getValidValue<MyObjectValueType>).bind(null, myObject); ``` **Output:** <!-- prettier-ignore --> ```tsx const myObject = { A: 1, B: 2, C: 3, } as const; type MyObjectValueType = (typeof myObject)[keyof typeof myObject]; function isValidValue<V extends number>( obj: Record<string, V>, value: number ): value is V { return Object.values(obj).includes(value as V); } function getValidValue<V extends number>( obj: Record<string, V>, value: string | number | null | undefined ): V | undefined { if (value === null || value === undefined) { return undefined; } else { const numberValue = Number(value); return isValidValue(obj, numberValue) ? numberValue : undefined; } } const getValidMyObjectValue = getValidValue<MyObjectValueType>.bind( null, myObject ); ``` **Expected behavior:** The parenthesis should not be removed from the Typescript instantiation expression. ```tsx const getValidMyObjectValue = (getValidValue<MyObjectValueType>).bind( null, myObject ); ``` If they are, it results in the following Typescript error ```sh TS1477: An instantiation expression cannot be followed by a property access. ``` [Typescript playground for unformatted code](https://www.typescriptlang.org/play?#code/MYewdgzgLgBAtgTwPICMBWBTYsC8MDeAUDDAIIBcMAjADTEwBClATHSQMKUDMhAvjAEMIMUJCgBuQoSgIADhhgBZZOixQAagIA2AVwwAVOQrwAKGfJAAzeCszYAlAG0A1hgRWY5jB8So7UAF1JQksdMGwAS3AYCIhNLQiAE3i9AB51GAwADygMMEThMB04FAwAJwA+E3oQdEoAJSwQMsTU6DKIsABzGhh1Ct76ADdtPUoikvLCe0oR3QVYvoJ6MowoHTKwGD81ADo5vQgTWrR7Xc7gXUSMI4OFIT77SV4pUPCoKK2utfiklIx0pkcnkCjAJqVKtUSCcGk0Wm0oB1ur1+mwYHdKO1Ol0YAAfMHFCF4glaLTEsLXSydDCJaaUDL4ikYKlgGnLEgRawmO4wHB8klk3H4nl8vBMlk0+zskgwVbrTYwcXU2kkfgYLQQBREGUicDQAmTMr-XkwAByhPK3NGGCe9BIco2W1iv2S1uO6F64PK-ylAH4DRDjZQlazEpJVXwpKJ9d8NNoksodthjaZYy7-qlE6pk9bDPIKmcUJ1EiYiqTer5s1AnkA) [Typescript playground for formatted code](https://www.typescriptlang.org/play?#code/MYewdgzgLgBAtgTwPICMBWBTYsC8MDeAUDDAIIBcMAjADTEwBClATHSQMKUDMdAvjAEMIMUJCgBuQoSgIADhhgBZZOixQAagIA2AVwwAVOQrwAKGfJAAzeCszYAlAG0A1hgRWY5jB8So7UAF1JQksdMGwAS3AYCIhNLQiAE3i9AB51GAwADygMMEThMB04FAwAJwA+E3oQdEoAJSwQMsTU6DKIsABzGhh1CrYYADdtPUoikvLCe0oR3QVYvoJ6MowoHTKwGD81ADo5vQgTWrR7Xc7gXUSMI4OFIT77SV4pUPCoKK2utfiklIx0pkcnkCjAJqVKtUSCcGk0Wm0oB1ur1+oM7pR2p0ujAAD5g4oQ3H4rRaIlha6WToYRLTSgZPHkjCUsDU5YkCLWEx3GA4XnE0k4vHc3l4RnM6n2NkkGCrdabGBiqmJSQkfgYLQQBREaUicDQfGTMr-HkwAByBPKXNGGCe9BIso2W1iv2S1uO6F64PK-0lAH4DRDjZRFSzlfQXi9CKJ9d8NNoksodthjXhYy7-qlE6pk9bDPIKrsUJ1ElD+YNfNmoNNxEA)
👋 @christopherschroer! Which version of TypeScript are you using? I just tried pasting ```ts const getValidMyObjectValue = getValidValue<MyObjectValueType>.bind( null, myObject ); ``` into TS playground and [it successfully generated JavaScript](https://www.typescriptlang.org/play?ts=5.0.2#code/MYewdgzgLgBA5gUygNQIYBsCWATAsgTwHkAjAKwWBQwFcEYBeeJNLbF2gHgJPMvYQAq+AA4IAfADpimMNgAUAKBgww1dOgA0SmAFsiZClAUBKANwKgA) for both v5.0.2 and 4.9.5. Apologies @kachkaev. There was an error in the pasted the code above. I have edited the original post/playground link. It should properly reflect the issue. I have also included links in the original post to typescript playground so you can see the difference As for which version of Typescript I am using, it is 5.0.2 I see, thanks! I’ve tried co come up with a shorter example and I _guess_ have been able to reproduce your issue: **Prettier 2.8.7** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAzArlMMCW0AEA5nDABJwA2FEAPAMoQC2cAKgJ4AOc+cAHvFAAmAZ3zB8AC0rUk+YTABOOKIXwBfAHwAKADpR8+GBJzDZDZuy56AlGaatOcANo6QUqhFcBdMXoMKSdAV9IxMAOndqAG49NT09SCh5OS4wHFQcMAB5ACMAKzhsfABeX31JaQhZVwB3CAUKQVcAGj98VAgq-FccgEMFFtj8XtFE+RioPRhHfDpU9MzLblLprghUFMKF7PzCmAmE6GTiGAAhCExBcg8S-C0T6+p6eYywJY1rMJzlQS1hF8yuQK2GsURAzRAEA4uCOyFA-QUEBqAAV+ghhMgQL0KDVemwMRCcgpemAANYkOi9ZgAGWUcGQqGxwjghOJZIpHBJykIyEU6BZIDgjBycEEglF1N6KnQvWIADF6oxejBcCpMb10DAIOC3DBGBQAOrGeD-ElwOjonC4ABuVrYmLAwgJIGUzIUMGRxMISoZTIFeWEvDo3IocAAiugIPBfRRmRDOQo3ZjVnBhGAlNCdRwlLADThBEZkAAOAAM8cRzINxI4mOzqbgCmt9IhAEdI-BPVCMSgRgBaKBwUWinUBNs4AKe2U+pCM2MC5mMHC8hT8iHCENwACCKqUOU1cGRDdpA5jcZA65UoYjUfpM79EJgvRyeYLEmQACYH8ScBRuQBhJhp0FYQAFYdXQZkWCfbtZzPa1+QASSEBAYDodMcGhTchDoaZQ1POA1DUIA) <!-- prettier-ignore --> ```sh --parser typescript ``` **Input:** <!-- prettier-ignore --> ```tsx function getHello<SomeType extends { hello: string }>( this: SomeType ): SomeType["hello"] { return this.hello; } const specificObject = { hello: "world", foo: "bar", } as const; type SpecificType = typeof specificObject; const getBoundHello = (getHello<SpecificType>).bind(specificObject); ``` **Output:** <!-- prettier-ignore --> ```tsx function getHello<SomeType extends { hello: string }>( this: SomeType ): SomeType["hello"] { return this.hello; } const specificObject = { hello: "world", foo: "bar", } as const; type SpecificType = typeof specificObject; const getBoundHello = getHello<SpecificType>.bind(specificObject); ``` ```diff -const getBoundHello = (getHello<SpecificType>).bind(specificObject); // no TS error +const getBoundHello = getHello<SpecificType>.bind(specificObject); // TS error ``` Pasting [before](https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAcwKZQBKoDbbgHgFkBPAFWIAdVFUAPKVMAEwGdEBvRACxzwC5ELKACcYYZIgC+APgAUAKESIoXGCwElyVeQEoNZSqgDaAIh644JgLodFiYehDCkKtQDpzeANzzJ8+RAIQoJUEDDAMBAA8gBGAFao0IgAvLZKnnACJgDucMLYTCYANHbAcJmIJjEAhsLFvojVbIFgQj4BQVAo6ABCcOBMWBYpiLJomLwEUIZwwCGJ4ZGxCdDSOm4xYkyyLKGL0fGJUDo+QA) / [after](https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABAcwKZQBKoDbbgHgFkBPAFWIAdVFUAPKVMAEwGdEBvRACxzwC5ELKACcYYZIgC+APgAUAKESIoXGCwElyVeQEoNZSqgDaAIh644JgLodFiYehDCkKtQDpzeANzzJ8+RAIQoJUEDDAMBAA8gBGAFao0IgAvLZKnnACJgDucMLYTCYANHbAcJmIJjEAhsLFvojVbIFgQj4BQVAo6ABCcOBMWBYp3Zi8BFCGcMAhieGRsQnQ0m4xYkyyLKHz0fGJUDo+QA) into the TypeScript playground produces the following error in the latter case: ```txt An instantiation expression cannot be followed by a property access. ``` My example is quite clumsy, so if you can come up with a concise and clear one, that can help. Either way, this is _probably_ a bug and Prettier should keep the parentheses. Thanks for reporting!
"2023-04-15T06:20:08Z"
3.0
[]
[ "tests/format/typescript/instantiation-expression/jsfmt.spec.js" ]
JavaScript
[]
[ "https://www.typescriptlang.org/play?#code/MYewdgzgLgBAtgTwPICMBWBTYsC8MDeAUDDAIIBcMAjADTEwBClATHSQMKUDMdAvjAEMIMUJCgBuQoSgIADhhgBZZOixQAagIA2AVwwAVOQrwAKGfJAAzeCszYAlAG0A1hgRWY5jB8So7UAF1JQksdMGwAS3AYCIhNLQiAE3i9AB51GAwADygMMEThMB04FAwAJwA+E3oQdEoAJSwQMsTU6DKIsABzGhh1CrYYADdtPUoikvLCe0oR3QVYvoJ6MowoHTKwGD81ADo5vQgTWrR7Xc7gXUSMI4OFIT77SV4pUPCoKK2utfiklIx0pkcnkCjAJqVKtUSCcGk0Wm0oB1ur1+oM7pR2p0ujAAD5g4oQ3H4rRaIlha6WToYRLTSgZPHkjCUsDU5YkCLWEx3GA4XnE0k4vHc3l4RnM6n2NkkGCrdabGBiqmJSQkfgYLQQBREaUicDQfGTMr-HkwAByBPKXNGGCe9BIso2W1iv2S1uO6F64PK-0lAH4DRDjZRFSzlfQXi9CKJ9d8NNoksodthjXhYy7-qlE6pk9bDPIKrsUJ1ElD+YNfNmoNNxEA", "https://www.typescriptlang.org/play?#code/MYewdgzgLgBAtgTwPICMBWBTYsC8MDeAUDDAIIBcMAjADTEwBClATHSQMKUDMhAvjAEMIMUJCgBuQoSgIADhhgBZZOixQAagIA2AVwwAVOQrwAKGfJAAzeCszYAlAG0A1hgRWY5jB8So7UAF1JQksdMGwAS3AYCIhNLQiAE3i9AB51GAwADygMMEThMB04FAwAJwA+E3oQdEoAJSwQMsTU6DKIsABzGhh1Ct76ADdtPUoikvLCe0oR3QVYvoJ6MowoHTKwGD81ADo5vQgTWrR7Xc7gXUSMI4OFIT77SV4pUPCoKK2utfiklIx0pkcnkCjAJqVKtUSCcGk0Wm0oB1ur1+mwYHdKO1Ol0YAAfMHFCF4glaLTEsLXSydDCJaaUDL4ikYKlgGnLEgRawmO4wHB8klk3H4nl8vBMlk0+zskgwVbrTYwcXU2kkfgYLQQBREGUicDQAmTMr-XkwAByhPK3NGGCe9BIco2W1iv2S1uO6F64PK-ylAH4DRDjZQlazEpJVXwpKJ9d8NNoksodthjaZYy7-qlE6pk9bDPIKmcUJ1EiYiqTer5s1AnkA", "https://prettier.io/playground/#N4Igxg9gdgLgprEAuc0DOMAEBbAngeQCMArOMLAXk2AB0pNMBBJTARgBo6GAhFgJk71MAYRYBmOgF9MAQzSZIUDAG46dGLgAOcTAFkCJMjABqMgDYBXOABUtOqgAoN2iADMcB0uQCUAbQDWcLhumM5wIXhEXjAAuqpQdK4WUOQAltCYqWimZqkAJjlWADzGmHAAHvBQefJQFtiEcABOAHwOXJgQJCwASmQQTXlFGE2pUADm7JjGLVMdAG7mVix1Dc103iyLljpZ09QdTXAwFk30UUYAdNtWaA5dxN6XY2CWeXB3Nzpy097xkmooEkUjB0vRxsccvlCnASmVKggaphVo1Wu0hA9ev1BsMYKMJlMZoIGF8WCMxuNMAAfZH1VHU2lmMwM5LvVxjOB5DYsUo01lwdlQTkHISpdwOL6YCjSxnMqk0yXSqj8wWc7wihgMI4nM6YFUcrlCaRwMxoHS0IQMRQYWlrJowqWYABydOaEqWcD+HS1x1O9CyUIKHvuJCmKOaMPVAH5baiHSx9UK8vEGACoGm6NasBCTOZ8voLuQHY4c4GYUUC4Yix7bNoWk9CGM8g46kyppEqzA-iB2CAIJpQehkKAZE0mhAAO4ABVHCDQyBA5gnMlw897hCaMjAgRgAGUZNg4AAZDnIVzmM3rzfb467zRbinIPFWXtwNZ5d55I8yCYWGQQgAxAZsBkGBQQmBcZAsGAIB7EAAAsYGwMwAHV4NSeA0HvMA4F3OcMNSeYMNwBcwDQNcQDGM0mhgKdN3GECzwvOBe2INByl3CkzDgABFCwIHgJjTRYkB7yaaiFzCNAwFGAc4M0fEYBQ-IYHg5AAA4AAZewUiAzRQzdNAXBSPmaeY4DggBHfj4Do-t5xQOQAFohU5Tk4KOazUiOOj-0YpBz2E3szWwVInyaF8QDQLi4EYMDRkIaC4CnZoTyFITLyimK+IEiyAuY3sYBkQhlLyVTkAEEA8RkVJcgmYQIGwfyQA+ABWOCLDNaxiocwLMvmKwAElqgQPcZNSAdGGqXcNG4jK4EkSQgA" ]
prettier/prettier
14,736
prettier__prettier-14736
[ "13017" ]
54404fc96faec9ace7f2422ce9c6ca4f63ab384c
diff --git a/src/language-js/print/array.js b/src/language-js/print/array.js --- a/src/language-js/print/array.js +++ b/src/language-js/print/array.js @@ -9,17 +9,19 @@ import { fill, } from "../../document/builders.js"; import hasNewline from "../../utils/has-newline.js"; +import isNextLineEmptyAfterIndex from "../../utils/is-next-line-empty.js"; +import skipInlineComment from "../../utils/skip-inline-comment.js"; +import skipTrailingComment from "../../utils/skip-trailing-comment.js"; import { shouldPrintComma, hasComment, CommentCheckFlags, - isNextLineEmpty, isNumericLiteral, isSignedNumericLiteral, isArrayOrTupleExpression, isObjectOrRecordExpression, } from "../utils/index.js"; -import { locStart } from "../loc.js"; +import { locStart, locEnd } from "../loc.js"; import { printOptionalToken } from "./misc.js"; import { printTypeAnnotationProperty } from "./type-annotation.js"; @@ -170,6 +172,18 @@ function isConciselyPrintedArray(node, options) { ); } +function isLineAfterElementEmpty({ node }, { originalText: text }) { + const skipComment = (idx) => + skipInlineComment(text, skipTrailingComment(text, idx)); + + const skipToComma = (currentIdx) => + text[currentIdx] === "," + ? currentIdx + : skipToComma(skipComment(currentIdx + 1)); + + return isNextLineEmptyAfterIndex(text, skipToComma(locEnd(node))); +} + function printArrayElements(path, options, elementsProperty, print) { const parts = []; @@ -180,7 +194,7 @@ function printArrayElements(path, options, elementsProperty, print) { parts.push([ ",", line, - node && isNextLineEmpty(node, options) ? softline : "", + node && isLineAfterElementEmpty(path, options) ? softline : "", ]); } }, elementsProperty); @@ -191,12 +205,12 @@ function printArrayElements(path, options, elementsProperty, print) { function printArrayElementsConcisely(path, options, print, trailingComma) { const parts = []; - path.each(({ node, isLast, next }) => { + path.each(({ isLast, next }) => { parts.push([print(), isLast ? trailingComma : ","]); if (!isLast) { parts.push( - isNextLineEmpty(node, options) + isLineAfterElementEmpty(path, options) ? [hardline, hardline] : hasComment(next, CommentCheckFlags.Leading | CommentCheckFlags.Line) ? hardline
diff --git a/tests/format/js/arrays/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/arrays/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/js/arrays/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/arrays/__snapshots__/jsfmt.spec.js.snap @@ -844,6 +844,87 @@ a = [ ] +b = [ + 100, + + (200) + , + + 300 + , + + 1 + , + 2, 3 +] + +c = [ + "apple", + "banana", + "blueberry", + + "red", + "blue" + , + "yellow", + + "broccoli", + "celery", + "lettuce" + , + + "green" + , + "green", + "green", + + //an egg + "egg", + //a bigger egg + "big egg" + //the biggest egg + , + "huge egg" + , + + //not an egg + "lasagna" + +] + +_ = [ + a, + + b // +] + +_ = [ + (a), + + b, // +]; + +_ = [ + ((((( + a = b/* comment */))/* comment */))), + + c // +] + +_ = [ + ((((( + (a = b)/* comment */))/* comment */))), + + c // +] + +_ = [ + (a=b + + ), + b, // +]; + =====================================output===================================== a = [ 1, 2, @@ -853,6 +934,73 @@ a = [ 4, ]; +b = [ + 100, + + 200, + + 300, + + 1, 2, 3, +]; + +c = [ + "apple", + "banana", + "blueberry", + + "red", + "blue", + "yellow", + + "broccoli", + "celery", + "lettuce", + + "green", + "green", + "green", + + //an egg + "egg", + //a bigger egg + "big egg", + //the biggest egg + "huge egg", + + //not an egg + "lasagna", +]; + +_ = [ + a, + + b, // +]; + +_ = [ + a, + + b, // +]; + +_ = [ + (a = b) /* comment */ /* comment */, + + c, // +]; + +_ = [ + (a = b) /* comment */ /* comment */, + + c, // +]; + +_ = [ + (a = b), + b, // +]; + ================================================================================ `; diff --git a/tests/format/js/arrays/preserve_empty_lines.js b/tests/format/js/arrays/preserve_empty_lines.js --- a/tests/format/js/arrays/preserve_empty_lines.js +++ b/tests/format/js/arrays/preserve_empty_lines.js @@ -10,3 +10,84 @@ a = [ ] + +b = [ + 100, + + (200) + , + + 300 + , + + 1 + , + 2, 3 +] + +c = [ + "apple", + "banana", + "blueberry", + + "red", + "blue" + , + "yellow", + + "broccoli", + "celery", + "lettuce" + , + + "green" + , + "green", + "green", + + //an egg + "egg", + //a bigger egg + "big egg" + //the biggest egg + , + "huge egg" + , + + //not an egg + "lasagna" + +] + +_ = [ + a, + + b // +] + +_ = [ + (a), + + b, // +]; + +_ = [ + ((((( + a = b/* comment */))/* comment */))), + + c // +] + +_ = [ + ((((( + (a = b)/* comment */))/* comment */))), + + c // +] + +_ = [ + (a=b + + ), + b, // +]; diff --git a/tests/format/json/json/__snapshots__/jsfmt.spec.js.snap b/tests/format/json/json/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/json/json/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/json/json/__snapshots__/jsfmt.spec.js.snap @@ -1565,6 +1565,7 @@ trailingComma: "all" 0.5, 98.6, 99.44, + 1066, 1e1, 0.1e1, @@ -1695,6 +1696,7 @@ trailingComma: "all" 0.5, 98.6, 99.44, + 1066, 1e1, 0.1e1, @@ -1825,6 +1827,7 @@ trailingComma: "es5" 0.5, 98.6, 99.44, + 1066, 1e1, 0.1e1, @@ -1955,6 +1958,7 @@ trailingComma: "es5" 0.5, 98.6, 99.44, + 1066, 1e1, 0.1e1,
(idempotence violation) Empty line after parenthesized array item **Prettier 2.7.1** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBtAOlABFghlgXiwCMAaTHCrMLAelswF0RSQIAHGAS2gGdlQuAE5CIAdwAKwhPxS4ANmNwBPfq2JDcYANZwYAZVwBbOABkuUOMgBmC3nHWade-ey0WA5shhCArg5A4I2I4ABNQsNNcKA9fXA84ADEIISNcGG4Y5BBcXxgIFhAACxgjeQB1Iq54XjcwOH0Zaq4AN2rlbLBeNRALeyEYCU0PNJs7AIArXgAPfU95OABFXwh4Mfl7VjchfuziXBD5QvYhCxhyrlCYIuQADgAGLdF7cs12bJO4fparVgBHFbwIYcWQ5XgAWksYTChSEcABXDhQ3ioyQtg2AXsRi43j8mPmS0BVjR41YMAOFyuNyQACYyZouPJPABhCBGVGBXgAVkKvnsABUDrJ0ZsQC1-ABJKARWD6MCnTgAQWl+hgygW63sAF8tUA) <!-- prettier-ignore --> ```sh --parser babel ``` **Input:** <!-- prettier-ignore --> ```jsx [ a = b, c // ] ``` **Output:** <!-- prettier-ignore --> ```jsx [ (a = b), c, // ]; ``` **Second Output:** <!-- prettier-ignore --> ```jsx [ (a = b), c, // ]; ```
I haven't been able to replicate this. I'm on macOS and ran a script to compare the output 1000 times, and they were all identical. it may be difficult to determine the cause without more information @solarized-fox the issue is to do with the second output not being equal to the first output, which means that idempotency is violated. This is still true for the latest Prettier: **Prettier 2.8.7** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBtAOlABFghlgXiwCMAaTHCrMLAelswF0RSQIAHGAS2gGdlQuAE5CIAdwAKwhPxS4ANmNwBPfq2JDcYANZwYAZVwBbOABkuUOMgBmC3nHWade-ey0WA5shhCArg5A4I2I4ABNQsNNcKA9fXA84ADEIISNcGG4Y5BBcXxgIFhAACxgjeQB1Iq54XjcwOH0Zaq4AN2rlbLBeNRALeyEYCU0PNJs7AIArXgAPfU95OABFXwh4Mfl7VjchfuziXBD5QvYhCxhyrlCYIuQADgAGLdF7cs12bJO4fparVgBHFbwIYcWQ5XgAWksYTChSEcABXDhQ3ioyQtg2AXsRi43j8mPmS0BVjR41YMAOFyuNyQACYyZouPJPABhCBGVGBXgAVkKvnsABUDrJ0ZsQC1-ABJKARWD6MCnTgAQWl+hgygW63sAF8tUA) <!-- prettier-ignore --> ```sh --parser babel ``` **Input:** <!-- prettier-ignore --> ```jsx [ a = b, c // ] ``` **Output:** <!-- prettier-ignore --> ```jsx [ (a = b), c, // ]; ``` **Second Output:** <!-- prettier-ignore --> ```jsx [ (a = b), c, // ]; ``` I checked Prettier `3.0.0-alpha.6` locally, got the same results. hmm, what OS are you on? I'm running macOS 12.6.x, and this script: ``` echo "[ a = b, c // ]" > foo.js git checkout 3.0.0-alpha.6 printf "$(yarn prettier --parser babel foo.js)\n" printf "$(yarn prettier --parser babel foo.js)\n" ``` produced this output on my machine: ``` HEAD is now at 432976de1 Release 3.0.0-alpha.6 [ (a = b), c, // ]; [ (a = b), c, // ]; ``` could it be possible the issue is connected to the environment somehow? I’m on macOS too, yep. Can you try adding `--write` to `prettier` commands and see what happens? By default, Prettier does not save the results of formatting so you get: ``` source → result 1 source → result 1 ``` instead of ``` source → result 1 result 1 → result 2 ``` If the idempotency principle is followed, we should get: ``` source → result 1 result 1 → result 1 result 1 → result 1 ... ∞ ... ``` ohhh I understand, the second output is supposed to use the input of the first. this gives me a few ideas, I’ll see if I can’t track this bug down I believe I've identified the problem! the node representing `a = b,` in the first input has a range ending on the character `,` while the node representing `(a = b),` has a range ending on the character `)` for some reason. the code tries to skip to the end of the line by passing over the characters `,; \t` of which `)` is not one it seems to me that the problem is with the range assigned to the node in the first place. for what it's worth, the actual location where the newline is omitted on the second output is [line 181 in array.js](https://github.com/prettier/prettier/blob/b232005022b063a7a3b8da2c87b94281a70188bb/src/language-js/print/array.js#L181), where a ternary evaluates differently between the two inputs incidentally since the problem seems to lie simply with the parens, I'm fairly confident that this issue can be boiled down to "these two statements should format the same": ``` _ = [ a = b, c // ] _ = [ (a = b), c, // ]; ``` I'll try and see if I can find a solution but the only part of the codebase I've really read so far is language-js/print so if the problem lies outside of that area (as I suspect it might) this might take me a bit okay after looking into it it appears that parens are just not (or not always) part of the character range covered by their respective node. this means that the last node on a line could be followed by a ")". so it seems the correct thing to do is just modify skipToLineEnd to also ignore ")". yay one character diff, I'll get a PR ready! @solarized-fox there will be comments, more parens ```js [ ((((( a = b/* comment */))/* comment */))), c // ] ``` @fisker adding that to the tests, although it seems the code already accounts for that. it's just the parens that trip it up, apparently
"2023-04-21T11:25:02Z"
3.0
[]
[ "tests/format/json/json/jsfmt.spec.js", "tests/format/js/arrays/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBtAOlABFghlgXiwCMAaTHCrMLAelswF0RSQIAHGAS2gGdlQuAE5CIAdwAKwhPxS4ANmNwBPfq2JDcYANZwYAZVwBbOABkuUOMgBmC3nHWade-ey0WA5shhCArg5A4I2I4ABNQsNNcKA9fXA84ADEIISNcGG4Y5BBcXxgIFhAACxgjeQB1Iq54XjcwOH0Zaq4AN2rlbLBeNRALeyEYCU0PNJs7AIArXgAPfU95OABFXwh4Mfl7VjchfuziXBD5QvYhCxhyrlCYIuQADgAGLdF7cs12bJO4fparVgBHFbwIYcWQ5XgAWksYTChSEcABXDhQ3ioyQtg2AXsRi43j8mPmS0BVjR41YMAOFyuNyQACYyZouPJPABhCBGVGBXgAVkKvnsABUDrJ0ZsQC1-ABJKARWD6MCnTgAQWl+hgygW63sAF8tUA" ]
prettier/prettier
14,788
prettier__prettier-14788
[ "14148" ]
dfe32bcc388388ed27dce93096e2f920086e3d00
diff --git a/src/cli/format.js b/src/cli/format.js --- a/src/cli/format.js +++ b/src/cli/format.js @@ -21,13 +21,24 @@ function diff(a, b) { class DebugError extends Error {} function handleError(context, filename, error, printedFilename) { - if (error instanceof errors.UndefinedParserError) { + const errorIsUndefinedParseError = + error instanceof errors.UndefinedParserError; + + if (printedFilename) { // Can't test on CI, `isTTY()` is always false, see ./is-tty.js /* c8 ignore next 3 */ - if ((context.argv.write || context.argv.ignoreUnknown) && printedFilename) { + if ( + (context.argv.write || context.argv.ignoreUnknown) && + errorIsUndefinedParseError + ) { printedFilename.clear(); + } else { + // Add newline to split errors from filename line. + process.stdout.write("\n"); } + } + if (errorIsUndefinedParseError) { if (context.argv.ignoreUnknown) { return; } @@ -38,11 +49,6 @@ function handleError(context, filename, error, printedFilename) { return; } - if (context.argv.write) { - // Add newline to split errors from filename line. - process.stdout.write("\n"); - } - const isParseError = Boolean(error?.loc); const isValidationError = /^Invalid \S+ value\./.test(error?.message);
diff --git a/tests/integration/__tests__/__snapshots__/line-after-filepath-with-errors.js.snap b/tests/integration/__tests__/__snapshots__/line-after-filepath-with-errors.js.snap new file mode 100644 --- /dev/null +++ b/tests/integration/__tests__/__snapshots__/line-after-filepath-with-errors.js.snap @@ -0,0 +1,85 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Line breaking after filepath with errors (stderr) 1`] = ` +"[error] invalid-1.js: SyntaxError: Unexpected token (1:8) +[error] > 1 | foo (+-) bar +[error] | ^ +[error] 2 | +[error] invalid-2.js: SyntaxError: Unexpected token (1:8) +[error] > 1 | foo (+-) bar +[error] | ^ +[error] 2 | +[error] No parser could be inferred for file "<cli>/syntax-errors/invalid-2.unknown"." +`; + +exports[`Line breaking after filepath with errors (stderr) 2`] = ` +"[error] invalid-1.js: SyntaxError: Unexpected token (1:8) +[error] > 1 | foo (+-) bar +[error] | ^ +[error] 2 | +[error] invalid-2.js: SyntaxError: Unexpected token (1:8) +[error] > 1 | foo (+-) bar +[error] | ^ +[error] 2 | +[error] No parser could be inferred for file "<cli>/syntax-errors/invalid-2.unknown"." +`; + +exports[`Line breaking after filepath with errors (stderr) 3`] = ` +"[error] invalid-1.js: SyntaxError: Unexpected token (1:8) +[error] > 1 | foo (+-) bar +[error] | ^ +[error] 2 | +[error] invalid-2.js: SyntaxError: Unexpected token (1:8) +[error] > 1 | foo (+-) bar +[error] | ^ +[error] 2 | +[error] No parser could be inferred for file "<cli>/syntax-errors/invalid-2.unknown"." +`; + +exports[`Line breaking after filepath with errors (stderr) 4`] = ` +"[error] invalid-1.js: SyntaxError: Unexpected token (1:8) +[error] > 1 | foo (+-) bar +[error] | ^ +[error] 2 | +[error] invalid-2.js: SyntaxError: Unexpected token (1:8) +[error] > 1 | foo (+-) bar +[error] | ^ +[error] 2 | +[error] No parser could be inferred for file "<cli>/syntax-errors/invalid-2.unknown"." +`; + +exports[`Line breaking after filepath with errors (stdout) 1`] = ` +"invalid-1.js +invalid-2.js +invalid-2.unknown +valid-1.jsfunction foo() {}" +`; + +exports[`Line breaking after filepath with errors (stdout) 2`] = ` +"invalid-1.js +invalid-2.js +invalid-2.unknown +valid-1.js" +`; + +exports[`Line breaking after filepath with errors (stdout) 3`] = ` +"Checking formatting... +invalid-1.js +invalid-2.js +invalid-2.unknown +valid-1.jsAll matched files use Prettier code style!" +`; + +exports[`Line breaking after filepath with errors (stdout) 4`] = ` +"invalid-1.js +invalid-2.js +invalid-2.unknownvalid-1.jsvalid-1.js 0ms" +`; + +exports[`Line breaking after filepath with errors (write) 1`] = `[]`; + +exports[`Line breaking after filepath with errors (write) 2`] = `[]`; + +exports[`Line breaking after filepath with errors (write) 3`] = `[]`; + +exports[`Line breaking after filepath with errors (write) 4`] = `[]`; diff --git a/tests/integration/__tests__/line-after-filepath-with-errors.js b/tests/integration/__tests__/line-after-filepath-with-errors.js new file mode 100644 --- /dev/null +++ b/tests/integration/__tests__/line-after-filepath-with-errors.js @@ -0,0 +1,18 @@ +import jestPathSerializer from "../path-serializer.js"; + +expect.addSnapshotSerializer(jestPathSerializer); + +describe("Line breaking after filepath with errors", () => { + runCli("cli/syntax-errors", ["./*.{js,unknown}"], { + stdoutIsTTY: true, + }).test({ status: 2 }); + runCli("cli/syntax-errors", ["--list-different", "./*.{js,unknown}"], { + stdoutIsTTY: true, + }).test({ status: 2 }); + runCli("cli/syntax-errors", ["--check", "./*.{js,unknown}"], { + stdoutIsTTY: true, + }).test({ status: 2 }); + runCli("cli/syntax-errors", ["--write", "./*.{js,unknown}"], { + stdoutIsTTY: true, + }).test({ status: 2 }); +}); diff --git a/tests/integration/cli/syntax-errors/invalid-1.js b/tests/integration/cli/syntax-errors/invalid-1.js new file mode 100644 --- /dev/null +++ b/tests/integration/cli/syntax-errors/invalid-1.js @@ -0,0 +1 @@ +foo (+-) bar diff --git a/tests/integration/cli/syntax-errors/invalid-2.js b/tests/integration/cli/syntax-errors/invalid-2.js new file mode 100644 --- /dev/null +++ b/tests/integration/cli/syntax-errors/invalid-2.js @@ -0,0 +1 @@ +foo (+-) bar diff --git a/tests/integration/cli/syntax-errors/invalid-2.unknown b/tests/integration/cli/syntax-errors/invalid-2.unknown new file mode 100644 diff --git a/tests/integration/cli/syntax-errors/valid-1.js b/tests/integration/cli/syntax-errors/valid-1.js new file mode 100644 --- /dev/null +++ b/tests/integration/cli/syntax-errors/valid-1.js @@ -0,0 +1 @@ +function foo() {}
--list-different logs errors after file path instead of in a new line **Environments:** - Prettier Version: 2.8.2 - Running Prettier via: CLI - Operating System: all **Steps to reproduce:** create a index.js file with a syntax issue in it, then run: ```bash npx prettier --list-different "./**/*.{js,jsx,ts,tsx,scss,json}" ``` **Actual behavior:** the output will be: ```log path/to/file/index.js[error] path/to/file/index.js: SyntaxError: Unexpected token, expected "," (5:1) [error] 3 | [error] 4 | console.log("test: create a js syntax error here" [error] > 5 | export { test }; [error] | ^ [error] 6 | ``` **Expected behavior:** ```log path/to/file/index.js [error] path/to/file/index.js: SyntaxError: Unexpected token, expected "," (5:1) [error] 3 | [error] 4 | console.log("test: create a js syntax error here" [error] > 5 | export { test }; [error] | ^ [error] 6 | ``` Also, it would be great to have a flag (e.g. `--no-error`) that will stop prettier from logging errors, and it will just log the file path, so the output will be: ```log path/to/file/index.js ```
@fisker, @thorn0, @sosukesuzuki sorry for disturbing you, would you please have a look at this issue?
"2023-05-03T08:50:13Z"
3.0
[]
[ "tests/integration/__tests__/line-after-filepath-with-errors.js" ]
JavaScript
[]
[]
prettier/prettier
14,830
prettier__prettier-14830
[ "14786" ]
20ab6d6f1c5bd774621230b493a3b71d39383a2c
diff --git a/src/language-js/print/object.js b/src/language-js/print/object.js --- a/src/language-js/print/object.js +++ b/src/language-js/print/object.js @@ -118,7 +118,8 @@ function printObject(path, options, print) { if ( (prop.node.type === "TSPropertySignature" || prop.node.type === "TSMethodSignature" || - prop.node.type === "TSConstructSignatureDeclaration") && + prop.node.type === "TSConstructSignatureDeclaration" || + prop.node.type === "TSCallSignatureDeclaration") && hasComment(prop.node, CommentCheckFlags.PrettierIgnore) ) { separatorParts.shift();
diff --git a/tests/format/typescript/call-signature/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/call-signature/__snapshots__/jsfmt.spec.js.snap new file mode 100644 --- /dev/null +++ b/tests/format/typescript/call-signature/__snapshots__/jsfmt.spec.js.snap @@ -0,0 +1,131 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`call-signature.ts format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +type T = { + (): void; + second: string; +}; + +type T = { + (): void; // prettier-ignore + second: string; +}; + +type T = { + (): void; // comment + second: string; +}; + +type T = { + first: string; + (): void; +}; + +type T = { + first: string; + (): void; // prettier-ignore +}; + +type T = { + first: string; + (): void; // comment +}; + +interface I { + (): void; + second: string; +} + +interface I { + (): void; // prettier-ignore + second: string; +} + +interface I { + (): void; // comment + second: string; +} + +interface I { + first: string; + (): void; +} + +interface I { + first: string; + (): void; // prettier-ignore +} + +interface I { + first: string; + (): void; // comment +} + +=====================================output===================================== +type T = { + (): void; + second: string; +}; + +type T = { + (): void; // prettier-ignore + second: string; +}; + +type T = { + (): void; // comment + second: string; +}; + +type T = { + first: string; + (): void; +}; + +type T = { + first: string; + (): void; // prettier-ignore +}; + +type T = { + first: string; + (): void; // comment +}; + +interface I { + (): void; + second: string; +} + +interface I { + (): void; // prettier-ignore + second: string; +} + +interface I { + (): void; // comment + second: string; +} + +interface I { + first: string; + (): void; +} + +interface I { + first: string; + (): void; // prettier-ignore +} + +interface I { + first: string; + (): void; // comment +} + +================================================================================ +`; diff --git a/tests/format/typescript/call-signature/call-signature.ts b/tests/format/typescript/call-signature/call-signature.ts new file mode 100644 --- /dev/null +++ b/tests/format/typescript/call-signature/call-signature.ts @@ -0,0 +1,59 @@ +type T = { + (): void; + second: string; +}; + +type T = { + (): void; // prettier-ignore + second: string; +}; + +type T = { + (): void; // comment + second: string; +}; + +type T = { + first: string; + (): void; +}; + +type T = { + first: string; + (): void; // prettier-ignore +}; + +type T = { + first: string; + (): void; // comment +}; + +interface I { + (): void; + second: string; +} + +interface I { + (): void; // prettier-ignore + second: string; +} + +interface I { + (): void; // comment + second: string; +} + +interface I { + first: string; + (): void; +} + +interface I { + first: string; + (): void; // prettier-ignore +} + +interface I { + first: string; + (): void; // comment +} diff --git a/tests/format/typescript/call-signature/jsfmt.spec.js b/tests/format/typescript/call-signature/jsfmt.spec.js new file mode 100644 --- /dev/null +++ b/tests/format/typescript/call-signature/jsfmt.spec.js @@ -0,0 +1 @@ +run_spec(import.meta, ["typescript"]);
Bug report: using `// prettier-ignore` on a call signature line leads to broken code on format **Prettier 2.8.8** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEMCeAHOACAYhCbAXm2AB0ptsAKASiWwDcIBLAEwG5sB6b7DAE5wYMFnAEBaFgHMoEIRSoBnOJChsGSmAJZRpHCgF8DUEABoQEDKOhLkoAIYCBEAO4AFJwjsoHAG1cHNDsLACMBBzAAa2EAZQcAWzgAGV04ZAAzfxUwiOi4jEjdaWRtAFc4CzgE0Lg2Njrkhz0yh2k4fAEEhxFi5BAHMpgIcxAACxgEvwB1MZZ4JUKwOFjveZZGebR+sCUQkF0VARh3COluzOzKkAArJQAPWOK-OABFMoh4S78ckEKBI79dBYJRgHTWUaCXQwabsGBjZAADgADBZBBAVNMIhh+oI4EdGOkLABHD7wU5WHwDJQSKBwOp1UZCUksISnNoXJBZH7XFQJFilAQVCxKZ5wACCIh0oSGcHc4lSdO+v1Fehe70+6S5VwsMAcoVhbHhyAATLqIiw-MUAMIQBKckD4gCsozKKgAKvqfNzfowKgBJdQIGCxMEsazi9SxdAvZVwQyGIA) <!-- prettier-ignore --> ```sh --parser typescript ``` **Input:** <!-- prettier-ignore --> ```tsx type Foo = { (): void; // prettier-ignore second: string; }; ``` This is for the `typescript` parser only, the `babel` parser seems unaffected. Key parts to reproduce: 1. Create a type definition (or an interface type, it has the same bug); 2. Add a call signature property (e.g. the `(): void` part in the linked playground), and `prettier-ignore` that line; 3. Add another property below it. The bug does not occur if the call signature is the last property in the type. **Output:** <!-- prettier-ignore --> ```tsx type Foo = { (): void;; // prettier-ignore second: string; }; ``` Due to the `;;` part, the code actually breaks and becomes invalid TypeScript on save. **Expected behavior:** The output contains no double semicolon, i.e. the `;;` part.
Hello, I don't have prior experience contributing to this project, but I would like to work on this issue as a good first issue. If I find a solution, I plan to submit a pull request.
"2023-05-17T03:57:50Z"
3.0
[]
[ "tests/format/typescript/call-signature/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEMCeAHOACAYhCbAXm2AB0ptsAKASiWwDcIBLAEwG5sB6b7DAE5wYMFnAEBaFgHMoEIRSoBnOJChsGSmAJZRpHCgF8DUEABoQEDKOhLkoAIYCBEAO4AFJwjsoHAG1cHNDsLACMBBzAAa2EAZQcAWzgAGV04ZAAzfxUwiOi4jEjdaWRtAFc4CzgE0Lg2Njrkhz0yh2k4fAEEhxFi5BAHMpgIcxAACxgEvwB1MZZ4JUKwOFjveZZGebR+sCUQkF0VARh3COluzOzKkAArJQAPWOK-OABFMoh4S78ckEKBI79dBYJRgHTWUaCXQwabsGBjZAADgADBZBBAVNMIhh+oI4EdGOkLABHD7wU5WHwDJQSKBwOp1UZCUksISnNoXJBZH7XFQJFilAQVCxKZ5wACCIh0oSGcHc4lSdO+v1Fehe70+6S5VwsMAcoVhbHhyAATLqIiw-MUAMIQBKckD4gCsozKKgAKvqfNzfowKgBJdQIGCxMEsazi9SxdAvZVwQyGIA" ]
prettier/prettier
14,858
prettier__prettier-14858
[ "14808" ]
2a864e515769073e7d668a94ceadb29ff58613a7
diff --git a/src/language-js/print/type-parameters.js b/src/language-js/print/type-parameters.js --- a/src/language-js/print/type-parameters.js +++ b/src/language-js/print/type-parameters.js @@ -7,6 +7,8 @@ import { group, indent, ifBreak, + lineSuffixBoundary, + indentIfBreak, } from "../../document/builders.js"; import { isTestCall, @@ -171,7 +173,13 @@ function printTypeParameter(path, options, print) { } if (node.constraint) { - parts.push(" extends", indent([line, print("constraint")])); + const groupId = Symbol("constraint"); + parts.push( + " extends", + group(indent(line), { id: groupId }), + lineSuffixBoundary, + indentIfBreak(print("constraint"), { groupId }) + ); } if (node.default) {
diff --git a/tests/format/typescript/typeparams/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/typeparams/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/typescript/typeparams/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/typescript/typeparams/__snapshots__/jsfmt.spec.js.snap @@ -404,12 +404,91 @@ export type OuterType3< export type OuterType4< LongerLongerLongerLongerInnerType extends - LongerLongerLongerLongerLongerLo | ngerLongerLongerOtherType, + | LongerLongerLongerLongerLongerLo + | ngerLongerLongerOtherType, > = { a: 1 }; ================================================================================ `; +exports[`line-breaking-after-extends-2.ts format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +a = { + parseFunctionBodyAndFinish< + T extends + | N.Function + | N.TSDeclareMethod + | N.TSDeclareFunction + | N.ClassPrivateMethod, + >() {} +} + +function parseFunctionBodyAndFinish< + T extends + | N.Function + | N.TSDeclareMethod + | N.TSDeclareFunction + | N.ClassPrivateMethod + | Foo + | Bar + | Baz +>(); + +function parseFunctionBodyAndFinish< + T extends // comment + N.Function | N.TSDeclareMethod | Baz +>(); + +function makeChainWalker< + ArgT extends { + options: ValidatedOptions; + dirname: string; + filepath?: string; + }, +>() {} + +=====================================output===================================== +a = { + parseFunctionBodyAndFinish< + T extends + | N.Function + | N.TSDeclareMethod + | N.TSDeclareFunction + | N.ClassPrivateMethod, + >() {}, +}; + +function parseFunctionBodyAndFinish< + T extends + | N.Function + | N.TSDeclareMethod + | N.TSDeclareFunction + | N.ClassPrivateMethod + | Foo + | Bar + | Baz, +>(); + +function parseFunctionBodyAndFinish< + T extends // comment + N.Function | N.TSDeclareMethod | Baz, +>(); + +function makeChainWalker< + ArgT extends { + options: ValidatedOptions; + dirname: string; + filepath?: string; + }, +>() {} + +================================================================================ +`; + exports[`long-function-arg.ts format 1`] = ` ====================================options===================================== parsers: ["typescript"] diff --git a/tests/format/typescript/typeparams/line-breaking-after-extends-2.ts b/tests/format/typescript/typeparams/line-breaking-after-extends-2.ts new file mode 100644 --- /dev/null +++ b/tests/format/typescript/typeparams/line-breaking-after-extends-2.ts @@ -0,0 +1,33 @@ +a = { + parseFunctionBodyAndFinish< + T extends + | N.Function + | N.TSDeclareMethod + | N.TSDeclareFunction + | N.ClassPrivateMethod, + >() {} +} + +function parseFunctionBodyAndFinish< + T extends + | N.Function + | N.TSDeclareMethod + | N.TSDeclareFunction + | N.ClassPrivateMethod + | Foo + | Bar + | Baz +>(); + +function parseFunctionBodyAndFinish< + T extends // comment + N.Function | N.TSDeclareMethod | Baz +>(); + +function makeChainWalker< + ArgT extends { + options: ValidatedOptions; + dirname: string; + filepath?: string; + }, +>() {}
Regression in v3 **Prettier pr-14803** [Playground link](https://deploy-preview-14803--prettier.netlify.app/playground/#N4Igxg9gdgLgprEAuEAzArlMMCW0AEAtgIYDWcAwgBbE5QDqxANuQE4A8AOlPvgIKsA5gBV8cAB7woAEwDO+YN168IAB1zRZSfADVmOacXjSA8urxRZAbiXLpOVlGKE422TFZ1BNnstQ4mOFUjKgB+Nw8vH14AXwAabgA+AAoASgUYkDiQNQ1LZFBiVlYIAHcABSKEWWQQZlLiAE8a7IAjVmIwchgAZWc4ABk6OGRUZlk4No6uuF7gsC9kD3RJkAnCHCXWFezZL0CARXQIeFHx1YArWXEe-bgjk5GkMaYJ7IBHY-hyktUalGIsgAtFA4HBpOCsiAPLQmF4KBBCCRaswmFC9lBBIE+DBIq10N84KwhqCzq9VlQYIQmPQqDh4LJ5nAetV6TgAG70xq1MCyFogdkrACSMgQvTAnnUfBkPRgjUCZLeIFUJQm9A6qlqKrgE1Y7JG2ToupgP2IgmRz3O2WCrF1tTlqh1Epw6ihKroMHoBhgVGQAA4AAzZVhwT4OOCm83ERWrGDEVpe6Q+5AAJmy6Amwnj-xeSrghFa4Ih0gGxEx6DNcAAYhBWCRcYsAQSICAYjEgA) <!-- prettier-ignore --> ```sh --parser typescript ``` **Input:** <!-- prettier-ignore --> ```tsx function makeChainWalker< ArgT extends { options: ValidatedOptions; dirname: string; filepath?: string; }, >() {} ``` **Output:** <!-- prettier-ignore --> ```tsx function makeChainWalker< ArgT extends { options: ValidatedOptions; dirname: string; filepath?: string; }, >() {} ``` **Expected behavior:** (V2 output should be preferred) ```tsx function makeChainWalker< ArgT extends { options: ValidatedOptions; dirname: string; filepath?: string; } >() {} ``` Maybe the same problem as https://github.com/prettier/prettier/issues/14809 https://github.com/babel/babel/pull/15617/files#r1187671092
"2023-05-25T07:00:10Z"
3.0
[]
[ "tests/format/typescript/typeparams/jsfmt.spec.js" ]
JavaScript
[]
[ "https://deploy-preview-14803--prettier.netlify.app/playground/#N4Igxg9gdgLgprEAuEAzArlMMCW0AEAtgIYDWcAwgBbE5QDqxANuQE4A8AOlPvgIKsA5gBV8cAB7woAEwDO+YN168IAB1zRZSfADVmOacXjSA8urxRZAbiXLpOVlGKE422TFZ1BNnstQ4mOFUjKgB+Nw8vH14AXwAabgA+AAoASgUYkDiQNQ1LZFBiVlYIAHcABSKEWWQQZlLiAE8a7IAjVmIwchgAZWc4ABk6OGRUZlk4No6uuF7gsC9kD3RJkAnCHCXWFezZL0CARXQIeFHx1YArWXEe-bgjk5GkMaYJ7IBHY-hyktUalGIsgAtFA4HBpOCsiAPLQmF4KBBCCRaswmFC9lBBIE+DBIq10N84KwhqCzq9VlQYIQmPQqDh4LJ5nAetV6TgAG70xq1MCyFogdkrACSMgQvTAnnUfBkPRgjUCZLeIFUJQm9A6qlqKrgE1Y7JG2ToupgP2IgmRz3O2WCrF1tTlqh1Epw6ihKroMHoBhgVGQAA4AAzZVhwT4OOCm83ERWrGDEVpe6Q+5AAJmy6Amwnj-xeSrghFa4Ih0gGxEx6DNcAAYhBWCRcYsAQSICAYjEgA" ]
prettier/prettier
15,076
prettier__prettier-15076
[ "15007" ]
c9b479edca4d16fcb8588840d684fb4f5a9d9a87
diff --git a/src/language-js/comments/handle-comments.js b/src/language-js/comments/handle-comments.js --- a/src/language-js/comments/handle-comments.js +++ b/src/language-js/comments/handle-comments.js @@ -208,7 +208,9 @@ function handleIfStatementComments({ addDanglingComment( precedingNode, comment, - markerForIfWithoutBlockAndSameLineComment, + precedingNode.type === "ExpressionStatement" + ? markerForIfWithoutBlockAndSameLineComment + : undefined, ); } else { addDanglingComment(enclosingNode, comment);
diff --git a/tests/format/js/if/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/if/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/js/if/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/if/__snapshots__/jsfmt.spec.js.snap @@ -93,26 +93,44 @@ parsers: ["babel", "flow", "typescript"] printWidth: 80 | printWidth =====================================input====================================== -if (a === 0) doSomething(); // comment A1 + if (a === 0) doSomething(); // comment A1 else if (a === 1) doSomethingElse(); // comment B1 else if (a === 2) doSomethingElse(); // comment C1 -if (a === 0) doSomething(); /* comment A2 */ + if (a === 0) doSomething(); /* comment A2 */ else if (a === 1) doSomethingElse(); /* comment B2 */ else if (a === 2) doSomethingElse(); /* comment C2 */ -if (a === 0) expr; // comment A3 + if (a === 0) expr; // comment A3 else if (a === 1) expr; // comment B3 else if (a === 2) expr; // comment C3 -if (a === 0) expr; /* comment A4 */ + if (a === 0) expr; /* comment A4 */ else if (a === 1) expr; /* comment B4 */ else if (a === 2) expr; /* comment C4 */ -if (a === 0) looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // comment A5 + if (a === 0) looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // comment A5 else if (a === 1) looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // comment B5 else if (a === 2) looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // comment C5 +function a() { + if (a) return; /* comment 6a */ + else return 2; + + if (a) return 1; /* comment 6b */ + else return 2; + + if (a) throw e; /* comment 6d */ + else return 2; + + // TODO[@fisker]: fix this + // if (a) var a = 1; /* comment 6e */ + // else return 2; + + if (a) if (b); /* comment 6f */ + else return 2; +} + =====================================output===================================== if (a === 0) doSomething(); // comment A1 else if (a === 1) doSomethingElse(); // comment B1 @@ -137,6 +155,25 @@ else if (a === 1) else if (a === 2) looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // comment C5 +function a() { + if (a) return /* comment 6a */; + else return 2; + + if (a) return 1 /* comment 6b */; + else return 2; + + if (a) throw e /* comment 6d */; + else return 2; + + // TODO[@fisker]: fix this + // if (a) var a = 1; /* comment 6e */ + // else return 2; + + if (a) + if (b /* comment 6f */); + else return 2; +} + ================================================================================ `; diff --git a/tests/format/js/if/expr_and_same_line_comments.js b/tests/format/js/if/expr_and_same_line_comments.js --- a/tests/format/js/if/expr_and_same_line_comments.js +++ b/tests/format/js/if/expr_and_same_line_comments.js @@ -1,19 +1,37 @@ -if (a === 0) doSomething(); // comment A1 + if (a === 0) doSomething(); // comment A1 else if (a === 1) doSomethingElse(); // comment B1 else if (a === 2) doSomethingElse(); // comment C1 -if (a === 0) doSomething(); /* comment A2 */ + if (a === 0) doSomething(); /* comment A2 */ else if (a === 1) doSomethingElse(); /* comment B2 */ else if (a === 2) doSomethingElse(); /* comment C2 */ -if (a === 0) expr; // comment A3 + if (a === 0) expr; // comment A3 else if (a === 1) expr; // comment B3 else if (a === 2) expr; // comment C3 -if (a === 0) expr; /* comment A4 */ + if (a === 0) expr; /* comment A4 */ else if (a === 1) expr; /* comment B4 */ else if (a === 2) expr; /* comment C4 */ -if (a === 0) looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // comment A5 + if (a === 0) looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // comment A5 else if (a === 1) looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // comment B5 else if (a === 2) looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // comment C5 + +function a() { + if (a) return; /* comment 6a */ + else return 2; + + if (a) return 1; /* comment 6b */ + else return 2; + + if (a) throw e; /* comment 6d */ + else return 2; + + // TODO[@fisker]: fix this + // if (a) var a = 1; /* comment 6e */ + // else return 2; + + if (a) if (b); /* comment 6f */ + else return 2; +}
Skip single characters was not printed. Please report this error! when ever i try to format my js file , it gives me this error ["ERROR" - 10:30:02 PM] Error formatting document. ["ERROR" - 10:30:02 PM] Comment "Skip single characters" was not printed. Please report this error!
Please use the [issue template](https://github.com/prettier/prettier/tree/main/.github/ISSUE_TEMPLATE) to help us reproduce the bug. What source code was producing the error? @kachkaev, I also have the same issue in typescript file after I updated to prettier 3.0.0 from 2.8.8 ``` const a = { project: "SchemaCheck.String()", ns_dcs: [ "SchemaCheck.StringArray()", (props:any) => { const val = props.value as string[] if (val.length == 2) return undefined // return success else return { message: 'array must include 2 items' } }, ], } ``` output in vscode: ``` ["INFO" - 1:30:39 PM] Formatting file:///home/op/packages/base-lib/src/coreTypes/messageTypes/ezDemoGre.ts ["INFO" - 1:30:39 PM] Using config file at '/home/op/packages/base-lib/.prettierrc.js' ["INFO" - 1:30:39 PM] PrettierInstance: { "modulePath": "/home/op/node_modules/prettier/index.cjs", "importResolver": {}, "callMethodResolvers": {}, "currentCallMethodId": 79, "version": "3.0.0" } ["INFO" - 1:30:39 PM] Using ignore file (if present) at /home/op/packages/base-lib/.prettierignore ["INFO" - 1:30:39 PM] File Info: { "ignored": false, "inferredParser": "typescript" } ["INFO" - 1:30:39 PM] Detected local configuration (i.e. .prettierrc or .editorconfig), VS Code configuration will not be used ["INFO" - 1:30:39 PM] Prettier Options: { "filepath": "/home/op/packages/base-lib/src/coreTypes/messageTypes/ezDemoGre.ts", "parser": "typescript", "arrowParens": "always", "bracketSpacing": true, "bracketSameLine": false, "jsxSingleQuote": true, "printWidth": 100, "quoteProps": "consistent", "rangeStart": 0, "rangeEnd": null, "semi": false, "singleQuote": true, "tabWidth": 2, "trailingComma": "es5", "useTabs": false, "endOfLine": "lf" } ["ERROR" - 1:30:39 PM] Error formatting document. ["ERROR" - 1:30:39 PM] Comment "return success" was not printed. Please report this error! Error: Comment "return success" was not printed. Please report this error! at ensureAllCommentsPrinted (file:///home/op/node_modules/prettier/index.mjs:17941:13) at printAstToDoc (file:///home/op/node_modules/prettier/index.mjs:18102:3) at async coreFormat (file:///home/op/node_modules/prettier/index.mjs:18405:14) at async formatWithCursor (file:///home/op/node_modules/prettier/index.mjs:18603:14) at async Module.format2 (file:///home/op/node_modules/prettier/index.mjs:21789:25) ["INFO" - 1:30:39 PM] Formatting completed in 13ms. ``` Ok I think I got the problem. [playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAdKB6DUIwAQDuEATgNYCWUA5npACZzpa3QDO+AhngLx7BMY8QgA7EIAKzhgYSPKhABlMAAs4AWw4BhVWFIA6BTGKUqACgCU8gDToBQvFFYB9OmFayA2nftzFK9Vo6+obG1ACCxMQcAJ4W1t72pqIQwu4cUNHmPAB8fAk+kI74AG4cADY8eMmpeqVlAK5weByseOyhVB4Auvn25ABmeKZ1emUIVDDKPLwATFnEcDD1xFB49VAM-ZRwdADceMwLSytt9WBgcKysvUJwZaxNR8urwHhql6wcVHCyAOQckRib3q7DwlDADQYeBmYPgalYvzwAF9ekibJhBEIulYhHYUVBbBjCCQKNQ8CkYORoOhCqDBrwkmJUkh0pkcnlViwing6pVqqxauVGs1Wu0TN10EIBkMRmNqJNptDzPxOfYnid1pttnQDoJ1atWGcLldJcjTXcHnh9Xw3h8vj88P9AdFgaDwZCmjDyHCEWaoEiQFYQBSqY5kKAAWICAAFAEIVjIEDlAgxBNBgBGUV0iwUHHeABltsh+uUHhms6Qc8IOGATMgjI0gw81OR68RGyBWCYxgBFeq4ODF0twIPiVgADwU3bgfYHQ-uI5AAEd+-Bo0yEygWgBaKBwHY7QMgIwcchlEyaCBqDSJ8plI9d6hjMIwIzkdP1NdwYiFvfzssgMoMBqGUADqyjepc1YXAo8beuQxTetEiZuGmIDFI0ACSGwIDASjGMIMBhBshjRGM-6LskDygVEwiJqIlzfsUg5BpQDzEDA65fDeSAlguQbVsQ7GJjA0TCJcYAETAR6iJQMCgeQdCTMgAAcAAMQYLCu5ALFxVA8XxAEwBw6YKUpyjIDMQYgnAAAqJmboZi7qOmOwMHQ+bpFQ9T2gAYiQGivnWW6fhAIBIkiQA) ### The Code in Question: ```typescript const a = { project: "SchemaCheck.String()", ns_dcs: [ "SchemaCheck.StringArray()", (props:any) => { const val = props.value as string[] if (val.length == 2) return undefined // return success else return { message: 'array must include 2 items' } }, ], } ``` ### Result So by formatting the former coed using prettier playground, I received the following error: ``` Error: Comment "return success" was not printed. Please report this error! at pu (https://prettier.io/lib/standalone.js:27:5829) at Ze (https://prettier.io/lib/standalone.js:27:7320) at async Ou (https://prettier.io/lib/standalone.js:27:11026) at async Rr (https://prettier.io/lib/standalone.js:32:581) at async formatCode (https://prettier.io/worker.js:170:12) at async handleFormatMessage (https://prettier.io/worker.js:82:24) at async self.onmessage (https://prettier.io/worker.js:37:14) ```` This error specifically refers to the one-line comment "return success" being adjacent to a real return statement. ### Solution: Curly brackets by adding curly brackets to the if-statement I was able to successfully run `prettier` ### The Code ```typescript const f = (props:any) => { const val = props.value as string[] if (val.length == 2){ return undefined // return success } else return { message: 'array must include 2 items' } } ``` ### The Reason - trying to prettify the comment as code because of "return ..." I think `Prettier` thinks the comment is a code incorrectly. Might be a bug in the breakdown to AST of single-line comments in single-line If-statements. Edit: @kachkaev That should give you more than enough info to take it from here 😄
"2023-07-11T05:58:03Z"
3.1
[]
[ "tests/format/js/if/jsfmt.spec.js" ]
JavaScript
[]
[]
prettier/prettier
15,204
prettier__prettier-15204
[ "15208" ]
892a1cfba6690a8fae154f307cd9079d2fe07c57
diff --git a/src/language-js/print/assignment.js b/src/language-js/print/assignment.js --- a/src/language-js/print/assignment.js +++ b/src/language-js/print/assignment.js @@ -205,7 +205,11 @@ function shouldBreakAfterOperator(path, options, print, hasShortKey) { let node = rightNode; const propertiesForPath = []; for (;;) { - if (node.type === "UnaryExpression") { + if ( + node.type === "UnaryExpression" || + node.type === "AwaitExpression" || + (node.type === "YieldExpression" && node.argument !== null) + ) { node = node.argument; propertiesForPath.push("argument"); } else if (node.type === "TSNonNullExpression") {
diff --git a/tests/format/js/assignment/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/assignment/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/js/assignment/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/assignment/__snapshots__/jsfmt.spec.js.snap @@ -278,6 +278,104 @@ printWidth: 80 ================================================================================ `; +exports[`discussion-15196.js format 1`] = ` +====================================options===================================== +parsers: ["babel", "flow", "typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +async function f() { + const { section, rubric, authors, tags } = await utils.upsertCommonData(mainData); + + const loooooooooooooooooooooooooong1 = await looooooooooooooong.looooooooooooooong.loooooong; + const loooooooooooooooooooooooooong2 = await looooooooooooooong.looooooooooooooong.loooooong(); + const loooooooooooooooooooooooooong3 = await looooooooooooooooooooooooooooooooooooooooooooog(); + const loooooooooooooooooooooooooong4 = !await looooooooooooooong.looooooooooooooong.loooooong; + const loooooooooooooooooooooooooong5 = void !!await looooooooooooooong.looooooooooooooong.loooooong; + + const longlonglonglonglonglonglong1 = await new Promise((resolve, reject) => { setTimeout(() => { resolve('foo'); }, 300); }) + const longlonglonglonglonglonglong2 = await { then(onFulfilled, onRejected) { onFulfilled(1234567890) } }; +} + +function* g() { + const { section, rubric, authors, tags } = yield utils.upsertCommonData(mainData); + + const loooooooooooooooooooooooooong1 = yield looooooooooooooong.looooooooooooooong.loooooong; + const loooooooooooooooooooooooooong2 = yield looooooooooooooong.looooooooooooooong.loooooong(); + const loooooooooooooooooooooooooong3 = yield looooooooooooooooooooooooooooooooooooooooooooog(); + const loooooooooooooooooooooooooong4 = !(yield looooooooooooooong.looooooooooooooong.loooooong); + const loooooooooooooooooooooooooong5 = void !!(yield looooooooooooooong.looooooooooooooong.loooooong); + const loooooooooooooooooooooooooong6 = yield* looooooooooooooong.looooooooooooooong.loooooong; + + const longlonglonglonglonglonglong1 = yield qwertyuiop(asdfghjkl, zxcvbnm, qwertyuiop, asdfghjkl); + const longlonglonglonglonglonglong2 = yield { qwertyuiop: 1234567890, asdfghjkl: 1234567890, zxcvbnm: 123456789 }; + + const x = yield; +} + +=====================================output===================================== +async function f() { + const { section, rubric, authors, tags } = + await utils.upsertCommonData(mainData); + + const loooooooooooooooooooooooooong1 = + await looooooooooooooong.looooooooooooooong.loooooong; + const loooooooooooooooooooooooooong2 = + await looooooooooooooong.looooooooooooooong.loooooong(); + const loooooooooooooooooooooooooong3 = + await looooooooooooooooooooooooooooooooooooooooooooog(); + const loooooooooooooooooooooooooong4 = + !(await looooooooooooooong.looooooooooooooong.loooooong); + const loooooooooooooooooooooooooong5 = + void !!(await looooooooooooooong.looooooooooooooong.loooooong); + + const longlonglonglonglonglonglong1 = await new Promise((resolve, reject) => { + setTimeout(() => { + resolve("foo"); + }, 300); + }); + const longlonglonglonglonglonglong2 = await { + then(onFulfilled, onRejected) { + onFulfilled(1234567890); + }, + }; +} + +function* g() { + const { section, rubric, authors, tags } = + yield utils.upsertCommonData(mainData); + + const loooooooooooooooooooooooooong1 = + yield looooooooooooooong.looooooooooooooong.loooooong; + const loooooooooooooooooooooooooong2 = + yield looooooooooooooong.looooooooooooooong.loooooong(); + const loooooooooooooooooooooooooong3 = + yield looooooooooooooooooooooooooooooooooooooooooooog(); + const loooooooooooooooooooooooooong4 = + !(yield looooooooooooooong.looooooooooooooong.loooooong); + const loooooooooooooooooooooooooong5 = + void !!(yield looooooooooooooong.looooooooooooooong.loooooong); + const loooooooooooooooooooooooooong6 = + yield* looooooooooooooong.looooooooooooooong.loooooong; + + const longlonglonglonglonglonglong1 = yield qwertyuiop( + asdfghjkl, + zxcvbnm, + qwertyuiop, + asdfghjkl, + ); + const longlonglonglonglonglonglong2 = yield { + qwertyuiop: 1234567890, + asdfghjkl: 1234567890, + zxcvbnm: 123456789, + }; + + const x = yield; +} + +================================================================================ +`; + exports[`issue-1419.js format 1`] = ` ====================================options===================================== parsers: ["babel", "flow", "typescript"] diff --git a/tests/format/js/assignment/discussion-15196.js b/tests/format/js/assignment/discussion-15196.js new file mode 100644 --- /dev/null +++ b/tests/format/js/assignment/discussion-15196.js @@ -0,0 +1,28 @@ +async function f() { + const { section, rubric, authors, tags } = await utils.upsertCommonData(mainData); + + const loooooooooooooooooooooooooong1 = await looooooooooooooong.looooooooooooooong.loooooong; + const loooooooooooooooooooooooooong2 = await looooooooooooooong.looooooooooooooong.loooooong(); + const loooooooooooooooooooooooooong3 = await looooooooooooooooooooooooooooooooooooooooooooog(); + const loooooooooooooooooooooooooong4 = !await looooooooooooooong.looooooooooooooong.loooooong; + const loooooooooooooooooooooooooong5 = void !!await looooooooooooooong.looooooooooooooong.loooooong; + + const longlonglonglonglonglonglong1 = await new Promise((resolve, reject) => { setTimeout(() => { resolve('foo'); }, 300); }) + const longlonglonglonglonglonglong2 = await { then(onFulfilled, onRejected) { onFulfilled(1234567890) } }; +} + +function* g() { + const { section, rubric, authors, tags } = yield utils.upsertCommonData(mainData); + + const loooooooooooooooooooooooooong1 = yield looooooooooooooong.looooooooooooooong.loooooong; + const loooooooooooooooooooooooooong2 = yield looooooooooooooong.looooooooooooooong.loooooong(); + const loooooooooooooooooooooooooong3 = yield looooooooooooooooooooooooooooooooooooooooooooog(); + const loooooooooooooooooooooooooong4 = !(yield looooooooooooooong.looooooooooooooong.loooooong); + const loooooooooooooooooooooooooong5 = void !!(yield looooooooooooooong.looooooooooooooong.loooooong); + const loooooooooooooooooooooooooong6 = yield* looooooooooooooong.looooooooooooooong.loooooong; + + const longlonglonglonglonglonglong1 = yield qwertyuiop(asdfghjkl, zxcvbnm, qwertyuiop, asdfghjkl); + const longlonglonglonglonglonglong2 = yield { qwertyuiop: 1234567890, asdfghjkl: 1234567890, zxcvbnm: 123456789 }; + + const x = yield; +}
line breaks after assignment instead of between parentheses / around parameters ### Discussed in https://github.com/prettier/prettier/discussions/15196 <div type='discussions-op-text'> <sup>Originally posted by **macgyver** August 1, 2023</sup> Just wondering if anybody can explain the formatting philosophy of converting a line like ```js const { section, rubric, authors, tags } = await utils.upsertCommonData(mainData); ``` into this: ```js const { section, rubric, authors, tags } = await utils.upsertCommonData( mainData ); ``` vs. this: ```js const { section, rubric, authors, tags } = await utils.upsertCommonData(mainData); ``` or even ```js const { section, rubric, authors, tags } = await utils.upsertCommonData(mainData); ``` (though I recognize that [putting operators at the start of a line](https://github.com/prettier/prettier/issues/3806) is controversial) it seems like keeping the code on two lines vs. three is more parsimonious in terms of vertical space, and groups the concepts better by dividing the code neatly into variable names, and assigned values. Having `mainData` dangling by itself at the end there just doesn't read that well (to me at least). What do other folks think? Is there a bigger concept at play here that prevents this from being the behavior? Thanks for your time and insights. My guess is that Prettier is trying to produce the longest line it can without exceeding the maximum line length, but in cases like this my feeling is that balancing the length of the lines it produces or trying to reduce the total number of lines produced would be a _prettier_ result.</div>
"2023-08-03T13:52:21Z"
3.1
[]
[ "tests/format/js/assignment/jsfmt.spec.js" ]
JavaScript
[]
[]
prettier/prettier
15,256
prettier__prettier-15256
[ "15252" ]
c01661f311a2e1e033f1f9cb127882cc13e293bd
diff --git a/src/language-js/print/call-expression.js b/src/language-js/print/call-expression.js --- a/src/language-js/print/call-expression.js +++ b/src/language-js/print/call-expression.js @@ -89,7 +89,8 @@ function isCommonsJsOrAmdCall(node, parentNode) { } if (node.callee.name === "require") { - return true; + const args = getCallArguments(node); + return (args.length === 1 && isStringLiteral(args[0])) || args.length > 1; } if (node.callee.name === "define") {
diff --git a/tests/format/js/require/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/require/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/js/require/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/require/__snapshots__/jsfmt.spec.js.snap @@ -11,6 +11,19 @@ const { one1, two1, three1, four1, five1, six1, seven1, eight1, nine1, ten1, ele const MyReallyExtrememlyLongModuleName = require('MyReallyExtrememlyLongModuleName'); +const plugin = require( + global.STANDALONE + ? path.join(__dirname, "../standalone.js") + : path.join(__dirname, "..") +); + +const plugin2 = require( + path.join( + __dirname, + global.STANDALONE ? "../standalone.js" : '..' + ) +); + =====================================output===================================== const { one, @@ -40,5 +53,15 @@ const { const MyReallyExtrememlyLongModuleName = require("MyReallyExtrememlyLongModuleName"); +const plugin = require( + global.STANDALONE + ? path.join(__dirname, "../standalone.js") + : path.join(__dirname, ".."), +); + +const plugin2 = require( + path.join(__dirname, global.STANDALONE ? "../standalone.js" : ".."), +); + ================================================================================ `; diff --git a/tests/format/js/require/require.js b/tests/format/js/require/require.js --- a/tests/format/js/require/require.js +++ b/tests/format/js/require/require.js @@ -2,3 +2,16 @@ const { one, two, three, four, five, six, seven, eight, nine, ten } = require('. const { one1, two1, three1, four1, five1, six1, seven1, eight1, nine1, ten1, eleven1 } = require('./my-utils'); const MyReallyExtrememlyLongModuleName = require('MyReallyExtrememlyLongModuleName'); + +const plugin = require( + global.STANDALONE + ? path.join(__dirname, "../standalone.js") + : path.join(__dirname, "..") +); + +const plugin2 = require( + path.join( + __dirname, + global.STANDALONE ? "../standalone.js" : '..' + ) +);
Ugly format for `require()` call **Prettier 3.0.0** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEcAeAHCAnGACSKAZ3wwBsBXAcwEso8BePbOARwppYAoqyIAjAIZkAdAGUAKgEEAcgBEpAGQDyMgKIAdengD8eDIJgALEQCsIdLgH0rAE05RBAWzgAaPBpAiRAehKCoW2FoODMiTwBKLTw8JH1DE3NLG3tsRxd3T29IiIBuLS10LFwCaBJ9Slp6Jis2Dm5eAWFxaXklVU1tPQNjMwsoazsHZzcPL19-QOCoUNNwkCjtOJ7E-sHU9NGskRzckFcQCAwYGjLkUEFsbAgAdwAFS4QiZBBhG8EAT2eD-mxBMAA1nAYGIRoo6HBkAAzYRENwgX7-IEggxgOhUZAwbAUeFwpw0THY3HoshwACKFAg8GhsPhczQYhJ5Mp1KQMLIcIO7CpcDu1wwzxQgiIAFoZnBbBL9iAsYIaGR0QBhCBOJyCF7CMjSohMqQwLE0fgUeB3ODYcEzGkc+FGGBOMgAdSMNHgRFRcDETxdNAAbi6Pi8wERviAfTiAJKBBAgsDYGjHKSBMQwD6kq2ckAYa5wh1-DAvLNwOHYH2Qg50YswPmCKhq9PwgzYYsvIT8OBag5ZugwB00WzGZAADgADAcWOxOLy-rX1WzaQcYIJ+L3+0ZkAAmA4UOESJeC9kZuBONu2SW2RQBKgUGtwABiODV+vRGuNEBAAF930A) <!-- prettier-ignore --> ```sh --parser babel ``` **Input:** <!-- prettier-ignore --> ```jsx export const plugin = require(global.STANDALONE ? path.join(__dirname, "../standalone.js") : path.join(__dirname, "..")); export const plugin = _equire(global.STANDALONE ? path.join(__dirname, "../standalone.js") : path.join(__dirname, "..")); ``` **Output:** <!-- prettier-ignore --> ```jsx export const plugin = require(global.STANDALONE ? path.join(__dirname, "../standalone.js") : path.join(__dirname, "..")); export const plugin = _equire( global.STANDALONE ? path.join(__dirname, "../standalone.js") : path.join(__dirname, ".."), ); ``` **Expected behavior:** <!-- prettier-ignore --> ```jsx export const plugin = require( global.STANDALONE ? path.join(__dirname, "../standalone.js") : path.join(__dirname, ".."), ); export const plugin = _equire( global.STANDALONE ? path.join(__dirname, "../standalone.js") : path.join(__dirname, ".."), ); ```
"2023-08-17T10:31:12Z"
3.1
[]
[ "tests/format/js/require/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEcAeAHCAnGACSKAZ3wwBsBXAcwEso8BePbOARwppYAoqyIAjAIZkAdAGUAKgEEAcgBEpAGQDyMgKIAdengD8eDIJgALEQCsIdLgH0rAE05RBAWzgAaPBpAiRAehKCoW2FoODMiTwBKLTw8JH1DE3NLG3tsRxd3T29IiIBuLS10LFwCaBJ9Slp6Jis2Dm5eAWFxaXklVU1tPQNjMwsoazsHZzcPL19-QOCoUNNwkCjtOJ7E-sHU9NGskRzckFcQCAwYGjLkUEFsbAgAdwAFS4QiZBBhG8EAT2eD-mxBMAA1nAYGIRoo6HBkAAzYRENwgX7-IEggxgOhUZAwbAUeFwpw0THY3HoshwACKFAg8GhsPhczQYhJ5Mp1KQMLIcIO7CpcDu1wwzxQgiIAFoZnBbBL9iAsYIaGR0QBhCBOJyCF7CMjSohMqQwLE0fgUeB3ODYcEzGkc+FGGBOMgAdSMNHgRFRcDETxdNAAbi6Pi8wERviAfTiAJKBBAgsDYGjHKSBMQwD6kq2ckAYa5wh1-DAvLNwOHYH2Qg50YswPmCKhq9PwgzYYsvIT8OBag5ZugwB00WzGZAADgADAcWOxOLy-rX1WzaQcYIJ+L3+0ZkAAmA4UOESJeC9kZuBONu2SW2RQBKgUGtwABiODV+vRGuNEBAAF930A" ]
prettier/prettier
15,286
prettier__prettier-15286
[ "15282" ]
999c2c27506735f67dfd22e0d5d6c381dda209ee
diff --git a/src/language-js/parse/typescript.js b/src/language-js/parse/typescript.js --- a/src/language-js/parse/typescript.js +++ b/src/language-js/parse/typescript.js @@ -40,7 +40,7 @@ function createParseError(error) { }); } -// https://typescript-eslint.io/architecture/parser/#jsx +// https://typescript-eslint.io/packages/parser/#jsx const isKnownFileType = (filepath) => /\.(?:js|mjs|cjs|jsx|ts|mts|cts|tsx)$/i.test(filepath); diff --git a/src/language-markdown/embed.js b/src/language-markdown/embed.js --- a/src/language-markdown/embed.js +++ b/src/language-markdown/embed.js @@ -17,7 +17,14 @@ function embed(path, options) { Math.max(3, getMaxContinuousCount(node.value, styleUnit) + 1), ); const newOptions = { parser }; - if (node.lang === "tsx") { + + // Override the filepath option. + // This is because whether the trailing comma of type parameters + // should be printed depends on whether it is `*.ts` or `*.tsx`. + // https://github.com/prettier/prettier/issues/15282 + if (node.lang === "ts" || node.lang === "typescript") { + newOptions.filepath = "dummy.ts"; + } else if (node.lang === "tsx") { newOptions.filepath = "dummy.tsx"; }
diff --git a/tests/format/markdown/code/__snapshots__/jsfmt.spec.js.snap b/tests/format/markdown/code/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/markdown/code/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/markdown/code/__snapshots__/jsfmt.spec.js.snap @@ -291,6 +291,33 @@ hello world ================================================================================ `; +exports[`ts-trailing-comma.md - {"proseWrap":"always"} format 1`] = ` +====================================options===================================== +parsers: ["markdown"] +printWidth: 80 +proseWrap: "always" + | printWidth +=====================================input====================================== +\`\`\`ts +const test = <T,>(value: T) => {}; +\`\`\` + +\`\`\`typescript +const test = <T,>(value: T) => {}; +\`\`\` + +=====================================output===================================== +\`\`\`ts +const test = <T>(value: T) => {}; +\`\`\` + +\`\`\`typescript +const test = <T>(value: T) => {}; +\`\`\` + +================================================================================ +`; + exports[`tsx-trailing-comma.md - {"proseWrap":"always"} format 1`] = ` ====================================options===================================== parsers: ["markdown"] diff --git a/tests/format/markdown/code/ts-trailing-comma.md b/tests/format/markdown/code/ts-trailing-comma.md new file mode 100644 --- /dev/null +++ b/tests/format/markdown/code/ts-trailing-comma.md @@ -0,0 +1,7 @@ +```ts +const test = <T,>(value: T) => {}; +``` + +```typescript +const test = <T,>(value: T) => {}; +```
Prettier prints a trailing comma after type argument list even if the languages is `ts` in markdown **Prettier 3.0.2** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEADdMDOAdKkqYwAExAvEQDwAqANAHwAUAlEaXUcAL4Dcu6quPhkwAPXPkIlWlWoxZsOnIahA0QEAA4wAltEzJQAQwBOxiAHcACiYT6UhgDbnDAT31qARscNgA1nBgAZUMAWzgAGW0oOGQAM0dMOE9vPwDAjR8ogHNkGGMAVySQRJDtXIKizGyHOABFfIh4OISigCtRQOq6hqakeIdEtQBHHrhLMw07EENMAFpouAATJdUQPMNtB2yAYQgQkMNkaYcHVaqoLJqAQRg87Q98+Es4Y0jo5oGigAsYEIcAdS+2ngmAyYDggVswO0ADdgS4jmBMO4QDDCgBJKDLWCBMDGbRaK5YwIwFw1D6DEAaMyJf7eDRHalwRLGGExNRRFkwcaGLIHClFDLGFlHA7GXyLCxQVbUqIwf7aRYwL7IAAcAAY1MY4CNtNqeXzDn0WmoYIYPAqlSqkAAmNT5RJUc12fqUuAhDxLZaLcKGC75XlwABiEGMB1u2SOhkeEBAnE4QA) <!-- prettier-ignore --> ```sh --parser markdown ``` **Input:** <!-- prettier-ignore --> ````markdown ```ts const t = <T,>() => {}; ``` ```tsx const t = <T,>() => {} ``` ```` **Output:** <!-- prettier-ignore --> ````markdown ```ts const t = <T,>() => {}; ``` ```tsx const t = <T,>() => {} ``` ```` The second codeblock prints a trailing comma and it's the correct behavior, however the first codeblock should remove the trailing comma **Expected behavior:** The first codeblock should not have a trailing comma
"2023-08-23T13:53:05Z"
3.1
[]
[ "tests/format/markdown/code/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEADdMDOAdKkqYwAExAvEQDwAqANAHwAUAlEaXUcAL4Dcu6quPhkwAPXPkIlWlWoxZsOnIahA0QEAA4wAltEzJQAQwBOxiAHcACiYT6UhgDbnDAT31qARscNgA1nBgAZUMAWzgAGW0oOGQAM0dMOE9vPwDAjR8ogHNkGGMAVySQRJDtXIKizGyHOABFfIh4OISigCtRQOq6hqakeIdEtQBHHrhLMw07EENMAFpouAATJdUQPMNtB2yAYQgQkMNkaYcHVaqoLJqAQRg87Q98+Es4Y0jo5oGigAsYEIcAdS+2ngmAyYDggVswO0ADdgS4jmBMO4QDDCgBJKDLWCBMDGbRaK5YwIwFw1D6DEAaMyJf7eDRHalwRLGGExNRRFkwcaGLIHClFDLGFlHA7GXyLCxQVbUqIwf7aRYwL7IAAcAAY1MY4CNtNqeXzDn0WmoYIYPAqlSqkAAmNT5RJUc12fqUuAhDxLZaLcKGC75XlwABiEGMB1u2SOhkeEBAnE4QA" ]
prettier/prettier
15,324
prettier__prettier-15324
[ "15314" ]
a35008fb0a010f92c1002ee074c6a7f3c0d8da41
diff --git a/src/language-js/comments/handle-comments.js b/src/language-js/comments/handle-comments.js --- a/src/language-js/comments/handle-comments.js +++ b/src/language-js/comments/handle-comments.js @@ -576,8 +576,8 @@ function handleLastFunctionArgComments({ precedingNode?.type === "AssignmentPattern" || precedingNode?.type === "ObjectPattern" || precedingNode?.type === "ArrayPattern" || - precedingNode?.type === "RestElement") && - enclosingNode && + precedingNode?.type === "RestElement" || + precedingNode?.type === "TSParameterProperty") && isRealFunctionLikeNode(enclosingNode) && getNextNonSpaceNonCommentCharacter(text, locEnd(comment)) === ")" ) {
diff --git a/tests/format/typescript/comments/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/comments/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/typescript/comments/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/typescript/comments/__snapshots__/jsfmt.spec.js.snap @@ -694,6 +694,31 @@ export class Point { ================================================================================ `; +exports[`ts-parameter-proerty.ts format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +class A { + constructor( + private readonly paramProp: Type, + // comment + ) { + } +} + +=====================================output===================================== +class A { + constructor( + private readonly paramProp: Type, + // comment + ) {} +} + +================================================================================ +`; + exports[`type_literals.ts format 1`] = ` ====================================options===================================== parsers: ["typescript"] diff --git a/tests/format/typescript/comments/ts-parameter-proerty.ts b/tests/format/typescript/comments/ts-parameter-proerty.ts new file mode 100644 --- /dev/null +++ b/tests/format/typescript/comments/ts-parameter-proerty.ts @@ -0,0 +1,7 @@ +class A { + constructor( + private readonly paramProp: Type, + // comment + ) { + } +}
Unstable comment location - after the last parameter property <!-- BEFORE SUBMITTING AN ISSUE: 1. Search for your issue on GitHub: https://github.com/prettier/prettier/issues A large number of opened issues are duplicates of existing issues. If someone has already opened an issue for what you are experiencing, you do not need to open a new issue — please add a 👍 reaction to the existing issue instead. 2. We get a lot of requests for adding options, but Prettier is built on the principle of being opinionated about code formatting. This means we add options only in the case of strict technical necessity. Find out more: https://prettier.io/docs/en/option-philosophy.html Don't fill the form below manually! Let a program create a report for you: 1. Go to https://prettier.io/playground 2. Paste your code and set options 3. Press the "Report issue" button in the lower right --> **Prettier 3.0.2** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAucAbAhgZ0wAgMIbY7AA6UOOkUmMATgK5gwS0AUZFnOADrQJYA3dPBy046ACbRUATx7pa6ALYAFWhCQ4AKjO5wANB04B6Y5QhKlCGEYCUxIwF8yjkPpARuMPtEzJQCuoA7ioKCH4o6KhB6DJ+7gBGimAA1nAwAMrKcAAyfFBwyABmUZgGIEnoqekZ3FX5AObIdPTlZUp8zQxtjahwAIr0EPDFpeUAVpgAHhm9A0MjSCWoZe4Ajgtwap4RIFgAtAVwEsduIHTofKiNeBZK6Mh7qKhnmHMAgjB0fAn08CpwWh5AqjFblAAWMCUqAA6uC+PBMHUwHAMuEEYIETJHmBsGcBK0AJJQE6wDJgfhed4kjIwGR9UGrEC8CBlGGKbiPXhwMq0ASFdz5XkwNToBr3RnlOq0XmPOl6TAUvheM68fIwGF8CQwcHIAAcAAZ3GINnwxKLxQ8lmN3DB0AlNdrdUgAEzuehlLT2iLLJlwJQJY4nCQ5dBQBr0MVwABiLHuX0aj3QfwgIEcjiAA) <!-- prettier-ignore --> ```sh --parser typescript ``` **Input:** <!-- prettier-ignore --> ```tsx class Class { constructor( private readonly paramProp: Type, // comment ) { } } ``` **Output:** <!-- prettier-ignore --> ```tsx class Class { constructor(private readonly paramProp: Type) // comment {} } ``` **Second Output:** <!-- prettier-ignore --> ```tsx class Class { constructor( private readonly paramProp: Type, // comment ) {} } ``` **Expected behavior:** Comment location should be stable. Similar to #11639
Tip: We have <kbd>show second format</kbd> option in playgroud left panel.
"2023-08-29T08:37:09Z"
3.1
[]
[ "tests/format/typescript/comments/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAucAbAhgZ0wAgMIbY7AA6UOOkUmMATgK5gwS0AUZFnOADrQJYA3dPBy046ACbRUATx7pa6ALYAFWhCQ4AKjO5wANB04B6Y5QhKlCGEYCUxIwF8yjkPpARuMPtEzJQCuoA7ioKCH4o6KhB6DJ+7gBGimAA1nAwAMrKcAAyfFBwyABmUZgGIEnoqekZ3FX5AObIdPTlZUp8zQxtjahwAIr0EPDFpeUAVpgAHhm9A0MjSCWoZe4Ajgtwap4RIFgAtAVwEsduIHTofKiNeBZK6Mh7qKhnmHMAgjB0fAn08CpwWh5AqjFblAAWMCUqAA6uC+PBMHUwHAMuEEYIETJHmBsGcBK0AJJQE6wDJgfhed4kjIwGR9UGrEC8CBlGGKbiPXhwMq0ASFdz5XkwNToBr3RnlOq0XmPOl6TAUvheM68fIwGF8CQwcHIAAcAAZ3GINnwxKLxQ8lmN3DB0AlNdrdUgAEzuehlLT2iLLJlwJQJY4nCQ5dBQBr0MVwABiLHuX0aj3QfwgIEcjiAA", "https://prettier.io/playground" ]
prettier/prettier
15,326
prettier__prettier-15326
[ "15325" ]
a35008fb0a010f92c1002ee074c6a7f3c0d8da41
diff --git a/src/language-js/comments/handle-comments.js b/src/language-js/comments/handle-comments.js --- a/src/language-js/comments/handle-comments.js +++ b/src/language-js/comments/handle-comments.js @@ -585,29 +585,20 @@ function handleLastFunctionArgComments({ return true; } + // Comment between function parameters parentheses and function body if ( - enclosingNode?.type === "FunctionDeclaration" && - followingNode?.type === "BlockStatement" + !isBlockComment(comment) && + (enclosingNode?.type === "FunctionDeclaration" || + enclosingNode?.type === "FunctionExpression" || + enclosingNode?.type === "ObjectMethod") && + followingNode?.type === "BlockStatement" && + enclosingNode.body === followingNode ) { - const functionParamRightParenIndex = (() => { - const parameters = getFunctionParameters(enclosingNode); - if (parameters.length > 0) { - return getNextNonSpaceNonCommentCharacterIndex( - text, - locEnd(parameters.at(-1)), - ); - } - const functionParamLeftParenIndex = - getNextNonSpaceNonCommentCharacterIndex(text, locEnd(enclosingNode.id)); - return ( - functionParamLeftParenIndex !== false && - getNextNonSpaceNonCommentCharacterIndex( - text, - functionParamLeftParenIndex + 1, - ) - ); - })(); - if (locStart(comment) > functionParamRightParenIndex) { + const characterAfterCommentIndex = getNextNonSpaceNonCommentCharacterIndex( + text, + locEnd(comment), + ); + if (characterAfterCommentIndex === locStart(followingNode)) { addBlockStatementFirstComment(followingNode, comment); return true; }
diff --git a/tests/format/js/comments/function/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/comments/function/__snapshots__/jsfmt.spec.js.snap new file mode 100644 --- /dev/null +++ b/tests/format/js/comments/function/__snapshots__/jsfmt.spec.js.snap @@ -0,0 +1,78 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`between-parentheses-and-function-body.js format 1`] = ` +====================================options===================================== +parsers: ["babel", "flow", "typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +function function_declaration() +// this is a function +{ + return 42 +} + +(function named() +// this is a function +{ + return 42 +})(); + + +(function () +// this is a function +{ + return 42 +})(); + +/* anonymous declaration */ +export default function () +// this is a function +{ + return 42 +} + +a = { + foo() + // this is a function + {}, + + bar: function() + // this is a function + {}, +} + +=====================================output===================================== +function function_declaration() { + // this is a function + return 42; +} + +(function named() { + // this is a function + return 42; +})(); + +(function () { + // this is a function + return 42; +})(); + +/* anonymous declaration */ +export default function () { + // this is a function + return 42; +} + +a = { + foo() { + // this is a function + }, + + bar: function () { + // this is a function + }, +}; + +================================================================================ +`; diff --git a/tests/format/js/comments/function/between-parentheses-and-function-body.js b/tests/format/js/comments/function/between-parentheses-and-function-body.js new file mode 100644 --- /dev/null +++ b/tests/format/js/comments/function/between-parentheses-and-function-body.js @@ -0,0 +1,35 @@ +function function_declaration() +// this is a function +{ + return 42 +} + +(function named() +// this is a function +{ + return 42 +})(); + + +(function () +// this is a function +{ + return 42 +})(); + +/* anonymous declaration */ +export default function () +// this is a function +{ + return 42 +} + +a = { + foo() + // this is a function + {}, + + bar: function() + // this is a function + {}, +} diff --git a/tests/format/js/comments/function/jsfmt.spec.js b/tests/format/js/comments/function/jsfmt.spec.js new file mode 100644 --- /dev/null +++ b/tests/format/js/comments/function/jsfmt.spec.js @@ -0,0 +1 @@ +run_spec(import.meta, ["babel", "flow", "typescript"]);
Error when formatting anonymous export default function **Prettier 3.0.2** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEcAeAHCAnGACAEzgDMBDAVwBt9jyowYBLaACgEoAdKAem7xgAWjAM54ReUnlr0m0LsC5482ODHLYoeACwAmLgF8QAGhAQMsqMOShS2bBADuABVsIrKUpQekAnlZMARtikYADWqgDKpAC2cAAyjFBwyGSUwnCBwWGRGCGJAObIMNjkGSDp0YxFJWXCBZRwAIrkEPApnukmAFbCaBH1TS1tSKmdIACOQ3BO9hjuIKTCALRJcEQExiDFpIyUBQDCENHRpMgLlJSbdVD5DQCCMMWMAeTwTnDYCUntaWUCMNFKAB1ITwYS5MBwCJuRhMABusJ8ZzAwn8IDhpQAklAiLAImBsIxzHccREYD4Gj8xhh7OkgcEMGcaXB0tg4ckTIlWTAZqR8icqWVcthWWcAqQAnBLiYaYkYEDGARBMgABwABhMKkmjBUvP5pxGHTKMAlCqVAmQOhM5HSABUJe5RmU4NFJQR1nFSDdyHy4AAxHAnR4FM4UGAQED6fRAA) <!-- prettier-ignore --> ```sh --parser babel ``` **Input:** <!-- prettier-ignore --> ```jsx export default function() // this is a function { return 42 } ``` **Output:** <!-- prettier-ignore --> ```jsx TypeError: Cannot read properties of null (reading 'range') at O (https://prettier.io/lib/plugins/estree.js:10:13646) at https://prettier.io/lib/plugins/estree.js:13:5419 at fu (https://prettier.io/lib/plugins/estree.js:13:5454) at https://prettier.io/lib/plugins/estree.js:13:769 at Array.some (<anonymous>) at Eo (https://prettier.io/lib/plugins/estree.js:13:761) at bn (https://prettier.io/lib/standalone.js:30:2799) at Ht (https://prettier.io/lib/standalone.js:30:8022) at je (https://prettier.io/lib/standalone.js:30:7194) at Gn (https://prettier.io/lib/standalone.js:30:11017) ``` **Expected behavior:** Found this during #15324
"2023-08-29T09:35:00Z"
3.1
[]
[ "tests/format/js/comments/function/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEcAeAHCAnGACAEzgDMBDAVwBt9jyowYBLaACgEoAdKAem7xgAWjAM54ReUnlr0m0LsC5482ODHLYoeACwAmLgF8QAGhAQMsqMOShS2bBADuABVsIrKUpQekAnlZMARtikYADWqgDKpAC2cAAyjFBwyGSUwnCBwWGRGCGJAObIMNjkGSDp0YxFJWXCBZRwAIrkEPApnukmAFbCaBH1TS1tSKmdIACOQ3BO9hjuIKTCALRJcEQExiDFpIyUBQDCENHRpMgLlJSbdVD5DQCCMMWMAeTwTnDYCUntaWUCMNFKAB1ITwYS5MBwCJuRhMABusJ8ZzAwn8IDhpQAklAiLAImBsIxzHccREYD4Gj8xhh7OkgcEMGcaXB0tg4ckTIlWTAZqR8icqWVcthWWcAqQAnBLiYaYkYEDGARBMgABwABhMKkmjBUvP5pxGHTKMAlCqVAmQOhM5HSABUJe5RmU4NFJQR1nFSDdyHy4AAxHAnR4FM4UGAQED6fRAA" ]
prettier/prettier
15,400
prettier__prettier-15400
[ "15341" ]
f4491b1274d0697f38f9110116a7dd8d7c295e84
diff --git a/src/language-markdown/clean.js b/src/language-markdown/clean.js --- a/src/language-markdown/clean.js +++ b/src/language-markdown/clean.js @@ -48,6 +48,16 @@ function clean(ast, newObj, parent) { newObj.label = collapseWhiteSpace(ast.label); } + if ( + (ast.type === "link" || ast.type === "image") && + ast.url && + ast.url.includes("(") + ) { + for (const character of "<>") { + newObj.url = ast.url.replaceAll(character, encodeURIComponent(character)); + } + } + if ( (ast.type === "definition" || ast.type === "link" || diff --git a/src/language-markdown/printer-markdown.js b/src/language-markdown/printer-markdown.js --- a/src/language-markdown/printer-markdown.js +++ b/src/language-markdown/printer-markdown.js @@ -778,6 +778,13 @@ function shouldRemainTheSameContent(path) { ); } +const encodeUrl = (url, characters) => { + for (const character of characters) { + url = url.replaceAll(character, encodeURIComponent(character)); + } + return url; +}; + /** * @param {string} url * @param {string[] | string} [dangerousCharOrChars] @@ -790,8 +797,9 @@ function printUrl(url, dangerousCharOrChars = []) { ? dangerousCharOrChars : [dangerousCharOrChars]), ]; + return new RegExp(dangerousChars.map((x) => `\\${x}`).join("|")).test(url) - ? `<${url}>` + ? `<${encodeUrl(url, "<>")}>` : url; }
diff --git a/tests/format/markdown/link/__snapshots__/jsfmt.spec.js.snap b/tests/format/markdown/link/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/markdown/link/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/markdown/link/__snapshots__/jsfmt.spec.js.snap @@ -47,6 +47,83 @@ proseWrap: "always" ================================================================================ `; +exports[`encodedLink.md - {"proseWrap":"always","singleQuote":true} format 1`] = ` +====================================options===================================== +parsers: ["markdown"] +printWidth: 80 +proseWrap: "always" +singleQuote: true + | printWidth +=====================================input====================================== +[link](https://www.google.fr/()foo->bar) +[link](https://www.google.fr/foo->bar) +[link](https://www.google.fr/foo-%3Ebar) +[link](https://www.google.fr/foo-<bar) +[link](https://www.google.fr/foo-%3Cbar) +![link](https://www.google.fr/()foo->bar) +![link](https://www.google.fr/foo->bar) +![link](https://www.google.fr/foo-%3Ebar) +![link](https://www.google.fr/foo-<bar) +![link](https://www.google.fr/foo-%3Cbar) +[link]: https://www.google.fr/()foo->bar +[link]: https://www.google.fr/foo->bar +[link]: https://www.google.fr/foo-%3Ebar +[link]: https://www.google.fr/foo-<bar +[link]: https://www.google.fr/foo-%3Cbar +=====================================output===================================== +[link](<https://www.google.fr/()foo-%3Ebar>) +[link](https://www.google.fr/foo->bar) [link](https://www.google.fr/foo-%3Ebar) +[link](https://www.google.fr/foo-<bar) [link](https://www.google.fr/foo-%3Cbar) +![link](<https://www.google.fr/()foo-%3Ebar>) +![link](https://www.google.fr/foo->bar) +![link](https://www.google.fr/foo-%3Ebar) +![link](https://www.google.fr/foo-<bar) +![link](https://www.google.fr/foo-%3Cbar) [link]: +https://www.google.fr/()foo->bar [link]: https://www.google.fr/foo->bar [link]: +https://www.google.fr/foo-%3Ebar [link]: https://www.google.fr/foo-<bar [link]: +https://www.google.fr/foo-%3Cbar + +================================================================================ +`; + +exports[`encodedLink.md - {"proseWrap":"always"} format 1`] = ` +====================================options===================================== +parsers: ["markdown"] +printWidth: 80 +proseWrap: "always" + | printWidth +=====================================input====================================== +[link](https://www.google.fr/()foo->bar) +[link](https://www.google.fr/foo->bar) +[link](https://www.google.fr/foo-%3Ebar) +[link](https://www.google.fr/foo-<bar) +[link](https://www.google.fr/foo-%3Cbar) +![link](https://www.google.fr/()foo->bar) +![link](https://www.google.fr/foo->bar) +![link](https://www.google.fr/foo-%3Ebar) +![link](https://www.google.fr/foo-<bar) +![link](https://www.google.fr/foo-%3Cbar) +[link]: https://www.google.fr/()foo->bar +[link]: https://www.google.fr/foo->bar +[link]: https://www.google.fr/foo-%3Ebar +[link]: https://www.google.fr/foo-<bar +[link]: https://www.google.fr/foo-%3Cbar +=====================================output===================================== +[link](<https://www.google.fr/()foo-%3Ebar>) +[link](https://www.google.fr/foo->bar) [link](https://www.google.fr/foo-%3Ebar) +[link](https://www.google.fr/foo-<bar) [link](https://www.google.fr/foo-%3Cbar) +![link](<https://www.google.fr/()foo-%3Ebar>) +![link](https://www.google.fr/foo->bar) +![link](https://www.google.fr/foo-%3Ebar) +![link](https://www.google.fr/foo-<bar) +![link](https://www.google.fr/foo-%3Cbar) [link]: +https://www.google.fr/()foo->bar [link]: https://www.google.fr/foo->bar [link]: +https://www.google.fr/foo-%3Ebar [link]: https://www.google.fr/foo-<bar [link]: +https://www.google.fr/foo-%3Cbar + +================================================================================ +`; + exports[`entity.md - {"proseWrap":"always","singleQuote":true} format 1`] = ` ====================================options===================================== parsers: ["markdown"] diff --git a/tests/format/markdown/link/encodedLink.md b/tests/format/markdown/link/encodedLink.md new file mode 100644 --- /dev/null +++ b/tests/format/markdown/link/encodedLink.md @@ -0,0 +1,15 @@ +[link](https://www.google.fr/()foo->bar) +[link](https://www.google.fr/foo->bar) +[link](https://www.google.fr/foo-%3Ebar) +[link](https://www.google.fr/foo-<bar) +[link](https://www.google.fr/foo-%3Cbar) +![link](https://www.google.fr/()foo->bar) +![link](https://www.google.fr/foo->bar) +![link](https://www.google.fr/foo-%3Ebar) +![link](https://www.google.fr/foo-<bar) +![link](https://www.google.fr/foo-%3Cbar) +[link]: https://www.google.fr/()foo->bar +[link]: https://www.google.fr/foo->bar +[link]: https://www.google.fr/foo-%3Ebar +[link]: https://www.google.fr/foo-<bar +[link]: https://www.google.fr/foo-%3Cbar \ No newline at end of file
When prettier inserts <> characters in markdown links, it should encode existing <> characters too. **Prettier 3.0.3** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBtANgSygawLoAUAFjDAA4DOSA9NQO4MB0A5hBM+nIwGYBO1BAJTc2AWgB8AIwCGvQYwA6UEABoQEMjEzQKyULN4Q6ABVkJdKaejrSAnrrWTe0sDjgwAytIC2cADLYcMjcVhRwjs6u7h5kLtjMyDC8AK7hIGHemIkpaRTxnACKyRDwwaFpAFYUAB4e+XBFJUFIIehhagCOxfDGhpTIINIUolBwcAAmE6ogSdKYWFDMAMIQ3t7SA1bo03mLnACCpLyYksk9cLwBo2VtaSTe6ADqRJjwFLFgcB7mr5gAbq9bAMwBQHCA-qkAJJQSawDxgY6afYwjwwWycG7tEBkQxhR7OMgDHFwMK8P5BNTYUkwXrSZjrTFpWK8UkDda8HDjIzKNQ47AwR6YcYwIjIAAcAAY1Lw4F1MDLafSNi1ymoYNJJILhaKkAAmNTJMIAFQ1FlaWLg3kkE0m4z80kWyTpcAAYhBeOtSPFNmcICAAL7+oA) <!-- prettier-ignore --> ```sh --parser markdown ``` **Input:** <!-- prettier-ignore --> ```markdown [link](https://www.google.fr/()foo->bar). ``` Note that the link contains a `>` character. **Output:** <!-- prettier-ignore --> ```markdown [link](<https://www.google.fr/()foo->bar>). ``` Now it's broken because of the `>` character inside the link matching the first `<`. **Expected behavior:** Either: <!-- prettier-ignore --> ```markdown [link](https://www.google.fr/()foo->bar). ``` (no change -- this is valid markdown) or: <!-- prettier-ignore --> ```markdown [link](<https://www.google.fr/()foo%3Ebar>). ``` The latter is probably easier to implement. See the spec in https://spec.commonmark.org/0.30/#link-destination. Thanks!
"2023-09-14T17:46:47Z"
3.1
[]
[ "tests/format/markdown/link/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBtANgSygawLoAUAFjDAA4DOSA9NQO4MB0A5hBM+nIwGYBO1BAJTc2AWgB8AIwCGvQYwA6UEABoQEMjEzQKyULN4Q6ABVkJdKaejrSAnrrWTe0sDjgwAytIC2cADLYcMjcVhRwjs6u7h5kLtjMyDC8AK7hIGHemIkpaRTxnACKyRDwwaFpAFYUAB4e+XBFJUFIIehhagCOxfDGhpTIINIUolBwcAAmE6ogSdKYWFDMAMIQ3t7SA1bo03mLnACCpLyYksk9cLwBo2VtaSTe6ADqRJjwFLFgcB7mr5gAbq9bAMwBQHCA-qkAJJQSawDxgY6afYwjwwWycG7tEBkQxhR7OMgDHFwMK8P5BNTYUkwXrSZjrTFpWK8UkDda8HDjIzKNQ47AwR6YcYwIjIAAcAAY1Lw4F1MDLafSNi1ymoYNJJILhaKkAAmNTJMIAFQ1FlaWLg3kkE0m4z80kWyTpcAAYhBeOtSPFNmcICAAL7+oA" ]
prettier/prettier
15,408
prettier__prettier-15408
[ "15315" ]
675490ae55fe1c0b797db13bf5f055711d2c0b69
diff --git a/src/language-js/embed/graphql.js b/src/language-js/embed/graphql.js --- a/src/language-js/embed/graphql.js +++ b/src/language-js/embed/graphql.js @@ -107,7 +107,7 @@ function printGraphqlComments(lines) { */ function isGraphQL({ node, parent }) { return ( - hasLanguageComment(node, "GraphQL") || + hasLanguageComment({ node, parent }, "GraphQL") || (parent && ((parent.type === "TaggedTemplateExpression" && ((parent.tag.type === "MemberExpression" && diff --git a/src/language-js/embed/html.js b/src/language-js/embed/html.js --- a/src/language-js/embed/html.js +++ b/src/language-js/embed/html.js @@ -102,7 +102,7 @@ async function printEmbedHtmlLike(parser, textToDoc, print, path, options) { */ function isHtml(path) { return ( - hasLanguageComment(path.node, "HTML") || + hasLanguageComment(path, "HTML") || path.match( (node) => node.type === "TemplateLiteral", (node, name) => diff --git a/src/language-js/embed/utils.js b/src/language-js/embed/utils.js --- a/src/language-js/embed/utils.js +++ b/src/language-js/embed/utils.js @@ -53,7 +53,7 @@ function isAngularComponentTemplate(path) { ); } -function hasLanguageComment(node, languageName) { +function hasLeadingBlockCommentWithName(node, languageName) { // This checks for a leading comment that is exactly `/* GraphQL */` // In order to be in line with other implementations of this comment tag // we will not trim the comment value and we will expect exactly one space on @@ -65,9 +65,27 @@ function hasLanguageComment(node, languageName) { ({ value }) => value === ` ${languageName} `, ); } +function hasLanguageComment({ node, parent }, languageName) { + return ( + hasLeadingBlockCommentWithName(node, languageName) || + (isAsConstExpression(parent) && + hasLeadingBlockCommentWithName(parent, languageName)) + ); +} + +function isAsConstExpression(node) { + return ( + node.type === "AsConstExpression" || + (node.type === "TSAsExpression" && + node.typeAnnotation.type === "TSTypeReference" && + node.typeAnnotation.typeName.type === "Identifier" && + node.typeAnnotation.typeName.name === "const") + ); +} export { isAngularComponentStyles, isAngularComponentTemplate, hasLanguageComment, + isAsConstExpression, };
diff --git a/tests/format/flow/as-const/__snapshots__/jsfmt.spec.js.snap b/tests/format/flow/as-const/__snapshots__/jsfmt.spec.js.snap new file mode 100644 --- /dev/null +++ b/tests/format/flow/as-const/__snapshots__/jsfmt.spec.js.snap @@ -0,0 +1,46 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`embedded.js [babel-flow] format 1`] = ` +"Unexpected token (3:11) + 1 | const GQL_QUERY_WITH_CONST = /* GraphQL */ \` + 2 | query S { shop } +> 3 | \` as const; + | ^ + 4 | + 5 | const HTML_WITH_CONST = /* HTML */ \` + 6 | <div>" +`; + +exports[`embedded.js format 1`] = ` +====================================options===================================== +parsers: ["flow"] +printWidth: 80 + | printWidth +=====================================input====================================== +const GQL_QUERY_WITH_CONST = /* GraphQL */ \` + query S { shop } +\` as const; + +const HTML_WITH_CONST = /* HTML */ \` +<div> +<h1>foo</h1> + <p>foo</p> +</div> +\` as const; + +=====================================output===================================== +const GQL_QUERY_WITH_CONST = /* GraphQL */ \` + query S { + shop + } +\` as const; + +const HTML_WITH_CONST = /* HTML */ \` + <div> + <h1>foo</h1> + <p>foo</p> + </div> +\` as const; + +================================================================================ +`; diff --git a/tests/format/flow/as-const/embedded.js b/tests/format/flow/as-const/embedded.js new file mode 100644 --- /dev/null +++ b/tests/format/flow/as-const/embedded.js @@ -0,0 +1,10 @@ +const GQL_QUERY_WITH_CONST = /* GraphQL */ ` + query S { shop } +` as const; + +const HTML_WITH_CONST = /* HTML */ ` +<div> +<h1>foo</h1> + <p>foo</p> +</div> +` as const; diff --git a/tests/format/flow/as-const/jsfmt.spec.js b/tests/format/flow/as-const/jsfmt.spec.js new file mode 100644 --- /dev/null +++ b/tests/format/flow/as-const/jsfmt.spec.js @@ -0,0 +1,5 @@ +run_spec(import.meta, ["flow"], { + errors: { + "babel-flow": ["embedded.js"], + }, +}); diff --git a/tests/format/typescript/as/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/as/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/typescript/as/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/typescript/as/__snapshots__/jsfmt.spec.js.snap @@ -133,6 +133,40 @@ const iter2 = createIterator( ================================================================================ `; +exports[`as-const-embedded.ts format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +const GQL_QUERY_WITH_CONST = /* GraphQL */ \` + query S { shop } +\` as const; + +const HTML_WITH_CONST = /* HTML */ \` +<div> +<h1>foo</h1> + <p>foo</p> +</div> +\` as const; + +=====================================output===================================== +const GQL_QUERY_WITH_CONST = /* GraphQL */ \` + query S { + shop + } +\` as const; + +const HTML_WITH_CONST = /* HTML */ \` + <div> + <h1>foo</h1> + <p>foo</p> + </div> +\` as const; + +================================================================================ +`; + exports[`assignment.ts format 1`] = ` ====================================options===================================== parsers: ["typescript"] diff --git a/tests/format/typescript/as/as-const-embedded.ts b/tests/format/typescript/as/as-const-embedded.ts new file mode 100644 --- /dev/null +++ b/tests/format/typescript/as/as-const-embedded.ts @@ -0,0 +1,10 @@ +const GQL_QUERY_WITH_CONST = /* GraphQL */ ` + query S { shop } +` as const; + +const HTML_WITH_CONST = /* HTML */ ` +<div> +<h1>foo</h1> + <p>foo</p> +</div> +` as const;
/* GraphQL */ comment tag does not format with typescript `as const` **Prettier 3.0.0** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuc0DOMAEAlA8gIVwBUBlAfQEUBVAUWwE0yB1ASSIAkyBhXAORKKYAvJgD0AKkwBxAE4BDAA4ALCgBlM40ZgAGAHSiZMARwCucGQE9MJTMExolEBZgC++7ZjlpMkKBgDc+vq+GDgExOTUdPTCYpKyiirqmjr6hqbmVjZ2Dk6u7oFQIAA0IE4wAJboyKByMjIQAO4ACnUIaMggcgA2jXIWHaUARvJgANZwMCRyALZwqhVQcMgAZj1ocMOjE1MKcmCLAObIMDJmpRszFSdnmyBoR91wFCYQ8KvrdwBWaAAeJI9nq93kg1t0NqVTG84M0GgoOigvABaJZwAAm6JKIFOcgq3SOXAgMxmck6PW6WIeUEOTwAgjBThUhiZ4M1zAslh9wXclDAZt0mEoKvA0HswHASO1hRUAG7CiydMBoQYgGVmFhQDGwEhgGQVBQwWmakgwCxPLkQkAKBobJjyBSda1wDYyGXLUqLF0wWFyQ4ki13PYyF2dIZyIZwbpImAq62LGBMCpomBKZAADgADKUZHBTBUcz6-aTQZ9SjBw4nk6mkAAmUomDZEcMIsGWuAzCNojFo1RyakmX1wABiEBkJIZRzJLIgIBcLiAA) <!-- prettier-ignore --> ```sh --parser babel-ts ``` **Input:** <!-- prettier-ignore --> ```tsx const ROBOTS_QUERY_WITH_CONST = /* GraphQL */ ` query S { shop } ` as const; const ROBOTS_QUERY = /* GraphQL */ ` query S { shop } `; ``` **Output:** <!-- prettier-ignore --> ```tsx const ROBOTS_QUERY_WITH_CONST = /* GraphQL */ ` query S { shop } ` as const; const ROBOTS_QUERY = /* GraphQL */ ` query S { shop } `; ``` **Expected behavior:** Should get the same formated result within the tagged string. ``` const ROBOTS_QUERY_WITH_CONST = /* GraphQL */ ` query S { shop } ` as const; const ROBOTS_QUERY = /* GraphQL */ ` query S { shop } `; ``` Of course, when it doesn't work with `as const`, you can drop that `as const` because it does not affect typescript's typing. However, there are places where dropping such `as const` might affect devs' experience
I don't think we need to support this. @hanayashiki Hi, can you tell me why this is needed? Is there any meaning in adding `as const` to template literal in TypeScript? > @hanayashiki Hi, can you tell me why this is needed? Is there any meaning in adding `as const` to template literal in TypeScript? If you don't use as const, it will be inferred as "string" instead of a string literal. thank you. I got that there are differences in the inference results. I think this is acceptable.
"2023-09-16T08:56:24Z"
3.1
[]
[ "tests/format/flow/as-const/jsfmt.spec.js", "tests/format/typescript/as/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuc0DOMAEAlA8gIVwBUBlAfQEUBVAUWwE0yB1ASSIAkyBhXAORKKYAvJgD0AKkwBxAE4BDAA4ALCgBlM40ZgAGAHSiZMARwCucGQE9MJTMExolEBZgC++7ZjlpMkKBgDc+vq+GDgExOTUdPTCYpKyiirqmjr6hqbmVjZ2Dk6u7oFQIAA0IE4wAJboyKByMjIQAO4ACnUIaMggcgA2jXIWHaUARvJgANZwMCRyALZwqhVQcMgAZj1ocMOjE1MKcmCLAObIMDJmpRszFSdnmyBoR91wFCYQ8KvrdwBWaAAeJI9nq93kg1t0NqVTG84M0GgoOigvABaJZwAAm6JKIFOcgq3SOXAgMxmck6PW6WIeUEOTwAgjBThUhiZ4M1zAslh9wXclDAZt0mEoKvA0HswHASO1hRUAG7CiydMBoQYgGVmFhQDGwEhgGQVBQwWmakgwCxPLkQkAKBobJjyBSda1wDYyGXLUqLF0wWFyQ4ki13PYyF2dIZyIZwbpImAq62LGBMCpomBKZAADgADKUZHBTBUcz6-aTQZ9SjBw4nk6mkAAmUomDZEcMIsGWuAzCNojFo1RyakmX1wABiEBkJIZRzJLIgIBcLiAA" ]
prettier/prettier
15,409
prettier__prettier-15409
[ "11910" ]
675490ae55fe1c0b797db13bf5f055711d2c0b69
diff --git a/src/language-js/comments/handle-comments.js b/src/language-js/comments/handle-comments.js --- a/src/language-js/comments/handle-comments.js +++ b/src/language-js/comments/handle-comments.js @@ -84,6 +84,7 @@ function handleEndOfLineComment(context) { handleVariableDeclaratorComments, handleBreakAndContinueStatementComments, handleSwitchDefaultCaseComments, + handleLastUnionElementInExpression, ].some((fn) => fn(context)); } @@ -887,6 +888,44 @@ function handleSwitchDefaultCaseComments({ return true; } +/** + * Handle `Comment2` and `Comment4`. + * + * type Foo = ( + * | "thing1" // Comment1 + * | "thing2" // Comment2 + * )[]; + * + * type Foo = ( + * | "thing1" // Comment3 + * | "thing2" // Comment4 + * ) & Bar; + * + * @param {CommentContext} context + * @returns {boolean} + */ +function handleLastUnionElementInExpression({ + comment, + precedingNode, + enclosingNode, + followingNode, +}) { + if ( + precedingNode && + (precedingNode.type === "TSUnionType" || + precedingNode.type === "UnionTypeAnnotation") && + (((enclosingNode.type === "TSArrayType" || + enclosingNode.type === "ArrayTypeAnnotation") && + followingNode === undefined) || + enclosingNode.type === "TSIntersectionType" || + enclosingNode.type === "IntersectionTypeAnnotation") + ) { + addTrailingComment(precedingNode.types.at(-1), comment); + return true; + } + return false; +} + /** * @param {Node} node * @returns {boolean}
diff --git a/tests/format/flow/union/__snapshots__/jsfmt.spec.js.snap b/tests/format/flow/union/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/flow/union/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/flow/union/__snapshots__/jsfmt.spec.js.snap @@ -22,6 +22,37 @@ const myValue = (callcallcallcallcallcall( ================================================================================ `; +exports[`comments.js format 1`] = ` +====================================options===================================== +parsers: ["flow"] +printWidth: 80 + | printWidth +=====================================input====================================== +type Foo = ( + | "thing1" // Comment1 + | "thing2" // Comment2 +)[]; // Final comment1 + +type Foo = ( + | "thing1" // Comment1 + | "thing2" // Comment2 +) & Bar; // Final comment2 + +=====================================output===================================== +type Foo = ( + | "thing1" // Comment1 + | "thing2" // Comment2 +)[]; // Final comment1 + +type Foo = ( + | "thing1" // Comment1 + | "thing2" // Comment2 +) & + Bar; // Final comment2 + +================================================================================ +`; + exports[`union.js format 1`] = ` ====================================options===================================== parsers: ["flow"] diff --git a/tests/format/flow/union/comments.js b/tests/format/flow/union/comments.js new file mode 100644 --- /dev/null +++ b/tests/format/flow/union/comments.js @@ -0,0 +1,9 @@ +type Foo = ( + | "thing1" // Comment1 + | "thing2" // Comment2 +)[]; // Final comment1 + +type Foo = ( + | "thing1" // Comment1 + | "thing2" // Comment2 +) & Bar; // Final comment2 diff --git a/tests/format/typescript/union/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/union/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/typescript/union/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/typescript/union/__snapshots__/jsfmt.spec.js.snap @@ -1,5 +1,36 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP +exports[`comments.ts format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +type Foo = ( + | "thing1" // Comment1 + | "thing2" // Comment2 +)[]; // Final comment1 + +type Foo = ( + | "thing1" // Comment1 + | "thing2" // Comment2 +) & Bar; // Final comment2 + +=====================================output===================================== +type Foo = ( + | "thing1" // Comment1 + | "thing2" // Comment2 +)[]; // Final comment1 + +type Foo = ( + | "thing1" // Comment1 + | "thing2" // Comment2 +) & + Bar; // Final comment2 + +================================================================================ +`; + exports[`inlining.ts format 1`] = ` ====================================options===================================== parsers: ["typescript"] diff --git a/tests/format/typescript/union/comments.ts b/tests/format/typescript/union/comments.ts new file mode 100644 --- /dev/null +++ b/tests/format/typescript/union/comments.ts @@ -0,0 +1,9 @@ +type Foo = ( + | "thing1" // Comment1 + | "thing2" // Comment2 +)[]; // Final comment1 + +type Foo = ( + | "thing1" // Comment1 + | "thing2" // Comment2 +) & Bar; // Final comment2
Last indented list item inline comment is being moved to outer comment and combined with existing comment **Prettier 2.5.0** [Playground link](https://prettier.io/playground/?source=post_page---------------------------#N4Igxg9gdgLgprEAuEB6VACAKgTwA5wDKYATgJZ4wZmxwkBmAhmHADpQ3wPNzYAWNAOYBGDMHasYjaUgwAKCTEkAfDAHIYAqCLUZ0GAMIQAtsYQxhiles1CATLv1HT5u4oCUAbQC6Abj2YAGI0jAA2GJAusOwAviAANCAQlGTQAM7IoIwkJBAA7gAK2QgZKGF5jDgZiQBGJMwA1nAwhIxmADI0cMhMoWlwtfVgTS14zELIMCQArgMgcMY1cAAmyyvtjNrTjIJwgRAkxowwMBNl0zAQCSB8MMahAOoC8GljLIQlZKcAbl84yOA0tUQDR+iQYAV6oIjj0wv1EgArNIAD0IQlCcAAitMIPBYX05mMSGCATVGEtQtc8ORYA8yMtNMgABwABkS1Ig-Qe9TwAOpcDB326iQAjjj4JDkqUQIw0gBaKBwFYra4kOBishqyE7GFIXrwkD9YxkSYzOZpdFY8XdPVwuZSGp0hl8ZB2RJTRhkUJCZy6+ZpACs12m-Sw5NK+rm31mAEkoGtYMRyJQAILxwgwHAY-H9GIxIA) <!-- prettier-ignore --> ```sh --parser babel ``` **Input:** <!-- prettier-ignore --> ```ts // TypeScript interface interface Thing1 { aaa: ( | 'thing1' // Comment1 | 'thing2' // Comment2 )[]; // Final comment } ``` **Output:** <!-- prettier-ignore --> ```ts // TypeScript interface interface Thing1 { aaa: ( | "thing1" // Comment1 | "thing2" )[]; // Comment2 // Final comment } ``` **Expected behavior:** ```ts // TypeScript interface interface Thing1 { aaa: ( | "thing1" // Comment1 | "thing2" // Comment2 )[]; // Final comment } ``` The placement of `Comment2` in the sample output is the point of concern. Curiously, using 'flow', 'babel', 'babel-flow' and 'typescript' parsers, the same incorrect output is obtained. But: when using `babel-ts` as the parser, it seems to generate the expected output. So, I'm thinking this is a bug in Prettier rather than in the parsers?
This is still happening in the latest version of Prettier, has anyone started looking into this? Another half year later, and it appears that this issue is *still* happening!!!
"2023-09-16T09:48:18Z"
3.1
[]
[ "tests/format/typescript/union/jsfmt.spec.js", "tests/format/flow/union/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/?source=post_page---------------------------#N4Igxg9gdgLgprEAuEB6VACAKgTwA5wDKYATgJZ4wZmxwkBmAhmHADpQ3wPNzYAWNAOYBGDMHasYjaUgwAKCTEkAfDAHIYAqCLUZ0GAMIQAtsYQxhiles1CATLv1HT5u4oCUAbQC6Abj2YAGI0jAA2GJAusOwAviAANCAQlGTQAM7IoIwkJBAA7gAK2QgZKGF5jDgZiQBGJMwA1nAwhIxmADI0cMhMoWlwtfVgTS14zELIMCQArgMgcMY1cAAmyyvtjNrTjIJwgRAkxowwMBNl0zAQCSB8MMahAOoC8GljLIQlZKcAbl84yOA0tUQDR+iQYAV6oIjj0wv1EgArNIAD0IQlCcAAitMIPBYX05mMSGCATVGEtQtc8ORYA8yMtNMgABwABkS1Ig-Qe9TwAOpcDB326iQAjjj4JDkqUQIw0gBaKBwFYra4kOBishqyE7GFIXrwkD9YxkSYzOZpdFY8XdPVwuZSGp0hl8ZB2RJTRhkUJCZy6+ZpACs12m-Sw5NK+rm31mAEkoGtYMRyJQAILxwgwHAY-H9GIxIA" ]
prettier/prettier
15,411
prettier__prettier-15411
[ "15410" ]
4169dbb871f29023fdb8ed4594c7bb19a758771e
diff --git a/src/language-markdown/print-whitespace.js b/src/language-markdown/print-whitespace.js --- a/src/language-markdown/print-whitespace.js +++ b/src/language-markdown/print-whitespace.js @@ -47,7 +47,7 @@ const noBreakAfter = new Set( * `"檜原村(ひのはらむら)\n以外には、"` */ const noBreakBefore = new Set( - "!%),.:;?]}¢°·'\"†‡›℃∶、。〃〆〕〗〞﹚﹜!"%'),.:;?]}~–—•〉》」︰︱︲︳﹐﹑﹒﹓﹔﹕﹖﹘︶︸︺︼︾﹀﹂﹗|、』】〙〟⦆»ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻‐゠〜~‼⁇⁈⁉・", + "!%),.:;?]}¢°·'\"†‡›℃∶、。〃〆〕〗〞﹚﹜!"%'),.:;?]}~–—•〉》」︰︱︲︳﹐﹑﹒﹓﹔﹕﹖﹘︶︸︺︼︾﹀﹂﹗|、』】〙〟⦆»ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻‐゠〜~‼⁇⁈⁉・゙゚", ); /**
diff --git a/tests/format/markdown/splitCjkText/__snapshots__/jsfmt.spec.js.snap b/tests/format/markdown/splitCjkText/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/markdown/splitCjkText/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/markdown/splitCjkText/__snapshots__/jsfmt.spec.js.snap @@ -17,7 +17,10 @@ proseWrap: "always" カ゚キ゚ク゚ケ゚コ゚でガギグゴ +nasalカ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚ + かつてはワ行のワ、ヰ、ヱ、ヲに濁点を付して [v] 音を表現すること(ワ゛、ヰ゛、ヱ゛、ヲ゛)も行われたが、一般的にはならなかった。 + =====================================output===================================== 這是一段很長很長很長很長很長很長很長很長很長很長很長很長很長很長很長很長很長很長 很長的段落 @@ -32,6 +35,10 @@ proseWrap: "always" カ゚キ゚ク゚ケ゚コ゚でガギグゴ +nasalカ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ +ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ +ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚ + かつてはワ行のワ、ヰ、ヱ、ヲに濁点を付して [v] 音を表現すること(ワ゛、ヰ゛、ヱ ゛、ヲ゛)も行われたが、一般的にはならなかった。 diff --git a/tests/format/markdown/splitCjkText/chinese-japanese.md b/tests/format/markdown/splitCjkText/chinese-japanese.md --- a/tests/format/markdown/splitCjkText/chinese-japanese.md +++ b/tests/format/markdown/splitCjkText/chinese-japanese.md @@ -8,4 +8,6 @@ カ゚キ゚ク゚ケ゚コ゚でガギグゴ -かつてはワ行のワ、ヰ、ヱ、ヲに濁点を付して [v] 音を表現すること(ワ゛、ヰ゛、ヱ゛、ヲ゛)も行われたが、一般的にはならなかった。 \ No newline at end of file +nasalカ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚カ゚キ゚ク゚ケ゚コ゚ + +かつてはワ行のワ、ヰ、ヱ、ヲに濁点を付して [v] 音を表現すること(ワ゛、ヰ゛、ヱ゛、ヲ゛)も行われたが、一般的にはならなかった。
Markdown: Don't split lines between Japanese kana & COMBINING KATAKANA-HIRAGANA (SEMI-)VOICED SOUND MARK <!-- BEFORE SUBMITTING AN ISSUE: 1. Search for your issue on GitHub: https://github.com/prettier/prettier/issues A large number of opened issues are duplicates of existing issues. If someone has already opened an issue for what you are experiencing, you do not need to open a new issue — please add a 👍 reaction to the existing issue instead. 2. We get a lot of requests for adding options, but Prettier is built on the principle of being opinionated about code formatting. This means we add options only in the case of strict technical necessity. Find out more: https://prettier.io/docs/en/option-philosophy.html Don't fill the form below manually! Let a program create a report for you: 1. Go to https://prettier.io/playground 2. Paste your code and set options 3. Press the "Report issue" button in the lower right --> **Prettier 3.0.3** [Playground link](https://prettier.io/playground/#.....) ```sh # Options (if any): --prose-wrap always ``` **Input:** ```markdown nasalか゚き゚く゚け゚こ゚カ゚キ゚ク゚ケ゚コ゚か゚き゚く゚け゚こ゚カ゚キ゚ク゚ケ゚コ゚か゚き゚く゚け゚こ゚カ゚キ゚ク゚ケ゚コ゚ ``` **Output:** ```markdown nasalか゚き゚く゚け゚こ゚カ゚キ゚ク゚ケ゚コ゚か゚き゚く゚け゚こ゚カ゚キ゚ク゚ケ ゚コ゚か゚き゚く゚け゚こ゚カ゚キ゚ク゚ケ゚コ゚ ``` **Expected behavior:** ```markdown nasalか゚き゚く゚け゚こ゚カ゚キ゚ク゚ケ゚コ゚か゚き゚く゚け゚こ゚カ゚キ゚ク゚ ケ゚コ゚か゚き゚く゚け゚こ゚カ゚キ゚ク゚ケ゚コ゚ ``` ケ゚ (U+30B1 U+309A; strict nasal-voiced katakana GE expression) must not be split. > [!NOTE] > This expression (semi-voiced sound mark for GA/GI/GU/GE/GO) doesn't appears in most text. `[hiragana or katakana] [U+3099 or U+309A]` (U+309B-U+309C are not affected)
"2023-09-16T14:20:33Z"
3.1
[]
[ "tests/format/markdown/splitCjkText/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#.....", "https://prettier.io/playground" ]
prettier/prettier
15,433
prettier__prettier-15433
[ "15155", "15079" ]
b37a120ab6459f25218b411baab66ee73de02af9
diff --git a/src/cli/expand-patterns.js b/src/cli/expand-patterns.js --- a/src/cli/expand-patterns.js +++ b/src/cli/expand-patterns.js @@ -11,22 +11,24 @@ async function* expandPatterns(context) { const seen = new Set(); let noResults = true; - for await (const pathOrError of expandPatternsInternal(context)) { + for await (const { filePath, ignoreUnknown, error } of expandPatternsInternal( + context, + )) { noResults = false; - if (typeof pathOrError !== "string") { - yield pathOrError; + if (error) { + yield { error }; continue; } - const fileName = path.resolve(pathOrError); + const filename = path.resolve(filePath); // filter out duplicates - if (seen.has(fileName)) { + if (seen.has(filename)) { continue; } - seen.add(fileName); - yield fileName; + seen.add(filename); + yield { filename, ignoreUnknown }; } if (noResults && context.argv.errorOnUnmatchedPattern !== false) { @@ -52,7 +54,6 @@ async function* expandPatternsInternal(context) { followSymbolicLinks: false, }; - let supportedFilesGlob; const cwd = process.cwd(); /** @type {Array<{ type: 'file' | 'dir' | 'glob'; glob: string; input: string; }>} */ @@ -87,10 +88,9 @@ async function* expandPatternsInternal(context) { const prefix = escapePathForGlob(fixWindowsSlashes(relativePath)); entries.push({ type: "dir", - glob: getSupportedFilesGlob().map( - (pattern) => `${prefix}/**/${pattern}`, - ), + glob: `${prefix}/**/*`, input: pattern, + ignoreUnknown: true, }); } } else if (pattern[0] === "!") { @@ -105,7 +105,7 @@ async function* expandPatternsInternal(context) { } } - for (const { type, glob, input } of entries) { + for (const { type, glob, input, ignoreUnknown } of entries) { let result; try { @@ -123,22 +123,7 @@ async function* expandPatternsInternal(context) { yield { error: `${errorMessages.emptyResults[type]}: "${input}".` }; } } else { - yield* sortPaths(result); - } - } - - function getSupportedFilesGlob() { - supportedFilesGlob ??= [...getSupportedFilesGlobWithoutCache()]; - return supportedFilesGlob; - } - - function* getSupportedFilesGlobWithoutCache() { - for (const { extensions = [], filenames = [] } of context.languages) { - yield* filenames; - - for (const extension of extensions) { - yield `*${extension.startsWith(".") ? extension : `.${extension}`}`; - } + yield* sortPaths(result).map((filePath) => ({ filePath, ignoreUnknown })); } } } diff --git a/src/cli/format.js b/src/cli/format.js --- a/src/cli/format.js +++ b/src/cli/format.js @@ -22,17 +22,16 @@ class DebugError extends Error { name = "DebugError"; } -function handleError(context, filename, error, printedFilename) { +function handleError(context, filename, error, printedFilename, ignoreUnknown) { + ignoreUnknown ||= context.argv.ignoreUnknown; + const errorIsUndefinedParseError = error instanceof errors.UndefinedParserError; if (printedFilename) { // Can't test on CI, `isTTY()` is always false, see ./is-tty.js /* c8 ignore next 3 */ - if ( - (context.argv.write || context.argv.ignoreUnknown) && - errorIsUndefinedParseError - ) { + if ((context.argv.write || ignoreUnknown) && errorIsUndefinedParseError) { printedFilename.clear(); } else { // Add newline to split errors from filename line. @@ -41,7 +40,7 @@ function handleError(context, filename, error, printedFilename) { } if (errorIsUndefinedParseError) { - if (context.argv.ignoreUnknown) { + if (ignoreUnknown) { return; } if (!context.argv.check && !context.argv.listDifferent) { @@ -313,16 +312,16 @@ async function formatFiles(context) { } } - for await (const pathOrError of expandPatterns(context)) { - if (typeof pathOrError === "object") { - context.logger.error(pathOrError.error); + for await (const { error, filename, ignoreUnknown } of expandPatterns( + context, + )) { + if (error) { + context.logger.error(error); // Don't exit, but set the exit code to 2 process.exitCode = 2; continue; } - const filename = pathOrError; - const isFileIgnored = isIgnored(filename); if ( isFileIgnored && @@ -391,7 +390,13 @@ async function formatFiles(context) { } output = result.formatted; } catch (error) { - handleError(context, fileNameToDisplay, error, printedFilename); + handleError( + context, + fileNameToDisplay, + error, + printedFilename, + ignoreUnknown, + ); continue; }
diff --git a/tests/integration/__tests__/__snapshots__/ignore-unknown.js.snap b/tests/integration/__tests__/__snapshots__/ignore-unknown.js.snap --- a/tests/integration/__tests__/__snapshots__/ignore-unknown.js.snap +++ b/tests/integration/__tests__/__snapshots__/ignore-unknown.js.snap @@ -18,25 +18,35 @@ exports[`Not matching pattern (stdout) 1`] = `""`; exports[`Not matching pattern (write) 1`] = `[]`; -exports[`ignore-unknown alias (stdout) 1`] = `"javascript.js"`; +exports[`ignore-unknown alias (stdout) 1`] = ` +"javascript.js +override.as-js-file" +`; exports[`ignore-unknown check (stderr) 1`] = ` "[warn] javascript.js -[warn] Code style issues found in the above file. Run Prettier to fix." +[warn] override.as-js-file +[warn] Code style issues found in 2 files. Run Prettier to fix." `; exports[`ignore-unknown check (stdout) 1`] = `"Checking formatting..."`; exports[`ignore-unknown check (write) 1`] = `[]`; -exports[`ignore-unknown dir (stdout) 1`] = `"javascript.js"`; +exports[`ignore-unknown dir (stdout) 1`] = ` +"javascript.js +override.as-js-file" +`; exports[`ignore-unknown pattern (stdout) 1`] = ` "javascript.js override.as-js-file" `; -exports[`ignore-unknown write (stdout) 1`] = `"javascript.js"`; +exports[`ignore-unknown write (stdout) 1`] = ` +"javascript.js +override.as-js-file" +`; exports[`ignore-unknown write (write) 1`] = ` [ @@ -45,5 +55,10 @@ exports[`ignore-unknown write (write) 1`] = ` ", "filename": "javascript.js", }, + { + "content": "const foo = "bar"; +", + "filename": "override.as-js-file", + }, ] `; diff --git a/tests/integration/__tests__/__snapshots__/infer-plugins-ext-dir.js.snap b/tests/integration/__tests__/__snapshots__/infer-plugins-ext-dir.js.snap new file mode 100644 --- /dev/null +++ b/tests/integration/__tests__/__snapshots__/infer-plugins-ext-dir.js.snap @@ -0,0 +1,17 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`infer file ext that supported by only plugins basic (stderr) 1`] = `""`; + +exports[`infer file ext that supported by only plugins with config option (stderr) 1`] = `""`; + +exports[`infer file ext that supported by only plugins with defaultOptions (stderr) 1`] = `""`; + +exports[`infer file ext that supported by only plugins with multiple config for nested dir (stderr) 1`] = `""`; + +exports[`infer file ext that supported by only plugins with multiple config for nested dir 2 (stderr) 1`] = `""`; + +exports[`infer file ext that supported by only plugins with multiple config for nested dir 2 (stderr) 2`] = `""`; + +exports[`infer file ext that supported by only plugins with overrides and defaultOptions (stderr) 1`] = `""`; + +exports[`infer file ext that supported by only plugins with overrides options (stderr) 1`] = `""`; diff --git a/tests/integration/__tests__/__snapshots__/patterns-dirs.js.snap b/tests/integration/__tests__/__snapshots__/patterns-dirs.js.snap --- a/tests/integration/__tests__/__snapshots__/patterns-dirs.js.snap +++ b/tests/integration/__tests__/__snapshots__/patterns-dirs.js.snap @@ -9,7 +9,8 @@ dir1/nested1/bn1.js dir2/a2.js dir2/b2.js dir2/nested2/an2.js -dir2/nested2/bn2.js" +dir2/nested2/bn2.js +dir2/node-shebang" `; exports[`1a - with *.foo plugin: prettier dir1 dir2 --plugin=../../plugins/extensions/plugin.cjs (stdout) 1`] = ` @@ -23,10 +24,11 @@ dir2/a2.foo dir2/a2.js dir2/b2.js dir2/nested2/an2.js -dir2/nested2/bn2.js" +dir2/nested2/bn2.js +dir2/node-shebang" `; -exports[`1c: prettier dir1 empty (stderr) 1`] = `"[error] No supported files were found in the directory: "empty"."`; +exports[`1c: prettier dir1 empty (stderr) 1`] = `""`; exports[`1c: prettier dir1 empty (stdout) 1`] = ` "dir1/a1.js @@ -64,7 +66,7 @@ dir2/nested2/bn2.js dir2/node-shebang" `; -exports[`4: prettier . 'dir2/**/*' (stderr) 1`] = `"[error] No parser could be inferred for file "<cli>/patterns-dirs/dir2/a2.foo"."`; +exports[`4: prettier . 'dir2/**/*' (stderr) 1`] = `""`; exports[`4: prettier . 'dir2/**/*' (stdout) 1`] = ` "!dir/a.js @@ -97,7 +99,8 @@ dir1/b1.js dir2/a2.js dir2/b2.js dir2/nested2/an2.js -dir2/nested2/bn2.js" +dir2/nested2/bn2.js +dir2/node-shebang" `; exports[`Negative patterns 3: prettier . '!dir1/nested1/an1.js' (stdout) 1`] = ` @@ -109,7 +112,8 @@ dir1/nested1/bn1.js dir2/a2.js dir2/b2.js dir2/nested2/an2.js -dir2/nested2/bn2.js" +dir2/nested2/bn2.js +dir2/node-shebang" `; exports[`Negative patterns 4: prettier '!nonexistent-dir1 !nonexistent-dir2' (stderr) 1`] = `"[error] No matching files. Patterns: !nonexistent-dir1 !nonexistent-dir2"`; @@ -130,7 +134,8 @@ dir1/nested1/bn1.js dir2/a2.js dir2/b2.js dir2/nested2/an2.js -dir2/nested2/bn2.js" +dir2/nested2/bn2.js +dir2/node-shebang" `; exports[`Trailing slash 2: prettier .// (stdout) 1`] = ` @@ -143,7 +148,8 @@ dir1/nested1/bn1.js dir2/a2.js dir2/b2.js dir2/nested2/an2.js -dir2/nested2/bn2.js" +dir2/nested2/bn2.js +dir2/node-shebang" `; exports[`Trailing slash 3: prettier dir1/ (stdout) 1`] = ` @@ -180,7 +186,8 @@ exports[`Trailing slash run in sub dir 1: prettier .. (stdout) 1`] = ` a2.js b2.js nested2/an2.js -nested2/bn2.js" +nested2/bn2.js +node-shebang" `; exports[`Trailing slash run in sub dir 2: prettier ../ (stdout) 1`] = ` @@ -193,7 +200,8 @@ exports[`Trailing slash run in sub dir 2: prettier ../ (stdout) 1`] = ` a2.js b2.js nested2/an2.js -nested2/bn2.js" +nested2/bn2.js +node-shebang" `; exports[`Trailing slash run in sub dir 3: prettier ../dir1 (stdout) 1`] = ` diff --git a/tests/integration/__tests__/infer-plugins-ext-dir.js b/tests/integration/__tests__/infer-plugins-ext-dir.js new file mode 100644 --- /dev/null +++ b/tests/integration/__tests__/infer-plugins-ext-dir.js @@ -0,0 +1,208 @@ +import { outdent } from "outdent"; + +describe("infer file ext that supported by only plugins", () => { + describe("basic", () => { + runCli("cli/infer-plugins-ext-dir/", ["--write", "src"]).test({ + status: 0, + stdout: "src/file.foo 0ms", + write: [ + { + content: "!contents\n", + filename: "src/file.foo", + }, + ], + }); + }); + + describe("with config option", () => { + runCli("cli/infer-plugins-ext-dir-with-config/", [ + "--config", + "foo.mjs", + "--write", + "src", + ]).test({ + status: 0, + stdout: "src/file.foo 0ms", + write: [ + { + content: "!contents\n", + filename: "src/file.foo", + }, + ], + }); + }); + + describe("with overrides options", () => { + runCli("cli/infer-plugins-ext-dir-with-overrides/", [ + "--write", + "src", + ]).test({ + status: 0, + stdout: "src/file.bar 0ms\nsrc/file.foo 0ms", + write: [ + { + content: "!contents\n", + filename: "src/file.bar", + }, + { + content: "!contents\n", + filename: "src/file.foo", + }, + ], + }); + }); + + describe("with defaultOptions", () => { + runCli("cli/infer-plugins-ext-dir-with-default-options/", [ + "--write", + "--no-editorconfig", + "src", + ]).test({ + status: 0, + stdout: "src/file.foo 0ms\nsrc/index.js 0ms", + write: [ + { + content: '{"tabWidth":8,"bracketSpacing":false}', + filename: "src/file.foo", + }, + { + // formatted with `tabWidth: 2` + content: outdent` + function main() { + console.log("Hello, World!"); + }\n + `, + filename: "src/index.js", + }, + ], + }); + }); + + describe("with overrides and defaultOptions", () => { + runCli("cli/infer-plugins-ext-dir-with-overrides-and-default-options/", [ + "--write", + "--no-editorconfig", + "src", + ]).test({ + status: 0, + stdout: "src/file.foo 0ms\nsrc/index.js 0ms", + write: [ + { + content: '{"tabWidth":8,"bracketSpacing":false}', + filename: "src/file.foo", + }, + { + // formatted with `tabWidth: 2` + content: outdent` + function main() { + console.log("Hello, World!"); + }\n + `, + filename: "src/index.js", + }, + ], + }); + }); + + describe("with multiple config for nested dir", () => { + runCli("cli/infer-plugins-with-multiple-config", [ + "--write", + "--no-editorconfig", + ".", + ]).test({ + status: 0, + stdout: outdent` + dir/.prettierrc.mjs 0ms + dir/subdir/.prettierrc.mjs 0ms + dir/subdir/2.foo 0ms + `, + write: [ + { + content: "export default {};\n", + filename: "dir/.prettierrc.mjs", + }, + { + content: outdent` + export default { + plugins: ["../../../../plugins/defaultOptions/plugin.cjs"], + };\n + `, + filename: "dir/subdir/.prettierrc.mjs", + }, + { + content: '{"tabWidth":8,"bracketSpacing":false}', + filename: "dir/subdir/2.foo", + }, + ], + }); + }); + + describe("with multiple config for nested dir 2", () => { + runCli("cli/infer-plugins-with-multiple-config", [ + "--write", + "--no-editorconfig", + "dir", + "dir/subdir", + ]).test({ + status: 0, + stdout: outdent` + dir/.prettierrc.mjs 0ms + dir/subdir/.prettierrc.mjs 0ms + dir/subdir/2.foo 0ms + `, + write: [ + { + content: "export default {};\n", + filename: "dir/.prettierrc.mjs", + }, + { + content: outdent` + export default { + plugins: ["../../../../plugins/defaultOptions/plugin.cjs"], + };\n + `, + filename: "dir/subdir/.prettierrc.mjs", + }, + { + content: '{"tabWidth":8,"bracketSpacing":false}', + filename: "dir/subdir/2.foo", + }, + ], + }); + }); + + describe("with multiple config for nested dir 2", () => { + runCli("cli/infer-plugins-ext-dir-with-complex-overrides", [ + "--write", + "--no-editorconfig", + ".", + ]).test({ + status: 0, + stdout: outdent` + .prettierrc.mjs 0ms + dir/2.foo 0ms + `, + write: [ + { + content: outdent` + export default { + overrides: [ + { + files: ["dir/*.foo"], + options: { + plugins: ["../../plugins/extensions/plugin.cjs"], + }, + }, + ], + };\n + `, + filename: ".prettierrc.mjs", + }, + { + content: "!2.foo\n", + filename: "dir/2.foo", + }, + ], + }); + }); +}); diff --git a/tests/integration/__tests__/patterns-dirs.js b/tests/integration/__tests__/patterns-dirs.js --- a/tests/integration/__tests__/patterns-dirs.js +++ b/tests/integration/__tests__/patterns-dirs.js @@ -12,22 +12,25 @@ const runCliWithoutGitignore = (dir, args, options) => runCli(dir, [...args, "--ignore-path", ".prettierignore"], options); // ESLint-like behavior +// // https://github.com/prettier/prettier/pull/6639#issuecomment-548949954 // +// Since 3.0: https://github.com/prettier/prettier/pull/15155#issuecomment-1723654981 +// // 1. `prettier dir1 dir2` – prettify all files with supported extensions inside `dir1` and `dir2`. // // 2. `prettier dir1 "dir2/**/*"` – prettify all files with supported extensions inside `dir1` // as well as all files matched by the `dir2/**/*` glob. -// If any of the latter files have unknown extensions – log an error for them. (*) +// Unsupported files are ignored as with `--ignore-unknown`. // // 3. `prettier non-exists-dir "dir2/**/*""` – log an error that `non-exists-dir` resulted in 0 files // and prettify all files matched by the `dir2/**/*` glob. -// If any of the latter files have unknown extensions – log an error for them. (*) +// Unsupported files are ignored as with `--ignore-unknown`. // (Note: ESLint just prints an error and doesn't process anything.) // // 4. `prettier . "dir2/**/*"` – prettify all files with supported extensions in `.` // and all files matched by the `dir2/**/*` glob. -// If any of the latter files have unknown extensions – log an error for them. (*) +// Unsupported files are ignored as with `--ignore-unknown`. // // (*) That error ("No parser could be inferred for file") doesn't affect the error code. @@ -40,7 +43,7 @@ testPatterns("1a - with *.foo plugin", [ testPatterns("1b - special characters in dir name", ["dir1", "!dir"], { stdout: expect.stringMatching(/!dir[/\\]a\.js/), }); -testPatterns("1c", ["dir1", "empty"], { status: 2 }); +testPatterns("1c", ["dir1", "empty"], { status: 1 }); testPatterns("2", ["dir1", "dir2/**/*"], { status: 1 }); diff --git a/tests/integration/cli/infer-plugins-ext-dir-with-complex-overrides/.prettierrc.mjs b/tests/integration/cli/infer-plugins-ext-dir-with-complex-overrides/.prettierrc.mjs new file mode 100644 --- /dev/null +++ b/tests/integration/cli/infer-plugins-ext-dir-with-complex-overrides/.prettierrc.mjs @@ -0,0 +1,10 @@ +export default { + overrides: [ + { + files: ["dir/*.foo"], + options: { + plugins: ["../../plugins/extensions/plugin.cjs"] + } + }, + ] +}; diff --git a/tests/integration/cli/infer-plugins-ext-dir-with-complex-overrides/1.foo b/tests/integration/cli/infer-plugins-ext-dir-with-complex-overrides/1.foo new file mode 100644 --- /dev/null +++ b/tests/integration/cli/infer-plugins-ext-dir-with-complex-overrides/1.foo @@ -0,0 +1 @@ +1.foo diff --git a/tests/integration/cli/infer-plugins-ext-dir-with-complex-overrides/dir/2.foo b/tests/integration/cli/infer-plugins-ext-dir-with-complex-overrides/dir/2.foo new file mode 100644 --- /dev/null +++ b/tests/integration/cli/infer-plugins-ext-dir-with-complex-overrides/dir/2.foo @@ -0,0 +1 @@ +2.foo diff --git a/tests/integration/cli/infer-plugins-ext-dir-with-config/foo.mjs b/tests/integration/cli/infer-plugins-ext-dir-with-config/foo.mjs new file mode 100644 --- /dev/null +++ b/tests/integration/cli/infer-plugins-ext-dir-with-config/foo.mjs @@ -0,0 +1,3 @@ +export default { + plugins: ["../../plugins/extensions/plugin.cjs"], +}; diff --git a/tests/integration/cli/infer-plugins-ext-dir-with-config/src/file.foo b/tests/integration/cli/infer-plugins-ext-dir-with-config/src/file.foo new file mode 100644 --- /dev/null +++ b/tests/integration/cli/infer-plugins-ext-dir-with-config/src/file.foo @@ -0,0 +1 @@ +contents diff --git a/tests/integration/cli/infer-plugins-ext-dir-with-default-options/.prettierrc.mjs b/tests/integration/cli/infer-plugins-ext-dir-with-default-options/.prettierrc.mjs new file mode 100644 --- /dev/null +++ b/tests/integration/cli/infer-plugins-ext-dir-with-default-options/.prettierrc.mjs @@ -0,0 +1,3 @@ +export default { + plugins: ["../../plugins/defaultOptions/plugin.cjs"] +}; diff --git a/tests/integration/cli/infer-plugins-ext-dir-with-default-options/src/file.foo b/tests/integration/cli/infer-plugins-ext-dir-with-default-options/src/file.foo new file mode 100644 --- /dev/null +++ b/tests/integration/cli/infer-plugins-ext-dir-with-default-options/src/file.foo @@ -0,0 +1 @@ +contents diff --git a/tests/integration/cli/infer-plugins-ext-dir-with-default-options/src/index.js b/tests/integration/cli/infer-plugins-ext-dir-with-default-options/src/index.js new file mode 100644 --- /dev/null +++ b/tests/integration/cli/infer-plugins-ext-dir-with-default-options/src/index.js @@ -0,0 +1,3 @@ +function main() { + console.log("Hello, World!"); +} diff --git a/tests/integration/cli/infer-plugins-ext-dir-with-overrides-and-default-options/.prettierrc.mjs b/tests/integration/cli/infer-plugins-ext-dir-with-overrides-and-default-options/.prettierrc.mjs new file mode 100644 --- /dev/null +++ b/tests/integration/cli/infer-plugins-ext-dir-with-overrides-and-default-options/.prettierrc.mjs @@ -0,0 +1,10 @@ +export default { + overrides: [ + { + files: ["*.foo"], + options: { + plugins: ["../../plugins/defaultOptions/plugin.cjs"] + } + } + ] +}; diff --git a/tests/integration/cli/infer-plugins-ext-dir-with-overrides-and-default-options/src/file.foo b/tests/integration/cli/infer-plugins-ext-dir-with-overrides-and-default-options/src/file.foo new file mode 100644 --- /dev/null +++ b/tests/integration/cli/infer-plugins-ext-dir-with-overrides-and-default-options/src/file.foo @@ -0,0 +1 @@ +contents diff --git a/tests/integration/cli/infer-plugins-ext-dir-with-overrides-and-default-options/src/index.js b/tests/integration/cli/infer-plugins-ext-dir-with-overrides-and-default-options/src/index.js new file mode 100644 --- /dev/null +++ b/tests/integration/cli/infer-plugins-ext-dir-with-overrides-and-default-options/src/index.js @@ -0,0 +1,3 @@ +function main() { + console.log("Hello, World!"); +} diff --git a/tests/integration/cli/infer-plugins-ext-dir-with-overrides/.prettierrc.mjs b/tests/integration/cli/infer-plugins-ext-dir-with-overrides/.prettierrc.mjs new file mode 100644 --- /dev/null +++ b/tests/integration/cli/infer-plugins-ext-dir-with-overrides/.prettierrc.mjs @@ -0,0 +1,16 @@ +export default { + overrides: [ + { + files: ["*.foo"], + options: { + plugins: ["../../plugins/extensions/plugin.cjs"] + } + }, + { + files: ["*.bar"], + options: { + plugins: ["../../plugins/extensions2/plugin.cjs"] + } + } + ] +}; diff --git a/tests/integration/cli/infer-plugins-ext-dir-with-overrides/src/file.bar b/tests/integration/cli/infer-plugins-ext-dir-with-overrides/src/file.bar new file mode 100644 --- /dev/null +++ b/tests/integration/cli/infer-plugins-ext-dir-with-overrides/src/file.bar @@ -0,0 +1 @@ +contents diff --git a/tests/integration/cli/infer-plugins-ext-dir-with-overrides/src/file.foo b/tests/integration/cli/infer-plugins-ext-dir-with-overrides/src/file.foo new file mode 100644 --- /dev/null +++ b/tests/integration/cli/infer-plugins-ext-dir-with-overrides/src/file.foo @@ -0,0 +1 @@ +contents diff --git a/tests/integration/cli/infer-plugins-ext-dir/.prettierrc.mjs b/tests/integration/cli/infer-plugins-ext-dir/.prettierrc.mjs new file mode 100644 --- /dev/null +++ b/tests/integration/cli/infer-plugins-ext-dir/.prettierrc.mjs @@ -0,0 +1,3 @@ +export default { + plugins: ["../../plugins/extensions/plugin.cjs"], +}; diff --git a/tests/integration/cli/infer-plugins-ext-dir/src/file.foo b/tests/integration/cli/infer-plugins-ext-dir/src/file.foo new file mode 100644 --- /dev/null +++ b/tests/integration/cli/infer-plugins-ext-dir/src/file.foo @@ -0,0 +1 @@ +contents diff --git a/tests/integration/cli/infer-plugins-with-multiple-config/dir/.prettierrc.mjs b/tests/integration/cli/infer-plugins-with-multiple-config/dir/.prettierrc.mjs new file mode 100644 --- /dev/null +++ b/tests/integration/cli/infer-plugins-with-multiple-config/dir/.prettierrc.mjs @@ -0,0 +1 @@ +export default { }; diff --git a/tests/integration/cli/infer-plugins-with-multiple-config/dir/1.foo b/tests/integration/cli/infer-plugins-with-multiple-config/dir/1.foo new file mode 100644 --- /dev/null +++ b/tests/integration/cli/infer-plugins-with-multiple-config/dir/1.foo @@ -0,0 +1 @@ +1.foo diff --git a/tests/integration/cli/infer-plugins-with-multiple-config/dir/subdir/.prettierrc.mjs b/tests/integration/cli/infer-plugins-with-multiple-config/dir/subdir/.prettierrc.mjs new file mode 100644 --- /dev/null +++ b/tests/integration/cli/infer-plugins-with-multiple-config/dir/subdir/.prettierrc.mjs @@ -0,0 +1,3 @@ +export default { + plugins: ["../../../../plugins/defaultOptions/plugin.cjs"] +} diff --git a/tests/integration/cli/infer-plugins-with-multiple-config/dir/subdir/2.foo b/tests/integration/cli/infer-plugins-with-multiple-config/dir/subdir/2.foo new file mode 100644 --- /dev/null +++ b/tests/integration/cli/infer-plugins-with-multiple-config/dir/subdir/2.foo @@ -0,0 +1 @@ +2.foo diff --git a/tests/integration/plugins/extensions2/plugin.cjs b/tests/integration/plugins/extensions2/plugin.cjs new file mode 100644 --- /dev/null +++ b/tests/integration/plugins/extensions2/plugin.cjs @@ -0,0 +1,24 @@ +"use strict"; + +module.exports = { + languages: [ + { + name: "bar", + parsers: ["bar-parser"], + extensions: [".bar"], + }, + ], + parsers: { + "bar-parser": { + parse: (text) => ({ text }), + astFormat: "bar-ast", + }, + }, + printers: { + "bar-ast": { + print(path) { + return ["!", path.getValue().text]; + }, + }, + }, +};
Load plugins from `.prettierrc` when initializing CLI context ## Description <!-- Please provide a brief summary of your changes: --> Fixes #15079 ## Checklist <!-- Please ensure you’ve done all of these things (if applicable). --> <!-- You can replace the `[ ]` with `[x]` to mark each task as done. --> - [x] I’ve added tests to confirm my change works. - [ ] (If the change is user-facing) I’ve added my changes to `changelog_unreleased/*/XXXX.md` file following `changelog_unreleased/TEMPLATE.md`. - [x] I’ve read the [contributing guidelines](https://github.com/prettier/prettier/blob/main/CONTRIBUTING.md). <!-- Please DO NOT remove the playground link --> **✨[Try the playground for this PR](https://prettier.io/playground-redirect)✨** [v3] plugins declared in `.prettierrc` are not loaded on directory <!-- BEFORE SUBMITTING AN ISSUE: 1. Search for your issue on GitHub: https://github.com/prettier/prettier/issues A large number of opened issues are duplicates of existing issues. If someone has already opened an issue for what you are experiencing, you do not need to open a new issue — please add a 👍 reaction to the existing issue instead. 2. If your issue is with a Prettier editor extension or add-on, please open the issue in the repo for that extension or add-on, instead of this repo. --> **Environments:** - Prettier Version: 3.0.0 - Running Prettier via: <!-- CLI, Node.js API, Browser API, etc. --> CLI - Runtime: <!-- Node.js v14, Chrome v83, etc. --> v18.16.0 - Operating System: <!-- Windows, Linux, macOS, etc. --> Linux - Prettier plugins (if any): <!-- e.g. @prettier/plugin-php --> prettier-plugin-sh **Steps to reproduce:** <!-- shell script, js code, or a link to the minimal reproducible repository --> https://github.com/un-ts/prettier/issues/273#issuecomment-1629109603 **Expected behavior:** Like prettier v2, `.sh` files should be checked **Actual behavior:** `.sh` files are not checked --- After debugging, `getSupportedFilesGlob` here https://github.com/prettier/prettier/blob/79d8a3983842d1d8a077f177ed8b983c1c596088/src/cli/expand-patterns.js#L130-L145 does not resolve `.sh` files correctly.
It's a known issue, are you sure it works in v2? @fisker I tried @devcrev's reproduction at https://github.com/devcrev/p-sh-old, it works on v2. ```log > [email protected] format > prettier --check . Checking formatting... [warn] level-0/go.sh [warn] level-0/hello.sh [warn] level-0/level-1/another.sh [warn] level-0/level-1/library.js [warn] level-0/level-1/runme.sh [warn] level-0/program.js [warn] Code style issues found in 6 files. Forgot to run Prettier? ``` Could be related to ***Plugin search feature has been removed***? I am having this same issue with the `.xml` files and `.properties` files in my project. I'm using [plugin-xml](https://github.com/prettier/plugin-xml) version 3.1.0 and the latest commit of[ prettier-plugin-properties](https://github.com/eemeli/prettier-plugin-properties) (`npm install -D [email protected]:eemeli/prettier-plugin-properties.git#0c7072dae2006c0d0a588f70b19940390a50add1`) I've noticed that you now need to specify something like `**/*.*` (rather than a folder, such as `.`) to the CLI command in order to parse files that have been registered by a plugin declared in the prettier configuration file. This wasn't the case with 2.*. It might be related to https://github.com/prettier/prettier/pull/14759, as @JounQin pointed out. Related issue I've opened in a plugin's repo (as I thought it no longer worked): https://github.com/shufo/prettier-plugin-blade/issues/213 The current documentation seems to indicate that the behavior should be as it was in version 2. ![image](https://github.com/prettier/prettier/assets/44066444/8265801a-6176-4c33-90f5-dc758cc0007a) This `package.json` script for v3 does what I want and what v2 did with `prettier . --check`: ``` "scripts": { "format": "prettier './**/*' --check --ignore-unknown" }, ``` I'm observing this bug, too. Running `npx prettier --write .` will ignore any `.svelte` files, running `npx prettier --plugin prettier-plugin-svelte --write . ` works. My debugging so far lead my to believe that this issue is with the file glob. The file glob is created from the context that is created at the start of the CLI run. If I pass the plugin, the context contains the info that Svelte files are eligible for formatting so the file glob includes Svelte files, else it doesn't. So the fix is either to adjust the context creation to also search for a `.prettierrc` starting from `process.cwd()` and load any plugins from there, or to widen the file glob to include all files, not just the ones the context says it knows about. @dummdidumm Indeed. Config files are resolved for each processed file, which is too late. I'll work on this
"2023-09-19T14:49:48Z"
3.1
[]
[ "tests/integration/__tests__/patterns-dirs.js", "tests/integration/__tests__/infer-plugins-ext-dir.js", "tests/integration/__tests__/ignore-unknown.js" ]
JavaScript
[]
[ "https://prettier.io/playground-redirect" ]
prettier/prettier
15,467
prettier__prettier-15467
[ "15396", "15396" ]
c140ed6b5354bc64d15f33eb9fbaa2571a375aa1
diff --git a/src/cli/format.js b/src/cli/format.js --- a/src/cli/format.js +++ b/src/cli/format.js @@ -437,7 +437,7 @@ async function formatFiles(context) { } else if (!context.argv.check && !context.argv.listDifferent) { const message = `${chalk.grey(fileNameToDisplay)} ${ Date.now() - start - }ms`; + }ms (unchanged)`; if (isCacheExists) { context.logger.log(`${message} (cached)`); } else {
diff --git a/tests/integration/__tests__/__snapshots__/line-after-filepath-with-errors.js.snap b/tests/integration/__tests__/__snapshots__/line-after-filepath-with-errors.js.snap --- a/tests/integration/__tests__/__snapshots__/line-after-filepath-with-errors.js.snap +++ b/tests/integration/__tests__/__snapshots__/line-after-filepath-with-errors.js.snap @@ -83,7 +83,7 @@ invalid-2.unknown [[called readline.clearLine(process.stdout)]] valid-1.js [[called readline.clearLine(process.stdout)]] -valid-1.js 0ms" +valid-1.js 0ms (unchanged)" `; exports[`Line breaking after filepath with errors (write) 1`] = `[]`; diff --git a/tests/integration/__tests__/__snapshots__/write.js.snap b/tests/integration/__tests__/__snapshots__/write.js.snap --- a/tests/integration/__tests__/__snapshots__/write.js.snap +++ b/tests/integration/__tests__/__snapshots__/write.js.snap @@ -2,7 +2,7 @@ exports[`do not write file with --write + formatted file (stderr) 1`] = `""`; -exports[`do not write file with --write + formatted file (stdout) 1`] = `"formatted.js 0ms"`; +exports[`do not write file with --write + formatted file (stdout) 1`] = `"formatted.js 0ms (unchanged)"`; exports[`do not write file with --write + invalid file (stderr) 1`] = ` "[error] invalid.js: SyntaxError: Unexpected token (1:17) diff --git a/tests/integration/__tests__/cache.js b/tests/integration/__tests__/cache.js --- a/tests/integration/__tests__/cache.js +++ b/tests/integration/__tests__/cache.js @@ -133,7 +133,7 @@ describe("--cache option", () => { expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), - expect.stringMatching(/^b\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -146,8 +146,8 @@ describe("--cache option", () => { ]); expect(secondStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms \(cached\)$/), - expect.stringMatching(/^b\.js .+ms \(cached\)$/), + expect.stringMatching(/^a\.js .+ms \(unchanged\) \(cached\)$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); }); @@ -167,7 +167,7 @@ describe("--cache option", () => { expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), - expect.stringMatching(/^b\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -182,7 +182,7 @@ describe("--cache option", () => { // the cache of `b.js` is only available. expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), - expect.stringMatching(/^b\.js .+ms \(cached\)$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); }); @@ -202,7 +202,7 @@ describe("--cache option", () => { expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), - expect.stringMatching(/^b\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -218,7 +218,7 @@ describe("--cache option", () => { // the cache of `b.js` is only available. expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), - expect.stringMatching(/^b\.js .+ms \(cached\)$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); }); @@ -234,7 +234,7 @@ describe("--cache option", () => { expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), - expect.stringMatching(/^b\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -250,7 +250,7 @@ describe("--cache option", () => { expect(secondStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), - expect.stringMatching(/^b\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); }); @@ -273,7 +273,7 @@ describe("--cache option", () => { expect(secondStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), - expect.stringMatching(/^b\.js .+ms \(cached\)$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); }); @@ -309,7 +309,7 @@ describe("--cache option", () => { expect(thirdStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), - expect.stringMatching(/^b\.js .+ms \(cached\)$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); }); @@ -336,7 +336,7 @@ describe("--cache option", () => { expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), - expect.stringMatching(/^b\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -394,7 +394,7 @@ describe("--cache option", () => { expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), - expect.stringMatching(/^b\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -404,8 +404,8 @@ describe("--cache option", () => { ); expect(secondStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms \(cached\)$/), - expect.stringMatching(/^b\.js .+ms \(cached\)$/), + expect.stringMatching(/^a\.js .+ms \(unchanged\) \(cached\)$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); }); @@ -425,7 +425,7 @@ describe("--cache option", () => { expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), - expect.stringMatching(/^b\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -440,7 +440,7 @@ describe("--cache option", () => { // the cache of `b.js` is only available. expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), - expect.stringMatching(/^b\.js .+ms \(cached\)$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); }); @@ -460,7 +460,7 @@ describe("--cache option", () => { expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), - expect.stringMatching(/^b\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -474,8 +474,8 @@ describe("--cache option", () => { ); expect(secondStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms \(cached\)$/), - expect.stringMatching(/^b\.js .+ms \(cached\)$/), + expect.stringMatching(/^a\.js .+ms \(unchanged\) \(cached\)$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); }); @@ -491,7 +491,7 @@ describe("--cache option", () => { expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), - expect.stringMatching(/^b\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -507,7 +507,7 @@ describe("--cache option", () => { expect(secondStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), - expect.stringMatching(/^b\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); }); @@ -530,7 +530,7 @@ describe("--cache option", () => { expect(secondStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), - expect.stringMatching(/^b\.js .+ms \(cached\)$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); }); @@ -566,7 +566,7 @@ describe("--cache option", () => { expect(thirdStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), - expect.stringMatching(/^b\.js .+ms \(cached\)$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); }); @@ -593,7 +593,7 @@ describe("--cache option", () => { expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), - expect.stringMatching(/^b\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -677,7 +677,7 @@ describe("--cache option", () => { expect(firstStdout.split("\n")).toEqual( expect.arrayContaining([ expect.stringMatching(/^a\.js .+ms$/), - expect.stringMatching(/^b\.js .+ms$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\)$/), ]), ); @@ -687,8 +687,8 @@ describe("--cache option", () => { ); expect(secondStdout.split("\n")).toEqual( expect.arrayContaining([ - expect.stringMatching(/^a\.js .+ms \(cached\)$/), - expect.stringMatching(/^b\.js .+ms \(cached\)$/), + expect.stringMatching(/^a\.js .+ms \(unchanged\) \(cached\)$/), + expect.stringMatching(/^b\.js .+ms \(unchanged\) \(cached\)$/), ]), ); });
`--write` to show text identifier for unchanged files ('grey color only' an accessibility concern 🧑‍🦯) The output of `--write` can't distinguish between changed and unchanged text if color is not visible. ### Suggestion: Distinguish using text. Consider that the use of color to distinguish changed vs unchanged files is not the best way to convey this difference. It has these problems: * Visually impaired users may use a two-tone terminal that doesn't output any color information. It's impossible to distinguish in such case. * Copying the log and pasting it somewhere else that only support plain text and no formatting, will cause the user to lose the color information. It's impossible to distinguish in such case. * Scripts that grep the output cannot distinguish the files unless they programmatically inspect the color information. The `(cached)` keyword is unreliable as it only appears when `isCacheExists` is true. * Cloud services that only log the text output and not the color information will not be able to display to the service user which files changed and which remain unchanged. I think while the grey color is useful to visually distinguish, to solve the above cases we should also add the keyword `(unchanged)` after the file name. See example below. ### Example demonstrating suggestion Take two exact copies of a project with three files, only the second of which will change in formatting. With the current version of Prettier, running `npx/yarn prettier --write .` on first copy: ``` path/to/file1.ext 1ms path/to/file2.ext 5ms path/to/file3.ext 0ms (cached) ``` _(can't show color but you can imagine it: file1 and file3 will be grey)_ With a fixed version of Prettier, running `npx/yarn prettier --write .` on second copy: ``` path/to/file1.ext 1ms (unchanged) path/to/file2.ext 5ms path/to/file3.ext 0ms (unchanged) (cached) ``` _(can't show color but you can imagine it: file1 and file3 will be grey)_ Note: Although `(cached)` only appears for cached unchanged files, I would suggest not combining the keywords to `(unchanged, cached)` because it's harder to grep for both `(unchanged)` and `(unchanged,` in the output. Also any scripts that grep for `/ \(cached\)$/` would start to fail. That's why I suggest `(unchanged) (cached)`. ### Relevant information Relevant code: https://github.com/prettier/prettier/blob/f7959cccbfaf38f685b660f39eed061f5eec5ec2/src/cli/format.js#L432-L441 Relevant issues: This was kind of hinted before in #3525 but apparently misunderstood. I believe the original author there possibly couldn't see the grey vs white distinction because the terminal didn't support colors, and everything was in the same color. This may have led to the **false** impression that all files are being overwritten when in reality, all filenames were being output to log, but only changed files were overwritten. If the output included the keyword `(unchanged)` this could possibly be avoided. Suggestion to reduce verbosity was moved to #15480. ### I can open a pull request I believe both suggestions can be achieved with a simple change: * On line 435, change ``}ms`;`` to ``}ms (unchanged)`;`` Just let me know if the suggestions are acceptable. `--write` to show text identifier for unchanged files ('grey color only' an accessibility concern 🧑‍🦯) The output of `--write` can't distinguish between changed and unchanged text if color is not visible. ### Suggestion: Distinguish using text. Consider that the use of color to distinguish changed vs unchanged files is not the best way to convey this difference. It has these problems: * Visually impaired users may use a two-tone terminal that doesn't output any color information. It's impossible to distinguish in such case. * Copying the log and pasting it somewhere else that only support plain text and no formatting, will cause the user to lose the color information. It's impossible to distinguish in such case. * Scripts that grep the output cannot distinguish the files unless they programmatically inspect the color information. The `(cached)` keyword is unreliable as it only appears when `isCacheExists` is true. * Cloud services that only log the text output and not the color information will not be able to display to the service user which files changed and which remain unchanged. I think while the grey color is useful to visually distinguish, to solve the above cases we should also add the keyword `(unchanged)` after the file name. See example below. ### Example demonstrating suggestion Take two exact copies of a project with three files, only the second of which will change in formatting. With the current version of Prettier, running `npx/yarn prettier --write .` on first copy: ``` path/to/file1.ext 1ms path/to/file2.ext 5ms path/to/file3.ext 0ms (cached) ``` _(can't show color but you can imagine it: file1 and file3 will be grey)_ With a fixed version of Prettier, running `npx/yarn prettier --write .` on second copy: ``` path/to/file1.ext 1ms (unchanged) path/to/file2.ext 5ms path/to/file3.ext 0ms (unchanged) (cached) ``` _(can't show color but you can imagine it: file1 and file3 will be grey)_ Note: Although `(cached)` only appears for cached unchanged files, I would suggest not combining the keywords to `(unchanged, cached)` because it's harder to grep for both `(unchanged)` and `(unchanged,` in the output. Also any scripts that grep for `/ \(cached\)$/` would start to fail. That's why I suggest `(unchanged) (cached)`. ### Relevant information Relevant code: https://github.com/prettier/prettier/blob/f7959cccbfaf38f685b660f39eed061f5eec5ec2/src/cli/format.js#L432-L441 Relevant issues: This was kind of hinted before in #3525 but apparently misunderstood. I believe the original author there possibly couldn't see the grey vs white distinction because the terminal didn't support colors, and everything was in the same color. This may have led to the **false** impression that all files are being overwritten when in reality, all filenames were being output to log, but only changed files were overwritten. If the output included the keyword `(unchanged)` this could possibly be avoided. Suggestion to reduce verbosity was moved to #15480. ### I can open a pull request I believe both suggestions can be achieved with a simple change: * On line 435, change ``}ms`;`` to ``}ms (unchanged)`;`` Just let me know if the suggestions are acceptable.
I agree with giving `(unchanged)` to output for accessibility. I agree with giving `(unchanged)` to output for accessibility.
"2023-09-27T16:24:28Z"
3.1
[]
[ "tests/integration/__tests__/line-after-filepath-with-errors.js", "tests/integration/__tests__/write.js" ]
JavaScript
[]
[]
prettier/prettier
15,472
prettier__prettier-15472
[ "8352" ]
b78d7c7d2d9889252211abc69fffef71f02f741a
diff --git a/src/language-css/printer-postcss.js b/src/language-css/printer-postcss.js --- a/src/language-css/printer-postcss.js +++ b/src/language-css/printer-postcss.js @@ -224,7 +224,9 @@ function genericPrint(path, options, print) { // If a Less file ends up being parsed with the SCSS parser, Less // variable declarations will be parsed as at-rules with names ending // with a colon, so keep the original case then. - isDetachedRulesetCallNode(node) || node.name.endsWith(":") + isDetachedRulesetCallNode(node) || + node.name.endsWith(":") || + isTemplatePlaceholderNode(node) ? node.name : maybeToLowerCase(node.name), node.params
diff --git a/tests/format/js/multiparser-css/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/multiparser-css/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/js/multiparser-css/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/multiparser-css/__snapshots__/jsfmt.spec.js.snap @@ -363,6 +363,48 @@ export const Group = styled.div\` ================================================================================ `; +exports[`issue-8352.js format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript", "flow"] +printWidth: 80 + | printWidth +=====================================input====================================== +const StyledComponent = styled.div\` + margin-right: -4px; + + \${Container}.isExpanded & { + transform: rotate(-180deg); + } +\`; + +const StyledComponent2 = styled.div\` + margin-right: -4px; + + \${abc}.camelCase + \${def}.camelCase & { + transform: rotate(-180deg); + } +\`; + +=====================================output===================================== +const StyledComponent = styled.div\` + margin-right: -4px; + + \${Container}.isExpanded & { + transform: rotate(-180deg); + } +\`; + +const StyledComponent2 = styled.div\` + margin-right: -4px; + + \${abc}.camelCase + \${def}.camelCase & { + transform: rotate(-180deg); + } +\`; + +================================================================================ +`; + exports[`issue-9072.js format 1`] = ` ====================================options===================================== parsers: ["babel", "typescript", "flow"] diff --git a/tests/format/js/multiparser-css/issue-8352.js b/tests/format/js/multiparser-css/issue-8352.js new file mode 100644 --- /dev/null +++ b/tests/format/js/multiparser-css/issue-8352.js @@ -0,0 +1,15 @@ +const StyledComponent = styled.div` + margin-right: -4px; + + ${Container}.isExpanded & { + transform: rotate(-180deg); + } +`; + +const StyledComponent2 = styled.div` + margin-right: -4px; + + ${abc}.camelCase + ${def}.camelCase & { + transform: rotate(-180deg); + } +`;
CSS selectors must not be lowercased in styled-components that reference other **Prettier 2.0.5** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuc0DOMAEBlGBPAGzgBMBhCAWwAdoEsBeTDQkgOmIEsA3AAwB0omTBQCGAJwDmHKAFoxHCQAsYSTDIAsVAB4BuAQKEASYOVgjpcMQF9WHNAFEtVEVGIlMAMkzADQzDDEXNAAzCDEKVTEIGBF4AAoZAEYADgAGNwkASj1BTCsBHh0QABoQCCoYDnRkUHEogHcABXEENGQQEQJ6kTw20oAjQLAAazgYbGcwaQlkAIBXOFLlCgIAdUUOeDRJuGxWze5NvHawND6QaTRLGEbAiVFkYM6r0oArNC0AISHR8ZEKOAAGQsj2eixA7y02GmRAAinNonBQQQXiBnGIrmJ2v0RP04AQSmj5LBVhxiDBFMg0qUqFErqtAlR2rS4JiuEjSgBHBHwW7lNooERoGRQOAkEiEsRwbkcKW3ET3ETI1FXCgcWZiBalNAwuDwxHK8Exfqk8mUpAAJlKAXMBGm5AoDxQrIArIS5lcACq4gVPFHgrgLACSrjo2DA8gqAEFXLgWIarFYgA) ```sh --parser babel ``` **Input:** ```jsx const StyledComponent = styled.div` margin-right: -4px; ${Container}.isExpanded & { transform: rotate(-180deg); } `; ``` **Output:** ```jsx const StyledComponent = styled.div` margin-right: -4px; ${Container}.isexpanded & { transform: rotate(-180deg); } `; ``` **Expected behavior:** The input and output should be the same, keeping the selector `.isExpanded` case. The output breaks the style since HTML selectors are case-sensitive.
This is the case with parser @typescript-eslint as well. Probably also with just eslint. Can confirm with `typescript-eslint`, thought maybe I had the syntax wrong at first. Going to use `/* prettier-ignore */` for now. bump. this issue arose for my styled-components heavy project when upgrading `eslint-config-prettier` from `6.15.0` to `8.3.0` and `eslint-plugin-prettier` from `3.1.4` to `3.4.0` also, if it helps debug, the unwanted lowercasing only seems to happen on the first instance of a class name selector attached to an interpolation in the line. further class names are not lowercased: [playground](https://prettier.io/playground/#N4Igxg9gdgLgprEAuc0DOMAEBlGBPAGzgBMBhCAWwAdoEsBeTDQkgOmIEsA3AAwB0omTBQCGAJwDmHKAFoxHCQAsYSTDIAsVAB4BuAQKEASYCIBGYAL6swIinAKkRaOJgDUmY8TgAzKzbsOTi4AZJjABkKYMGIiUGjeEGIUqmIQMCLwABQyAIwAHAAMXhIAlHqCmBYCPDogADQgEFQwHOjIoOKpAO4ACuIIaMggIgRdIniDDaYxYADWcDDYVCJg0hLI0QCucA1wFKYkXsQAMrESmyIScABiiaIwLVDrKCKbMBD1IMoUBADqihx4GhlmA4NgBoDuIC8EMwGhJiBpM4xDAejEJKJkN4Rs4GgArNBaABCM3mi1scGO0jgWJxOxABK02DWRAAips0jSkNiCLiQMsxMihqYzPZPlR5LBfhxiDBFMhCg0JRBnL8YlQhhK4MiuDSGgBHDnwNFNQYvNAyKBwEgkT5iOCGjj2tGXTHcukNZwUDgbMTbT0suDszm03n09KmaWy+VIABMDWiIg4BDW5AobpA2oArJ9Ns4ACpmM08vlcbYASSgXlg2DA8maAEEq7gWKHnBYLEA)
"2023-09-28T03:53:49Z"
3.1
[]
[ "tests/format/js/multiparser-css/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuc0DOMAEBlGBPAGzgBMBhCAWwAdoEsBeTDQkgOmIEsA3AAwB0omTBQCGAJwDmHKAFoxHCQAsYSTDIAsVAB4BuAQKEASYOVgjpcMQF9WHNAFEtVEVGIlMAMkzADQzDDEXNAAzCDEKVTEIGBF4AAoZAEYADgAGNwkASj1BTCsBHh0QABoQCCoYDnRkUHEogHcABXEENGQQEQJ6kTw20oAjQLAAazgYbGcwaQlkAIBXOFLlCgIAdUUOeDRJuGxWze5NvHawND6QaTRLGEbAiVFkYM6r0oArNC0AISHR8ZEKOAAGQsj2eixA7y02GmRAAinNonBQQQXiBnGIrmJ2v0RP04AQSmj5LBVhxiDBFMg0qUqFErqtAlR2rS4JiuEjSgBHBHwW7lNooERoGRQOAkEiEsRwbkcKW3ET3ETI1FXCgcWZiBalNAwuDwxHK8Exfqk8mUpAAJlKAXMBGm5AoDxQrIArIS5lcACq4gVPFHgrgLACSrjo2DA8gqAEFXLgWIarFYgA" ]
prettier/prettier
15,525
prettier__prettier-15525
[ "15284" ]
427a84d24203e2d54160cde153a1e6a6390fe65a
diff --git a/src/language-js/utils/index.js b/src/language-js/utils/index.js --- a/src/language-js/utils/index.js +++ b/src/language-js/utils/index.js @@ -6,6 +6,7 @@ import isNextLineEmptyAfterIndex from "../../utils/is-next-line-empty.js"; import getStringWidth from "../../utils/get-string-width.js"; import { locStart, locEnd, hasSameLocStart } from "../loc.js"; import getVisitorKeys from "../traverse/get-visitor-keys.js"; +import printString from "../../utils/print-string.js"; import createTypeCheckFunction from "./create-type-check-function.js"; import isBlockComment from "./is-block-comment.js"; import isNodeMatches from "./is-node-matches.js"; @@ -544,7 +545,9 @@ function getExpressionInnerNodeCount(node, maxCount) { } const LONE_SHORT_ARGUMENT_THRESHOLD_RATE = 0.25; -function isLoneShortArgument(node, { printWidth }) { +function isLoneShortArgument(node, options) { + const { printWidth } = options; + if (hasComment(node)) { return false; } @@ -568,7 +571,7 @@ function isLoneShortArgument(node, { printWidth }) { } if (isStringLiteral(node)) { - return rawText(node).length <= threshold; + return printString(rawText(node), options).length <= threshold; } if (node.type === "TemplateLiteral") {
diff --git a/tests/format/js/strings/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/strings/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/js/strings/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/strings/__snapshots__/jsfmt.spec.js.snap @@ -1,5 +1,51 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP +exports[`escaped.js - {"trailingComma":"all"} format 1`] = ` +====================================options===================================== +parsers: ["babel", "flow"] +printWidth: 80 +trailingComma: "all" + | printWidth +=====================================input====================================== +export const MSG_GENERIC_OPERATION_FAILURE_BODY_1 = + goog.getMsg("That's all we know"); + +export const MSG_GENERIC_OPERATION_FAILURE_BODY_2 = + goog.getMsg("That\\'s all we know"); + +=====================================output===================================== +export const MSG_GENERIC_OPERATION_FAILURE_BODY_1 = + goog.getMsg("That's all we know"); + +export const MSG_GENERIC_OPERATION_FAILURE_BODY_2 = + goog.getMsg("That's all we know"); + +================================================================================ +`; + +exports[`escaped.js - {"trailingComma":"es5"} format 1`] = ` +====================================options===================================== +parsers: ["babel", "flow"] +printWidth: 80 +trailingComma: "es5" + | printWidth +=====================================input====================================== +export const MSG_GENERIC_OPERATION_FAILURE_BODY_1 = + goog.getMsg("That's all we know"); + +export const MSG_GENERIC_OPERATION_FAILURE_BODY_2 = + goog.getMsg("That\\'s all we know"); + +=====================================output===================================== +export const MSG_GENERIC_OPERATION_FAILURE_BODY_1 = + goog.getMsg("That's all we know"); + +export const MSG_GENERIC_OPERATION_FAILURE_BODY_2 = + goog.getMsg("That's all we know"); + +================================================================================ +`; + exports[`multiline-literal.js - {"trailingComma":"all"} format 1`] = ` ====================================options===================================== parsers: ["babel", "flow"] diff --git a/tests/format/js/strings/escaped.js b/tests/format/js/strings/escaped.js new file mode 100644 --- /dev/null +++ b/tests/format/js/strings/escaped.js @@ -0,0 +1,5 @@ +export const MSG_GENERIC_OPERATION_FAILURE_BODY_1 = + goog.getMsg("That's all we know"); + +export const MSG_GENERIC_OPERATION_FAILURE_BODY_2 = + goog.getMsg("That\'s all we know");
Prettier formatting is inconsistent when using escaping in string **Prettier 3.0.3** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEcAeAHCAnGACSKAZ3wFkBlAcQH1KBRAOToCUBJAYWoHkAFFgQQAqrLg2oAxfqwAyAVWZ1qAIS4ARAJp4AvAB0oeAwHMIEQwDpDcGKSKGAFAHJBACwCGMHTodE8rgDZ+eADucHgA1lAQQQ4AlADcIAA0IBAYMACW0ETIoK7Y2FE8eQjZKP5BrgCe2ckARtiuYGFW5K4AtnDS6VBwyABm-kRwdQ1NLRiN3YbIMNgArsMgQ23pM-OLRFN+cACKcxDw-YOLAFZEaORbu-uHSAN+Q8kAjjdwPAUYpSCuRAC0PXAACZApIgWaudJ+KbsCBtNquZDfAKgzZQQzbfgwWbpWpzeA8ODYLo9I4PRbOGBtPwAdWc6XgRAmYDg5BK9PSADd6ZVEWAiDUQByFqwoMDYOQwNh0ml+KLyDBKttSY8QBgCkNqQ0MIi1XAhtgOb1kt19TB3q5DPDlYsJth9Yjaq5anA-KC1d0YNT0oCYM5kAAOAAMyWwcBe6VD5stCLux2SMCdXp9fqQACZknMhoInaV7iq4G1nYDgYDpK40XMLXBxDh4VipojXHiICAAL6toA) <!-- prettier-ignore --> ```sh --parser babel ``` **Input:** <!-- prettier-ignore --> ```jsx export const MSG_GENERIC_OPERATION_FAILURE_BODY = goog.getMsg('That\'s all we know'); ``` **Output:** <!-- prettier-ignore --> ```jsx export const MSG_GENERIC_OPERATION_FAILURE_BODY = goog.getMsg( "That's all we know", ); ``` **Second Output:** <!-- prettier-ignore --> ```jsx export const MSG_GENERIC_OPERATION_FAILURE_BODY = goog.getMsg("That's all we know"); ```
Note that the first snippet has a That's which contains a "\'" to escape the apostrophe Please follow the issue template. This issue has been automatically closed because there has been no response to our request for more information from the original author. With only the information that is currently in the issue, we don't have enough information to take action. Please reach out if you have or find the answers we need so that we can investigate further.
"2023-10-20T08:13:02Z"
3.1
[]
[ "tests/format/js/strings/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEcAeAHCAnGACSKAZ3wFkBlAcQH1KBRAOToCUBJAYWoHkAFFgQQAqrLg2oAxfqwAyAVWZ1qAIS4ARAJp4AvAB0oeAwHMIEQwDpDcGKSKGAFAHJBACwCGMHTodE8rgDZ+eADucHgA1lAQQQ4AlADcIAA0IBAYMACW0ETIoK7Y2FE8eQjZKP5BrgCe2ckARtiuYGFW5K4AtnDS6VBwyABm-kRwdQ1NLRiN3YbIMNgArsMgQ23pM-OLRFN+cACKcxDw-YOLAFZEaORbu-uHSAN+Q8kAjjdwPAUYpSCuRAC0PXAACZApIgWaudJ+KbsCBtNquZDfAKgzZQQzbfgwWbpWpzeA8ODYLo9I4PRbOGBtPwAdWc6XgRAmYDg5BK9PSADd6ZVEWAiDUQByFqwoMDYOQwNh0ml+KLyDBKttSY8QBgCkNqQ0MIi1XAhtgOb1kt19TB3q5DPDlYsJth9Yjaq5anA-KC1d0YNT0oCYM5kAAOAAMyWwcBe6VD5stCLux2SMCdXp9fqQACZknMhoInaV7iq4G1nYDgYDpK40XMLXBxDh4VipojXHiICAAL6toA" ]
prettier/prettier
15,547
prettier__prettier-15547
[ "15534" ]
e682577c08e83c0ab272fc73ad1633883ad5d1a5
diff --git a/src/language-js/print/assignment.js b/src/language-js/print/assignment.js --- a/src/language-js/print/assignment.js +++ b/src/language-js/print/assignment.js @@ -141,11 +141,13 @@ function chooseLayout(path, options, print, leftDoc, rightPropertyName) { return "never-break-after-operator"; } + const canBreakLeftDoc = canBreak(leftDoc); + if ( isComplexDestructuring(node) || isComplexTypeAliasParams(node) || hasComplexTypeAnnotation(node) || - (isArrowFunctionVariableDeclarator(node) && canBreak(leftDoc)) + (isArrowFunctionVariableDeclarator(node) && canBreakLeftDoc) ) { return "break-lhs"; } @@ -163,12 +165,13 @@ function chooseLayout(path, options, print, leftDoc, rightPropertyName) { } if ( - hasShortKey || - rightNode.type === "TemplateLiteral" || - rightNode.type === "TaggedTemplateExpression" || - rightNode.type === "BooleanLiteral" || - isNumericLiteral(rightNode) || - rightNode.type === "ClassExpression" + !canBreakLeftDoc && + (hasShortKey || + rightNode.type === "TemplateLiteral" || + rightNode.type === "TaggedTemplateExpression" || + rightNode.type === "BooleanLiteral" || + isNumericLiteral(rightNode) || + rightNode.type === "ClassExpression") ) { return "never-break-after-operator"; }
diff --git a/tests/format/angular/angular/__snapshots__/jsfmt.spec.js.snap b/tests/format/angular/angular/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/angular/angular/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/angular/angular/__snapshots__/jsfmt.spec.js.snap @@ -1147,7 +1147,8 @@ printWidth: 1 (target)=" a[ b - ] = 1 + ] = + 1 " (target)=" (a) // hello diff --git a/tests/format/js/assignment/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/assignment/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/js/assignment/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/assignment/__snapshots__/jsfmt.spec.js.snap @@ -784,6 +784,33 @@ const { _id: id3 } = ================================================================================ `; +exports[`issue-15534.js format 1`] = ` +====================================options===================================== +parsers: ["babel", "flow", "typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +params["redirectTo"] = \`\${window.location.pathname}\${window.location.search}\${window.location.hash}\`; + +params["redirectTo"]["codePointAt"]["name"] = + \`\${window.location.pathname}\${window.location.search}\${window.location.hash}\`; + +params.redirectTo.bar.bar.ba.barab["foo"].abr = + \`\${window.location.pathname}\${window.location.search}\${window.location.hash}\`; + +=====================================output===================================== +params["redirectTo"] = + \`\${window.location.pathname}\${window.location.search}\${window.location.hash}\`; + +params["redirectTo"]["codePointAt"]["name"] = + \`\${window.location.pathname}\${window.location.search}\${window.location.hash}\`; + +params.redirectTo.bar.bar.ba.barab["foo"].abr = + \`\${window.location.pathname}\${window.location.search}\${window.location.hash}\`; + +================================================================================ +`; + exports[`lone-arg.js format 1`] = ` ====================================options===================================== parsers: ["babel", "flow", "typescript"] diff --git a/tests/format/js/assignment/issue-15534.js b/tests/format/js/assignment/issue-15534.js new file mode 100644 --- /dev/null +++ b/tests/format/js/assignment/issue-15534.js @@ -0,0 +1,7 @@ +params["redirectTo"] = `${window.location.pathname}${window.location.search}${window.location.hash}`; + +params["redirectTo"]["codePointAt"]["name"] = + `${window.location.pathname}${window.location.search}${window.location.hash}`; + +params.redirectTo.bar.bar.ba.barab["foo"].abr = + `${window.location.pathname}${window.location.search}${window.location.hash}`;
Assignment of template literal to indexed access property causes odd formatting I noticed today that assigning a template literal string to an indexed access property of an object can lead to odd formatting where the property access is broken into many lines. This does not happen if 1) dot property access is used instead or 2) the RHS string literal uses normal quotes instead of template literal quotes. Thanks for considering this issue! **Prettier 3.0.3** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAHAhgJ3QWwM4DaAOiJnACYCWZYMAKhCQLoAEAvCwAYAkwA7pSjkIfAHQAbCGHQxK0URhgALKLjgBfXgKEiJUmXKii8cLGCWb+g4WMnTZ8pejwXOAbhAAaEBFQOoeMigWJgiAApYCIEo6OJ86ACegd4ARthgANZwMADKagAygnDIAGaxJqnpWbkYYIIA5sgwmACucN4mOJRNre0geA3icACKLRDwpeV9AFZ4AB45gyNjE0hl4hUgAI4rcGGhqNEgzgC0UHAUFF4gzeiU4g0AwhA4OOjIx+Li1wNQ9UMAQRgzUoKRa8DCcEwhXOkw2fSUMBw4gA6kpKPA8LU4DkohjKAA3DEJD5gPDJEAEtoASSECFyYEwlD8AKEORgCSGcM2qFCJhR2FQH15cBMmAJxW8gjFMH26Hqb25fQwmDFHxS6BScG+3l5ghgKMo5GUyAAHAAGbxkHbUPbYBXvNZTbwwTWG41KZAAJm8LRMdE10XWmzgOC15HIFHy6D+LXlcAAYhBMG9gQ0PuhwRAQOp1EA) <!-- prettier-ignore --> ```sh --parser babel ``` **Input:** <!-- prettier-ignore --> ```jsx params["redirectTo"] = `${window.location.pathname}${window.location.search}${window.location.hash}`; ``` **Output:** <!-- prettier-ignore --> ```jsx params[ "redirectTo" ] = `${window.location.pathname}${window.location.search}${window.location.hash}`; ``` **Expected behavior:** <!-- prettier-ignore --> ```jsx params["redirectTo"] = `${window.location.pathname}${window.location.search}${window.location.hash}`; ```
As a temporary solution do `params.redirectTo`. Might be short enough to wrap around
"2023-10-27T12:27:58Z"
3.1
[]
[ "tests/format/angular/angular/jsfmt.spec.js", "tests/format/js/assignment/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAHAhgJ3QWwM4DaAOiJnACYCWZYMAKhCQLoAEAvCwAYAkwA7pSjkIfAHQAbCGHQxK0URhgALKLjgBfXgKEiJUmXKii8cLGCWb+g4WMnTZ8pejwXOAbhAAaEBFQOoeMigWJgiAApYCIEo6OJ86ACegd4ARthgANZwMADKagAygnDIAGaxJqnpWbkYYIIA5sgwmACucN4mOJRNre0geA3icACKLRDwpeV9AFZ4AB45gyNjE0hl4hUgAI4rcGGhqNEgzgC0UHAUFF4gzeiU4g0AwhA4OOjIx+Li1wNQ9UMAQRgzUoKRa8DCcEwhXOkw2fSUMBw4gA6kpKPA8LU4DkohjKAA3DEJD5gPDJEAEtoASSECFyYEwlD8AKEORgCSGcM2qFCJhR2FQH15cBMmAJxW8gjFMH26Hqb25fQwmDFHxS6BScG+3l5ghgKMo5GUyAAHAAGbxkHbUPbYBXvNZTbwwTWG41KZAAJm8LRMdE10XWmzgOC15HIFHy6D+LXlcAAYhBMG9gQ0PuhwRAQOp1EA" ]
prettier/prettier
15,605
prettier__prettier-15605
[ "14207", "14737" ]
1a00467677fe97d40409e646152ed8b60b4b7da5
diff --git a/src/language-handlebars/printer-glimmer.js b/src/language-handlebars/printer-glimmer.js --- a/src/language-handlebars/printer-glimmer.js +++ b/src/language-handlebars/printer-glimmer.js @@ -366,7 +366,7 @@ function print(path, options, print) { ]; } case "PathExpression": - return node.original; + return printPathExpression(node); case "BooleanLiteral": return String(node.value); @@ -764,6 +764,42 @@ function printBlockParams(node) { return ["as |", node.blockParams.join(" "), "|"]; } +// https://handlebarsjs.com/guide/expressions.html#literal-segments +const PATH_EXPRESSION_FORBIDDEN_CHARACTERS = new Set( + "!\"#%&'()*+,./;<=>@[\\]^`{|}~", +); +const PATH_EXPRESSION_FORBIDDEN_IN_FIRST_PART = new Set([ + "true", + "false", + "null", + "undefined", +]); +const isPathExpressionPartNeedBrackets = (part, index) => + (index !== 0 && PATH_EXPRESSION_FORBIDDEN_IN_FIRST_PART.has(part)) || + /\s/.test(part) || + /^\d/.test(part) || + Array.prototype.some.call(part, (character) => + PATH_EXPRESSION_FORBIDDEN_CHARACTERS.has(character), + ); +function printPathExpression(node) { + if (node.data || (node.parts.length === 1 && node.original.includes("/"))) { + // check if node has data, or + // check if node is a legacy path expression (and leave it alone) + return node.original; + } + + let { parts } = node; + if (node.this) { + parts = ["this", ...parts]; + } + + return parts + .map((part, index) => + isPathExpressionPartNeedBrackets(part, index) ? `[${part}]` : part, + ) + .join("."); +} + const printer = { print, massageAstNode: clean,
diff --git a/tests/format/handlebars/path-expressions/__snapshots__/jsfmt.spec.js.snap b/tests/format/handlebars/path-expressions/__snapshots__/jsfmt.spec.js.snap new file mode 100644 --- /dev/null +++ b/tests/format/handlebars/path-expressions/__snapshots__/jsfmt.spec.js.snap @@ -0,0 +1,119 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`keyword-expressions.hbs format 1`] = ` +====================================options===================================== +parsers: ["glimmer"] +printWidth: 80 + | printWidth +=====================================input====================================== +<div> + {{true.foo}} + {{foo.[true]}} + {{false.foo}} + {{foo.[false]}} + {{null.foo}} + {{foo.[null]}} + {{undefined.foo}} + {{foo.[undefined]}} +</div> + +=====================================output===================================== +<div> + {{true.foo}} + {{foo.[true]}} + {{false.foo}} + {{foo.[false]}} + {{null.foo}} + {{foo.[null]}} + {{undefined.foo}} + {{foo.[undefined]}} +</div> +================================================================================ +`; + +exports[`literal-expressions.hbs format 1`] = ` +====================================options===================================== +parsers: ["glimmer"] +printWidth: 80 + | printWidth +=====================================input====================================== +<div> + {{array.[true]}} + {{[dot.]}} + {{array.2.[@#].[1]}} + {{array.2.[a b]}} + {{this.test}} + {{#if @foo}} + {{/if}} + <!-- legacy path format, which glimmer does not parse - we don't want to wrap with brackets --> + {{foo/bar/baz ab=cd}} +</div> + +=====================================output===================================== +<div> + {{array.[true]}} + {{[dot.]}} + {{array.[2].[@#].[1]}} + {{array.[2].[a b]}} + {{this.test}} + {{#if @foo}}{{/if}} + <!-- legacy path format, which glimmer does not parse - we don't want to wrap with brackets --> + {{foo/bar/baz ab=cd}} +</div> +================================================================================ +`; + +exports[`numeric-expressions.hbs format 1`] = ` +====================================options===================================== +parsers: ["glimmer"] +printWidth: 80 + | printWidth +=====================================input====================================== +<div> + {{people.[1].name}} + {{people.[1]}} + {{array.[1].barray.[13]}} + {{array.[1234]}} + {{array.[123].[item-class]}} + {{array.[12].item}} + {{people.[1a]}} +</div> + +<ul class="people_list"> + {{#each people}} + <li>{{array.[2]}}</li> + {{/each}} +</ul> + +<div> + {{#if @foo}} + {{bar.[1]}} + {{bar.1.name}} + {{/if}} +</div> + +=====================================output===================================== +<div> + {{people.[1].name}} + {{people.[1]}} + {{array.[1].barray.[13]}} + {{array.[1234]}} + {{array.[123].item-class}} + {{array.[12].item}} + {{people.[1a]}} +</div> + +<ul class="people_list"> + {{#each people}} + <li>{{array.[2]}}</li> + {{/each}} +</ul> + +<div> + {{#if @foo}} + {{bar.[1]}} + {{bar.[1].name}} + {{/if}} +</div> +================================================================================ +`; diff --git a/tests/format/handlebars/path-expressions/jsfmt.spec.js b/tests/format/handlebars/path-expressions/jsfmt.spec.js new file mode 100644 --- /dev/null +++ b/tests/format/handlebars/path-expressions/jsfmt.spec.js @@ -0,0 +1 @@ +run_spec(import.meta, ["glimmer"]); diff --git a/tests/format/handlebars/path-expressions/keyword-expressions.hbs b/tests/format/handlebars/path-expressions/keyword-expressions.hbs new file mode 100644 --- /dev/null +++ b/tests/format/handlebars/path-expressions/keyword-expressions.hbs @@ -0,0 +1,10 @@ +<div> + {{true.foo}} + {{foo.[true]}} + {{false.foo}} + {{foo.[false]}} + {{null.foo}} + {{foo.[null]}} + {{undefined.foo}} + {{foo.[undefined]}} +</div> diff --git a/tests/format/handlebars/path-expressions/literal-expressions.hbs b/tests/format/handlebars/path-expressions/literal-expressions.hbs new file mode 100644 --- /dev/null +++ b/tests/format/handlebars/path-expressions/literal-expressions.hbs @@ -0,0 +1,11 @@ +<div> + {{array.[true]}} + {{[dot.]}} + {{array.2.[@#].[1]}} + {{array.2.[a b]}} + {{this.test}} + {{#if @foo}} + {{/if}} + <!-- legacy path format, which glimmer does not parse - we don't want to wrap with brackets --> + {{foo/bar/baz ab=cd}} +</div> diff --git a/tests/format/handlebars/path-expressions/numeric-expressions.hbs b/tests/format/handlebars/path-expressions/numeric-expressions.hbs new file mode 100644 --- /dev/null +++ b/tests/format/handlebars/path-expressions/numeric-expressions.hbs @@ -0,0 +1,22 @@ +<div> + {{people.[1].name}} + {{people.[1]}} + {{array.[1].barray.[13]}} + {{array.[1234]}} + {{array.[123].[item-class]}} + {{array.[12].item}} + {{people.[1a]}} +</div> + +<ul class="people_list"> + {{#each people}} + <li>{{array.[2]}}</li> + {{/each}} +</ul> + +<div> + {{#if @foo}} + {{bar.[1]}} + {{bar.1.name}} + {{/if}} +</div>
Handlebars / Glimmer: Square brackets removed from array index - causes SyntaxError **Prettier 2.8.3** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuExgAc4XQGzgOgG0BGAXXygEMBbOAXzoB0o1Ns8iyGQAaEbGAEtoAZ2ShKAJ0kQA7gAUpCMSko5ZlAJ5i+AI0mUwAazgwAyjTgAZQVDjIAZmpFw9B46bPpDtgObIYSQBXVxA4al04ABMo6KtKKF8gyl84ADEISWpKGCFE5BBKIJgIXhAACxhqHAB1csF4EW8wODNlBsEANwbNArARHRBbF0kYeQNfbMdnUIArEQAPMz88AEUgiHhpnBc+b0kRgt8cQWpaSTL0SVsYGsEomHLkAA4ABj2ZFxqDdAKruBGnXsfAAjht4ONsCpCiIALR2aLRMqSOBgwQo8YpKZIJw7UIuaiCALBfErOAAQVy110xTg8jgkhsdm2uxAIjJ6029hxMz4MEoujuDyeSAATHyDIITokAMIQM6UAoAgCsZSCLgAKgKVLjWZ0QgBJKCxWBmMDXdAwcnGswwTR4Fn0OhAA) <!-- prettier-ignore --> ```sh --parser glimmer ``` **Input:** <!-- prettier-ignore --> ```hbs {{people.[1].name}} {{people.[1]}} ``` **Output:** <!-- prettier-ignore --> ```hbs {{people.1.name}} {{people.1}} ``` When parsed, this output produces a syntax error on the second line ``` SyntaxError: Parse error on line 2: ...e.1.name}}{{people.1}} ----------------------^ Expecting 'ID', got 'NUMBER' (2:10) 1 | {{people.1.name}} > 2 | {{people.1}} ``` **Expected behavior:** Prettier should only remove square brackets when the array index is followed by another property. The correct output for the given input would be: ```hbs {{people.1.name}} {{people.[1]}} ``` Fix square brackets removed from end of array ## Description Fixes issue #14207 and handles literal segments. ## Checklist - [ ] I’ve added tests to confirm my change works. - [ ] (If changing the API or CLI) I’ve documented the changes I’ve made (in the `docs/` directory). - [ ] (If the change is user-facing) I’ve added my changes to `changelog_unreleased/*/XXXX.md` file following `changelog_unreleased/TEMPLATE.md`. - [x] I’ve read the [contributing guidelines](https://github.com/prettier/prettier/blob/main/CONTRIBUTING.md). **✨[Try the playground for this PR](https://prettier.io/playground-redirect)✨**
Hi guys! Can I work on this? I assume we need to change this file (Not sure which function we need to change yet) https://github.com/prettier/prettier/blob/main/src/language-handlebars/printer-glimmer.js @shogohida Still interested? Related code should be here https://github.com/prettier/prettier/blob/ddf3b43c33e2e98f6413b5232ad623876d96738e/src/language-handlebars/printer-glimmer.js#L396-L398 According to [this](https://handlebarsjs.com/guide/expressions.html#literal-segments), there are other cases except numbers, need put in `[]`. @fisker Yeah, thanks for your comment! I checked the link you provided. Is this the case for this issue? ![スクリーンショット 2023-03-25 22 10 31](https://user-images.githubusercontent.com/10365357/227719181-7f8fcae7-b074-41ad-9cfc-b50335f011de.png) I'm not sure how I should change the code yet... Can you give me more advice? Hi, I haven't seen any updates on this so I was hoping I could start working on it. I've gotten a bit of progress with it. LGTM! The example says not only the last part need add `[]` https://handlebarsjs.com/guide/expressions.html#literal-segments ``` {{!-- wrong: {{array.0.item}} --}} correct: array.[0].item: {{array.[0].item}} ``` Let's check every part to be safe?
"2023-11-08T20:36:02Z"
3.1
[]
[ "tests/format/handlebars/path-expressions/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuExgAc4XQGzgOgG0BGAXXygEMBbOAXzoB0o1Ns8iyGQAaEbGAEtoAZ2ShKAJ0kQA7gAUpCMSko5ZlAJ5i+AI0mUwAazgwAyjTgAZQVDjIAZmpFw9B46bPpDtgObIYSQBXVxA4al04ABMo6KtKKF8gyl84ADEISWpKGCFE5BBKIJgIXhAACxhqHAB1csF4EW8wODNlBsEANwbNArARHRBbF0kYeQNfbMdnUIArEQAPMz88AEUgiHhpnBc+b0kRgt8cQWpaSTL0SVsYGsEomHLkAA4ABj2ZFxqDdAKruBGnXsfAAjht4ONsCpCiIALR2aLRMqSOBgwQo8YpKZIJw7UIuaiCALBfErOAAQVy110xTg8jgkhsdm2uxAIjJ6029hxMz4MEoujuDyeSAATHyDIITokAMIQM6UAoAgCsZSCLgAKgKVLjWZ0QgBJKCxWBmMDXdAwcnGswwTR4Fn0OhAA", "https://prettier.io/playground-redirect" ]
prettier/prettier
15,606
prettier__prettier-15606
[ "14991" ]
811eb0a08505c2a1aad4ef9dfae6db8065063dd5
diff --git a/src/language-html/clean.js b/src/language-html/clean.js --- a/src/language-html/clean.js +++ b/src/language-html/clean.js @@ -12,6 +12,14 @@ const ignoredProperties = new Set([ "valueTokens", ]); +const embeddedAngularControlFlowBlocks = new Set([ + "if", + "else if", + "for", + "switch", + "case", +]); + function clean(ast, newNode) { if (ast.type === "text" || ast.type === "comment") { return null; @@ -29,6 +37,16 @@ function clean(ast, newNode) { if (ast.type === "docType") { delete newNode.value; } + + if (ast.type === "block") { + for (const parameter of newNode.parameters) { + if (embeddedAngularControlFlowBlocks.has(ast.name)) { + delete parameter.expression; + } else { + parameter.expression = parameter.expression.trim(); + } + } + } } clean.ignoredProperties = ignoredProperties; diff --git a/src/language-html/embed.js b/src/language-html/embed.js --- a/src/language-html/embed.js +++ b/src/language-html/embed.js @@ -23,6 +23,15 @@ import { import isVueSfcWithTypescriptScript from "./utils/is-vue-sfc-with-typescript-script.js"; import getNodeContent from "./get-node-content.js"; import printAttribute from "./embed/attribute.js"; +import printAngularControlFlowBlockParameters from "./embed/angular-control-flow-block-parameters.js"; + +const embeddedAngularControlFlowBlocks = new Set([ + "if", + "else if", + "for", + "switch", + "case", +]); function embed(path, options) { const { node } = path; @@ -135,6 +144,17 @@ function embed(path, options) { case "front-matter": return (textToDoc) => printFrontMatter(node, textToDoc); + + // TODO: This should work on `blockParameter`, but currently we don't have a parser for it. + case "block": + if ( + !embeddedAngularControlFlowBlocks.has(node.name) || + node.parameters.length === 0 + ) { + return; + } + + return printAngularControlFlowBlockParameters; } } diff --git a/src/language-html/embed/angular-control-flow-block-parameters.js b/src/language-html/embed/angular-control-flow-block-parameters.js new file mode 100644 --- /dev/null +++ b/src/language-html/embed/angular-control-flow-block-parameters.js @@ -0,0 +1,27 @@ +import { formatAttributeValue, shouldHugJsExpression } from "./utils.js"; + +async function printAngularControlFlowBlockParameters( + textToDoc, + print, + path, + /* options,*/ +) { + const { node } = path; + const code = node.parameters.map(({ expression }) => expression).join("; "); + + const doc = await formatAttributeValue( + code, + textToDoc, + { + parser: "__ng_directive", + __isInHtmlAttribute: false, + trailingComma: "none", + }, + shouldHugJsExpression, + ); + + // We have to put the doc on the node, since `node.parameters` is not a valid "node" + node.__embed_parameters_doc = doc; +} + +export default printAngularControlFlowBlockParameters; diff --git a/src/language-html/parser-html.js b/src/language-html/parser-html.js --- a/src/language-html/parser-html.js +++ b/src/language-html/parser-html.js @@ -38,6 +38,13 @@ import { locStart, locEnd } from "./loc.js"; * @typedef {{filepath?: string}} Options */ +// `@else if` +function normalizeAngularControlFlowBlockName(node) { + if (node.type === "block") { + node.name = node.name.toLowerCase().replaceAll(/\s+/g, " ").trim(); + } +} + /** * @param {string} input * @param {ParseOptions} parseOptions @@ -62,6 +69,7 @@ function ngHtmlParser(input, parseOptions, options) { ? (...args) => shouldParseAsRawText(...args) ? TagContentType.RAW_TEXT : undefined : undefined, + tokenizeAngularBlocks: name === "angular" ? true : undefined, }); if (name === "vue") { @@ -236,6 +244,7 @@ function ngHtmlParser(input, parseOptions, options) { addTagDefinition(node); normalizeName(node); fixSourceSpan(node); + normalizeAngularControlFlowBlockName(node); } })(), rootNodes, diff --git a/src/language-html/print/angular-control-flow-block-settings.evaluate.js b/src/language-html/print/angular-control-flow-block-settings.evaluate.js new file mode 100644 --- /dev/null +++ b/src/language-html/print/angular-control-flow-block-settings.evaluate.js @@ -0,0 +1,65 @@ +const DEFAULT_ANGULAR_CONTROL_FLOW_BLOCK_SETTINGS = { + isFollowingBlock: false, + followingBlocks: new Set(), +}; + +const ANGULAR_CONTROL_FLOW_BLOCK_SETTINGS = new Map( + [ + { + name: "if", + isFollowingBlock: false, + followingBlocks: ["else if", "else"], + }, + { + name: "else if", + isFollowingBlock: true, + followingBlocks: ["else if", "else"], + }, + { name: "else", isFollowingBlock: true, followingBlocks: [] }, + + { name: "switch", isFollowingBlock: false, followingBlocks: [] }, + { name: "case", isFollowingBlock: false, followingBlocks: [] }, + { name: "default", isFollowingBlock: false, followingBlocks: [] }, + + { name: "for", isFollowingBlock: false, followingBlocks: ["empty"] }, + { name: "empty", isFollowingBlock: true, followingBlocks: [] }, + + { + name: "defer", + isFollowingBlock: false, + followingBlocks: ["placeholder", "error", "loading"], + }, + + { + name: "placeholder", + isFollowingBlock: true, + followingBlocks: ["placeholder", "error", "loading"], + }, + + { + name: "error", + isFollowingBlock: true, + followingBlocks: ["placeholder", "error", "loading"], + }, + + { + name: "loading", + isFollowingBlock: true, + followingBlocks: ["placeholder", "error", "loading"], + }, + ].map((settings) => [ + settings.name, + { + DEFAULT_ANGULAR_CONTROL_FLOW_BLOCK_SETTINGS, + ...settings, + followingBlocks: settings.followingBlocks + ? new Set(settings.followingBlocks) + : DEFAULT_ANGULAR_CONTROL_FLOW_BLOCK_SETTINGS.followingBlocks, + }, + ]), +); + +export default { + DEFAULT_ANGULAR_CONTROL_FLOW_BLOCK_SETTINGS, + ANGULAR_CONTROL_FLOW_BLOCK_SETTINGS, +}; diff --git a/src/language-html/print/angular-control-flow-block.js b/src/language-html/print/angular-control-flow-block.js new file mode 100644 --- /dev/null +++ b/src/language-html/print/angular-control-flow-block.js @@ -0,0 +1,84 @@ +import { + group, + hardline, + softline, + line, + indent, + join, +} from "../../document/builders.js"; +import { printChildren } from "./children.js"; +import settings from "./angular-control-flow-block-settings.evaluate.js"; + +const unClosedBlocks = new WeakSet(); + +function printAngularControlFlowBlock(path, options, print) { + const { node } = path; + const setting = + settings.ANGULAR_CONTROL_FLOW_BLOCK_SETTINGS.get(node.name) ?? + settings.DEFAULT_ANGULAR_CONTROL_FLOW_BLOCK_SETTINGS; + const docs = []; + + const previousBlock = findPreviousBlock(path); + + if (setting.isFollowingBlock && unClosedBlocks.has(previousBlock)) { + docs.push("} "); + } + + docs.push("@", node.name); + + if (node.parameters.length > 0) { + const parametersDoc = group( + node.__embed_parameters_doc ?? [ + indent([softline, join([";", line], path.map(print, "parameters"))]), + softline, + ], + ); + + docs.push(" (", parametersDoc, ")"); + } + + docs.push(" {"); + const shouldPrintCloseBracket = shouldCloseBlock( + node, + setting.followingBlocks, + ); + + if (!shouldPrintCloseBracket) { + unClosedBlocks.add(node); + } + + if (node.children.length > 0) { + node.firstChild.hasLeadingSpaces = true; + node.lastChild.hasTrailingSpaces = true; + docs.push(indent([hardline, printChildren(path, options, print)])); + if (shouldPrintCloseBracket) { + docs.push(hardline, "}"); + } + } else if (shouldPrintCloseBracket) { + docs.push("}"); + } + + return group(docs, { shouldBreak: true }); +} + +function shouldCloseBlock(node, names) { + return !( + names.size > 0 && + node.next?.type === "block" && + names.has(node.next.name) + ); +} + +function findPreviousBlock(path) { + const { siblings, index } = path; + + for (let i = index - 1; i >= 0; i--) { + const sibling = siblings[i]; + + if (sibling.type === "block") { + return sibling; + } + } +} + +export { printAngularControlFlowBlock }; diff --git a/src/language-html/print/tag.js b/src/language-html/print/tag.js --- a/src/language-html/print/tag.js +++ b/src/language-html/print/tag.js @@ -128,6 +128,7 @@ function needsToBorrowPrevClosingTagEndMarker(node) { return ( node.prev && node.prev.type !== "docType" && + node.type !== "block" && !isTextLikeNode(node.prev) && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces diff --git a/src/language-html/printer-html.js b/src/language-html/printer-html.js --- a/src/language-html/printer-html.js +++ b/src/language-html/printer-html.js @@ -6,6 +6,7 @@ import { fill, group, hardline } from "../document/builders.js"; import { cleanDoc, replaceEndOfLine } from "../document/utils.js"; import UnexpectedNodeError from "../utils/unexpected-node-error.js"; import getPreferredQuote from "../utils/get-preferred-quote.js"; +import htmlWhitespaceUtils from "../utils/html-whitespace-utils.js"; import clean from "./clean.js"; import { unescapeQuoteEntities, getTextValueParts } from "./utils/index.js"; import preprocess from "./print-preprocess.js"; @@ -20,6 +21,7 @@ import { } from "./print/tag.js"; import { printElement } from "./print/element.js"; import { printChildren } from "./print/children.js"; +import { printAngularControlFlowBlock } from "./print/angular-control-flow-block.js"; import getVisitorKeys from "./get-visitor-keys.js"; function genericPrint(path, options, print) { @@ -37,6 +39,11 @@ function genericPrint(path, options, print) { case "ieConditionalComment": return printElement(path, options, print); + case "block": + return printAngularControlFlowBlock(path, options, print); + case "blockParameter": + return htmlWhitespaceUtils.trim(node.expression); + case "ieConditionalStartComment": case "ieConditionalEndComment": return [printOpeningTagStart(node), printClosingTagEnd(node)]; diff --git a/src/language-html/visitor-keys.js b/src/language-html/visitor-keys.js --- a/src/language-html/visitor-keys.js +++ b/src/language-html/visitor-keys.js @@ -11,6 +11,8 @@ const visitorKeys = { comment: [], attribute: [], cdata: [], + block: ["children", "parameters"], + blockParameter: [], }; export default visitorKeys; diff --git a/src/language-js/print/angular.js b/src/language-js/print/angular.js --- a/src/language-js/print/angular.js +++ b/src/language-js/print/angular.js @@ -62,7 +62,9 @@ function printAngular(path, options, print) { const shouldNotPrintColon = isNgForOf(path) || (((index === 1 && - (node.key.name === "then" || node.key.name === "else")) || + (node.key.name === "then" || + node.key.name === "else" || + node.key.name === "as")) || (index === 2 && node.key.name === "else" && parent.body[index - 1].type === "NGMicrosyntaxKeyedExpression" && @@ -88,13 +90,11 @@ function printAngular(path, options, print) { } } -function isNgForOf({ node, index, parent }) { +function isNgForOf({ node, index }) { return ( node.type === "NGMicrosyntaxKeyedExpression" && node.key.name === "of" && - index === 1 && - parent.body[0].type === "NGMicrosyntaxLet" && - parent.body[0].value === null + index === 1 ); }
diff --git a/tests/format/angular/control-flow/__snapshots__/jsfmt.spec.js.snap b/tests/format/angular/control-flow/__snapshots__/jsfmt.spec.js.snap new file mode 100644 --- /dev/null +++ b/tests/format/angular/control-flow/__snapshots__/jsfmt.spec.js.snap @@ -0,0 +1,551 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`after-close-tag.html format 1`] = ` +====================================options===================================== +parsers: ["angular"] +printWidth: 80 + | printWidth +=====================================input====================================== +<ion-list class="timeline" appScrollItem> + @for (let item of items; index as i; trackBy: trackByFn) { + <app-tweet-item></app-tweet-item>@if ( + areaId && + canTweet + ) { + <ion-item class="recommend-trust-up" lines="full"></ion-item> + } + } +</ion-list> + +<ng-container *ngIf=" + areaId && + canTweet +"> +<ion-item class="recommend-trust-up" lines="full"></ion-item> +</ng-container> + + +@if ( + areaId && + canTweet + ) { + <ion-item class="recommend-trust-up" lines="full"></ion-item> + } + +=====================================output===================================== +<ion-list class="timeline" appScrollItem> + @for (let item of items; index as i; trackBy: trackByFn) { + <app-tweet-item></app-tweet-item> + @if (areaId && canTweet) { + <ion-item class="recommend-trust-up" lines="full"></ion-item> + } + } +</ion-list> + +<ng-container *ngIf="areaId && canTweet"> + <ion-item class="recommend-trust-up" lines="full"></ion-item> +</ng-container> + +@if (areaId && canTweet) { + <ion-item class="recommend-trust-up" lines="full"></ion-item> +} + +================================================================================ +`; + +exports[`defer.html format 1`] = ` +====================================options===================================== +parsers: ["angular"] +printWidth: 80 + | printWidth +=====================================input====================================== +@defer (when isCheckedDefer()) { +<app-c1/> +} +@placeholder { +<span>Placeholder</span> +} +@error { +<span>Error</span> +} +@loading(minimum 1s) { +<span>Loading...</span> +} + + +@defer (on interaction) { +<span>Clicked</span> +} +@placeholder { +<span>Placeholder (click on it!)</span> +} + + +@defer (on hover) { +<span>Hovered</span> +} +@placeholder { +<span>Placeholder (hover it!)</span> +} + + +@defer (on idle) { +<span>Browser has reached an idle state</span> +} +@placeholder { +<span>Placeholder</span> +} + + +@defer (on timer(5s)) { +<span>Visible after 5s</span> +} +@placeholder { +<span>Placeholder</span> +} + + +@defer (on viewport) { +<app-c2 text="The block entered the viewport"/> +} +@placeholder { +<span>Placeholder</span> +} + + +@defer (on interaction; prefetch on hover) { +<app-c3/> +} +@placeholder { +<span>Placeholder (hover it, then click on it!)</span> +} + + +@defer (on interaction; prefetch on hover) { +<app-c3/> +} +@placeholder { +<span>Placeholder (hover it, then click on it!)</span> +} + +=====================================output===================================== +@defer (when isCheckedDefer()) { + <app-c1 /> +} @placeholder { + <span>Placeholder</span> +} @error { + <span>Error</span> +} @loading (minimum 1s) { + <span>Loading...</span> +} + +@defer (on interaction) { + <span>Clicked</span> +} @placeholder { + <span>Placeholder (click on it!)</span> +} + +@defer (on hover) { + <span>Hovered</span> +} @placeholder { + <span>Placeholder (hover it!)</span> +} + +@defer (on idle) { + <span>Browser has reached an idle state</span> +} @placeholder { + <span>Placeholder</span> +} + +@defer (on timer(5s)) { + <span>Visible after 5s</span> +} @placeholder { + <span>Placeholder</span> +} + +@defer (on viewport) { + <app-c2 text="The block entered the viewport" /> +} @placeholder { + <span>Placeholder</span> +} + +@defer (on interaction; prefetch on hover) { + <app-c3 /> +} @placeholder { + <span>Placeholder (hover it, then click on it!)</span> +} + +@defer (on interaction; prefetch on hover) { + <app-c3 /> +} @placeholder { + <span>Placeholder (hover it, then click on it!)</span> +} + +================================================================================ +`; + +exports[`element-tags.html format 1`] = ` +====================================options===================================== +parsers: ["angular"] +printWidth: 80 + | printWidth +=====================================input====================================== +@if (true) {<img />} + +=====================================output===================================== +@if (true) { + <img /> +} + +================================================================================ +`; + +exports[`for.html format 1`] = ` +====================================options===================================== +parsers: ["angular"] +printWidth: 80 + | printWidth +=====================================input====================================== +<ul> +@for ( + let + + item of items;index as +i; + trackBy: trackByFn +) { +<li><strong>{{item.name}}</strong></li> +} +@empty { +<span>The collection is empty</span> +} +</ul> + + +<li *ngFor=" + let + + item of items;index as +i; + trackBy: trackByFn +"></li> + + + +<ul> +@for (item of collection; track item.id; let index = $index, first = $first; let last = $last, even = $even, odd = $odd; let count = $count) { + +<li><strong>{{item.name}}</strong> index={{index}} first={{first}} last={{last}} even={{even}} odd={{odd}} count={{count}}</li> + +} +</ul> + +<ul> +@for (item of + emptyCollection; track item.id;) { +<li><strong>{{item.name}}</strong></li> +} +@empty { + <span>The collection is empty</span> +} +</ul> +<li *ngFor=" +item of + emptyCollection; track item.id; +"></li> + +=====================================output===================================== +<ul> + @for (let item of items; index as i; trackBy: trackByFn) { + <li> + <strong>{{ item.name }}</strong> + </li> + } @empty { + <span>The collection is empty</span> + } +</ul> + +<li *ngFor="let item of items; index as i; trackBy: trackByFn"></li> + +<ul> + @for ( + item of collection; + track item.id; + let index = $index, first = $first; + let last = $last, even = $even, odd = $odd; + let count = $count + ) { + <li> + <strong>{{ item.name }}</strong> index={{ index }} first={{ + first + }} + last={{ last }} even={{ even }} odd={{ odd }} count={{ count }} + </li> + } +</ul> + +<ul> + @for (item of emptyCollection; track: item.id) { + <li> + <strong>{{ item.name }}</strong> + </li> + } @empty { + <span>The collection is empty</span> + } +</ul> +<li *ngFor="item of emptyCollection; track: item.id"></li> + +================================================================================ +`; + +exports[`if.html format 1`] = ` +====================================options===================================== +parsers: ["angular"] +printWidth: 80 + | printWidth +=====================================input====================================== +<h3>&#64;if and &#64;else</h3> +<div> +<input #checkbox type="checkbox" [checked]="isChecked()" (change)="isChecked.set(checkbox.checked)" id="checkbox"/> +</div> +<div> +@if (isChecked()) { +<span>Checked</span> +} +@else { +<span>Not checked</span> +} +</div> + +@if (users$ | async; as users) { {{ users.length }} } +@else if (users$ | async; as users) { {{ users.length }} } + +<div *ngIf="users$ | async; as users">{{ users.length }}</div> + +@else {} + + +@if (isDev) {} +@else if (test) {} + +@if (foo( "quotes")) {} +@else if (foo( 'quotes')) {} + +@if ( widthCategory !== undefined && widthCategory > +topStartToSideStartMaxSize) { +<app-component /> +} + +@if ( widthCategory; as item) { +} + +<div *ngIf="widthCategory; as item"></div> + +=====================================output===================================== +<h3>&#64;if and &#64;else</h3> +<div> + <input + #checkbox + type="checkbox" + [checked]="isChecked()" + (change)="isChecked.set(checkbox.checked)" + id="checkbox" + /> +</div> +<div> + @if (isChecked()) { + <span>Checked</span> + } @else { + <span>Not checked</span> + } +</div> + +@if (users$ | async; as users) { + {{ users.length }} +} @else if (users$ | async; as users) { + {{ users.length }} +} + +<div *ngIf="users$ | async; as users">{{ users.length }}</div> + +@else {} + +@if (isDev) { +} @else if (test) {} + +@if (foo("quotes")) { +} @else if (foo("quotes")) {} + +@if ( + widthCategory !== undefined && widthCategory > topStartToSideStartMaxSize +) { + <app-component /> +} + +@if (widthCategory; as item) {} + +<div *ngIf="widthCategory; as item"></div> + +================================================================================ +`; + +exports[`mix.html format 1`] = ` +====================================options===================================== +parsers: ["angular"] +printWidth: 80 + | printWidth +=====================================input====================================== +@if (user.isHuman) { +<human-profile [data]="user" /> +} @else if (user.isRobot) { +<!-- robot users are rare, so load their profiles lazily --> +@defer { +<robot-profile [data]="user" /> +} +} @else { +<p>The profile is unknown!</p> +} + +=====================================output===================================== +@if (user.isHuman) { + <human-profile [data]="user" /> +} @else if (user.isRobot) { + <!-- robot users are rare, so load their profiles lazily --> + @defer { + <robot-profile [data]="user" /> + } +} @else { + <p>The profile is unknown!</p> +} + +================================================================================ +`; + +exports[`switch.html format 1`] = ` +====================================options===================================== +parsers: ["angular"] +printWidth: 80 + | printWidth +=====================================input====================================== +@switch (radioValue()) { +@case (1) { +<span>Case 1</span> +} +@case (2) { +<span>Case 2</span> +} +@default { +<span>Default case (Not 1 or 2)</span> +} +} + + +@switch( + should +.be.formatted +) { + @case( + should +.be.formatted) {} +} + +=====================================output===================================== +@switch (radioValue()) { + @case (1) { + <span>Case 1</span> + } + @case (2) { + <span>Case 2</span> + } + @default { + <span>Default case (Not 1 or 2)</span> + } +} + +@switch (should.be.formatted) { + @case (should.be.formatted) {} +} + +================================================================================ +`; + +exports[`unclosed.html format 1`] = ` +====================================options===================================== +parsers: ["angular"] +printWidth: 80 + | printWidth +=====================================input====================================== +@empty{} + +@else {} + +=====================================output===================================== +@empty {} + +@else {} + +================================================================================ +`; + +exports[`unknown-block.html format 1`] = ` +====================================options===================================== +parsers: ["angular"] +printWidth: 80 + | printWidth +=====================================input====================================== +@unknown (foo) { +} @unknown (foo) { +} + +=====================================output===================================== +@unknown (foo) {} +@unknown (foo) {} + +================================================================================ +`; + +exports[`with-comment.html format 1`] = ` +====================================options===================================== +parsers: ["angular"] +printWidth: 80 + | printWidth +=====================================input====================================== +<div> + <!-- comment --> + <span>Not checked</span> +</div> + + +<!-- comment --> +@if (isChecked()) { +<span> + Checked + <!-- comment --> +</span> +} <!-- comment --> +@else { +<span>Not checked</span> +} +<!-- comment --> + +=====================================output===================================== +<div> + <!-- comment --> + <span>Not checked</span> +</div> + +<!-- comment --> +@if (isChecked()) { + <span> + Checked + <!-- comment --> + </span> +} +<!-- comment --> +@else { + <span>Not checked</span> +} +<!-- comment --> + +================================================================================ +`; diff --git a/tests/format/angular/control-flow/after-close-tag.html b/tests/format/angular/control-flow/after-close-tag.html new file mode 100644 --- /dev/null +++ b/tests/format/angular/control-flow/after-close-tag.html @@ -0,0 +1,25 @@ +<ion-list class="timeline" appScrollItem> + @for (let item of items; index as i; trackBy: trackByFn) { + <app-tweet-item></app-tweet-item>@if ( + areaId && + canTweet + ) { + <ion-item class="recommend-trust-up" lines="full"></ion-item> + } + } +</ion-list> + +<ng-container *ngIf=" + areaId && + canTweet +"> +<ion-item class="recommend-trust-up" lines="full"></ion-item> +</ng-container> + + +@if ( + areaId && + canTweet + ) { + <ion-item class="recommend-trust-up" lines="full"></ion-item> + } diff --git a/tests/format/angular/control-flow/defer.html b/tests/format/angular/control-flow/defer.html new file mode 100644 --- /dev/null +++ b/tests/format/angular/control-flow/defer.html @@ -0,0 +1,68 @@ +@defer (when isCheckedDefer()) { +<app-c1/> +} +@placeholder { +<span>Placeholder</span> +} +@error { +<span>Error</span> +} +@loading(minimum 1s) { +<span>Loading...</span> +} + + +@defer (on interaction) { +<span>Clicked</span> +} +@placeholder { +<span>Placeholder (click on it!)</span> +} + + +@defer (on hover) { +<span>Hovered</span> +} +@placeholder { +<span>Placeholder (hover it!)</span> +} + + +@defer (on idle) { +<span>Browser has reached an idle state</span> +} +@placeholder { +<span>Placeholder</span> +} + + +@defer (on timer(5s)) { +<span>Visible after 5s</span> +} +@placeholder { +<span>Placeholder</span> +} + + +@defer (on viewport) { +<app-c2 text="The block entered the viewport"/> +} +@placeholder { +<span>Placeholder</span> +} + + +@defer (on interaction; prefetch on hover) { +<app-c3/> +} +@placeholder { +<span>Placeholder (hover it, then click on it!)</span> +} + + +@defer (on interaction; prefetch on hover) { +<app-c3/> +} +@placeholder { +<span>Placeholder (hover it, then click on it!)</span> +} diff --git a/tests/format/angular/control-flow/element-tags.html b/tests/format/angular/control-flow/element-tags.html new file mode 100644 --- /dev/null +++ b/tests/format/angular/control-flow/element-tags.html @@ -0,0 +1 @@ +@if (true) {<img />} diff --git a/tests/format/angular/control-flow/embedded-language-formatting-off/__snapshots__/jsfmt.spec.js.snap b/tests/format/angular/control-flow/embedded-language-formatting-off/__snapshots__/jsfmt.spec.js.snap new file mode 100644 --- /dev/null +++ b/tests/format/angular/control-flow/embedded-language-formatting-off/__snapshots__/jsfmt.spec.js.snap @@ -0,0 +1,18 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`if.html - {"embeddedLanguageFormatting":"off"} format 1`] = ` +====================================options===================================== +embeddedLanguageFormatting: "off" +parsers: ["angular"] +printWidth: 80 + | printWidth +=====================================input====================================== +@if (should. not. format) { } +@else if (should. not. format) { } + +=====================================output===================================== +@if (should. not. format) { +} @else if (should. not. format) {} + +================================================================================ +`; diff --git a/tests/format/angular/control-flow/embedded-language-formatting-off/if.html b/tests/format/angular/control-flow/embedded-language-formatting-off/if.html new file mode 100644 --- /dev/null +++ b/tests/format/angular/control-flow/embedded-language-formatting-off/if.html @@ -0,0 +1,2 @@ +@if (should. not. format) { } +@else if (should. not. format) { } diff --git a/tests/format/angular/control-flow/embedded-language-formatting-off/jsfmt.spec.js b/tests/format/angular/control-flow/embedded-language-formatting-off/jsfmt.spec.js new file mode 100644 --- /dev/null +++ b/tests/format/angular/control-flow/embedded-language-formatting-off/jsfmt.spec.js @@ -0,0 +1 @@ +run_spec(import.meta, ["angular"], { embeddedLanguageFormatting: "off" }); diff --git a/tests/format/angular/control-flow/for.html b/tests/format/angular/control-flow/for.html new file mode 100644 --- /dev/null +++ b/tests/format/angular/control-flow/for.html @@ -0,0 +1,47 @@ +<ul> +@for ( + let + + item of items;index as +i; + trackBy: trackByFn +) { +<li><strong>{{item.name}}</strong></li> +} +@empty { +<span>The collection is empty</span> +} +</ul> + + +<li *ngFor=" + let + + item of items;index as +i; + trackBy: trackByFn +"></li> + + + +<ul> +@for (item of collection; track item.id; let index = $index, first = $first; let last = $last, even = $even, odd = $odd; let count = $count) { + +<li><strong>{{item.name}}</strong> index={{index}} first={{first}} last={{last}} even={{even}} odd={{odd}} count={{count}}</li> + +} +</ul> + +<ul> +@for (item of + emptyCollection; track item.id;) { +<li><strong>{{item.name}}</strong></li> +} +@empty { + <span>The collection is empty</span> +} +</ul> +<li *ngFor=" +item of + emptyCollection; track item.id; +"></li> diff --git a/tests/format/angular/control-flow/if.html b/tests/format/angular/control-flow/if.html new file mode 100644 --- /dev/null +++ b/tests/format/angular/control-flow/if.html @@ -0,0 +1,36 @@ +<h3>&#64;if and &#64;else</h3> +<div> +<input #checkbox type="checkbox" [checked]="isChecked()" (change)="isChecked.set(checkbox.checked)" id="checkbox"/> +</div> +<div> +@if (isChecked()) { +<span>Checked</span> +} +@else { +<span>Not checked</span> +} +</div> + +@if (users$ | async; as users) { {{ users.length }} } +@else if (users$ | async; as users) { {{ users.length }} } + +<div *ngIf="users$ | async; as users">{{ users.length }}</div> + +@else {} + + +@if (isDev) {} +@else if (test) {} + +@if (foo( "quotes")) {} +@else if (foo( 'quotes')) {} + +@if ( widthCategory !== undefined && widthCategory > +topStartToSideStartMaxSize) { +<app-component /> +} + +@if ( widthCategory; as item) { +} + +<div *ngIf="widthCategory; as item"></div> diff --git a/tests/format/angular/control-flow/jsfmt.spec.js b/tests/format/angular/control-flow/jsfmt.spec.js new file mode 100644 --- /dev/null +++ b/tests/format/angular/control-flow/jsfmt.spec.js @@ -0,0 +1 @@ +run_spec(import.meta, ["angular"]); diff --git a/tests/format/angular/control-flow/mix.html b/tests/format/angular/control-flow/mix.html new file mode 100644 --- /dev/null +++ b/tests/format/angular/control-flow/mix.html @@ -0,0 +1,10 @@ +@if (user.isHuman) { +<human-profile [data]="user" /> +} @else if (user.isRobot) { +<!-- robot users are rare, so load their profiles lazily --> +@defer { +<robot-profile [data]="user" /> +} +} @else { +<p>The profile is unknown!</p> +} diff --git a/tests/format/angular/control-flow/small-print-width/__snapshots__/jsfmt.spec.js.snap b/tests/format/angular/control-flow/small-print-width/__snapshots__/jsfmt.spec.js.snap new file mode 100644 --- /dev/null +++ b/tests/format/angular/control-flow/small-print-width/__snapshots__/jsfmt.spec.js.snap @@ -0,0 +1,26 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`test.html - {"printWidth":20} format 1`] = ` +====================================options===================================== +parsers: ["angular"] +printWidth: 20 + | printWidth +=====================================input====================================== +@unknown (long expression;long expression;long expression;long expression;long expression;long expression;long expression;long expression;) { + +} + +=====================================output===================================== +@unknown ( + long expression; + long expression; + long expression; + long expression; + long expression; + long expression; + long expression; + long expression +) {} + +================================================================================ +`; diff --git a/tests/format/angular/control-flow/small-print-width/jsfmt.spec.js b/tests/format/angular/control-flow/small-print-width/jsfmt.spec.js new file mode 100644 --- /dev/null +++ b/tests/format/angular/control-flow/small-print-width/jsfmt.spec.js @@ -0,0 +1 @@ +run_spec(import.meta, ["angular"], { printWidth: 20 }); diff --git a/tests/format/angular/control-flow/small-print-width/test.html b/tests/format/angular/control-flow/small-print-width/test.html new file mode 100644 --- /dev/null +++ b/tests/format/angular/control-flow/small-print-width/test.html @@ -0,0 +1,3 @@ +@unknown (long expression;long expression;long expression;long expression;long expression;long expression;long expression;long expression;) { + +} diff --git a/tests/format/angular/control-flow/switch.html b/tests/format/angular/control-flow/switch.html new file mode 100644 --- /dev/null +++ b/tests/format/angular/control-flow/switch.html @@ -0,0 +1,21 @@ +@switch (radioValue()) { +@case (1) { +<span>Case 1</span> +} +@case (2) { +<span>Case 2</span> +} +@default { +<span>Default case (Not 1 or 2)</span> +} +} + + +@switch( + should +.be.formatted +) { + @case( + should +.be.formatted) {} +} diff --git a/tests/format/angular/control-flow/unclosed.html b/tests/format/angular/control-flow/unclosed.html new file mode 100644 --- /dev/null +++ b/tests/format/angular/control-flow/unclosed.html @@ -0,0 +1,3 @@ +@empty{} + +@else {} diff --git a/tests/format/angular/control-flow/unknown-block.html b/tests/format/angular/control-flow/unknown-block.html new file mode 100644 --- /dev/null +++ b/tests/format/angular/control-flow/unknown-block.html @@ -0,0 +1,3 @@ +@unknown (foo) { +} @unknown (foo) { +} diff --git a/tests/format/angular/control-flow/with-comment.html b/tests/format/angular/control-flow/with-comment.html new file mode 100644 --- /dev/null +++ b/tests/format/angular/control-flow/with-comment.html @@ -0,0 +1,17 @@ +<div> + <!-- comment --> + <span>Not checked</span> +</div> + + +<!-- comment --> +@if (isChecked()) { +<span> + Checked + <!-- comment --> +</span> +} <!-- comment --> +@else { +<span>Not checked</span> +} +<!-- comment --> diff --git a/tests/integration/__tests__/parser-api.js b/tests/integration/__tests__/parser-api.js --- a/tests/integration/__tests__/parser-api.js +++ b/tests/integration/__tests__/parser-api.js @@ -47,6 +47,7 @@ test("parsers should allow omit optional arguments", async () => { expect(typeof parsers[0][1].parse).toBe("function"); const code = { graphql: "type A {hero: Character}", + angular: "<div></div>", }; for (const [name, { parse }] of parsers) { await expect( diff --git a/tests/unit/__snapshots__/visitor-keys.js.snap b/tests/unit/__snapshots__/visitor-keys.js.snap --- a/tests/unit/__snapshots__/visitor-keys.js.snap +++ b/tests/unit/__snapshots__/visitor-keys.js.snap @@ -1390,6 +1390,11 @@ exports[`visitor keys graphql 1`] = ` exports[`visitor keys html 1`] = ` { "attribute": [], + "block": [ + "children", + "parameters", + ], + "blockParameter": [], "cdata": [], "comment": [], "docType": [],
Support for the new Angular Control Flow Syntax Angular is introducing a new control flow syntax in it's [RFC](https://github.com/angular/angular/discussions/50719). I'm opening this issue in order to track the support for it in the prettier formatter. Because the new sytanx follows the svelte syntax a lot, I believe we can learn/be-inspired/copy a lot from the svelte one.
Update: Angular choose to go with @-syntax for the control flow. https://blog.angular.io/meet-angulars-new-control-flow-a02c6eee7843 Thanks for opening this. With v17 right around the corner, I hope this gets some love in time. To provide some concrete dates: the Angular v17 release candidate will be mid-October, and v17 final is expected early November. Thank you for sharing, I'll look into this. Notes: - Introduce AST fro control flow: https://github.com/angular/angular/pull/51299 - Control flow keywords are `defer`, `switch`, `for`, `if` @sosukesuzuki cant wait to see it arrive thanks for taking your time and doing it 🎉 > Notes: > > * Introduce AST fro control flow: [Introduce AST for control flow angular/angular#51299](https://github.com/angular/angular/pull/51299) > * Control flow keywords are `defer`, `switch`, `for`, `if` The full list of keywords: - Defer: `@defer`, `@placeholder`, `@loading`, `@error` - Conditionals: `@if`, `@else`, `@else if`, `@switch`, `@case`, `@default` - Loops: `@for`, `@empty` The keywords are followed by optional parentheses, then curly braces, e.g.: ``` @if (foo) { <span></span> } @else if (bar) { <div></div> } ``` Let us know if you need anything from us. Thank you for your time and effort! This looks like a big change needed to our HTML printer (maybe also parser?). Latest angular template parser supports `tokenizeBlocks?` option( https://github.com/angular/angular/commit/29aaded0c3fbf669a95ea70928b4458579fbcc39 ). I think we need to enable that when `parser="angular"` for parsing blocks (`@if`, `@else`, `@defer`, etc...). So, I plan that I would start by updating angular-html-parser to the latest version. Can I confirm that this will ensure that control flow blocks will always have a newline between them and the enclosing code? So this: ``` @if (foo) { <span></span> } @else if (bar) { <div></div> } ``` Never this: ``` @if (foo) { <span> </span> } ``` now that Angular 17 has just release, any updates to this? Thanks in advance!
"2023-11-09T03:11:12Z"
3.1
[]
[ "tests/unit/visitor-keys.js", "tests/format/angular/control-flow/embedded-language-formatting-off/jsfmt.spec.js", "tests/format/angular/control-flow/small-print-width/jsfmt.spec.js", "tests/format/angular/control-flow/jsfmt.spec.js" ]
JavaScript
[]
[]
prettier/prettier
15,708
prettier__prettier-15708
[ "15707" ]
bb4ad267738918a3fd823ea018598337f3a19fed
diff --git a/src/language-js/comments/handle-comments.js b/src/language-js/comments/handle-comments.js --- a/src/language-js/comments/handle-comments.js +++ b/src/language-js/comments/handle-comments.js @@ -62,6 +62,7 @@ function handleOwnLineComment(context) { handleLabeledStatementComments, handleBreakAndContinueStatementComments, handleNestedConditionalExpressionComments, + handleCommentsInDestructuringPattern, ].some((fn) => fn(context)); } @@ -976,6 +977,44 @@ function handleLastUnionElementInExpression({ return false; } +/** + * const [ + * foo, + * // bar + * // baz + * ]: Foo = foo(); + * + * const { + * foo, + * // bar + * // baz + * }: Foo = foo(); + * + */ +function handleCommentsInDestructuringPattern({ + comment, + enclosingNode, + precedingNode, + followingNode, +}) { + if ( + (enclosingNode?.type === "ObjectPattern" || + enclosingNode?.type === "ArrayPattern") && + followingNode?.type === "TSTypeAnnotation" + ) { + if (precedingNode) { + addTrailingComment(precedingNode, comment); + } else { + // const { + // // bar + // // baz + // }: Foo = expr; + addDanglingComment(enclosingNode, comment); + } + return true; + } +} + /** * @param {Node} node * @returns {boolean}
diff --git a/tests/format/typescript/comments/15707.ts b/tests/format/typescript/comments/15707.ts new file mode 100644 --- /dev/null +++ b/tests/format/typescript/comments/15707.ts @@ -0,0 +1,55 @@ +const { + foo, + // bar + // baz +}: Foo = expr; + +const { + foo1, + // bar + foo2, + // baz +}: Foo = expr; + +const [ + foo, + // bar + // baz +]: Foo = expr; + +const [ + foo1, + // bar + foo2, + // baz +]: Foo = expr; + +function method({ + foo, + // bar = "bar", + // bazz = "bazz", +}: Foo) {} + +function method({ + foo1, + // bar = "bar", + foo2 + // bazz = "bazz", +}: Foo) {} + +function method([ + foo, + // bar = "bar", + foo2 + // bazz = "bazz", +]: Foo) {} + +const { + // bar + // baz +}: Foo = expr; + +const [ + // bar + // baz +]: Foo = expr; diff --git a/tests/format/typescript/comments/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/comments/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/typescript/comments/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/typescript/comments/__snapshots__/jsfmt.spec.js.snap @@ -1,5 +1,127 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP +exports[`15707.ts format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +const { + foo, + // bar + // baz +}: Foo = expr; + +const { + foo1, + // bar + foo2, + // baz +}: Foo = expr; + +const [ + foo, + // bar + // baz +]: Foo = expr; + +const [ + foo1, + // bar + foo2, + // baz +]: Foo = expr; + +function method({ + foo, + // bar = "bar", + // bazz = "bazz", +}: Foo) {} + +function method({ + foo1, + // bar = "bar", + foo2 + // bazz = "bazz", +}: Foo) {} + +function method([ + foo, + // bar = "bar", + foo2 + // bazz = "bazz", +]: Foo) {} + +const { + // bar + // baz +}: Foo = expr; + +const [ + // bar + // baz +]: Foo = expr; + +=====================================output===================================== +const { + foo, + // bar + // baz +}: Foo = expr; + +const { + foo1, + // bar + foo2, + // baz +}: Foo = expr; + +const [ + foo, + // bar + // baz +]: Foo = expr; + +const [ + foo1, + // bar + foo2, + // baz +]: Foo = expr; + +function method({ + foo, + // bar = "bar", + // bazz = "bazz", +}: Foo) {} + +function method({ + foo1, + // bar = "bar", + foo2, + // bazz = "bazz", +}: Foo) {} + +function method([ + foo, + // bar = "bar", + foo2, + // bazz = "bazz", +]: Foo) {} + +const { + // bar + // baz +}: Foo = expr; + +const [ + // bar + // baz +]: Foo = expr; + +================================================================================ +`; + exports[`abstract_class.ts format 1`] = ` ====================================options===================================== parsers: ["typescript"]
Object destructuring in parameters with type and comments results in non-stable format loop **Prettier 3.1.0** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAdKcAeAHCAnGAAgBM4AzAQwFcAbIsGigZycIDEIJDh1DDIoTGHipgY+ABTBCvPoTKcANLL4B6VYQBGFPIQC8MkNryoQyqHMLqtFAF639h7fdPm+AXyTtOASSgBLGABKbnd0dzMQCGwYf2gmZFAdPAgAdwAFHQQElAoaVIoATwTFIzwKMABrOBgAZQoAWzgAGX8MZEoaJjhSzXKqmtrsCraAc2RhKh6Qbob-CZFprGw4PH8m2DyAFVWoHX84HM7u0qYxmjgARSoIeA68k5AAKyZMWvOrm7ukY+mARy+cHSKWwORAzAAtBg4KRiJFhBR-DQxgBhCANBoUZDgmg0SJnKCjC4AQRgwn8mio8HSq1a7R+D2mAAsYA0aAB1JmBQ7DMBwWrZQL+ABugUK2LALEiwqmflIsFqYDWMWJUGItRghQu9y602wKW67PK2Gx+sOq2FcEibW6BGBFFGmJ1j2GeFt2M1KyYSv8MUi+raMHZ-mIMCZyAAHAAGUp4OAA-xx+2OrEM3WlGAUTTB0PhpAAJlKVG6WyzR0ZpTgDU0MNhzQohKoDrgHDwmLJY2x1HEIHc7iAA) <!-- prettier-ignore --> ```sh --parser typescript ``` **Input:** <!-- prettier-ignore --> ```ts export default class Foo { constructor({ foo, // bar = "bar", // bazz = "bazz", }: FooInit) {} } ``` **Output:** <!-- prettier-ignore --> ```ts export default class Foo { constructor({ foo, } // bar = "bar", // bazz = "bazz", : FooInit) {} } ``` **Expected behavior:** I would expect no changes whatsoever to the original input: ```ts export default class Foo { constructor({ foo, // bar = "bar", // bazz = "bazz", }: FooInit) {} } ``` **Notes** This behaviour is actually fairly buggy, not only is the output not desirable, the output *isn't stable*, feeding the output back into prettier changes it again: ```ts export default class Foo { constructor({ foo, // bar = "bar", } // bazz = "bazz", : FooInit) {} } ``` which feeding back in becomes (and will from now on alternate between this and the above printing): ```ts export default class Foo { constructor({ foo, // bar = "bar", // bazz = "bazz", }: FooInit) {} } ```
"2023-11-23T14:00:08Z"
3.2
[]
[ "tests/format/typescript/comments/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAdKcAeAHCAnGAAgBM4AzAQwFcAbIsGigZycIDEIJDh1DDIoTGHipgY+ABTBCvPoTKcANLL4B6VYQBGFPIQC8MkNryoQyqHMLqtFAF639h7fdPm+AXyTtOASSgBLGABKbnd0dzMQCGwYf2gmZFAdPAgAdwAFHQQElAoaVIoATwTFIzwKMABrOBgAZQoAWzgAGX8MZEoaJjhSzXKqmtrsCraAc2RhKh6Qbob-CZFprGw4PH8m2DyAFVWoHX84HM7u0qYxmjgARSoIeA68k5AAKyZMWvOrm7ukY+mARy+cHSKWwORAzAAtBg4KRiJFhBR-DQxgBhCANBoUZDgmg0SJnKCjC4AQRgwn8mio8HSq1a7R+D2mAAsYA0aAB1JmBQ7DMBwWrZQL+ABugUK2LALEiwqmflIsFqYDWMWJUGItRghQu9y602wKW67PK2Gx+sOq2FcEibW6BGBFFGmJ1j2GeFt2M1KyYSv8MUi+raMHZ-mIMCZyAAHAAGUp4OAA-xx+2OrEM3WlGAUTTB0PhpAAJlKVG6WyzR0ZpTgDU0MNhzQohKoDrgHDwmLJY2x1HEIHc7iAA" ]
prettier/prettier
15,748
prettier__prettier-15748
[ "15738" ]
56408635eb01002940513e89fa5e8d9c98c9a5af
diff --git a/src/language-html/print/children.js b/src/language-html/print/children.js --- a/src/language-html/print/children.js +++ b/src/language-html/print/children.js @@ -7,6 +7,8 @@ import { hardline, } from "../../document/builders.js"; import { replaceEndOfLine } from "../../document/utils.js"; +import isNonEmptyArray from "../../utils/is-non-empty-array.js"; +import htmlWhitespaceUtils from "../../utils/html-whitespace-utils.js"; import { locStart, locEnd } from "../loc.js"; import { forceBreakChildren, @@ -25,22 +27,41 @@ import { needsToBorrowParentClosingTagStartMarker, } from "./tag.js"; +function getEndLocation(node) { + const endLocation = locEnd(node); + + // Element can be unclosed + if ( + node.type === "element" && + !node.endSourceSpan && + isNonEmptyArray(node.children) + ) { + return Math.max(endLocation, getEndLocation(node.children.at(-1))); + } + + return endLocation; +} + function printChild(childPath, options, print) { const child = childPath.node; if (hasPrettierIgnore(child)) { + const endLocation = getEndLocation(child); + return [ printOpeningTagPrefix(child, options), replaceEndOfLine( - options.originalText.slice( - locStart(child) + - (child.prev && needsToBorrowNextOpeningTagStartMarker(child.prev) - ? printOpeningTagStartMarker(child).length - : 0), - locEnd(child) - - (child.next && needsToBorrowPrevClosingTagEndMarker(child.next) - ? printClosingTagEndMarker(child, options).length - : 0), + htmlWhitespaceUtils.trimEnd( + options.originalText.slice( + locStart(child) + + (child.prev && needsToBorrowNextOpeningTagStartMarker(child.prev) + ? printOpeningTagStartMarker(child).length + : 0), + endLocation - + (child.next && needsToBorrowPrevClosingTagEndMarker(child.next) + ? printClosingTagEndMarker(child, options).length + : 0), + ), ), ), printClosingTagSuffix(child, options),
diff --git a/tests/format/html/prettier_ignore/__snapshots__/jsfmt.spec.js.snap b/tests/format/html/prettier_ignore/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/html/prettier_ignore/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/html/prettier_ignore/__snapshots__/jsfmt.spec.js.snap @@ -117,6 +117,60 @@ printWidth: 80 ================================================================================ `; +exports[`issue-15738.html format 1`] = ` +====================================options===================================== +parsers: ["html"] +printWidth: 80 + | printWidth +=====================================input====================================== +<head></head> +<link + rel="stylesheet" + href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css" +/> +<style>marked-md:not(:defined) { display: none }</style> +<script type="module" src="../auto.js"></script> +<!-- prettier-ignore --> +<marked-md display="block"><plaintext> +# Hello world! + +\`\`\`html +<p>Look at these <span id="html">HTML tags</span></p> +<div class="box">They aren't being <code>interpreted</code> as actual HTML</div> +\`\`\` + +But this HTML is <mark>actually parsed</mark> just like **normal**. + +> <em>Markdown</em> lets you include <strong>arbitrary</strong> <abbr>HTML</abbr> in it. + +=====================================output===================================== +<head></head> +<link + rel="stylesheet" + href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css" +/> +<style> + marked-md:not(:defined) { + display: none; + } +</style> +<script type="module" src="../auto.js"></script> +<!-- prettier-ignore --> +<marked-md display="block"><plaintext> +# Hello world! + +\`\`\`html +<p>Look at these <span id="html">HTML tags</span></p> +<div class="box">They aren't being <code>interpreted</code> as actual HTML</div> +\`\`\` + +But this HTML is <mark>actually parsed</mark> just like **normal**. + +> <em>Markdown</em> lets you include <strong>arbitrary</strong> <abbr>HTML</abbr> in it. + +================================================================================ +`; + exports[`long_lines.html format 1`] = ` ====================================options===================================== parsers: ["html"] @@ -160,3 +214,44 @@ A super long string that has been marked as ignore because it was probably gener ================================================================================ `; + +exports[`unclosed.html format 1`] = ` +====================================options===================================== +parsers: ["html"] +printWidth: 80 + | printWidth +=====================================input====================================== +<!-- prettier-ignore --> +<div> +# Hello world! +<span> + +=====================================output===================================== +<!-- prettier-ignore --> +<div> +# Hello world! +<span> + +================================================================================ +`; + +exports[`unclosed2.html format 1`] = ` +====================================options===================================== +parsers: ["html"] +printWidth: 80 + | printWidth +=====================================input====================================== +<!-- prettier-ignore --> +<p> +# Hello world! +<div> + +=====================================output===================================== +<!-- prettier-ignore --> +<p> +# Hello world! + +<div></div> + +================================================================================ +`; diff --git a/tests/format/html/prettier_ignore/issue-15738.html b/tests/format/html/prettier_ignore/issue-15738.html new file mode 100644 --- /dev/null +++ b/tests/format/html/prettier_ignore/issue-15738.html @@ -0,0 +1,19 @@ +<head></head> +<link + rel="stylesheet" + href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css" +/> +<style>marked-md:not(:defined) { display: none }</style> +<script type="module" src="../auto.js"></script> +<!-- prettier-ignore --> +<marked-md display="block"><plaintext> +# Hello world! + +```html +<p>Look at these <span id="html">HTML tags</span></p> +<div class="box">They aren't being <code>interpreted</code> as actual HTML</div> +``` + +But this HTML is <mark>actually parsed</mark> just like **normal**. + +> <em>Markdown</em> lets you include <strong>arbitrary</strong> <abbr>HTML</abbr> in it. diff --git a/tests/format/html/prettier_ignore/unclosed.html b/tests/format/html/prettier_ignore/unclosed.html new file mode 100644 --- /dev/null +++ b/tests/format/html/prettier_ignore/unclosed.html @@ -0,0 +1,4 @@ +<!-- prettier-ignore --> +<div> +# Hello world! +<span> diff --git a/tests/format/html/prettier_ignore/unclosed2.html b/tests/format/html/prettier_ignore/unclosed2.html new file mode 100644 --- /dev/null +++ b/tests/format/html/prettier_ignore/unclosed2.html @@ -0,0 +1,4 @@ +<!-- prettier-ignore --> +<p> +# Hello world! +<div>
Prettier removes unterminated HTML tag & content <details><summary>old text</summary> **Prettier 3.1.0** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAFnAhgEwHyoD0mueAOlKgDYCWUA1hQARMBOcVAvGSAM4wBPKnF6Y4MHsybp2AM24h0MGAAdeSQoTA4oAOgBWvHBxoA3VrqjjCUFQFtCAdyzwLYXrwACAJkIQArjBOLnBuHpJQhOSU-EJweHZYrPRwOAC0djhIUBAwABRIxrJ0qQCUTMBMODS8KlRYAkhMOVZMAL5EscLRqLxgrDQqMEyCKnAKdhA4-sI8TLysYAq6uoRYgRAGvDwEhH0DQz0AhGlpTCrsyjShaTQA5jnsTKc9icmpGThVNXUNCgBGVAgYEYIAIvzo8AAHjBogBiJgACQ4QKYjggrCoOCOFAoAAMCUo7FQKKgVHgADIQCD0JguEaYXhwJi9FRYKBMGg4BREklgxEAFQAshSRlg7rxOmyoLtyaTqqYmGB6h4ARAoTsBZgBHT2FAAOTDf5wOh3FmQYx4SGhC7iVJEC3xOm8OlgGD+LBUJHCilEBXRAl43FQABCgQZNW9Is5LtQb3oeCwbo9VCoOrZrCZOCI8bwTH0-n4TFoKSYACoy49ElQK7pg3nUHA7HghUl6DgII5KIQm3nhDAXQIApyoMr-MYWfxWNA7onWP8aDBWEkBJ0lzOG1h-v9WHhBSKiFud3m6JyYHWoCAADQgCBDGjQXjIUBJaeOAAKSQQT5QnucAifG8dyTFIYAAZSwOw4ApEpkFkT0mSA5cQXEMC2TAU1kCXfw4BvJk7BoLDWBwm84ChMYBig2BPQFUIoCSa4f3gqhEL4U1hAARX8XI4DghDcJAQwoTA9i4C4ni+JYgSAEduPgd9pzUZAQCwXg0isVJUmvEAlywGhaCgO4AGEIDsRJlM9KhtN4USAEFlAGf5Ajgd9QhgqxJNY3kAHV0EXER0LgMDv0XMxFwEZT3EAkBTBwgBJKBjFgMD+kGGBbMSsDBGETyBIuCAmW85cVGU20mVYUxeJvOhypgBTxXMpBmNYjNyuU3ltIuSFvK5GB0GQAAOAAGG92Fkmh2Hqu5GuagSYC3HqcD65BvBvQs4AFLcmP40i7GNHBjBwCl2TuD07jgAAxDFEiuQyLI2EA2jaIA) <!-- prettier-ignore --> ```sh --parser html ``` **Input:** <!-- prettier-ignore --> ````html <head></head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css" /> <style>marked-md:not(:defined) { display: none }</style> <script type="module" src="../auto.js"></script> <!-- prettier-ignore --> <marked-md display="block"><plaintext> # Hello world! ```html <p>Look at these <span id="html">HTML tags</span></p> <div class="box">They aren't being <code>interpreted</code> as actual HTML</div> ``` But this HTML is <mark>actually parsed</mark> just like **normal**. > <em>Markdown</em> lets you include <strong>arbitrary</strong> <abbr>HTML</abbr> in it. ```` **Output:** <!-- prettier-ignore --> ```html <head></head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css" /> <style> marked-md:not(:defined) { display: none; } </style> <script type="module" src="../auto.js"></script> <!-- prettier-ignore --> <marked-md display="block"> ``` **Expected behavior:** idk but it should definitely NOT eat my entire html block for breakfast lol 😅 </details> ## PART 1 **Prettier 3.1.0** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAtgTwLQFdZwBO6AllAIbwAm2YuAzjBOtnADZzoIwB8q9YQiQAOMAAQxMwuAF4qlcjwA6UAMrM4EuAA8YucmzHyY5MamE8A7iRgALMfQ1iAEgBUAsgBlsbEgGs4VBMAc3oeMXIoKjF0CEJNIPJQiKiJWzJQ5SgAdQhLAEIxTwgYejEIADMzNy9sTwBJAGkAUXDjUzIxWyJNO0oxSwSqCDEoEvDLSPEmMQAjTWFyQno4aPJ6FVQaz3DZ3HEyRjhyaIArBnEAKkvF+hWqa4iy00YhKGCJEbtNOkZmMXYnG4KhAABoQBBRCRoPRkKAloQ8gAFJYIWEoAyTTCw8GzQjkMABGCqchcTxkODICoGFa4-GEuDExZgDLIGCEXBwcErUhsjlckA6aRCLiwAyuIgUIRwdHUti0kD0DIcACKuBKlKQcoVp3o2lUyrgao1VJpAoAjur4EjEcJ0SB1tgoHBVqswSB2eQSL53gBhZjocjIB1sNjupXvDgAQRg7JIe2tRHJztN8oFthg6DY2XS8HozLgqjRNhIADcbJhg2A7u7S5z6lFuKpBCIYFGoqpJBxUwrhIiVtl8cJg32ZURS5TwYciDAbUlAz2BYtlkRgxms+6+2QYNkSFQ7MgABwABnB8UtJHic+CC61ZvBJlmu-3tmQACZwQw4K5yLNZffBXQeYqCoVZPEiYJ9GCOAADE4kDWNWQxfYIBAABfNCgA) <!-- prettier-ignore --> ```sh --parser html ``` **Input:** <!-- prettier-ignore --> ```html <my-unterminated-custom-element><script type=data> Some textual data <p>with some HTML-like<tags> and more <tags and things> Wow! Lots of <HTML-LIKE> data in here that we <do not> want to be parsed as <HTML> but instead just **passed** as a string to the custom element ``` **Output:** <!-- prettier-ignore --> ```html SyntaxError: Unexpected character "EOF" (5:1) 3 | Wow! Lots of <HTML-LIKE> data in here that we <do not> want to be parsed as 4 | <HTML> but instead just **passed** as a string to the custom element > 5 | | ^ ``` **Expected behavior:** not error lol ## PART 2 **Prettier 3.1.0** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAhAWkwAgA4BOcMMAlnAZqQOZQRE7YB8AOlKgLYCemArrBQ6koAQ3gATTGF4BnGBA6Y4AGzgcEMJqhlgCpPDBwwueOAF5xYkaygBlBXCNwAHjF4jlOSzBE5UeJgB3UhgACxwZBxwACQAVAFkAGUxlUgBrOFQfahkmHBEocRwOekcskRz8wqNQ4RybAHUIQPQcRIgYGRwIADM-OKTMRIBJAGkAUTzvX2EcUIpHMLEcQLLxCBw6TRWCw3kcACNHPBECGTgikRk2VAHEvIPeQ2E5OBEigCtZQwAqH5OZOdxH98l1fHI9FBqEYNmFHNI5AocCo1BobgB6HR6AxMEAAGhAEAMpGgMmQoFOBGaAAVTggySgPIERFwyQSDgQRGAMjBbCJ1IlhHBkD0POd2ZzucRbCcwHVkDACLw4ATzkIFUqVSAXKY9OpYB5YhRRHo4AzRcpxSAZHVVABFXgdYVIC1Wj4yZy2W1wB1OkVirUAR0d8GpVLwDJAV0wUDgFwu+JAipEpFSUIAwgoOCJkFHlMpEzaoaoAIIkPSPUMUQWx-2WrWhGAcZQNWrwGSyuC2ekhUgANxCXFzYEBib7yuGhQ0tl0+hgJcKtmMqjrVsIEHODU5eFzhDNFD7woJLwoMDDFWzq61JzOFFzjebicIwhgDVI4jCyAAHAAGAlEYNSCIc9qEvF0AwJHwDjfD9QmQAAmAlZDgWIRAOc0IO1DgjnEcQLkSApqHcag4AAMXobMSHlRknggEAAF96KAA) <!-- prettier-ignore --> ```sh --parser html ``` **Input:** <!-- prettier-ignore --> ```html <!-- prettier-ignore --> <my-unterminated-custom-element><script type=data> Some textual data <p>with some HTML-like<tags> and more <tags and things> Wow! Lots of <HTML-LIKE> data in here that we <do not> want to be parsed as <HTML> but instead just **passed** as a string to the custom element </script> ``` **Output:** <!-- prettier-ignore --> ```html <!-- prettier-ignore --> <my-unterminated-custom-element> ``` **Expected behavior:** not delete the element. it only seems to delete the element when the prettier-ignore directive is there but it might also happen at other times too idk.
"2023-12-04T15:11:14Z"
3.2
[]
[ "tests/format/html/prettier_ignore/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAFnAhgEwHyoD0mueAOlKgDYCWUA1hQARMBOcVAvGSAM4wBPKnF6Y4MHsybp2AM24h0MGAAdeSQoTA4oAOgBWvHBxoA3VrqjjCUFQFtCAdyzwLYXrwACAJkIQArjBOLnBuHpJQhOSU-EJweHZYrPRwOAC0djhIUBAwABRIxrJ0qQCUTMBMODS8KlRYAkhMOVZMAL5EscLRqLxgrDQqMEyCKnAKdhA4-sI8TLysYAq6uoRYgRAGvDwEhH0DQz0AhGlpTCrsyjShaTQA5jnsTKc9icmpGThVNXUNCgBGVAgYEYIAIvzo8AAHjBogBiJgACQ4QKYjggrCoOCOFAoAAMCUo7FQKKgVHgADIQCD0JguEaYXhwJi9FRYKBMGg4BREklgxEAFQAshSRlg7rxOmyoLtyaTqqYmGB6h4ARAoTsBZgBHT2FAAOTDf5wOh3FmQYx4SGhC7iVJEC3xOm8OlgGD+LBUJHCilEBXRAl43FQABCgQZNW9Is5LtQb3oeCwbo9VCoOrZrCZOCI8bwTH0-n4TFoKSYACoy49ElQK7pg3nUHA7HghUl6DgII5KIQm3nhDAXQIApyoMr-MYWfxWNA7onWP8aDBWEkBJ0lzOG1h-v9WHhBSKiFud3m6JyYHWoCAADQgCBDGjQXjIUBJaeOAAKSQQT5QnucAifG8dyTFIYAAZSwOw4ApEpkFkT0mSA5cQXEMC2TAU1kCXfw4BvJk7BoLDWBwm84ChMYBig2BPQFUIoCSa4f3gqhEL4U1hAARX8XI4DghDcJAQwoTA9i4C4ni+JYgSAEduPgd9pzUZAQCwXg0isVJUmvEAlywGhaCgO4AGEIDsRJlM9KhtN4USAEFlAGf5Ajgd9QhgqxJNY3kAHV0EXER0LgMDv0XMxFwEZT3EAkBTBwgBJKBjFgMD+kGGBbMSsDBGETyBIuCAmW85cVGU20mVYUxeJvOhypgBTxXMpBmNYjNyuU3ltIuSFvK5GB0GQAAOAAGG92Fkmh2Hqu5GuagSYC3HqcD65BvBvQs4AFLcmP40i7GNHBjBwCl2TuD07jgAAxDFEiuQyLI2EA2jaIA", "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAhAWkwAgA4BOcMMAlnAZqQOZQRE7YB8AOlKgLYCemArrBQ6koAQ3gATTGF4BnGBA6Y4AGzgcEMJqhlgCpPDBwwueOAF5xYkaygBlBXCNwAHjF4jlOSzBE5UeJgB3UhgACxwZBxwACQAVAFkAGUxlUgBrOFQfahkmHBEocRwOekcskRz8wqNQ4RybAHUIQPQcRIgYGRwIADM-OKTMRIBJAGkAUTzvX2EcUIpHMLEcQLLxCBw6TRWCw3kcACNHPBECGTgikRk2VAHEvIPeQ2E5OBEigCtZQwAqH5OZOdxH98l1fHI9FBqEYNmFHNI5AocCo1BobgB6HR6AxMEAAGhAEAMpGgMmQoFOBGaAAVTggySgPIERFwyQSDgQRGAMjBbCJ1IlhHBkD0POd2ZzucRbCcwHVkDACLw4ATzkIFUqVSAXKY9OpYB5YhRRHo4AzRcpxSAZHVVABFXgdYVIC1Wj4yZy2W1wB1OkVirUAR0d8GpVLwDJAV0wUDgFwu+JAipEpFSUIAwgoOCJkFHlMpEzaoaoAIIkPSPUMUQWx-2WrWhGAcZQNWrwGSyuC2ekhUgANxCXFzYEBib7yuGhQ0tl0+hgJcKtmMqjrVsIEHODU5eFzhDNFD7woJLwoMDDFWzq61JzOFFzjebicIwhgDVI4jCyAAHAAGAlEYNSCIc9qEvF0AwJHwDjfD9QmQAAmAlZDgWIRAOc0IO1DgjnEcQLkSApqHcag4AAMXobMSHlRknggEAAF96KAA", "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAtgTwLQFdZwBO6AllAIbwAm2YuAzjBOtnADZzoIwB8q9YQiQAOMAAQxMwuAF4qlcjwA6UAMrM4EuAA8YucmzHyY5MamE8A7iRgALMfQ1iAEgBUAsgBlsbEgGs4VBMAc3oeMXIoKjF0CEJNIPJQiKiJWzJQ5SgAdQhLAEIxTwgYejEIADMzNy9sTwBJAGkAUXDjUzIxWyJNO0oxSwSqCDEoEvDLSPEmMQAjTWFyQno4aPJ6FVQaz3DZ3HEyRjhyaIArBnEAKkvF+hWqa4iy00YhKGCJEbtNOkZmMXYnG4KhAABoQBBRCRoPRkKAloQ8gAFJYIWEoAyTTCw8GzQjkMABGCqchcTxkODICoGFa4-GEuDExZgDLIGCEXBwcErUhsjlckA6aRCLiwAyuIgUIRwdHUti0kD0DIcACKuBKlKQcoVp3o2lUyrgao1VJpAoAjur4EjEcJ0SB1tgoHBVqswSB2eQSL53gBhZjocjIB1sNjupXvDgAQRg7JIe2tRHJztN8oFthg6DY2XS8HozLgqjRNhIADcbJhg2A7u7S5z6lFuKpBCIYFGoqpJBxUwrhIiVtl8cJg32ZURS5TwYciDAbUlAz2BYtlkRgxms+6+2QYNkSFQ7MgABwABnB8UtJHic+CC61ZvBJlmu-3tmQACZwQw4K5yLNZffBXQeYqCoVZPEiYJ9GCOAADE4kDWNWQxfYIBAABfNCgA" ]
prettier/prettier
15,756
prettier__prettier-15756
[ "7912" ]
4c3cfa7a813e072ae4f581ecf6c5b27ebb063f15
diff --git a/src/language-js/print/module.js b/src/language-js/print/module.js --- a/src/language-js/print/module.js +++ b/src/language-js/print/module.js @@ -148,7 +148,7 @@ function printModuleSource(path, options, print) { /** @type{Doc[]} */ const parts = []; - if (!shouldNotPrintSpecifiers(node, options)) { + if (shouldPrintSpecifiers(node, options)) { parts.push(" from"); } parts.push(" ", print("source")); @@ -159,7 +159,7 @@ function printModuleSource(path, options, print) { function printModuleSpecifiers(path, options, print) { const { node } = path; - if (shouldNotPrintSpecifiers(node, options)) { + if (!shouldPrintSpecifiers(node, options)) { return ""; } @@ -231,21 +231,22 @@ function printModuleSpecifiers(path, options, print) { return parts; } -function shouldNotPrintSpecifiers(node, options) { - const { type, importKind, source, specifiers } = node; - +function shouldPrintSpecifiers(node, options) { if ( - type !== "ImportDeclaration" || - isNonEmptyArray(specifiers) || - importKind === "type" + node.type !== "ImportDeclaration" || + isNonEmptyArray(node.specifiers) || + node.importKind === "type" ) { - return false; + return true; } - // TODO: check tokens - return !/{\s*}/.test( - options.originalText.slice(locStart(node), locStart(source)), + const text = getTextWithoutComments( + options, + locStart(node), + locStart(node.source), ); + + return text.trimEnd().endsWith("from"); } function getTextWithoutComments(options, start, end) { @@ -288,8 +289,8 @@ function getImportAttributesOrAssertionsKeyword(node, options) { const textBetweenSourceAndAttributes = getTextWithoutComments( options, - node.source.range[1], - node.attributes[0].range[0], + locEnd(node.source), + locStart(node.attributes[0]), ); if (textBetweenSourceAndAttributes.trimStart().startsWith("assert")) {
diff --git a/tests/format/js/import/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/import/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/js/import/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/import/__snapshots__/jsfmt.spec.js.snap @@ -286,9 +286,92 @@ printWidth: 80 | printWidth =====================================input====================================== import { } from '@types/googlemaps'; +import 'a'; +import /* comment */ 'a'; +import // comment +'a'; +import { /* comment */ } from 'a'; +import /* comment */ {} from 'a'; +import {} /* comment */ from 'a'; +import {} from /* comment */ 'a'; +import /* comment */ {/* comment */} /* comment */ from /* comment */ 'a'; +import { + // comment +} from 'a'; +import // comment +{} from 'a'; +import {} +// comment +from 'a'; +import {} from +// comment +'a'; +import +// comment +{ +// comment +} +// comment +from +// comment +'a'; + +import // {} from +'a'; +import {} from // comment ends with from +'a'; +import {} from /* comment ends with from */ 'a'; +import {} from // comment not ends with from ___ +'a'; +import {} from /* comment not ends with from ___ */ 'a'; + +import // comment ends with from +'a'; +import /* comment ends with from */ 'a'; +import // comment not ends with from ___ +'a'; +import /* comment not ends with from ___ */ 'a'; =====================================output===================================== import {} from "@types/googlemaps"; +import "a"; +import /* comment */ "a"; +import // comment +"a"; +import {} from /* comment */ "a"; +import {} from /* comment */ "a"; +import {} from /* comment */ "a"; +import {} from /* comment */ "a"; +import {} from /* comment */ /* comment */ /* comment */ /* comment */ "a"; +import {} from // comment +"a"; +import {} from // comment +"a"; +import {} from // comment +"a"; +import {} from // comment +"a"; +import {} from // comment +// comment +// comment +// comment +"a"; + +import // {} from +"a"; +import {} from // comment ends with from +"a"; +import {} from /* comment ends with from */ "a"; +import {} from // comment not ends with from ___ +"a"; +import {} from /* comment not ends with from ___ */ "a"; + +import // comment ends with from +"a"; +import /* comment ends with from */ "a"; +import // comment not ends with from ___ +"a"; +import /* comment not ends with from ___ */ "a"; ================================================================================ `; @@ -300,9 +383,92 @@ printWidth: 80 | printWidth =====================================input====================================== import { } from '@types/googlemaps'; +import 'a'; +import /* comment */ 'a'; +import // comment +'a'; +import { /* comment */ } from 'a'; +import /* comment */ {} from 'a'; +import {} /* comment */ from 'a'; +import {} from /* comment */ 'a'; +import /* comment */ {/* comment */} /* comment */ from /* comment */ 'a'; +import { + // comment +} from 'a'; +import // comment +{} from 'a'; +import {} +// comment +from 'a'; +import {} from +// comment +'a'; +import +// comment +{ +// comment +} +// comment +from +// comment +'a'; + +import // {} from +'a'; +import {} from // comment ends with from +'a'; +import {} from /* comment ends with from */ 'a'; +import {} from // comment not ends with from ___ +'a'; +import {} from /* comment not ends with from ___ */ 'a'; + +import // comment ends with from +'a'; +import /* comment ends with from */ 'a'; +import // comment not ends with from ___ +'a'; +import /* comment not ends with from ___ */ 'a'; =====================================output===================================== import {} from "@types/googlemaps"; +import "a"; +import /* comment */ "a"; +import // comment +"a"; +import {} from /* comment */ "a"; +import {} from /* comment */ "a"; +import {} from /* comment */ "a"; +import {} from /* comment */ "a"; +import {} from /* comment */ /* comment */ /* comment */ /* comment */ "a"; +import {} from // comment +"a"; +import {} from // comment +"a"; +import {} from // comment +"a"; +import {} from // comment +"a"; +import {} from // comment +// comment +// comment +// comment +"a"; + +import // {} from +"a"; +import {} from // comment ends with from +"a"; +import {} from /* comment ends with from */ "a"; +import {} from // comment not ends with from ___ +"a"; +import {} from /* comment not ends with from ___ */ "a"; + +import // comment ends with from +"a"; +import /* comment ends with from */ "a"; +import // comment not ends with from ___ +"a"; +import /* comment not ends with from ___ */ "a"; ================================================================================ `; diff --git a/tests/format/js/import/empty-import.js b/tests/format/js/import/empty-import.js --- a/tests/format/js/import/empty-import.js +++ b/tests/format/js/import/empty-import.js @@ -1 +1,46 @@ import { } from '@types/googlemaps'; +import 'a'; +import /* comment */ 'a'; +import // comment +'a'; +import { /* comment */ } from 'a'; +import /* comment */ {} from 'a'; +import {} /* comment */ from 'a'; +import {} from /* comment */ 'a'; +import /* comment */ {/* comment */} /* comment */ from /* comment */ 'a'; +import { + // comment +} from 'a'; +import // comment +{} from 'a'; +import {} +// comment +from 'a'; +import {} from +// comment +'a'; +import +// comment +{ +// comment +} +// comment +from +// comment +'a'; + +import // {} from +'a'; +import {} from // comment ends with from +'a'; +import {} from /* comment ends with from */ 'a'; +import {} from // comment not ends with from ___ +'a'; +import {} from /* comment not ends with from ___ */ 'a'; + +import // comment ends with from +'a'; +import /* comment ends with from */ 'a'; +import // comment not ends with from ___ +'a'; +import /* comment not ends with from ___ */ 'a'; diff --git a/tests/format/typescript/import-export/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/import-export/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/typescript/import-export/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/typescript/import-export/__snapshots__/jsfmt.spec.js.snap @@ -1,5 +1,102 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP +exports[`empty-import.ts format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +import type { } from '@types/googlemaps'; +import 'a'; +import /* comment */ 'a'; +import // comment +'a'; +import type { /* comment */ } from 'a'; +import /* comment */ type {} from 'a'; +import type {} /* comment */ from 'a'; +import type {} from /* comment */ 'a'; +import /* comment */ type {/* comment */} /* comment */ from /* comment */ 'a'; +import type { + // comment +} from 'a'; +import // comment +type {} from 'a'; +import type {} +// comment +from 'a'; +import type {} from +// comment +'a'; +import type +// comment +{ +// comment +} +// comment +from +// comment +'a'; + +import // {} from +'a'; +import type {} from // comment ends with from +'a'; +import type {} from /* comment ends with from */ 'a'; +import type {} from // comment not ends with from ___ +'a'; +import type {} from /* comment not ends with from ___ */ 'a'; + +import // comment ends with from +'a'; +import /* comment ends with from */ 'a'; +import // comment not ends with from ___ +'a'; +import /* comment not ends with from ___ */ 'a'; + +=====================================output===================================== +import type {} from "@types/googlemaps"; +import "a"; +import /* comment */ "a"; +import // comment +"a"; +import type {} from /* comment */ "a"; +import type {} from /* comment */ "a"; +import type {} from /* comment */ "a"; +import type {} from /* comment */ "a"; +import type {} from /* comment */ /* comment */ /* comment */ /* comment */ "a"; +import type {} from // comment +"a"; +import type {} from // comment +"a"; +import type {} from // comment +"a"; +import type {} from // comment +"a"; +import type {} from // comment +// comment +// comment +// comment +"a"; + +import // {} from +"a"; +import type {} from // comment ends with from +"a"; +import type {} from /* comment ends with from */ "a"; +import type {} from // comment not ends with from ___ +"a"; +import type {} from /* comment not ends with from ___ */ "a"; + +import // comment ends with from +"a"; +import /* comment ends with from */ "a"; +import // comment not ends with from ___ +"a"; +import /* comment not ends with from ___ */ "a"; + +================================================================================ +`; + exports[`type-modifier.ts format 1`] = ` ====================================options===================================== parsers: ["typescript"] diff --git a/tests/format/typescript/import-export/empty-import.ts b/tests/format/typescript/import-export/empty-import.ts new file mode 100644 --- /dev/null +++ b/tests/format/typescript/import-export/empty-import.ts @@ -0,0 +1,46 @@ +import type { } from '@types/googlemaps'; +import 'a'; +import /* comment */ 'a'; +import // comment +'a'; +import type { /* comment */ } from 'a'; +import /* comment */ type {} from 'a'; +import type {} /* comment */ from 'a'; +import type {} from /* comment */ 'a'; +import /* comment */ type {/* comment */} /* comment */ from /* comment */ 'a'; +import type { + // comment +} from 'a'; +import // comment +type {} from 'a'; +import type {} +// comment +from 'a'; +import type {} from +// comment +'a'; +import type +// comment +{ +// comment +} +// comment +from +// comment +'a'; + +import // {} from +'a'; +import type {} from // comment ends with from +'a'; +import type {} from /* comment ends with from */ 'a'; +import type {} from // comment not ends with from ___ +'a'; +import type {} from /* comment not ends with from ___ */ 'a'; + +import // comment ends with from +'a'; +import /* comment ends with from */ 'a'; +import // comment not ends with from ___ +'a'; +import /* comment not ends with from ___ */ 'a';
Curly braces and `from` keyword stripped off of `import` statements **Prettier 2.0.2** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEB6VACA7hATgawGcAdKASwFsAHPGDYAXwwDNcIKMByQ9uGACzJQA5p1Kl0GAEa44AQyKlKNXHWAZUAKgyQKFBHU2Ymrdlx76AtFTlh8c4XDFQJmGfKIYYECEuq16UgwNTABhdn1YUhM2Dm5eDAgBOAwbOwcnEAAaEAgqGDJoQmRQOVw2LAAFMoRilDkANwgyABNskBlbfD4AZTShYWQYXABXOBz+GAoAGwB1QXhCNLge2rIChvWAT2RwQmKcoUI4VUrcBwo5ZGY5aeOcgCtCAA8AIXO7Xrl9ABkhOGut3uICezx6A2mcAAiiMkgCkDc7uMQDZcMdcLspHIpHBpu0qLghDBZq0BMgABwABhyBIgx1m5youwJcHRDQBOQAjrD4Gc8nUQHJCJYoHA4C1xe1ZNyyLIzhcrgigcjjhQyICkTlCBDoTz4cMxjkYNiSS0yUgAExG85kaYDcJ6RUgKDQDkgEbHAAq2LqiOBDTGAEkoBLYD0wIT8gBBEM9GBbSEa44MBhAA) ```sh --arrow-parens avoid --parser babel --no-semi --single-quote --trailing-comma none ``` You may wonder what would be the use case for this kind of behavior. It happened to me as I wrote a generator cli for a project creating several files based on user input data and automatically applying a prettier format when those are generated. One of the files provides the empty import statement with the comment in the middle of the curly braces to invite the developer to import what he should from a precise package. I currently use the first version commented with `// works` in the example to work around the issue. **Input:** ```jsx // works import {} from 'something' // breaks import { /* comment */ } from 'some-package' // breaks too import { // Comment } from 'some other package' ``` **Output:** ```jsx // works import {} from 'something' // breaks import /* comment */ 'some-package' // breaks too import // Comment 'some other package' ``` **Expected behavior:** ```jsx // works import {} from 'something' // breaks import { /* comment */ } from 'some-package' // breaks too import { // Comment } from 'some other package' ```
Strictly speaking, this doesn't break code. Still, better to fix it. @thorn0 I'm trying to fix this, do you know is there token info in those parser? I can't find anything. We have to use source code? https://github.com/prettier/prettier/blob/aeeb2ff7a8231e2f3a0b2474fd35b4419fe0d97a/src/language-js/printer-estree.js#L1083-L1087 I'm trying to check if it ends with `from`, but might contains comments.
"2023-12-05T07:52:55Z"
3.2
[]
[ "tests/format/js/import/jsfmt.spec.js", "tests/format/typescript/import-export/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEB6VACA7hATgawGcAdKASwFsAHPGDYAXwwDNcIKMByQ9uGACzJQA5p1Kl0GAEa44AQyKlKNXHWAZUAKgyQKFBHU2Ymrdlx76AtFTlh8c4XDFQJmGfKIYYECEuq16UgwNTABhdn1YUhM2Dm5eDAgBOAwbOwcnEAAaEAgqGDJoQmRQOVw2LAAFMoRilDkANwgyABNskBlbfD4AZTShYWQYXABXOBz+GAoAGwB1QXhCNLge2rIChvWAT2RwQmKcoUI4VUrcBwo5ZGY5aeOcgCtCAA8AIXO7Xrl9ABkhOGut3uICezx6A2mcAAiiMkgCkDc7uMQDZcMdcLspHIpHBpu0qLghDBZq0BMgABwABhyBIgx1m5youwJcHRDQBOQAjrD4Gc8nUQHJCJYoHA4C1xe1ZNyyLIzhcrgigcjjhQyICkTlCBDoTz4cMxjkYNiSS0yUgAExG85kaYDcJ6RUgKDQDkgEbHAAq2LqiOBDTGAEkoBLYD0wIT8gBBEM9GBbSEa44MBhAA" ]
prettier/prettier
15,806
prettier__prettier-15806
[ "15785" ]
66a23c9331e2c652f8e08fd05a65d2bea7fe5c1a
diff --git a/src/language-js/print/call-expression.js b/src/language-js/print/call-expression.js --- a/src/language-js/print/call-expression.js +++ b/src/language-js/print/call-expression.js @@ -61,7 +61,11 @@ function printCallExpression(path, options, print) { !isDynamicImport && !isNew && isMemberish(node.callee) && - !path.call((path) => pathNeedsParens(path, options), "callee") + !path.call( + (path) => pathNeedsParens(path, options), + "callee", + ...(node.callee.type === "ChainExpression" ? ["expression"] : []), + ) ) { return printMemberChain(path, options, print); } diff --git a/src/language-js/print/member-chain.js b/src/language-js/print/member-chain.js --- a/src/language-js/print/member-chain.js +++ b/src/language-js/print/member-chain.js @@ -50,6 +50,14 @@ import { // MemberExpression and CallExpression. We need to traverse the AST // and make groups out of it to print it in the desired way. function printMemberChain(path, options, print) { + /* c8 ignore next 6 */ + if (path.node.type === "ChainExpression") { + return path.call( + () => printMemberChain(path, options, print), + "expression", + ); + } + const { parent } = path; const isExpressionStatement = !parent || parent.type === "ExpressionStatement"; @@ -88,6 +96,11 @@ function printMemberChain(path, options, print) { function rec(path) { const { node } = path; + + if (node.type === "ChainExpression") { + return path.call(() => rec(path), "expression"); + } + if ( isCallExpression(node) && (isMemberish(node.callee) || isCallExpression(node.callee)) diff --git a/src/language-js/print/member.js b/src/language-js/print/member.js --- a/src/language-js/print/member.js +++ b/src/language-js/print/member.js @@ -1,19 +1,31 @@ import { group, indent, label, softline } from "../../document/builders.js"; import { + getCallArguments, isCallExpression, isMemberExpression, isNumericLiteral, } from "../utils/index.js"; import { printOptionalToken } from "./misc.js"; +const isCallExpressionWithArguments = (node) => { + if (node.type === "ChainExpression" || node.type === "TSNonNullExpression") { + node = node.expression; + } + return isCallExpression(node) && getCallArguments(node).length > 0; +}; + function printMemberExpression(path, options, print) { const objectDoc = print("object"); const lookupDoc = printMemberLookup(path, options, print); - const { node, parent } = path; + const { node } = path; const firstNonMemberParent = path.findAncestor( (node) => !(isMemberExpression(node) || node.type === "TSNonNullExpression"), ); + const firstNonChainElementWrapperParent = path.findAncestor( + (node) => + !(node.type === "ChainExpression" || node.type === "TSNonNullExpression"), + ); const shouldInline = (firstNonMemberParent && @@ -24,13 +36,10 @@ function printMemberExpression(path, options, print) { node.computed || (node.object.type === "Identifier" && node.property.type === "Identifier" && - !isMemberExpression(parent)) || - ((parent.type === "AssignmentExpression" || - parent.type === "VariableDeclarator") && - ((isCallExpression(node.object) && node.object.arguments.length > 0) || - (node.object.type === "TSNonNullExpression" && - isCallExpression(node.object.expression) && - node.object.expression.arguments.length > 0) || + !isMemberExpression(firstNonChainElementWrapperParent)) || + ((firstNonChainElementWrapperParent.type === "AssignmentExpression" || + firstNonChainElementWrapperParent.type === "VariableDeclarator") && + (isCallExpressionWithArguments(node.object) || objectDoc.label?.memberChain)); return label(objectDoc.label, [ diff --git a/src/language-js/utils/create-type-check-function.js b/src/language-js/utils/create-type-check-function.js --- a/src/language-js/utils/create-type-check-function.js +++ b/src/language-js/utils/create-type-check-function.js @@ -1,5 +1,12 @@ -function createTypeCheckFunction(types) { - types = new Set(types); +/** @typedef {import("../types/estree.js").Node} Node */ +/** @typedef {import("../types/estree.js").Comment} Comment */ + +/** + * @param {string[]} typesArray + * @returns {(node: Node | Comment) => Boolean} + */ +function createTypeCheckFunction(typesArray) { + const types = new Set(typesArray); return (node) => types.has(node?.type); } diff --git a/src/language-js/utils/index.js b/src/language-js/utils/index.js --- a/src/language-js/utils/index.js +++ b/src/language-js/utils/index.js @@ -124,10 +124,6 @@ const isLineComment = createTypeCheckFunction([ "InterpreterDirective", ]); -/** - * @param {Node} node - * @returns {boolean} - */ const isExportDeclaration = createTypeCheckFunction([ "ExportDefaultDeclaration", "DeclareExportDeclaration", @@ -136,19 +132,11 @@ const isExportDeclaration = createTypeCheckFunction([ "DeclareExportAllDeclaration", ]); -/** - * @param {Node} node - * @returns {boolean} - */ const isArrayOrTupleExpression = createTypeCheckFunction([ "ArrayExpression", "TupleExpression", ]); -/** - * @param {Node} node - * @returns {boolean} - */ const isObjectOrRecordExpression = createTypeCheckFunction([ "ObjectExpression", "RecordExpression", @@ -191,10 +179,6 @@ function isRegExpLiteral(node) { ); } -/** - * @param {Node} node - * @returns {boolean} - */ const isLiteral = createTypeCheckFunction([ "Literal", "BooleanLiteral", @@ -207,10 +191,6 @@ const isLiteral = createTypeCheckFunction([ "StringLiteral", ]); -/** - * @param {Node} node - * @returns {boolean} - */ const isSingleWordType = createTypeCheckFunction([ "Identifier", "ThisExpression", @@ -220,20 +200,12 @@ const isSingleWordType = createTypeCheckFunction([ "Import", ]); -/** - * @param {Node} node - * @returns {boolean} - */ const isObjectType = createTypeCheckFunction([ "ObjectTypeAnnotation", "TSTypeLiteral", "TSMappedType", ]); -/** - * @param {Node} node - * @returns {boolean} - */ const isFunctionOrArrowExpression = createTypeCheckFunction([ "FunctionExpression", "ArrowFunctionExpression", @@ -269,10 +241,6 @@ function isAngularTestWrapper(node) { ); } -/** - * @param {Node} node - * @returns {boolean} - */ const isJsxElement = createTypeCheckFunction(["JSXElement", "JSXFragment"]); function isGetterOrSetter(node) { @@ -314,10 +282,6 @@ function isTypeAnnotationAFunction(node) { ); } -/** - * @param {Node} node - * @returns {boolean} - */ const isBinaryish = createTypeCheckFunction([ "BinaryExpression", "LogicalExpression", @@ -438,23 +402,22 @@ function isTestCall(node, parent) { return false; } -/** - * @param {Node} node - * @returns {boolean} - */ -const isCallExpression = createTypeCheckFunction([ - "CallExpression", - "OptionalCallExpression", -]); +/** @return {(node: Node) => boolean} */ +const skipChainExpression = (fn) => (node) => { + if (node?.type === "ChainExpression") { + node = node.expression; + } -/** - * @param {Node} node - * @returns {boolean} - */ -const isMemberExpression = createTypeCheckFunction([ - "MemberExpression", - "OptionalMemberExpression", -]); + return fn(node); +}; + +const isCallExpression = skipChainExpression( + createTypeCheckFunction(["CallExpression", "OptionalCallExpression"]), +); + +const isMemberExpression = skipChainExpression( + createTypeCheckFunction(["MemberExpression", "OptionalMemberExpression"]), +); /** * @@ -717,7 +680,7 @@ function isFunctionCompositionArgs(args) { return true; } } else if (isCallExpression(arg)) { - for (const childArg of arg.arguments) { + for (const childArg of getCallArguments(arg)) { if (isFunctionOrArrowExpression(childArg)) { return true; } @@ -1050,6 +1013,10 @@ function getCallArguments(node) { return callArgumentsCache.get(node); } + if (node.type === "ChainExpression") { + return getCallArguments(node.expression); + } + let args = node.arguments; if (node.type === "ImportExpression") { args = [node.source]; @@ -1071,6 +1038,14 @@ function getCallArguments(node) { function iterateCallArgumentsPath(path, iteratee) { const { node } = path; + + if (node.type === "ChainExpression") { + return path.call( + () => iterateCallArgumentsPath(path, iteratee), + "expression", + ); + } + if (node.type === "ImportExpression") { path.call((sourcePath) => iteratee(sourcePath, 0), "source"); @@ -1089,17 +1064,22 @@ function iterateCallArgumentsPath(path, iteratee) { } function getCallArgumentSelector(node, index) { + const selectors = []; + if (node.type === "ChainExpression") { + selectors.push("expression"); + } + if (node.type === "ImportExpression") { if (index === 0 || index === (node.attributes || node.options ? -2 : -1)) { - return "source"; + return [...selectors, "source"]; } // import attributes if (node.attributes && (index === 1 || index === -1)) { - return "attributes"; + return [...selectors, "attributes"]; } // deprecated import assertions if (node.options && (index === 1 || index === -1)) { - return "options"; + return [...selectors, "options"]; } throw new RangeError("Invalid argument index"); } @@ -1110,7 +1090,7 @@ function getCallArgumentSelector(node, index) { if (index < 0 || index >= node.arguments.length) { throw new RangeError("Invalid argument index"); } - return ["arguments", index]; + return [...selectors, "arguments", index]; } function isPrettierIgnoreComment(comment) {
diff --git a/tests/format/js/chain-expression/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/chain-expression/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/js/chain-expression/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/chain-expression/__snapshots__/jsfmt.spec.js.snap @@ -1,5 +1,86 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP +exports[`issue-15785-1.js format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript", "flow"] +printWidth: 80 + | printWidth +=====================================input====================================== +function someFunctionName( + someLongBreakingParameterName, + anotherLongParameterName, +) { + return isEqual(a?.map(([t, _]) => t?.id), b?.map(([t, _]) => t?.id)); + return isEqual(a.map(([t, _]) => t?.id), b.map(([t, _]) => t?.id)); +} + + +=====================================output===================================== +function someFunctionName( + someLongBreakingParameterName, + anotherLongParameterName, +) { + return isEqual( + a?.map(([t, _]) => t?.id), + b?.map(([t, _]) => t?.id), + ); + return isEqual( + a.map(([t, _]) => t?.id), + b.map(([t, _]) => t?.id), + ); +} + +================================================================================ +`; + +exports[`issue-15785-2.js format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript", "flow"] +printWidth: 80 + | printWidth +=====================================input====================================== +const theValue = Object.entries(someLongObjectName).filter( + ([listingId]) => someListToCompareToHere?.includes(listingId), +); +const theValue2 = Object.entries(someLongObjectName).filter( + ([listingId]) => someListToCompareToHere.includes(listingId), +); + +=====================================output===================================== +const theValue = Object.entries(someLongObjectName).filter(([listingId]) => + someListToCompareToHere?.includes(listingId), +); +const theValue2 = Object.entries(someLongObjectName).filter(([listingId]) => + someListToCompareToHere.includes(listingId), +); + +================================================================================ +`; + +exports[`issue-15785-3.js format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript", "flow"] +printWidth: 80 + | printWidth +=====================================input====================================== +logger.log( + \`A long template string with a conditional: \${channel?.id}, and then some more content that continues until \${JSON.stringify(location)}\` +); +logger.log( + \`A long template string with a conditional: \${channel.id}, and then some more content that continues until \${JSON.stringify(location)}\` +); + +=====================================output===================================== +logger.log( + \`A long template string with a conditional: \${channel?.id}, and then some more content that continues until \${JSON.stringify(location)}\`, +); +logger.log( + \`A long template string with a conditional: \${channel.id}, and then some more content that continues until \${JSON.stringify(location)}\`, +); + +================================================================================ +`; + exports[`test.js format 1`] = ` ====================================options===================================== parsers: ["babel", "typescript", "flow"] @@ -27,3 +108,111 @@ new (a?.())(); ================================================================================ `; + +exports[`test-2.js format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript", "flow"] +printWidth: 80 + | printWidth +=====================================input====================================== +{{{{ + const [lastCommittedX, lastCommittedY] = + multiElement?.lastCommittedPoint ?? [0, 0]; +}}}} + +=====================================output===================================== +{ + { + { + { + const [lastCommittedX, lastCommittedY] = + multiElement?.lastCommittedPoint ?? [0, 0]; + } + } + } +} + +================================================================================ +`; + +exports[`test-3.js format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript", "flow"] +printWidth: 80 + | printWidth +=====================================input====================================== +function getLanguageByInterpreter(languages, file) { + return languages.find((language) => language.interpreters?.includes(interpreter), + ); + return languages.find((language) =>language.interpreters.includes(interpreter), + ); +} + +=====================================output===================================== +function getLanguageByInterpreter(languages, file) { + return languages.find((language) => + language.interpreters?.includes(interpreter), + ); + return languages.find((language) => + language.interpreters.includes(interpreter), + ); +} + +================================================================================ +`; + +exports[`test-4.js format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript", "flow"] +printWidth: 80 + | printWidth +=====================================input====================================== +// https://github.com/marmelab/react-admin/blob/8c1ddfeb4e011a94609d709c0f4f139fb5d480e8/packages/ra-data-localstorage/src/index.ts#L112 +export default (params) => { + return { + updateMany: (resource, params) => { + updateLocalStorage(() => { + params.ids.forEach(id => { + const index = data.data.data.data.data[resource]?.findIndex( + record => record.id == id + ); + const index2 = data.data.data.data.data[resource].findIndex( + record => record.id == id + ); + data[resource][index] = { + ...data[resource][index], + ...params.data, + }; + }); + }); + return baseDataProvider.updateMany(resource, params); + }, + } +} + +=====================================output===================================== +// https://github.com/marmelab/react-admin/blob/8c1ddfeb4e011a94609d709c0f4f139fb5d480e8/packages/ra-data-localstorage/src/index.ts#L112 +export default (params) => { + return { + updateMany: (resource, params) => { + updateLocalStorage(() => { + params.ids.forEach((id) => { + const index = data.data.data.data.data[resource]?.findIndex( + (record) => record.id == id, + ); + const index2 = data.data.data.data.data[resource].findIndex( + (record) => record.id == id, + ); + data[resource][index] = { + ...data[resource][index], + ...params.data, + }; + }); + }); + return baseDataProvider.updateMany(resource, params); + }, + }; +}; + +================================================================================ +`; diff --git a/tests/format/js/chain-expression/issue-15785-1.js b/tests/format/js/chain-expression/issue-15785-1.js new file mode 100644 --- /dev/null +++ b/tests/format/js/chain-expression/issue-15785-1.js @@ -0,0 +1,8 @@ +function someFunctionName( + someLongBreakingParameterName, + anotherLongParameterName, +) { + return isEqual(a?.map(([t, _]) => t?.id), b?.map(([t, _]) => t?.id)); + return isEqual(a.map(([t, _]) => t?.id), b.map(([t, _]) => t?.id)); +} + diff --git a/tests/format/js/chain-expression/issue-15785-2.js b/tests/format/js/chain-expression/issue-15785-2.js new file mode 100644 --- /dev/null +++ b/tests/format/js/chain-expression/issue-15785-2.js @@ -0,0 +1,6 @@ +const theValue = Object.entries(someLongObjectName).filter( + ([listingId]) => someListToCompareToHere?.includes(listingId), +); +const theValue2 = Object.entries(someLongObjectName).filter( + ([listingId]) => someListToCompareToHere.includes(listingId), +); diff --git a/tests/format/js/chain-expression/issue-15785-3.js b/tests/format/js/chain-expression/issue-15785-3.js new file mode 100644 --- /dev/null +++ b/tests/format/js/chain-expression/issue-15785-3.js @@ -0,0 +1,6 @@ +logger.log( + `A long template string with a conditional: ${channel?.id}, and then some more content that continues until ${JSON.stringify(location)}` +); +logger.log( + `A long template string with a conditional: ${channel.id}, and then some more content that continues until ${JSON.stringify(location)}` +); diff --git a/tests/format/js/chain-expression/test-2.js b/tests/format/js/chain-expression/test-2.js new file mode 100644 --- /dev/null +++ b/tests/format/js/chain-expression/test-2.js @@ -0,0 +1,4 @@ +{{{{ + const [lastCommittedX, lastCommittedY] = + multiElement?.lastCommittedPoint ?? [0, 0]; +}}}} diff --git a/tests/format/js/chain-expression/test-3.js b/tests/format/js/chain-expression/test-3.js new file mode 100644 --- /dev/null +++ b/tests/format/js/chain-expression/test-3.js @@ -0,0 +1,6 @@ +function getLanguageByInterpreter(languages, file) { + return languages.find((language) => language.interpreters?.includes(interpreter), + ); + return languages.find((language) =>language.interpreters.includes(interpreter), + ); +} diff --git a/tests/format/js/chain-expression/test-4.js b/tests/format/js/chain-expression/test-4.js new file mode 100644 --- /dev/null +++ b/tests/format/js/chain-expression/test-4.js @@ -0,0 +1,22 @@ +// https://github.com/marmelab/react-admin/blob/8c1ddfeb4e011a94609d709c0f4f139fb5d480e8/packages/ra-data-localstorage/src/index.ts#L112 +export default (params) => { + return { + updateMany: (resource, params) => { + updateLocalStorage(() => { + params.ids.forEach(id => { + const index = data.data.data.data.data[resource]?.findIndex( + record => record.id == id + ); + const index2 = data.data.data.data.data[resource].findIndex( + record => record.id == id + ); + data[resource][index] = { + ...data[resource][index], + ...params.data, + }; + }); + }); + return baseDataProvider.updateMany(resource, params); + }, + } +} diff --git a/tests/format/typescript/chain-expression/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/chain-expression/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/typescript/chain-expression/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/typescript/chain-expression/__snapshots__/jsfmt.spec.js.snap @@ -19,3 +19,42 @@ printWidth: 80 ================================================================================ `; + +exports[`test2.ts format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +{{ + const rotation1 = getTransformHandles(arrow, h.state.zoom, 'mouse') + .rotation!; + const rotation2 = getTransformHandles(arrow, h.state.zoom, 'mouse') + .rotation; + const rotation3 = getTransformHandles(arrow, h.state.zoom, 'mouse') + ?.rotation; +}} + +=====================================output===================================== +{ + { + const rotation1 = getTransformHandles( + arrow, + h.state.zoom, + "mouse", + ).rotation!; + const rotation2 = getTransformHandles( + arrow, + h.state.zoom, + "mouse", + ).rotation; + const rotation3 = getTransformHandles( + arrow, + h.state.zoom, + "mouse", + )?.rotation; + } +} + +================================================================================ +`; diff --git a/tests/format/typescript/chain-expression/test2.ts b/tests/format/typescript/chain-expression/test2.ts new file mode 100644 --- /dev/null +++ b/tests/format/typescript/chain-expression/test2.ts @@ -0,0 +1,8 @@ +{{ + const rotation1 = getTransformHandles(arrow, h.state.zoom, 'mouse') + .rotation!; + const rotation2 = getTransformHandles(arrow, h.state.zoom, 'mouse') + .rotation; + const rotation3 = getTransformHandles(arrow, h.state.zoom, 'mouse') + ?.rotation; +}}
Different output for optional call/member expression using `typescript` parser vs `babel` and `babel-ts` **Prettier 3.1.1** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEB6VACAwgQQMoCiGAjEgDpToYByEATgLYCGANhgEZwAWTAbgJb0ANBhhc4GAAb8AzgQCOAV1aSMYVm3Z04TANYyAdBQBmiqGBiCoGGRAZwAYmYtXqTewAoKGG3bgAZaABzACFtPX4oIIAFJjp3OHg6N3shbwwmKAgxODpAqNj4+ySUuDSoAEoMYHTtGEU6a1kFZRYPJgNmAAcPDwBtGBEAfQBdKoBeAD5RAH4DfgATCpF2TqYe-sGMUYnpmDnFioqAbgoAXwoKKgB1cWsmMDA4GRlRCCkmVUyFqXZVWQwEC6lmgrBEMAAnl1nmA6PxgRgFhBnlAAOQwDjhXRXTA5NQaFaKDHsJicNjfDikuAsAC0MFeSKMUFM5hB1ls9icrNcCS81l89nyoSxkRicQSJQS5R8mWy4jywUKEtypXKVRq-LqDSaciUrHac26vQGwzGGCms3mSxWhvWxq2O3NewOSxO50ulEwuEIGAATORPTR6MxNNw+II6ODxFJjPwWElVOoWGxFDJnhkMEE6BBFNCfiwmBCcxiPF0ia8cjiMnRswB3DBwAAeXW0LysGC64uKuVe0FE0ZkCQwLEiEiYrzIIFj8dyk4qTMgUBkGJyADVWIoJOMMAB5dgAKzgFgMCBgcOeHg5AWCe8PFlK8+nST5Pn6I+XooAkgszRar-5ZBgAAVCAsDsTttBAgAJXI4HmcwWEUBYL3fSwom-ZYKDdKAq2ufgxAyawgTZVgMHsBhODoBtm1bGQrBWKlaXpDBdDgOAugrLgAXHDMsxzPMqwLIsiUJFcoRhOEETMPjc1efDAVgd4mAwKA4HrEdVIXaBl37OB10QrddwPI8YBPWBzxkS8-CFW8TIfAwn1yF8MDfQCvx-XYBQCQCQLAhgILgaDYIOBCkJQtz0OtLDThwwNvSIABmAMqFoRhSM4HgBGEXTRDgfyC3gaiW2eOi+y0HR9AyFdo1jOgdMiJIuggAqrCZFgICCIJcgMdqgmcyQcGHYJcvyphCuXOEogwWt8K4DNFwWfCrFYJAMAAEmAMAeCgVSWCtM4RApHJ2T8Mj6AkRd4FgfsxrUaA0M3V4zEsNgNoAKTwHdqAMCbRX4YwIQ8dr1DZCozkkaKPRuWbCMBYFlrYcjKKK2j6NEcSZFheEMSRFF0UxCqctq5cqwa3ImpavsKUiZcdB+cq9E4iQ0wWtqOq6ugeo6-rBvaqb4FG8az1FaaYeUhaltBFhVo2rbMl2l0DsIn5jq8s7tDu2BTxujFLsiR6MGeuN1uAD6vp+4Won+wHgbGqwwYhypjhAIQQGIqwZGQUA4jrQoEE9lBWFrQtPddrQHlYmA8ASADVOQYxWDTMP4jASO8E7MBRWQM9N1dtMGH4bO6FzkAm2hOF7FgVggNyKA4n4Z548TsoQDoqIWDgABFRRsjgJuWCTkB9xkRs8FFDvu97-vB6UXvomzDjkBAccaVUuBkIWF2QDPJg41FPzmCXjQt7boIO5wGBhfYIk4GiXJY77pAE4HluuBgBgWFufDngzuA8H9paAhIRLzAC8LevBNyfigMhWAeAsbAhwNAvAkIO7Txbi2CAaZrjxC6EvYqaY6C8D7q7GmuQYDzyYEEQ+T9m6uwggQpeJIyRb20Eofg2gKFUKYGg12MBSR4QWGIZAvpXapkCqSAOz9B55U4AsDe-hMhBGUF1BwwYxpoSCEfIkEAt4tgagIoRSBiC+gAAxnDOEAA) <!-- prettier-ignore --> ```sh --parser babel --print-width 120 ``` **Input:** <!-- prettier-ignore --> ```jsx // CASE 1: // Normal behavior, the `isEqual` call breaks. function someFunctionName( someLongBreakingParameterName, anotherLongParameterName, ) { return isEqual(a.map(([t, _]) => t?.id), b.map(([t, _]) => t?.id)); } // When access to `a` and `b` is optional, typescript doesn't break // the call, but babel and babel-ts do. function someFunctionName( someLongBreakingParameterName, anotherLongParameterName, ) { return isEqual(a?.map(([t, _]) => t?.id), b?.map(([t, _]) => t?.id)); } // CASE 2: // Normal behavior, the `filter` call uses a grouped layout (puts the // arrow expression parameters on the same line as "filter"). const theValue = Object.entries(someLongObjectName).filter( ([listingId]) => someListToCompareToHere.includes(listingId), ); // With an optional member expression, babel-ts keeps this as a grouped // layout, but typescript ungroups it onto a new line. const theValue = Object.entries(someLongObjectName).filter( ([listingId]) => someListToCompareToHere?.includes(listingId), ); // CASE 3: // Normal behavior, the template expression breaks at the first interpolation. logger.log( `A long template string with a conditional: ${channel.id}, and then some more content that continues until ${JSON.stringify(location)}` ); // With an optional member expression, typescript doesn't break the first // interpolation and instead breaks the second. logger.log( `A long template string with a conditional: ${channel?.id}, and then some more content that continues until ${JSON.stringify(location)}` ); ``` **Output:** <!-- prettier-ignore --> ```jsx // CASE 1: // Normal behavior, the `isEqual` call breaks. function someFunctionName(someLongBreakingParameterName, anotherLongParameterName) { return isEqual( a.map(([t, _]) => t?.id), b.map(([t, _]) => t?.id), ); } // When access to `a` and `b` is optional, typescript doesn't break // the call, but babel and babel-ts do. function someFunctionName(someLongBreakingParameterName, anotherLongParameterName) { return isEqual( a?.map(([t, _]) => t?.id), b?.map(([t, _]) => t?.id), ); } // CASE 2: // Normal behavior, the `filter` call uses a grouped layout (puts the // arrow expression parameters on the same line as "filter"). const theValue = Object.entries(someLongObjectName).filter(([listingId]) => someListToCompareToHere.includes(listingId), ); // With an optional member expression, babel-ts keeps this as a grouped // layout, but typescript ungroups it onto a new line. const theValue = Object.entries(someLongObjectName).filter(([listingId]) => someListToCompareToHere?.includes(listingId), ); // CASE 3: // Normal behavior, the template expression breaks at the first interpolation. logger.log( `A long template string with a conditional: ${ channel.id }, and then some more content that continues until ${JSON.stringify(location)}`, ); // With an optional member expression, typescript doesn't break the first // interpolation and instead breaks the second. logger.log( `A long template string with a conditional: ${ channel?.id }, and then some more content that continues until ${JSON.stringify(location)}`, ); ``` **Expected behavior:** The output from each of these 3 cases should match regardless of which parser is used (`babel`, `babel-ts`, or `typescript`). The consistent difference here is whether the expression is `optional` or not. Inspecting the parsed ASTs, Babel (and thus babel-ts) parses these as distinct node types (`OptionalCallExpression` and `OptionalMemberExpression`), but the TypeScript parser just uses the plain `CallExpression` and `MemberExpression` nodes with an extra `optional` property on them. From https://github.com/prettier/prettier/issues/10244, it seems like maybe in the past (or in a different situation), these were parsed as `ChainExpression`, which then got transformed by Prettier into the appropriate optional expression nodes, but that is no longer the case, so the transform doesn't pick them up and convert as needed.
As an additional note, it looks like the parser hierarchy is set up to prefer `typescript` first and then use `babel-ts` otherwise: https://github.com/prettier/prettier/blob/c1ebae2e8303841e59bc02e9e719a93e964ab0e9/src/language-js/languages.evaluate.js#L61. I wonder if preferring `babel-ts` first would make sense, though, since that's already true for regular js, and it would mean more consistent parsing to match it. Obviously TypeScript itself is the best source of truth, but the potential differences in the AST over time will lead to this kind of drift and might be avoidable by using the same parser when possible. For CASE1, it probably comes from here. https://github.com/prettier/prettier/blob/1d45bce62575cc4415225545a4d6941f9b91748a/src/language-js/utils/index.js#L718 To find anonymous function in argument, it only checks CallExpression and OptionalCallExpression. However, for TypeScript ESTree, expression like `a?.map(([t, _]) => t?.id)` is not CallExpression nor OptionalCallExpression, but ChainExpression, that has CallExpression as a child ([playground](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAjA-AOgLYEMAOAFIQNowA0ABAPoC6AlJQLwB8lMWAlgCb0A6UEORAR8MTtADOyULgBOciAHcACvITSUuADZLcAT2nDUc3GADWcGAGVc2OABlOUOMgBmOyXGOmLV6-hmzgDmyDByAK7eIF7YnGGR0XAAHvhwcpz2sDoAKulQ8pxwmh7aXsKSIdpwAIoREPDuntEAVpLJ1lW19Y1IpeUgAI49cCqK+JoguJIAtC5w3AtCIOG4nNohAMIQ2HjIU9ray5VQwdUAgjDhnKgR8CrpTi5NZdEAFjDY2gDqb5zwkkCYDg1g0-04ADd-vp9mBJEYQBCogBJKCLWDWMAZMTnNHWGD6aovAb4RReb6mfD7UnFdIQ1zCZxeOQwMa4YJ7PrNYSBOTM-YEtKSLGcMTLUnOGDfHgwN7IACMACYAAzCORwYacdVsjm4YnRGC4VDS7iy5CK4QRLw5I0lbkgODYVALRbcBy4U4RdlwABiEDkeCuIX2uDuEBAAF8I0A)). Perhaps `isCallExpression` can cause other similar inconsistencies. Edit: A similar case looks handled well: https://github.com/prettier/prettier/blob/eebf0e4b5ec8ac24393c56ced4b4819d4c551f31/src/language-js/print/assignment.js#L352
"2023-12-15T05:58:37Z"
3.2
[]
[ "tests/format/js/chain-expression/jsfmt.spec.js", "tests/format/typescript/chain-expression/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEB6VACAwgQQMoCiGAjEgDpToYByEATgLYCGANhgEZwAWTAbgJb0ANBhhc4GAAb8AzgQCOAV1aSMYVm3Z04TANYyAdBQBmiqGBiCoGGRAZwAYmYtXqTewAoKGG3bgAZaABzACFtPX4oIIAFJjp3OHg6N3shbwwmKAgxODpAqNj4+ySUuDSoAEoMYHTtGEU6a1kFZRYPJgNmAAcPDwBtGBEAfQBdKoBeAD5RAH4DfgATCpF2TqYe-sGMUYnpmDnFioqAbgoAXwoKKgB1cWsmMDA4GRlRCCkmVUyFqXZVWQwEC6lmgrBEMAAnl1nmA6PxgRgFhBnlAAOQwDjhXRXTA5NQaFaKDHsJicNjfDikuAsAC0MFeSKMUFM5hB1ls9icrNcCS81l89nyoSxkRicQSJQS5R8mWy4jywUKEtypXKVRq-LqDSaciUrHac26vQGwzGGCms3mSxWhvWxq2O3NewOSxO50ulEwuEIGAATORPTR6MxNNw+II6ODxFJjPwWElVOoWGxFDJnhkMEE6BBFNCfiwmBCcxiPF0ia8cjiMnRswB3DBwAAeXW0LysGC64uKuVe0FE0ZkCQwLEiEiYrzIIFj8dyk4qTMgUBkGJyADVWIoJOMMAB5dgAKzgFgMCBgcOeHg5AWCe8PFlK8+nST5Pn6I+XooAkgszRar-5ZBgAAVCAsDsTttBAgAJXI4HmcwWEUBYL3fSwom-ZYKDdKAq2ufgxAyawgTZVgMHsBhODoBtm1bGQrBWKlaXpDBdDgOAugrLgAXHDMsxzPMqwLIsiUJFcoRhOEETMPjc1efDAVgd4mAwKA4HrEdVIXaBl37OB10QrddwPI8YBPWBzxkS8-CFW8TIfAwn1yF8MDfQCvx-XYBQCQCQLAhgILgaDYIOBCkJQtz0OtLDThwwNvSIABmAMqFoRhSM4HgBGEXTRDgfyC3gaiW2eOi+y0HR9AyFdo1jOgdMiJIuggAqrCZFgICCIJcgMdqgmcyQcGHYJcvyphCuXOEogwWt8K4DNFwWfCrFYJAMAAEmAMAeCgVSWCtM4RApHJ2T8Mj6AkRd4FgfsxrUaA0M3V4zEsNgNoAKTwHdqAMCbRX4YwIQ8dr1DZCozkkaKPRuWbCMBYFlrYcjKKK2j6NEcSZFheEMSRFF0UxCqctq5cqwa3ImpavsKUiZcdB+cq9E4iQ0wWtqOq6ugeo6-rBvaqb4FG8az1FaaYeUhaltBFhVo2rbMl2l0DsIn5jq8s7tDu2BTxujFLsiR6MGeuN1uAD6vp+4Won+wHgbGqwwYhypjhAIQQGIqwZGQUA4jrQoEE9lBWFrQtPddrQHlYmA8ASADVOQYxWDTMP4jASO8E7MBRWQM9N1dtMGH4bO6FzkAm2hOF7FgVggNyKA4n4Z548TsoQDoqIWDgABFRRsjgJuWCTkB9xkRs8FFDvu97-vB6UXvomzDjkBAccaVUuBkIWF2QDPJg41FPzmCXjQt7boIO5wGBhfYIk4GiXJY77pAE4HluuBgBgWFufDngzuA8H9paAhIRLzAC8LevBNyfigMhWAeAsbAhwNAvAkIO7Txbi2CAaZrjxC6EvYqaY6C8D7q7GmuQYDzyYEEQ+T9m6uwggQpeJIyRb20Eofg2gKFUKYGg12MBSR4QWGIZAvpXapkCqSAOz9B55U4AsDe-hMhBGUF1BwwYxpoSCEfIkEAt4tgagIoRSBiC+gAAxnDOEAA" ]
prettier/prettier
15,826
prettier__prettier-15826
[ "15168", "13677" ]
ff9c0839ac618f0cdd10462bfd1d380da43d52e6
diff --git a/src/language-js/comments/handle-comments.js b/src/language-js/comments/handle-comments.js --- a/src/language-js/comments/handle-comments.js +++ b/src/language-js/comments/handle-comments.js @@ -21,7 +21,6 @@ import { isObjectProperty, isPrettierIgnoreComment, isUnionType, - markerForIfWithoutBlockAndSameLineComment, } from "../utils/index.js"; import isBlockComment from "../utils/is-block-comment.js"; import isTypeCastComment from "../utils/is-type-cast-comment.js"; @@ -202,7 +201,7 @@ function handleIfStatementComments({ addTrailingComment(precedingNode, comment); } else { const isSingleLineComment = - comment.type === "SingleLine" || + isLineComment(comment) || comment.loc.start.line === comment.loc.end.line; const isSameLineComment = comment.loc.start.line === precedingNode.loc.start.line; @@ -211,13 +210,7 @@ function handleIfStatementComments({ // if (cond1) expr1; // comment A // else if (cond2) expr2; // comment A // else expr3; - addDanglingComment( - precedingNode, - comment, - precedingNode.type === "ExpressionStatement" - ? markerForIfWithoutBlockAndSameLineComment - : undefined, - ); + addTrailingComment(precedingNode, comment); } else { addDanglingComment(enclosingNode, comment); } diff --git a/src/language-js/print/estree.js b/src/language-js/print/estree.js --- a/src/language-js/print/estree.js +++ b/src/language-js/print/estree.js @@ -371,12 +371,12 @@ function printEstree(path, options, print, args) { adjustClause(node.body, print("body")), ]); case "IfStatement": { - const con = adjustClause(node.consequent, print("consequent")); + const consequent = adjustClause(node.consequent, print("consequent")); const opening = group([ "if (", group([indent([softline, print("test")]), softline]), ")", - con, + consequent, ]); parts.push(opening); diff --git a/src/language-js/print/expression-statement.js b/src/language-js/print/expression-statement.js --- a/src/language-js/print/expression-statement.js +++ b/src/language-js/print/expression-statement.js @@ -1,9 +1,3 @@ -import { printDanglingComments } from "../../main/comments/print.js"; -import { - CommentCheckFlags, - hasComment, - markerForIfWithoutBlockAndSameLineComment, -} from "../utils/index.js"; import { isSingleJsxExpressionStatementInMarkdown, isSingleVueEventBindingExpressionStatement, @@ -23,21 +17,6 @@ function printExpressionStatement(path, options, print) { parts.push(";"); } - if ( - hasComment( - path.node, - CommentCheckFlags.Dangling, - ({ marker }) => marker === markerForIfWithoutBlockAndSameLineComment, - ) - ) { - parts.push( - " ", - printDanglingComments(path, options, { - marker: markerForIfWithoutBlockAndSameLineComment, - }), - ); - } - return parts; } diff --git a/src/language-js/utils/index.js b/src/language-js/utils/index.js --- a/src/language-js/utils/index.js +++ b/src/language-js/utils/index.js @@ -1197,13 +1197,6 @@ function isObjectProperty(node) { ); } -/** - * This is used as a marker for dangling comments. - */ -const markerForIfWithoutBlockAndSameLineComment = Symbol( - "ifWithoutBlockAndSameLineComment", -); - const isBinaryCastExpression = createTypeCheckFunction([ // TS "TSAsExpression", @@ -1284,7 +1277,6 @@ export { isUnionType, iterateCallArgumentsPath, iterateFunctionParametersPath, - markerForIfWithoutBlockAndSameLineComment, needsHardlineAfterDanglingComment, rawText, shouldFlatten,
diff --git a/tests/config/format-test.js b/tests/config/format-test.js --- a/tests/config/format-test.js +++ b/tests/config/format-test.js @@ -46,6 +46,7 @@ const unstableTests = new Map( "jsx/comments/in-attributes.js", ["js/ignore/semi/asi.js", (options) => options.semi === false], "typescript/union/consistent-with-flow/single-type.ts", + "js/if/non-block.js", ].map((fixture) => { const [file, isUnstable = () => true] = Array.isArray(fixture) ? fixture diff --git a/tests/format/js/if/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/if/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/js/if/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/if/__snapshots__/jsfmt.spec.js.snap @@ -123,25 +123,28 @@ function a() { if (a) throw e; /* comment 6d */ else return 2; - // TODO[@fisker]: fix this - // if (a) var a = 1; /* comment 6e */ - // else return 2; + if (a) var a = 1; /* comment 6e */ + else return 2; if (a) if (b); /* comment 6f */ else return 2; } =====================================output===================================== -if (a === 0) doSomething(); // comment A1 -else if (a === 1) doSomethingElse(); // comment B1 +if (a === 0) + doSomething(); // comment A1 +else if (a === 1) + doSomethingElse(); // comment B1 else if (a === 2) doSomethingElse(); // comment C1 if (a === 0) doSomething(); /* comment A2 */ else if (a === 1) doSomethingElse(); /* comment B2 */ else if (a === 2) doSomethingElse(); /* comment C2 */ -if (a === 0) expr; // comment A3 -else if (a === 1) expr; // comment B3 +if (a === 0) + expr; // comment A3 +else if (a === 1) + expr; // comment B3 else if (a === 2) expr; // comment C3 if (a === 0) expr; /* comment A4 */ @@ -156,18 +159,17 @@ else if (a === 2) looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // comment C5 function a() { - if (a) return /* comment 6a */; + if (a) return; /* comment 6a */ else return 2; - if (a) return 1 /* comment 6b */; + if (a) return 1; /* comment 6b */ else return 2; - if (a) throw e /* comment 6d */; + if (a) throw e; /* comment 6d */ else return 2; - // TODO[@fisker]: fix this - // if (a) var a = 1; /* comment 6e */ - // else return 2; + if (a) var a = 1; /* comment 6e */ + else return 2; if (a) if (b /* comment 6f */); @@ -294,6 +296,71 @@ async function f5() { ================================================================================ `; +exports[`issue-15168.js format 1`] = ` +====================================options===================================== +parsers: ["babel", "flow", "typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +for (const division of collidingDivisions) { + if (!division.properties.canRemove) { + if (division.canContainSingleParagraph(startParagraph)) continue; // selection starting in r/o div: always OK to delete + else if (endParagraph !== division.endParagraph && division.canContainSingleParagraph(endParagraph)) continue; // selection ending in r/o div: OK to delete IF it is NOT last paragraph (which would get absorbed) + else { // selection over whole r/o div OR ending in last paragraph (which would get absorbed) -> FAIL + console.warn('deleteSelectedTextAndJoinRemainingNodes(): cannot delete because of must-keep division: ' + division.properties.name); + } + } +} + +=====================================output===================================== +for (const division of collidingDivisions) { + if (!division.properties.canRemove) { + if (division.canContainSingleParagraph(startParagraph)) + continue; // selection starting in r/o div: always OK to delete + else if ( + endParagraph !== division.endParagraph && + division.canContainSingleParagraph(endParagraph) + ) + continue; // selection ending in r/o div: OK to delete IF it is NOT last paragraph (which would get absorbed) + else { + // selection over whole r/o div OR ending in last paragraph (which would get absorbed) -> FAIL + console.warn( + "deleteSelectedTextAndJoinRemainingNodes(): cannot delete because of must-keep division: " + + division.properties.name, + ); + } + } +} + +================================================================================ +`; + +exports[`non-block.js format 1`] = ` +====================================options===================================== +parsers: ["babel", "flow", "typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +if (foo) for (i = 2; i > 0; i--) console.log(i); // foo +else bar(); + +if (foo) do { console.log(i) } while(i--) // foo +else bar(); + +=====================================output===================================== +if (foo) + for (i = 2; i > 0; i--) console.log(i); // foo +else bar(); + +if (foo) + do { + console.log(i); + } while (i--); // foo +else bar(); + +================================================================================ +`; + exports[`trailing_comment.js format 1`] = ` ====================================options===================================== parsers: ["babel", "flow", "typescript"] diff --git a/tests/format/js/if/expr_and_same_line_comments.js b/tests/format/js/if/expr_and_same_line_comments.js --- a/tests/format/js/if/expr_and_same_line_comments.js +++ b/tests/format/js/if/expr_and_same_line_comments.js @@ -28,9 +28,8 @@ function a() { if (a) throw e; /* comment 6d */ else return 2; - // TODO[@fisker]: fix this - // if (a) var a = 1; /* comment 6e */ - // else return 2; + if (a) var a = 1; /* comment 6e */ + else return 2; if (a) if (b); /* comment 6f */ else return 2; diff --git a/tests/format/js/if/issue-15168.js b/tests/format/js/if/issue-15168.js new file mode 100644 --- /dev/null +++ b/tests/format/js/if/issue-15168.js @@ -0,0 +1,9 @@ +for (const division of collidingDivisions) { + if (!division.properties.canRemove) { + if (division.canContainSingleParagraph(startParagraph)) continue; // selection starting in r/o div: always OK to delete + else if (endParagraph !== division.endParagraph && division.canContainSingleParagraph(endParagraph)) continue; // selection ending in r/o div: OK to delete IF it is NOT last paragraph (which would get absorbed) + else { // selection over whole r/o div OR ending in last paragraph (which would get absorbed) -> FAIL + console.warn('deleteSelectedTextAndJoinRemainingNodes(): cannot delete because of must-keep division: ' + division.properties.name); + } + } +} diff --git a/tests/format/js/if/non-block.js b/tests/format/js/if/non-block.js new file mode 100644 --- /dev/null +++ b/tests/format/js/if/non-block.js @@ -0,0 +1,5 @@ +if (foo) for (i = 2; i > 0; i--) console.log(i); // foo +else bar(); + +if (foo) do { console.log(i) } while(i--) // foo +else bar();
Comment in `IfStatement` not printed. **Prettier 3.0.0** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAzArlMMCW0AEAhgBQCU+wAOlPvjqvsYeQG6EBO+Y+AvPgIz4A9ACouEALYSEMfADZC+EUIDc1WnAA2AZzj52cGOnY0ATGqgBfEABoQEAA65o25KA7sIAdwAKHBK4ohJpehACernYARuyEYADWhgDKhNIAMjhQcMiowbrRsQnJDnGZAObIMOzocHa6EjiV1bUg2uWacACK6BDwOXktAFbaAB5J7V09fUi5Oi0AjlNwPp4OgSCE2gC0WXAAJvu2IFWEOJrlAMKSEoTIG5qaR21QZR0AgjBVOFHo8D5w7AyWX6czsAAsYBJNAB1ME4eDaEpgOBJALwnAseFhO5gbSREAsGoASSgB1gSTA7BwTjepKSMDCHRB+RADk8umhsQcdzZcF07BY2TsmX5MBWhDKN2ZLRK7H5dyihCiWiObMyMGhOD2MDByAAHAAGOwGRY4AziyW3GYDOwwJWa7W6pCmOzoXQAFSVgVmLLgEmVewOezShBe6AlcAAYhB2DdPuU7oRfhAQJZLEA) <!-- prettier-ignore --> ```sh --parser babel ``` **Input:** <!-- prettier-ignore --> ```jsx function a() { if (a) var c = 1 /* comment 6a */; else return 2; } ``` **Output:** <!-- prettier-ignore --> ```jsx Error: Comment "comment 6a" was not printed. Please report this error! at pu (https://prettier.io/lib/standalone.js:27:5829) at Ze (https://prettier.io/lib/standalone.js:27:7320) at async Ou (https://prettier.io/lib/standalone.js:27:11026) at async Rr (https://prettier.io/lib/standalone.js:32:581) at async formatCode (https://prettier.io/worker.js:170:12) at async handleFormatMessage (https://prettier.io/worker.js:82:24) at async self.onmessage (https://prettier.io/worker.js:37:14) ``` **Expected behavior:** See https://github.com/prettier/prettier/pull/15076#discussion_r1259242307 fix: Print dangling comments for `break|continue|debugger` ## Description <!-- Please provide a brief summary of your changes: --> Some comments after `break|continue|debugger` cannot be printed. Fixes #12655 ## Checklist <!-- Please ensure you’ve done all of these things (if applicable). --> <!-- You can replace the `[ ]` with `[x]` to mark each task as done. --> - [x] I’ve added tests to confirm my change works. - [ ] (If changing the API or CLI) I’ve documented the changes I’ve made (in the `docs/` directory). - [x] (If the change is user-facing) I’ve added my changes to `changelog_unreleased/*/XXXX.md` file following `changelog_unreleased/TEMPLATE.md`. - [x] I’ve read the [contributing guidelines](https://github.com/prettier/prettier/blob/main/CONTRIBUTING.md). <!-- Please DO NOT remove the playground link --> **✨[Try the playground for this PR](https://prettier.io/playground-redirect)✨**
Same problem with version 3.0.0 in the following **TypeScript** snippet: ``` for (const division of collidingDivisions) { if (!division.properties.canRemove) { if (division.canContainSingleParagraph(startParagraph)) continue; // selection starting in r/o div: always OK to delete else if (endParagraph !== division.endParagraph && division.canContainSingleParagraph(endParagraph)) continue; // selection ending in r/o div: OK to delete IF it is NOT last paragraph (which would get absorbed) else { // selection over whole r/o div OR ending in last paragraph (which would get absorbed) -> FAIL console.warn('deleteSelectedTextAndJoinRemainingNodes(): cannot delete because of must-keep division: ' + division.properties.name); return { success: false, reason: DeleteAndJoinErrorReason.READONLY_DIVISION }; } } } ``` **Error:** ``` [error] EditableArticle.ts: Error: Comment "selection starting in r/o div: always OK to delete" was not printed. Please report this error! [error] at ensureAllCommentsPrinted [error] at printAstToDoc [error] at async coreFormat [error] at async formatWithCursor [error] at async formatFiles [error] at async main [error] at async Module.run ``` This is duplicated to #15470 Sorry I mistook Unstable **Prettier pr-13677** [Playground link](https://deploy-preview-13677--prettier.netlify.app/playground/#N4Igxg9gdgLgprEAuEAzCAnABACgNx4CUWwAOlOVlgJaq4wYCucxARhnAIYDWWA9HywwAFtQDOWSAFspCGAHIJcAB7j4UMHCwB3agBs9Wdl17UY5PJSxw9Yregg5ClilAC+IADQgIABxjU0GLIoJwYGBDaAAphCMEonHranACewd7snGDccDAAypyyADLUUHDIqIl2GRhZOfm+WaUA5sgMzN5wUqxwACa9fUWcUM2MnM1wAGKYUpwwASPIIJyMMBBeIMIwUnoA6qLwYo2aeXFm1ABuZilLYGLpIKV2GDBRtc2zFVVw3gBWYso8i09HAAIqMCDwL62H4gRoYZ5LVicHp6Da+DClGC7ai9ETIAAcAAZvBiIHZdrVfEsMXBnhdyt4AI4Q+BvPzxZZiAC0ZT6fQ2HBZ1A4b3GnyQlRh3jsUmobSYsLEwLBrPKku+3hgKJxeOEyAATFravoWgBhCAyThLRJo7yMOwAFRR8Sl1RAF2YAEkoANYHkwJj-ABBX15GApEHQuxuNxAA) <!-- prettier-ignore --> ```sh --parser babel ``` **Input:** <!-- prettier-ignore --> ```jsx for (;;) { if (true) break // this comment's existence will break it ; else foo(); } ``` **Output:** <!-- prettier-ignore --> ```jsx for (;;) { if (true) break; // this comment's existence will break it else foo(); } ``` **Second Output:** <!-- prettier-ignore --> ```jsx for (;;) { if (true) break; // this comment's existence will break it else foo(); } ``` [repl](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAzCAnABACgNx4CUWwAOlOVlgJaq4wYCucxARhnAIYDWWA9HywwAFtQDOWSAFspCGAHIJcAB7j4UMHCwB3agBs9Wdl17UY5PJSxw9Yregg5ClilAC+IADQgIABxjU0GLIoJwYGBDaAAphCMEonHranACewd7snGDccDAAypyyADLUUHDIqIl2GRhZOfm+WaUA5sgMzN5wUqxwACa9fUWcUM2MnM1wAGKYUpwwASPIIJyMMBBeIMIwUnoA6qLwYo2aeXFm1ABuZilLYGLpIKV2GDBRtc2zFVVw3gBWYso8i09HAAIqMCDwL62H4gRoYZ5LVicHp6Da+DClGC7ai9ETIAAcAAZvBiIHZdrVfEsMXBnhdyt4AI4Q+BvPzxZZiAC0ZT6fQ2HBZ1A4b3GnyQlRh3jsUmobSYsLEwLBrPKku+3hgKJxeOEyAATFravoWgBhCAyThLOkAVg2jDsABUUfEpdUQBdmABJKADWB5MCY-wAQT9eRgKRB0LsbjcQA) Should have nothing to do with this PR, as is the current main branch. I don't understand why only node18 fails.😕 > I don't understand why only node18 fails.😕 `FULL_TEST=1 yarn test ...` Seems you fixed a idempotence issue, remove this line https://github.com/prettier/prettier/blob/f38111fec6c35b513370832a84bdac8b5663763d/tests/config/format-test.js#L42 Yeah, I improved the error message a little bit. Can you add a changelog? Does fixing idempotency need to be stated in the changelog? That seems like the title is a bit too long. You can use two changelog entry, name `13677.md` and `13677-2.md` Something seems not right here. These comments should be attached as trailing to those statements, not as dangling. Did you try to fix it that way @liuxingbaoyu ? No. babel has it as a trailing comment, but espree doesn't. https://astexplorer.net/#/gist/134357615990b3d06424d14bf13c2831/07bcca7af325512345159821b3e8b0e7e937bc64 And I tested in prettier, same result even with babel, so I'm not sure if this is intentional and worried that it affects more, I didn't touch it. He is talking about our own comment attach logic https://github.com/prettier/prettier/blob/next/src/main/comments.js I still don't understand the comment logic here, but I can only do so much. 😅 @liuxingbaoyu You correctly identified the problematic place in the code. But it needs a fix for a more general case as that logic (added in #12017) can add dangling comments to _any_ kind of statement (not only `break/continue/debugger`) whereas only a few statements support them. The idea with adding dangling comments with a marker is valid, but they should've been added to `IfStatement`. I don't understand what needs to be done, what is this comment expected as? Dangling Comments of `ifStatement`? But this behavior appears to be intentional in https://github.com/prettier/prettier/pull/12017. Also it looks like the way in https://github.com/prettier/prettier/pull/12017/files#diff-0aaa38223318fb8c3d0133b3b8d8f4cbc48d37209f26f3b818398d1ccc28994aR184-R217 is similar to my original commit. Sorry, I don't have a full solution in mind. I'm just pointing out that the bug isn't specific to `break/continue/debugger` (examples: [one](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBLAZgAgBTohASkzwCcdVMBeTAJgG5MKA+TABgdQFpOjIoBnCABs4AOiEQA5tlQEGAennF8AHShwh-OJgBGAQxLY5akABoQEAA4xU0fslAGSEAO4AFAwnso9Ql3oBPe3MdEj0wAGs4GABlPQBbOAAZVHVkdF8tELDI6JjLcNTJZBgSAFc4czh4nTgAEzr6pL0oSTK9STgAMQgSeL0YG1bkED0ymAgzEAALGHihAHVp1Hh+ArA4GK8V1AA3FYCRsH5gtAE4Ehg3MMl+9MzKkAArfgAPGKKRAEUyiHh7zSPAokLQkEb6WpCKaWEipGALVB1GDTZAADlY5hhEC0CzClhGMLgoN2cCmAEdfvBrlZvKN+Jx1PV6lMSHAKahWdcOnckBlAeYtPFUCVyo9+J84D8-qTeQ9zDA9DoEUiUUgaPKwqghEUAMIQeI8kBEgCsUzKWgAKorvHysiBdhUAJJQRqwGJgWHWACCLpiMACIgBWgAvsGgA), [two](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBLAZgAgBTohASkwBMJNhNIoBnCAGzgDo6IBzbVIgX0wHcALVAw4BaEUQD0EzHggAdKHDrU4mAEYBDAE7YCAbhAAaEBAAOMVNGrJQ2rRF4AFbQmsoNdXhoCe142q0NMABrOBgAZQ0AWzgAGVRFZHQPFX9AkLDw0yCE1mQYLQBXOGM4KLU4YmJK2I0oVkKNVjgAMQgtKI0YC3rkEA1CmAgjEH4YKLoAdUF4amywOHDXVAsANxXvPrBqPzQaOC0YR0DWTqSUkpAAK2oAD3DchgBFQoh4c+VL7K0VLT7NCp0EamLQJGCTVDEGD8ZAADgADMYQRAVJNAqY+iC4L9VnARgBHV7wY5mNz9agiRSVSojLRwQmoOnHJpnJDJT7GFRRVD5IqXaiPOAvN54tkXYwwDRqCFQmFIABMEsCQlyAGEIFFWSBsQBWEaFFQAFSlbnZqRAq2KAEkoNVYOEwKDzABBW3hGDeBgfFRcLhAA)). I'll look into it if I have time.
"2023-12-18T11:47:49Z"
3.2
[]
[ "tests/format/js/if/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground-redirect", "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAzArlMMCW0AEAhgBQCU+wAOlPvjqvsYeQG6EBO+Y+AvPgIz4A9ACouEALYSEMfADZC+EUIDc1WnAA2AZzj52cGOnY0ATGqgBfEABoQEAA65o25KA7sIAdwAKHBK4ohJpehACernYARuyEYADWhgDKhNIAMjhQcMiowbrRsQnJDnGZAObIMOzocHa6EjiV1bUg2uWacACK6BDwOXktAFbaAB5J7V09fUi5Oi0AjlNwPp4OgSCE2gC0WXAAJvu2IFWEOJrlAMKSEoTIG5qaR21QZR0AgjBVOFHo8D5w7AyWX6czsAAsYBJNAB1ME4eDaEpgOBJALwnAseFhO5gbSREAsGoASSgB1gSTA7BwTjepKSMDCHRB+RADk8umhsQcdzZcF07BY2TsmX5MBWhDKN2ZLRK7H5dyihCiWiObMyMGhOD2MDByAAHAAGOwGRY4AziyW3GYDOwwJWa7W6pCmOzoXQAFSVgVmLLgEmVewOezShBe6AlcAAYhB2DdPuU7oRfhAQJZLEA" ]
prettier/prettier
15,827
prettier__prettier-15827
[ "15810" ]
66a23c9331e2c652f8e08fd05a65d2bea7fe5c1a
diff --git a/src/language-html/print/angular-control-flow-block.js b/src/language-html/print/angular-control-flow-block.js --- a/src/language-html/print/angular-control-flow-block.js +++ b/src/language-html/print/angular-control-flow-block.js @@ -6,6 +6,7 @@ import { line, softline, } from "../../document/builders.js"; +import { hasPrettierIgnore } from "../utils/index.js"; import ANGULAR_CONTROL_FLOW_BLOCK_SETTINGS from "./angular-control-flow-block-settings.evaluate.js"; import { printChildren } from "./children.js"; @@ -51,7 +52,8 @@ function isPreviousBlockUnClosed(path) { const { previous } = path; return ( previous?.type === "angularControlFlowBlock" && - !shouldCloseBlock(path.previous) + !hasPrettierIgnore(previous) && + !shouldCloseBlock(previous) ); }
diff --git a/tests/format/angular/control-flow/__snapshots__/jsfmt.spec.js.snap b/tests/format/angular/control-flow/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/angular/control-flow/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/angular/control-flow/__snapshots__/jsfmt.spec.js.snap @@ -426,6 +426,48 @@ topStartToSideStartMaxSize) { ================================================================================ `; +exports[`ignore.html format 1`] = ` +====================================options===================================== +parsers: ["angular"] +printWidth: 80 + | printWidth +=====================================input====================================== +<!-- prettier-ignore --> +@if (condition) { + Foo +} @else { + Other +} + + +@if (condition) { + Foo +} +<!-- prettier-ignore --> +@else { + Other +} + +=====================================output===================================== +<!-- prettier-ignore --> +@if (condition) { + Foo +} +@else { + Other +} + +@if (condition) { + Foo +} +<!-- prettier-ignore --> +@else { + Other +} + +================================================================================ +`; + exports[`mix.html format 1`] = ` ====================================options===================================== parsers: ["angular"] diff --git a/tests/format/angular/control-flow/ignore.html b/tests/format/angular/control-flow/ignore.html new file mode 100644 --- /dev/null +++ b/tests/format/angular/control-flow/ignore.html @@ -0,0 +1,15 @@ +<!-- prettier-ignore --> +@if (condition) { + Foo +} @else { + Other +} + + +@if (condition) { + Foo +} +<!-- prettier-ignore --> +@else { + Other +}
Angular block syntax + prettier-ignore prints extra closing brace **Prettier 3.1.1** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAhAWkwAgA4BOcMMAlnAZqQOZQRE7YB8AOlAAKkBmOAFJFAAmpMtACUOYGxw4AYhAhsAvjnZwANgGc4k6TgDyMABYVlIADQgIeUVE3JQAQwIEIAdwAKzhPZSP1bo4AnvaWAEYEjmAA1sQAyo4AtnAAMqRQcMhc-trhkTHxeFHp1MgwBACucJbaiaRlldUgcAAeeBSkybD+ACoUUM7kvtlaTZol6nAAihUQ8Fk5TQBWmi1xE9Oz80gjuSAAjltwHq54viCOmpgZcIK3FiDljqTqJQDCEImJjsgX6uoPcZQaiTACCJAIpDCFXgHgoaQyC1GliMMES6gA6kYRHBNEUwHA4j4RKQAG4iIK-MCaUIgUlVACSQgQMDiYEhNlBQjiMCCkyRe0IEG0GMieF+hFxFFJmUs6W0BBgJ0c1G+AqaRQICt+jmBFXUzgehHSMAxpEExmQAA4AAyWIiHUhEZWqn47RaWGCOMJmi1GZAAJksFW0PW9ww9zUSYVud0EKV11AqKrg8gI3xIJR1MIgICUSiAA) <!-- prettier-ignore --> ```sh --parser angular ``` **Input:** <!-- prettier-ignore --> ```html <!-- prettier-ignore --> @if (condition) { Foo } @else { Other } ``` **Output:** <!-- prettier-ignore --> ```html <!-- prettier-ignore --> @if (condition) { Foo } } @else { Other } ``` **Expected behavior:** For the extra brace not to be printed: <!-- prettier-ignore --> ```html <!-- prettier-ignore --> @if (condition) { Foo } @else { Other } ```
"2023-12-18T13:05:40Z"
3.2
[]
[ "tests/format/angular/control-flow/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAhAWkwAgA4BOcMMAlnAZqQOZQRE7YB8AOlAAKkBmOAFJFAAmpMtACUOYGxw4AYhAhsAvjnZwANgGc4k6TgDyMABYVlIADQgIeUVE3JQAQwIEIAdwAKzhPZSP1bo4AnvaWAEYEjmAA1sQAyo4AtnAAMqRQcMhc-trhkTHxeFHp1MgwBACucJbaiaRlldUgcAAeeBSkybD+ACoUUM7kvtlaTZol6nAAihUQ8Fk5TQBWmi1xE9Oz80gjuSAAjltwHq54viCOmpgZcIK3FiDljqTqJQDCEImJjsgX6uoPcZQaiTACCJAIpDCFXgHgoaQyC1GliMMES6gA6kYRHBNEUwHA4j4RKQAG4iIK-MCaUIgUlVACSQgQMDiYEhNlBQjiMCCkyRe0IEG0GMieF+hFxFFJmUs6W0BBgJ0c1G+AqaRQICt+jmBFXUzgehHSMAxpEExmQAA4AAyWIiHUhEZWqn47RaWGCOMJmi1GZAAJksFW0PW9ww9zUSYVud0EKV11AqKrg8gI3xIJR1MIgICUSiAA" ]
prettier/prettier
15,870
prettier__prettier-15870
[ "14234" ]
3a90b356530f713917240650f59289ddf303909f
diff --git a/src/language-graphql/printer-graphql.js b/src/language-graphql/printer-graphql.js --- a/src/language-graphql/printer-graphql.js +++ b/src/language-graphql/printer-graphql.js @@ -384,7 +384,7 @@ function genericPrint(path, options, print) { " =", ifBreak("", " "), indent([ - ifBreak([line, " "]), + ifBreak([line, "| "]), join([line, "| "], path.map(print, "types")), ]), ]
diff --git a/tests/format/graphql/union-types/__snapshots__/jsfmt.spec.js.snap b/tests/format/graphql/union-types/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/graphql/union-types/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/graphql/union-types/__snapshots__/jsfmt.spec.js.snap @@ -16,6 +16,8 @@ union myThirdUnion = AVeryVeryVeryLongNamedTypeName | ASecondVeryVeryVeryLongedN union longUnion = A | B | C | D | E | F | G | H | I | J | K | L | A | B | C | D | E | F | G | H | I | J | K | L +union SearchResult = Conference| Festival | Concert | Venue | Conference| Festival | Concert | Venue + # comment # comment2 union union = B | C | D @@ -23,17 +25,17 @@ union union = B | C | D union myUnion = ATypeName | ASecondTypeName union tooLongNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee = - A + | A | B union mySecondUnion = ATypeName | ASecondTypeName | AThirdTypeName union myThirdUnion = - AVeryVeryVeryLongNamedTypeName + | AVeryVeryVeryLongNamedTypeName | ASecondVeryVeryVeryLongedNameTypeName union longUnion = - A + | A | B | C | D @@ -58,6 +60,16 @@ union longUnion = | K | L +union SearchResult = + | Conference + | Festival + | Concert + | Venue + | Conference + | Festival + | Concert + | Venue + # comment # comment2 union union = B | C | D diff --git a/tests/format/graphql/union-types/union_types.graphql b/tests/format/graphql/union-types/union_types.graphql --- a/tests/format/graphql/union-types/union_types.graphql +++ b/tests/format/graphql/union-types/union_types.graphql @@ -8,6 +8,8 @@ union myThirdUnion = AVeryVeryVeryLongNamedTypeName | ASecondVeryVeryVeryLongedN union longUnion = A | B | C | D | E | F | G | H | I | J | K | L | A | B | C | D | E | F | G | H | I | J | K | L +union SearchResult = Conference| Festival | Concert | Venue | Conference| Festival | Concert | Venue + # comment # comment2 union union = B | C | D \ No newline at end of file
Improve GraphQL union types formatting I think we can make consistency for printing union types (`|`) between TS and Gql. What do you think? **Prettier 2.8.3** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBXKBLaACAynAQwCcwALAJTgGdUAbGbAXgB0oAfbAYWgDM4iEYOBwBi1GBgBuBWtg7coQogw4A1BKjhyuvfoOHYxVCdNnzoSldnVRNrEABoQEAA4ToVZKGJEIAdwAFYgRPFBk-AgBPTycAIyICMABrOBhcAgBbOAAZDCg4ZB4ZKjg4hOTU3BdEvIBzZBgiTSc4DNi4ABMOzuyCKFrUAlq4EQgiDIIYCX7kEAJUGAhHEFIYDNoAdVIMeCpqoXwoKh2pHcjZsCoYkDyS5QCE2onC4tKQACsqAA9cOto4ACKqAg8BetBKTmqRDus1qCRcpAAjrRli4iHkYBsMB0YKRkAAOAAMkN8JQ28NmaOo-EkBSciOB8AerlCcyoAFp8p1OssBAyMAIHkNnkgiuC3iUMhgGk0JX84ABBKbo2ILOABfi5fJgiEgY79f5AkEFUWvJwwAixLE4vFIABM5oSGFodW4GRFIGoAFZlqgSgAVS2hMW6ySaACSUG6sFwYHRbgVUdwMEi-x1cAAvhmgA) <!-- prettier-ignore --> ```sh --parser graphql ``` **Input:** <!-- prettier-ignore --> ```graphql union SearchResult = Conference| Festival | Concert | Venue | Conference| Festival | Concert | Venue ``` **Output:** <!-- prettier-ignore --> ```graphql union SearchResult = Conference | Festival | Concert | Venue | Conference | Festival | Concert | Venue ``` **Expected behavior:** ```graphql union SearchResult = | Conference | Festival | Concert | Venue | Conference | Festival | Concert | Venue ```
HI @sosukesuzuki - can you please assigned this to me ? this will be my first contribution to prettier library :) @ArchitGajjar Go ahead! @sosukesuzuki - I made some changes and execute below commands. > yarn build:website > cd website/playground > npm run start Here, I'm seeing my changes are not reflected in playground when I test. How do you verify your changes are reflected while testing into local ? ``` $ touch test.js $ yarn debug test.js ```
"2024-01-03T08:56:40Z"
3.2
[]
[ "tests/format/graphql/union-types/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBXKBLaACAynAQwCcwALAJTgGdUAbGbAXgB0oAfbAYWgDM4iEYOBwBi1GBgBuBWtg7coQogw4A1BKjhyuvfoOHYxVCdNnzoSldnVRNrEABoQEAA4ToVZKGJEIAdwAFYgRPFBk-AgBPTycAIyICMABrOBhcAgBbOAAZDCg4ZB4ZKjg4hOTU3BdEvIBzZBgiTSc4DNi4ABMOzuyCKFrUAlq4EQgiDIIYCX7kEAJUGAhHEFIYDNoAdVIMeCpqoXwoKh2pHcjZsCoYkDyS5QCE2onC4tKQACsqAA9cOto4ACKqAg8BetBKTmqRDus1qCRcpAAjrRli4iHkYBsMB0YKRkAAOAAMkN8JQ28NmaOo-EkBSciOB8AerlCcyoAFp8p1OssBAyMAIHkNnkgiuC3iUMhgGk0JX84ABBKbo2ILOABfi5fJgiEgY79f5AkEFUWvJwwAixLE4vFIABM5oSGFodW4GRFIGoAFZlqgSgAVS2hMW6ySaACSUG6sFwYHRbgVUdwMEi-x1cAAvhmgA" ]
prettier/prettier
15,887
prettier__prettier-15887
[ "15784" ]
e9b8764fc4c770aaa8e5d9b982bda40a83a4cf2a
diff --git a/src/language-js/print/angular.js b/src/language-js/print/angular.js --- a/src/language-js/print/angular.js +++ b/src/language-js/print/angular.js @@ -66,7 +66,7 @@ function printAngular(path, options, print) { (node.key.name === "then" || node.key.name === "else" || node.key.name === "as")) || - (index === 2 && + ((index === 2 || index === 3) && ((node.key.name === "else" && parent.body[index - 1].type === "NGMicrosyntaxKeyedExpression" && parent.body[index - 1].key.name === "then") ||
diff --git a/tests/format/angular/control-flow/__snapshots__/jsfmt.spec.js.snap b/tests/format/angular/control-flow/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/angular/control-flow/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/angular/control-flow/__snapshots__/jsfmt.spec.js.snap @@ -285,6 +285,12 @@ item of <div *ngFor="item of items; track item"></div> </div> +<div> + @for (item of items; let i = $index; track block) {} + + <div *ngFor="item of items; let i = $index; track block"></div> +</div> + =====================================output===================================== <ul> @for (let item of items; index as i; trackBy: trackByFn) { @@ -332,6 +338,12 @@ item of <div *ngFor="item of items; track item"></div> </div> +<div> + @for (item of items; let i = $index; track block) {} + + <div *ngFor="item of items; let i = $index; track block"></div> +</div> + ================================================================================ `; diff --git a/tests/format/angular/control-flow/for.html b/tests/format/angular/control-flow/for.html --- a/tests/format/angular/control-flow/for.html +++ b/tests/format/angular/control-flow/for.html @@ -52,3 +52,9 @@ <div *ngFor="item of items; track item"></div> </div> + +<div> + @for (item of items; let i = $index; track block) {} + + <div *ngFor="item of items; let i = $index; track block"></div> +</div>
Prettier adds a colon after 'track' **Prettier 3.1.1** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBLAtgBwgJxgAmHwGEALAQygHM4AROeMGVaAZRh3PioE8AaEhCzQEBAL74AZjiH4AOiAAClKgFcANuRwB6SDjgKA3HKgZseQvgCqsVOvoBnDhB74J02QsXUocLttVbdQBaABM4JxkeIxMTRRtmewjnHgAKAEo44iFsX1hU4BN8fDAKajoGOCYWKCQSMpp6RmY2Di44XgA6AHkoAAVVB1I+IvwHOHUqmFw6hTgAD3IsSYURqGL4Zfa6gANR4sVJXHxU1E38CEl8M7h0B0N8SYJUfABefAASVChw+Ye2sAAa3wACN1BAgelCGJRjs1mJMr55uYCGBNA4HPgAKKLZZwQijSBQSKqJi4DLQ2LrfDUXoASVMMApwBhUFG1AAgpJ4DgAGqoOAAdwZZ2ZrPZVF6ZBUETFVOKtKgjhScqgrJAfBAEEwLWJyFAWhkgr6WgQDmQIHI6kF5B45s1IM4QIYrCWcAAMt84MhJFbxg6nYCXZhyGBvlRkBxVHBNeN0KhIzho5qFpg4DgMKIrQAVdNQLQC81IX3qf0gBzhyYARVUEHgPr9MZAACsHPNWJW4DW697i43NQBHWvwPoyTBFy0OYK+ODhUIakBtOzh7LodDkC1W9QLivUSYcmAcVAg1Qj9Oe3wN0tN0gwdDqADqpBuDhDYDgrDNZ1QADczjwLTADEFx-aMGXCWBWDADMdQ5H52B4SYrzLTAZHGB9OEwC1UIidMf29TVvnGPBR3IKh12QpsQxwYiLRBcgQQmBdUO+GAH1QUIYFIZAAA4AAZNX0IdUH0UjyI3Ptr01GAGPYzjuKQAAmTVBjgbMGKLEsy1uRjQjnd0VFUMi4AAMVwddD3DTdTwgEAxDEIA) <!-- prettier-ignore --> ```sh --parser babel ``` **Input:** <!-- prettier-ignore --> ```jsx import { ChangeDetectionStrategy, Component } from "@angular/core"; import { UntilDestroy } from "@ngneat/until-destroy"; @UntilDestroy() @Component({ changeDetection: ChangeDetectionStrategy.OnPush, selector: "example", template: ` @for (item of items; let i = $index; track block) {} `, }) export class Example { constructor() {} ngOnInit() {} ngAfterViewInit() {} ngOnChanges() {} ngOnDestroy() {} } ``` **Output:** <!-- prettier-ignore --> ```jsx import { ChangeDetectionStrategy, Component } from "@angular/core"; import { UntilDestroy } from "@ngneat/until-destroy"; @UntilDestroy() @Component({ changeDetection: ChangeDetectionStrategy.OnPush, selector: "example", template: ` @for (item of items; let i = $index; track: block) {} `, }) export class Example { constructor() {} ngOnInit() {} ngAfterViewInit() {} ngOnChanges() {} ngOnDestroy() {} } ``` **Expected behavior:** I was expecting no changes to the Input code, but Prettier adds a colon after 'track' , which is invalid syntax for Angular 17's control flow
"2024-01-07T14:25:43Z"
3.2
[]
[ "tests/format/angular/control-flow/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBLAtgBwgJxgAmHwGEALAQygHM4AROeMGVaAZRh3PioE8AaEhCzQEBAL74AZjiH4AOiAAClKgFcANuRwB6SDjgKA3HKgZseQvgCqsVOvoBnDhB74J02QsXUocLttVbdQBaABM4JxkeIxMTRRtmewjnHgAKAEo44iFsX1hU4BN8fDAKajoGOCYWKCQSMpp6RmY2Di44XgA6AHkoAAVVB1I+IvwHOHUqmFw6hTgAD3IsSYURqGL4Zfa6gANR4sVJXHxU1E38CEl8M7h0B0N8SYJUfABefAASVChw+Ye2sAAa3wACN1BAgelCGJRjs1mJMr55uYCGBNA4HPgAKKLZZwQijSBQSKqJi4DLQ2LrfDUXoASVMMApwBhUFG1AAgpJ4DgAGqoOAAdwZZ2ZrPZVF6ZBUETFVOKtKgjhScqgrJAfBAEEwLWJyFAWhkgr6WgQDmQIHI6kF5B45s1IM4QIYrCWcAAMt84MhJFbxg6nYCXZhyGBvlRkBxVHBNeN0KhIzho5qFpg4DgMKIrQAVdNQLQC81IX3qf0gBzhyYARVUEHgPr9MZAACsHPNWJW4DW697i43NQBHWvwPoyTBFy0OYK+ODhUIakBtOzh7LodDkC1W9QLivUSYcmAcVAg1Qj9Oe3wN0tN0gwdDqADqpBuDhDYDgrDNZ1QADczjwLTADEFx-aMGXCWBWDADMdQ5H52B4SYrzLTAZHGB9OEwC1UIidMf29TVvnGPBR3IKh12QpsQxwYiLRBcgQQmBdUO+GAH1QUIYFIZAAA4AAZNX0IdUH0UjyI3Ptr01GAGPYzjuKQAAmTVBjgbMGKLEsy1uRjQjnd0VFUMi4AAMVwddD3DTdTwgEAxDEIA" ]
prettier/prettier
15,888
prettier__prettier-15888
[ "15564", "15563" ]
4371840055b77d8bbf60f0c7fee8a75f2a777276
diff --git a/src/language-js/clean.js b/src/language-js/clean.js --- a/src/language-js/clean.js +++ b/src/language-js/clean.js @@ -79,7 +79,8 @@ function clean(original, cloned, parent) { original.type === "PropertyDefinition" || original.type === "TSDeclareMethod" || original.type === "TSPropertySignature" || - original.type === "ObjectTypeProperty") && + original.type === "ObjectTypeProperty" || + original.type === "ImportAttribute") && typeof original.key === "object" && original.key && (original.key.type === "Literal" || diff --git a/src/language-js/print/estree.js b/src/language-js/print/estree.js --- a/src/language-js/print/estree.js +++ b/src/language-js/print/estree.js @@ -228,7 +228,7 @@ function printEstree(path, options, print, args) { case "ExportDefaultSpecifier": return printModuleSpecifier(path, options, print); case "ImportAttribute": - return [print("key"), ": ", print("value")]; + return printProperty(path, options, print); case "Import": return "import"; diff --git a/src/language-js/print/property.js b/src/language-js/print/property.js --- a/src/language-js/print/property.js +++ b/src/language-js/print/property.js @@ -26,7 +26,8 @@ function printPropertyKey(path, options, print) { const objectHasStringProp = ( parent.properties || parent.body || - parent.members + parent.members || + parent.attributes ).some( (prop) => !prop.computed && diff --git a/src/language-js/utils/index.js b/src/language-js/utils/index.js --- a/src/language-js/utils/index.js +++ b/src/language-js/utils/index.js @@ -616,6 +616,7 @@ function isStringPropSafeToUnquote(node, options) { )) || (isSimpleNumber(node.key.value) && String(Number(node.key.value)) === node.key.value && + node.type !== "ImportAttribute" && (options.parser === "babel" || options.parser === "acorn" || options.parser === "espree" ||
diff --git a/tests/format/js/import-attributes/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/import-attributes/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/js/import-attributes/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/import-attributes/__snapshots__/jsfmt.spec.js.snap @@ -24,6 +24,84 @@ exports[`dynamic-import.js [meriyah] format 1`] = ` Cause: [1:20]: Expected ')'" `; +exports[`dynamic-import.js - {"quoteProps":"consistent"} [acorn] format 1`] = ` +"Unexpected token (1:20) +> 1 | import("./foo.json", { with: { type: "json" } }); + | ^ + 2 | +Cause: Unexpected token (1:19)" +`; + +exports[`dynamic-import.js - {"quoteProps":"consistent"} [espree] format 1`] = ` +"Unexpected token , (1:20) +> 1 | import("./foo.json", { with: { type: "json" } }); + | ^ + 2 | +Cause: Unexpected token ," +`; + +exports[`dynamic-import.js - {"quoteProps":"consistent"} [meriyah] format 1`] = ` +"Expected ')' (1:20) +> 1 | import("./foo.json", { with: { type: "json" } }); + | ^ + 2 | +Cause: [1:20]: Expected ')'" +`; + +exports[`dynamic-import.js - {"quoteProps":"consistent"} format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript"] +printWidth: 80 +quoteProps: "consistent" + | printWidth +=====================================input====================================== +import("./foo.json", { with: { type: "json" } }); + +=====================================output===================================== +import("./foo.json", { with: { type: "json" } }); + +================================================================================ +`; + +exports[`dynamic-import.js - {"quoteProps":"preserve"} [acorn] format 1`] = ` +"Unexpected token (1:20) +> 1 | import("./foo.json", { with: { type: "json" } }); + | ^ + 2 | +Cause: Unexpected token (1:19)" +`; + +exports[`dynamic-import.js - {"quoteProps":"preserve"} [espree] format 1`] = ` +"Unexpected token , (1:20) +> 1 | import("./foo.json", { with: { type: "json" } }); + | ^ + 2 | +Cause: Unexpected token ," +`; + +exports[`dynamic-import.js - {"quoteProps":"preserve"} [meriyah] format 1`] = ` +"Expected ')' (1:20) +> 1 | import("./foo.json", { with: { type: "json" } }); + | ^ + 2 | +Cause: [1:20]: Expected ')'" +`; + +exports[`dynamic-import.js - {"quoteProps":"preserve"} format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript"] +printWidth: 80 +quoteProps: "preserve" + | printWidth +=====================================input====================================== +import("./foo.json", { with: { type: "json" } }); + +=====================================output===================================== +import("./foo.json", { with: { type: "json" } }); + +================================================================================ +`; + exports[`dynamic-import.js format 1`] = ` ====================================options===================================== parsers: ["babel", "typescript"] @@ -71,6 +149,126 @@ exports[`empty.js [meriyah] format 1`] = ` Cause: [2:36]: Unexpected token: 'with'" `; +exports[`empty.js - {"quoteProps":"consistent"} [acorn] format 1`] = ` +"Unexpected token (2:33) + 1 | export * as foo from "foo.json" +> 2 | export * as bar from "bar.json" with { } + | ^ + 3 | export * as baz from "baz.json" with { /* comment */ } + 4 | + 5 | import * as foo from "foo.json" +Cause: Unexpected token (2:32)" +`; + +exports[`empty.js - {"quoteProps":"consistent"} [espree] format 1`] = ` +"Unexpected token with (2:33) + 1 | export * as foo from "foo.json" +> 2 | export * as bar from "bar.json" with { } + | ^ + 3 | export * as baz from "baz.json" with { /* comment */ } + 4 | + 5 | import * as foo from "foo.json" +Cause: Unexpected token with" +`; + +exports[`empty.js - {"quoteProps":"consistent"} [meriyah] format 1`] = ` +"Unexpected token: 'with' (2:36) + 1 | export * as foo from "foo.json" +> 2 | export * as bar from "bar.json" with { } + | ^ + 3 | export * as baz from "baz.json" with { /* comment */ } + 4 | + 5 | import * as foo from "foo.json" +Cause: [2:36]: Unexpected token: 'with'" +`; + +exports[`empty.js - {"quoteProps":"consistent"} format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript"] +printWidth: 80 +quoteProps: "consistent" + | printWidth +=====================================input====================================== +export * as foo from "foo.json" +export * as bar from "bar.json" with { } +export * as baz from "baz.json" with { /* comment */ } + +import * as foo from "foo.json" +import * as bar from "bar.json" with { } +import * as baz from "baz.json" with { /* comment */ } + +=====================================output===================================== +export * as foo from "foo.json"; +export * as bar from "bar.json" with {}; +export * as baz from "baz.json" /* comment */ with {}; + +import * as foo from "foo.json"; +import * as bar from "bar.json" with {}; +import * as baz from "baz.json" /* comment */ with {}; + +================================================================================ +`; + +exports[`empty.js - {"quoteProps":"preserve"} [acorn] format 1`] = ` +"Unexpected token (2:33) + 1 | export * as foo from "foo.json" +> 2 | export * as bar from "bar.json" with { } + | ^ + 3 | export * as baz from "baz.json" with { /* comment */ } + 4 | + 5 | import * as foo from "foo.json" +Cause: Unexpected token (2:32)" +`; + +exports[`empty.js - {"quoteProps":"preserve"} [espree] format 1`] = ` +"Unexpected token with (2:33) + 1 | export * as foo from "foo.json" +> 2 | export * as bar from "bar.json" with { } + | ^ + 3 | export * as baz from "baz.json" with { /* comment */ } + 4 | + 5 | import * as foo from "foo.json" +Cause: Unexpected token with" +`; + +exports[`empty.js - {"quoteProps":"preserve"} [meriyah] format 1`] = ` +"Unexpected token: 'with' (2:36) + 1 | export * as foo from "foo.json" +> 2 | export * as bar from "bar.json" with { } + | ^ + 3 | export * as baz from "baz.json" with { /* comment */ } + 4 | + 5 | import * as foo from "foo.json" +Cause: [2:36]: Unexpected token: 'with'" +`; + +exports[`empty.js - {"quoteProps":"preserve"} format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript"] +printWidth: 80 +quoteProps: "preserve" + | printWidth +=====================================input====================================== +export * as foo from "foo.json" +export * as bar from "bar.json" with { } +export * as baz from "baz.json" with { /* comment */ } + +import * as foo from "foo.json" +import * as bar from "bar.json" with { } +import * as baz from "baz.json" with { /* comment */ } + +=====================================output===================================== +export * as foo from "foo.json"; +export * as bar from "bar.json" with {}; +export * as baz from "baz.json" /* comment */ with {}; + +import * as foo from "foo.json"; +import * as bar from "bar.json" with {}; +import * as baz from "baz.json" /* comment */ with {}; + +================================================================================ +`; + exports[`empty.js format 1`] = ` ====================================options===================================== parsers: ["babel", "typescript"] @@ -127,10 +325,41 @@ exports[`keyword-detect.js [meriyah] format 1`] = ` Cause: [1:38]: Unexpected token: 'with'" `; -exports[`keyword-detect.js format 1`] = ` +exports[`keyword-detect.js - {"quoteProps":"consistent"} [acorn] format 1`] = ` +"Unexpected token (1:35) +> 1 | import "./test.json" /* assert */ with /* assert */ { type: "json" } + | ^ + 2 | import {} from "./test.json" /* assert */ with /* assert */ { type: "json" } + 3 | import "./test.json" /* with */ assert /* with */ { type: "json" } + 4 | import {} from "./test.json" /* with */ assert /* with */ { type: "json" } +Cause: Unexpected token (1:34)" +`; + +exports[`keyword-detect.js - {"quoteProps":"consistent"} [espree] format 1`] = ` +"Unexpected token with (1:35) +> 1 | import "./test.json" /* assert */ with /* assert */ { type: "json" } + | ^ + 2 | import {} from "./test.json" /* assert */ with /* assert */ { type: "json" } + 3 | import "./test.json" /* with */ assert /* with */ { type: "json" } + 4 | import {} from "./test.json" /* with */ assert /* with */ { type: "json" } +Cause: Unexpected token with" +`; + +exports[`keyword-detect.js - {"quoteProps":"consistent"} [meriyah] format 1`] = ` +"Unexpected token: 'with' (1:38) +> 1 | import "./test.json" /* assert */ with /* assert */ { type: "json" } + | ^ + 2 | import {} from "./test.json" /* assert */ with /* assert */ { type: "json" } + 3 | import "./test.json" /* with */ assert /* with */ { type: "json" } + 4 | import {} from "./test.json" /* with */ assert /* with */ { type: "json" } +Cause: [1:38]: Unexpected token: 'with'" +`; + +exports[`keyword-detect.js - {"quoteProps":"consistent"} format 1`] = ` ====================================options===================================== parsers: ["babel", "typescript"] printWidth: 80 +quoteProps: "consistent" | printWidth =====================================input====================================== import "./test.json" /* assert */ with /* assert */ { type: "json" } @@ -159,43 +388,216 @@ export * from "./test.json" /* with */ /* with */ assert { type: "json" }; ================================================================================ `; -exports[`multi-types.js [acorn] format 1`] = ` -"Unexpected token (1:31) -> 1 | import json from "./foo.json" with { type: "json", type: "bar" }; - | ^ - 2 | -Cause: Unexpected token (1:30)" +exports[`keyword-detect.js - {"quoteProps":"preserve"} [acorn] format 1`] = ` +"Unexpected token (1:35) +> 1 | import "./test.json" /* assert */ with /* assert */ { type: "json" } + | ^ + 2 | import {} from "./test.json" /* assert */ with /* assert */ { type: "json" } + 3 | import "./test.json" /* with */ assert /* with */ { type: "json" } + 4 | import {} from "./test.json" /* with */ assert /* with */ { type: "json" } +Cause: Unexpected token (1:34)" `; -exports[`multi-types.js [espree] format 1`] = ` -"Unexpected token with (1:31) -> 1 | import json from "./foo.json" with { type: "json", type: "bar" }; - | ^ - 2 | +exports[`keyword-detect.js - {"quoteProps":"preserve"} [espree] format 1`] = ` +"Unexpected token with (1:35) +> 1 | import "./test.json" /* assert */ with /* assert */ { type: "json" } + | ^ + 2 | import {} from "./test.json" /* assert */ with /* assert */ { type: "json" } + 3 | import "./test.json" /* with */ assert /* with */ { type: "json" } + 4 | import {} from "./test.json" /* with */ assert /* with */ { type: "json" } Cause: Unexpected token with" `; -exports[`multi-types.js [meriyah] format 1`] = ` -"Unexpected token: 'with' (1:34) -> 1 | import json from "./foo.json" with { type: "json", type: "bar" }; - | ^ - 2 | -Cause: [1:34]: Unexpected token: 'with'" +exports[`keyword-detect.js - {"quoteProps":"preserve"} [meriyah] format 1`] = ` +"Unexpected token: 'with' (1:38) +> 1 | import "./test.json" /* assert */ with /* assert */ { type: "json" } + | ^ + 2 | import {} from "./test.json" /* assert */ with /* assert */ { type: "json" } + 3 | import "./test.json" /* with */ assert /* with */ { type: "json" } + 4 | import {} from "./test.json" /* with */ assert /* with */ { type: "json" } +Cause: [1:38]: Unexpected token: 'with'" `; -exports[`multi-types.js format 1`] = ` +exports[`keyword-detect.js - {"quoteProps":"preserve"} format 1`] = ` ====================================options===================================== parsers: ["babel", "typescript"] printWidth: 80 +quoteProps: "preserve" | printWidth =====================================input====================================== -import json from "./foo.json" with { type: "json", type: "bar" }; - -=====================================output===================================== -import json from "./foo.json" with { type: "json", type: "bar" }; +import "./test.json" /* assert */ with /* assert */ { type: "json" } +import {} from "./test.json" /* assert */ with /* assert */ { type: "json" } +import "./test.json" /* with */ assert /* with */ { type: "json" } +import {} from "./test.json" /* with */ assert /* with */ { type: "json" } -================================================================================ -`; +export {} from "./test.json" /* assert */ with /* assert */ { type: "json" } +export {} from "./test.json" /* with */ assert /* with */ { type: "json" } + +export * from "./test.json" /* assert */ with /* assert */ { type: "json" } +export * from "./test.json" /* with */ assert /* with */ { type: "json" } + +=====================================output===================================== +import "./test.json" /* assert */ /* assert */ with { type: "json" }; +import {} from "./test.json" /* assert */ /* assert */ with { type: "json" }; +import "./test.json" /* with */ /* with */ assert { type: "json" }; +import {} from "./test.json" /* with */ /* with */ assert { type: "json" }; + +export {} from "./test.json" /* assert */ /* assert */ with { type: "json" }; +export {} from "./test.json" /* with */ /* with */ assert { type: "json" }; + +export * from "./test.json" /* assert */ /* assert */ with { type: "json" }; +export * from "./test.json" /* with */ /* with */ assert { type: "json" }; + +================================================================================ +`; + +exports[`keyword-detect.js format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +import "./test.json" /* assert */ with /* assert */ { type: "json" } +import {} from "./test.json" /* assert */ with /* assert */ { type: "json" } +import "./test.json" /* with */ assert /* with */ { type: "json" } +import {} from "./test.json" /* with */ assert /* with */ { type: "json" } + +export {} from "./test.json" /* assert */ with /* assert */ { type: "json" } +export {} from "./test.json" /* with */ assert /* with */ { type: "json" } + +export * from "./test.json" /* assert */ with /* assert */ { type: "json" } +export * from "./test.json" /* with */ assert /* with */ { type: "json" } + +=====================================output===================================== +import "./test.json" /* assert */ /* assert */ with { type: "json" }; +import {} from "./test.json" /* assert */ /* assert */ with { type: "json" }; +import "./test.json" /* with */ /* with */ assert { type: "json" }; +import {} from "./test.json" /* with */ /* with */ assert { type: "json" }; + +export {} from "./test.json" /* assert */ /* assert */ with { type: "json" }; +export {} from "./test.json" /* with */ /* with */ assert { type: "json" }; + +export * from "./test.json" /* assert */ /* assert */ with { type: "json" }; +export * from "./test.json" /* with */ /* with */ assert { type: "json" }; + +================================================================================ +`; + +exports[`multi-types.js [acorn] format 1`] = ` +"Unexpected token (1:31) +> 1 | import json from "./foo.json" with { type: "json", type: "bar" }; + | ^ + 2 | +Cause: Unexpected token (1:30)" +`; + +exports[`multi-types.js [espree] format 1`] = ` +"Unexpected token with (1:31) +> 1 | import json from "./foo.json" with { type: "json", type: "bar" }; + | ^ + 2 | +Cause: Unexpected token with" +`; + +exports[`multi-types.js [meriyah] format 1`] = ` +"Unexpected token: 'with' (1:34) +> 1 | import json from "./foo.json" with { type: "json", type: "bar" }; + | ^ + 2 | +Cause: [1:34]: Unexpected token: 'with'" +`; + +exports[`multi-types.js - {"quoteProps":"consistent"} [acorn] format 1`] = ` +"Unexpected token (1:31) +> 1 | import json from "./foo.json" with { type: "json", type: "bar" }; + | ^ + 2 | +Cause: Unexpected token (1:30)" +`; + +exports[`multi-types.js - {"quoteProps":"consistent"} [espree] format 1`] = ` +"Unexpected token with (1:31) +> 1 | import json from "./foo.json" with { type: "json", type: "bar" }; + | ^ + 2 | +Cause: Unexpected token with" +`; + +exports[`multi-types.js - {"quoteProps":"consistent"} [meriyah] format 1`] = ` +"Unexpected token: 'with' (1:34) +> 1 | import json from "./foo.json" with { type: "json", type: "bar" }; + | ^ + 2 | +Cause: [1:34]: Unexpected token: 'with'" +`; + +exports[`multi-types.js - {"quoteProps":"consistent"} format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript"] +printWidth: 80 +quoteProps: "consistent" + | printWidth +=====================================input====================================== +import json from "./foo.json" with { type: "json", type: "bar" }; + +=====================================output===================================== +import json from "./foo.json" with { type: "json", type: "bar" }; + +================================================================================ +`; + +exports[`multi-types.js - {"quoteProps":"preserve"} [acorn] format 1`] = ` +"Unexpected token (1:31) +> 1 | import json from "./foo.json" with { type: "json", type: "bar" }; + | ^ + 2 | +Cause: Unexpected token (1:30)" +`; + +exports[`multi-types.js - {"quoteProps":"preserve"} [espree] format 1`] = ` +"Unexpected token with (1:31) +> 1 | import json from "./foo.json" with { type: "json", type: "bar" }; + | ^ + 2 | +Cause: Unexpected token with" +`; + +exports[`multi-types.js - {"quoteProps":"preserve"} [meriyah] format 1`] = ` +"Unexpected token: 'with' (1:34) +> 1 | import json from "./foo.json" with { type: "json", type: "bar" }; + | ^ + 2 | +Cause: [1:34]: Unexpected token: 'with'" +`; + +exports[`multi-types.js - {"quoteProps":"preserve"} format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript"] +printWidth: 80 +quoteProps: "preserve" + | printWidth +=====================================input====================================== +import json from "./foo.json" with { type: "json", type: "bar" }; + +=====================================output===================================== +import json from "./foo.json" with { type: "json", type: "bar" }; + +================================================================================ +`; + +exports[`multi-types.js format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +import json from "./foo.json" with { type: "json", type: "bar" }; + +=====================================output===================================== +import json from "./foo.json" with { type: "json", type: "bar" }; + +================================================================================ +`; exports[`non-type.js [acorn] format 1`] = ` "Unexpected token (1:28) @@ -221,6 +623,84 @@ exports[`non-type.js [meriyah] format 1`] = ` Cause: [1:31]: Unexpected token: 'with'" `; +exports[`non-type.js - {"quoteProps":"consistent"} [acorn] format 1`] = ` +"Unexpected token (1:28) +> 1 | import foo from "foo.json" with { lazy: "true" }; + | ^ + 2 | +Cause: Unexpected token (1:27)" +`; + +exports[`non-type.js - {"quoteProps":"consistent"} [espree] format 1`] = ` +"Unexpected token with (1:28) +> 1 | import foo from "foo.json" with { lazy: "true" }; + | ^ + 2 | +Cause: Unexpected token with" +`; + +exports[`non-type.js - {"quoteProps":"consistent"} [meriyah] format 1`] = ` +"Unexpected token: 'with' (1:31) +> 1 | import foo from "foo.json" with { lazy: "true" }; + | ^ + 2 | +Cause: [1:31]: Unexpected token: 'with'" +`; + +exports[`non-type.js - {"quoteProps":"consistent"} format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript"] +printWidth: 80 +quoteProps: "consistent" + | printWidth +=====================================input====================================== +import foo from "foo.json" with { lazy: "true" }; + +=====================================output===================================== +import foo from "foo.json" with { lazy: "true" }; + +================================================================================ +`; + +exports[`non-type.js - {"quoteProps":"preserve"} [acorn] format 1`] = ` +"Unexpected token (1:28) +> 1 | import foo from "foo.json" with { lazy: "true" }; + | ^ + 2 | +Cause: Unexpected token (1:27)" +`; + +exports[`non-type.js - {"quoteProps":"preserve"} [espree] format 1`] = ` +"Unexpected token with (1:28) +> 1 | import foo from "foo.json" with { lazy: "true" }; + | ^ + 2 | +Cause: Unexpected token with" +`; + +exports[`non-type.js - {"quoteProps":"preserve"} [meriyah] format 1`] = ` +"Unexpected token: 'with' (1:31) +> 1 | import foo from "foo.json" with { lazy: "true" }; + | ^ + 2 | +Cause: [1:31]: Unexpected token: 'with'" +`; + +exports[`non-type.js - {"quoteProps":"preserve"} format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript"] +printWidth: 80 +quoteProps: "preserve" + | printWidth +=====================================input====================================== +import foo from "foo.json" with { lazy: "true" }; + +=====================================output===================================== +import foo from "foo.json" with { lazy: "true" }; + +================================================================================ +`; + exports[`non-type.js format 1`] = ` ====================================options===================================== parsers: ["babel", "typescript"] @@ -235,6 +715,194 @@ import foo from "foo.json" with { lazy: "true" }; ================================================================================ `; +exports[`quoted-keys.js [acorn] format 1`] = ` +"Unexpected token (1:29) +> 1 | import json from './mod.js' with { "type":"json" }; + | ^ + 2 | import json from './mod.js' with { "foobar":"json" }; + 3 | import json from './mod.js' with { "type-foo" :"json" }; + 4 | import json from './mod.js' with { "333foo" :"json" }; +Cause: Unexpected token (1:28)" +`; + +exports[`quoted-keys.js [espree] format 1`] = ` +"Unexpected token with (1:29) +> 1 | import json from './mod.js' with { "type":"json" }; + | ^ + 2 | import json from './mod.js' with { "foobar":"json" }; + 3 | import json from './mod.js' with { "type-foo" :"json" }; + 4 | import json from './mod.js' with { "333foo" :"json" }; +Cause: Unexpected token with" +`; + +exports[`quoted-keys.js [meriyah] format 1`] = ` +"Unexpected token: 'with' (1:32) +> 1 | import json from './mod.js' with { "type":"json" }; + | ^ + 2 | import json from './mod.js' with { "foobar":"json" }; + 3 | import json from './mod.js' with { "type-foo" :"json" }; + 4 | import json from './mod.js' with { "333foo" :"json" }; +Cause: [1:32]: Unexpected token: 'with'" +`; + +exports[`quoted-keys.js - {"quoteProps":"consistent"} [acorn] format 1`] = ` +"Unexpected token (1:29) +> 1 | import json from './mod.js' with { "type":"json" }; + | ^ + 2 | import json from './mod.js' with { "foobar":"json" }; + 3 | import json from './mod.js' with { "type-foo" :"json" }; + 4 | import json from './mod.js' with { "333foo" :"json" }; +Cause: Unexpected token (1:28)" +`; + +exports[`quoted-keys.js - {"quoteProps":"consistent"} [espree] format 1`] = ` +"Unexpected token with (1:29) +> 1 | import json from './mod.js' with { "type":"json" }; + | ^ + 2 | import json from './mod.js' with { "foobar":"json" }; + 3 | import json from './mod.js' with { "type-foo" :"json" }; + 4 | import json from './mod.js' with { "333foo" :"json" }; +Cause: Unexpected token with" +`; + +exports[`quoted-keys.js - {"quoteProps":"consistent"} [meriyah] format 1`] = ` +"Unexpected token: 'with' (1:32) +> 1 | import json from './mod.js' with { "type":"json" }; + | ^ + 2 | import json from './mod.js' with { "foobar":"json" }; + 3 | import json from './mod.js' with { "type-foo" :"json" }; + 4 | import json from './mod.js' with { "333foo" :"json" }; +Cause: [1:32]: Unexpected token: 'with'" +`; + +exports[`quoted-keys.js - {"quoteProps":"consistent"} format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript"] +printWidth: 80 +quoteProps: "consistent" + | printWidth +=====================================input====================================== +import json from './mod.js' with { "type":"json" }; +import json from './mod.js' with { "foobar":"json" }; +import json from './mod.js' with { "type-foo" :"json" }; +import json from './mod.js' with { "333foo" :"json" }; +import json from './mod.js' with { "0" :"json" }; +import json from './mod.js' with { "0n" :"json" }; +import json from './mod.js' with { "33333" :"json" }; +import json from './mod.js' with { "33333n" :"json" }; +import json from './mod.js' with { "33333b" :"json" }; +import json from './mod.js' with { "03333" :"json" }; + +=====================================output===================================== +import json from "./mod.js" with { type: "json" }; +import json from "./mod.js" with { foobar: "json" }; +import json from "./mod.js" with { "type-foo": "json" }; +import json from "./mod.js" with { "333foo": "json" }; +import json from "./mod.js" with { "0": "json" }; +import json from "./mod.js" with { "0n": "json" }; +import json from "./mod.js" with { "33333": "json" }; +import json from "./mod.js" with { "33333n": "json" }; +import json from "./mod.js" with { "33333b": "json" }; +import json from "./mod.js" with { "03333": "json" }; + +================================================================================ +`; + +exports[`quoted-keys.js - {"quoteProps":"preserve"} [acorn] format 1`] = ` +"Unexpected token (1:29) +> 1 | import json from './mod.js' with { "type":"json" }; + | ^ + 2 | import json from './mod.js' with { "foobar":"json" }; + 3 | import json from './mod.js' with { "type-foo" :"json" }; + 4 | import json from './mod.js' with { "333foo" :"json" }; +Cause: Unexpected token (1:28)" +`; + +exports[`quoted-keys.js - {"quoteProps":"preserve"} [espree] format 1`] = ` +"Unexpected token with (1:29) +> 1 | import json from './mod.js' with { "type":"json" }; + | ^ + 2 | import json from './mod.js' with { "foobar":"json" }; + 3 | import json from './mod.js' with { "type-foo" :"json" }; + 4 | import json from './mod.js' with { "333foo" :"json" }; +Cause: Unexpected token with" +`; + +exports[`quoted-keys.js - {"quoteProps":"preserve"} [meriyah] format 1`] = ` +"Unexpected token: 'with' (1:32) +> 1 | import json from './mod.js' with { "type":"json" }; + | ^ + 2 | import json from './mod.js' with { "foobar":"json" }; + 3 | import json from './mod.js' with { "type-foo" :"json" }; + 4 | import json from './mod.js' with { "333foo" :"json" }; +Cause: [1:32]: Unexpected token: 'with'" +`; + +exports[`quoted-keys.js - {"quoteProps":"preserve"} format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript"] +printWidth: 80 +quoteProps: "preserve" + | printWidth +=====================================input====================================== +import json from './mod.js' with { "type":"json" }; +import json from './mod.js' with { "foobar":"json" }; +import json from './mod.js' with { "type-foo" :"json" }; +import json from './mod.js' with { "333foo" :"json" }; +import json from './mod.js' with { "0" :"json" }; +import json from './mod.js' with { "0n" :"json" }; +import json from './mod.js' with { "33333" :"json" }; +import json from './mod.js' with { "33333n" :"json" }; +import json from './mod.js' with { "33333b" :"json" }; +import json from './mod.js' with { "03333" :"json" }; + +=====================================output===================================== +import json from "./mod.js" with { "type": "json" }; +import json from "./mod.js" with { "foobar": "json" }; +import json from "./mod.js" with { "type-foo": "json" }; +import json from "./mod.js" with { "333foo": "json" }; +import json from "./mod.js" with { "0": "json" }; +import json from "./mod.js" with { "0n": "json" }; +import json from "./mod.js" with { "33333": "json" }; +import json from "./mod.js" with { "33333n": "json" }; +import json from "./mod.js" with { "33333b": "json" }; +import json from "./mod.js" with { "03333": "json" }; + +================================================================================ +`; + +exports[`quoted-keys.js format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +import json from './mod.js' with { "type":"json" }; +import json from './mod.js' with { "foobar":"json" }; +import json from './mod.js' with { "type-foo" :"json" }; +import json from './mod.js' with { "333foo" :"json" }; +import json from './mod.js' with { "0" :"json" }; +import json from './mod.js' with { "0n" :"json" }; +import json from './mod.js' with { "33333" :"json" }; +import json from './mod.js' with { "33333n" :"json" }; +import json from './mod.js' with { "33333b" :"json" }; +import json from './mod.js' with { "03333" :"json" }; + +=====================================output===================================== +import json from "./mod.js" with { type: "json" }; +import json from "./mod.js" with { foobar: "json" }; +import json from "./mod.js" with { "type-foo": "json" }; +import json from "./mod.js" with { "333foo": "json" }; +import json from "./mod.js" with { "0": "json" }; +import json from "./mod.js" with { "0n": "json" }; +import json from "./mod.js" with { "33333": "json" }; +import json from "./mod.js" with { "33333n": "json" }; +import json from "./mod.js" with { "33333b": "json" }; +import json from "./mod.js" with { "03333": "json" }; + +================================================================================ +`; + exports[`re-export.js [acorn] format 1`] = ` "Unexpected token (1:44) > 1 | export { default as foo2 } from "foo.json" with { type: "json" }; @@ -265,6 +933,104 @@ exports[`re-export.js [meriyah] format 1`] = ` Cause: [1:47]: Unexpected token: 'with'" `; +exports[`re-export.js - {"quoteProps":"consistent"} [acorn] format 1`] = ` +"Unexpected token (1:44) +> 1 | export { default as foo2 } from "foo.json" with { type: "json" }; + | ^ + 2 | export * from "foo.json" with { type: "json" }; + 3 | export * as foo3 from "foo.json" with { type: "json" }; + 4 | +Cause: Unexpected token (1:43)" +`; + +exports[`re-export.js - {"quoteProps":"consistent"} [espree] format 1`] = ` +"Unexpected token with (1:44) +> 1 | export { default as foo2 } from "foo.json" with { type: "json" }; + | ^ + 2 | export * from "foo.json" with { type: "json" }; + 3 | export * as foo3 from "foo.json" with { type: "json" }; + 4 | +Cause: Unexpected token with" +`; + +exports[`re-export.js - {"quoteProps":"consistent"} [meriyah] format 1`] = ` +"Unexpected token: 'with' (1:47) +> 1 | export { default as foo2 } from "foo.json" with { type: "json" }; + | ^ + 2 | export * from "foo.json" with { type: "json" }; + 3 | export * as foo3 from "foo.json" with { type: "json" }; + 4 | +Cause: [1:47]: Unexpected token: 'with'" +`; + +exports[`re-export.js - {"quoteProps":"consistent"} format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript"] +printWidth: 80 +quoteProps: "consistent" + | printWidth +=====================================input====================================== +export { default as foo2 } from "foo.json" with { type: "json" }; +export * from "foo.json" with { type: "json" }; +export * as foo3 from "foo.json" with { type: "json" }; + +=====================================output===================================== +export { default as foo2 } from "foo.json" with { type: "json" }; +export * from "foo.json" with { type: "json" }; +export * as foo3 from "foo.json" with { type: "json" }; + +================================================================================ +`; + +exports[`re-export.js - {"quoteProps":"preserve"} [acorn] format 1`] = ` +"Unexpected token (1:44) +> 1 | export { default as foo2 } from "foo.json" with { type: "json" }; + | ^ + 2 | export * from "foo.json" with { type: "json" }; + 3 | export * as foo3 from "foo.json" with { type: "json" }; + 4 | +Cause: Unexpected token (1:43)" +`; + +exports[`re-export.js - {"quoteProps":"preserve"} [espree] format 1`] = ` +"Unexpected token with (1:44) +> 1 | export { default as foo2 } from "foo.json" with { type: "json" }; + | ^ + 2 | export * from "foo.json" with { type: "json" }; + 3 | export * as foo3 from "foo.json" with { type: "json" }; + 4 | +Cause: Unexpected token with" +`; + +exports[`re-export.js - {"quoteProps":"preserve"} [meriyah] format 1`] = ` +"Unexpected token: 'with' (1:47) +> 1 | export { default as foo2 } from "foo.json" with { type: "json" }; + | ^ + 2 | export * from "foo.json" with { type: "json" }; + 3 | export * as foo3 from "foo.json" with { type: "json" }; + 4 | +Cause: [1:47]: Unexpected token: 'with'" +`; + +exports[`re-export.js - {"quoteProps":"preserve"} format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript"] +printWidth: 80 +quoteProps: "preserve" + | printWidth +=====================================input====================================== +export { default as foo2 } from "foo.json" with { type: "json" }; +export * from "foo.json" with { type: "json" }; +export * as foo3 from "foo.json" with { type: "json" }; + +=====================================output===================================== +export { default as foo2 } from "foo.json" with { type: "json" }; +export * from "foo.json" with { type: "json" }; +export * as foo3 from "foo.json" with { type: "json" }; + +================================================================================ +`; + exports[`re-export.js format 1`] = ` ====================================options===================================== parsers: ["babel", "typescript"] @@ -307,6 +1073,84 @@ exports[`static-import.js [meriyah] format 1`] = ` Cause: [1:34]: Unexpected token: 'with'" `; +exports[`static-import.js - {"quoteProps":"consistent"} [acorn] format 1`] = ` +"Unexpected token (1:31) +> 1 | import json from "./foo.json" with { type: "json" }; + | ^ + 2 | +Cause: Unexpected token (1:30)" +`; + +exports[`static-import.js - {"quoteProps":"consistent"} [espree] format 1`] = ` +"Unexpected token with (1:31) +> 1 | import json from "./foo.json" with { type: "json" }; + | ^ + 2 | +Cause: Unexpected token with" +`; + +exports[`static-import.js - {"quoteProps":"consistent"} [meriyah] format 1`] = ` +"Unexpected token: 'with' (1:34) +> 1 | import json from "./foo.json" with { type: "json" }; + | ^ + 2 | +Cause: [1:34]: Unexpected token: 'with'" +`; + +exports[`static-import.js - {"quoteProps":"consistent"} format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript"] +printWidth: 80 +quoteProps: "consistent" + | printWidth +=====================================input====================================== +import json from "./foo.json" with { type: "json" }; + +=====================================output===================================== +import json from "./foo.json" with { type: "json" }; + +================================================================================ +`; + +exports[`static-import.js - {"quoteProps":"preserve"} [acorn] format 1`] = ` +"Unexpected token (1:31) +> 1 | import json from "./foo.json" with { type: "json" }; + | ^ + 2 | +Cause: Unexpected token (1:30)" +`; + +exports[`static-import.js - {"quoteProps":"preserve"} [espree] format 1`] = ` +"Unexpected token with (1:31) +> 1 | import json from "./foo.json" with { type: "json" }; + | ^ + 2 | +Cause: Unexpected token with" +`; + +exports[`static-import.js - {"quoteProps":"preserve"} [meriyah] format 1`] = ` +"Unexpected token: 'with' (1:34) +> 1 | import json from "./foo.json" with { type: "json" }; + | ^ + 2 | +Cause: [1:34]: Unexpected token: 'with'" +`; + +exports[`static-import.js - {"quoteProps":"preserve"} format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript"] +printWidth: 80 +quoteProps: "preserve" + | printWidth +=====================================input====================================== +import json from "./foo.json" with { type: "json" }; + +=====================================output===================================== +import json from "./foo.json" with { type: "json" }; + +================================================================================ +`; + exports[`static-import.js format 1`] = ` ====================================options===================================== parsers: ["babel", "typescript"] @@ -345,6 +1189,84 @@ exports[`without-from.js [meriyah] format 1`] = ` Cause: [1:17]: Unexpected token: 'with'" `; +exports[`without-from.js - {"quoteProps":"consistent"} [acorn] format 1`] = ` +"Unexpected token (1:14) +> 1 | import "foo" with { type: "json" } + | ^ + 2 | +Cause: Unexpected token (1:13)" +`; + +exports[`without-from.js - {"quoteProps":"consistent"} [espree] format 1`] = ` +"Unexpected token with (1:14) +> 1 | import "foo" with { type: "json" } + | ^ + 2 | +Cause: Unexpected token with" +`; + +exports[`without-from.js - {"quoteProps":"consistent"} [meriyah] format 1`] = ` +"Unexpected token: 'with' (1:17) +> 1 | import "foo" with { type: "json" } + | ^ + 2 | +Cause: [1:17]: Unexpected token: 'with'" +`; + +exports[`without-from.js - {"quoteProps":"consistent"} format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript"] +printWidth: 80 +quoteProps: "consistent" + | printWidth +=====================================input====================================== +import "foo" with { type: "json" } + +=====================================output===================================== +import "foo" with { type: "json" }; + +================================================================================ +`; + +exports[`without-from.js - {"quoteProps":"preserve"} [acorn] format 1`] = ` +"Unexpected token (1:14) +> 1 | import "foo" with { type: "json" } + | ^ + 2 | +Cause: Unexpected token (1:13)" +`; + +exports[`without-from.js - {"quoteProps":"preserve"} [espree] format 1`] = ` +"Unexpected token with (1:14) +> 1 | import "foo" with { type: "json" } + | ^ + 2 | +Cause: Unexpected token with" +`; + +exports[`without-from.js - {"quoteProps":"preserve"} [meriyah] format 1`] = ` +"Unexpected token: 'with' (1:17) +> 1 | import "foo" with { type: "json" } + | ^ + 2 | +Cause: [1:17]: Unexpected token: 'with'" +`; + +exports[`without-from.js - {"quoteProps":"preserve"} format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript"] +printWidth: 80 +quoteProps: "preserve" + | printWidth +=====================================input====================================== +import "foo" with { type: "json" } + +=====================================output===================================== +import "foo" with { type: "json" }; + +================================================================================ +`; + exports[`without-from.js format 1`] = ` ====================================options===================================== parsers: ["babel", "typescript"] diff --git a/tests/format/js/import-attributes/jsfmt.spec.js b/tests/format/js/import-attributes/jsfmt.spec.js --- a/tests/format/js/import-attributes/jsfmt.spec.js +++ b/tests/format/js/import-attributes/jsfmt.spec.js @@ -1,34 +1,44 @@ +const errors = { + acorn: [ + "dynamic-import.js", + "empty.js", + "multi-types.js", + "static-import.js", + "re-export.js", + "without-from.js", + "non-type.js", + "keyword-detect.js", + "quoted-keys.js", + ], + espree: [ + "dynamic-import.js", + "empty.js", + "multi-types.js", + "static-import.js", + "re-export.js", + "without-from.js", + "non-type.js", + "keyword-detect.js", + "quoted-keys.js", + ], + meriyah: [ + "dynamic-import.js", + "empty.js", + "multi-types.js", + "static-import.js", + "re-export.js", + "without-from.js", + "non-type.js", + "keyword-detect.js", + "quoted-keys.js", + ], +}; +runFormatTest(import.meta, ["babel", "typescript"], { errors }); runFormatTest(import.meta, ["babel", "typescript"], { - errors: { - acorn: [ - "dynamic-import.js", - "empty.js", - "multi-types.js", - "static-import.js", - "re-export.js", - "without-from.js", - "non-type.js", - "keyword-detect.js", - ], - espree: [ - "dynamic-import.js", - "empty.js", - "multi-types.js", - "static-import.js", - "re-export.js", - "without-from.js", - "non-type.js", - "keyword-detect.js", - ], - meriyah: [ - "dynamic-import.js", - "empty.js", - "multi-types.js", - "static-import.js", - "re-export.js", - "without-from.js", - "non-type.js", - "keyword-detect.js", - ], - }, + quoteProps: "consistent", + errors, +}); +runFormatTest(import.meta, ["babel", "typescript"], { + quoteProps: "preserve", + errors, }); diff --git a/tests/format/js/import-attributes/quoted-keys.js b/tests/format/js/import-attributes/quoted-keys.js new file mode 100644 --- /dev/null +++ b/tests/format/js/import-attributes/quoted-keys.js @@ -0,0 +1,10 @@ +import json from './mod.js' with { "type":"json" }; +import json from './mod.js' with { "foobar":"json" }; +import json from './mod.js' with { "type-foo" :"json" }; +import json from './mod.js' with { "333foo" :"json" }; +import json from './mod.js' with { "0" :"json" }; +import json from './mod.js' with { "0n" :"json" }; +import json from './mod.js' with { "33333" :"json" }; +import json from './mod.js' with { "33333n" :"json" }; +import json from './mod.js' with { "33333b" :"json" }; +import json from './mod.js' with { "03333" :"json" };
Safely remove quotes from keys in Import Attributes ## Description <!-- Please provide a brief summary of your changes: --> Fixes #15563 ## Checklist <!-- Please ensure you’ve done all of these things (if applicable). --> <!-- You can replace the `[ ]` with `[x]` to mark each task as done. --> - [x] I’ve added tests to confirm my change works. - [ ] (If changing the API or CLI) I’ve documented the changes I’ve made (in the `docs/` directory). - [ ] (If the change is user-facing) I’ve added my changes to `changelog_unreleased/*/XXXX.md` file following `changelog_unreleased/TEMPLATE.md`. - [x] I’ve read the [contributing guidelines](https://github.com/prettier/prettier/blob/main/CONTRIBUTING.md). <!-- Please DO NOT remove the playground link --> **✨[Try the playground for this PR](https://prettier.io/playground-redirect)✨** Remove quotes in import attribute **Prettier 3.0.3** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBLAtgBwgJxgAmAF98AzHCdfAcmvwHdUYALQ-AHRBgE9M5OknAFYBnaJ3xEQAGhARMMVNBHJQAQxwV6ABQ0IVKNQBt6a7itkAjHGrABrODADKa9HAAyqKHGSljIuCsbe0cnTFsvAHNkGBwAV0CQAPRUGPjEkSijOABFOIh4X39E0QAPJyzc-MKkPyMA2QBHarhtCkwDEDURAFpvOAATQZkuG1QjKIBhSnQ1ZC6jIxHMqEjsgEEYWNRLOPhtOBxPbyL6xOYYdCMAdWYmOBFwsDgnfSZUADcmbnmwEQsQB8EgBJKBDWBOMA4VAKdZgpw8bJpBKyTAUALXGyYeZoh6HD4+WReAJ4NpqSKzU4NEDhHAk+aWNSWOBLVHQ2DXVADFjIAAcAAZZDg4M1UMKyRS5rVirIYEzOdzmMgAEyyOIBAAqTIMdWpcHQzIGQwG7jUqzi5LgADFcLMtlF5mo9hAQEQiEA) <!-- prettier-ignore --> ```sh --parser babel ``` **Input:** <!-- prettier-ignore --> ```jsx import {} from '' with { "type":"json" } ``` **Output:** <!-- prettier-ignore --> ```jsx import {} from "" with { "type": "json" }; ``` **Expected behavior:** ```jsx import {} from "" with { type: "json" }; ```
For some reason FULL_TEST is failing. I'll investigate later. It is intended to remove quotes from keys in object literals. Does Import Attribute keys have a different meaning depending on whether it is quoted or not? --- **Prettier 3.0.3** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuc0DOMAEAzCFMC8mwmAOiLhOUpgMyYC+A3KVCADQgQAOMAlumSgAhgCdREAO4AFMQjTIQwgDaThATwWcARqOFgA1nBgBlYQFs4AGT5Q4ybCrRwdew8ZPd9tgObIYogCuLiDO5nz+QSFovspwAIqBEPAOTiEAVmgAHiaxCUkpSI7KzpwAjgVw0hLcCijCaAC0dnAAJm0cIAHCfMq+AMIQ5ubCiirKnTFQPnEAgjABfNqB8NJwojZ2qSUhABYw5soA6rt88GheYHAm8md8AG5n6opgaFog98EAklDtsCZgUR8XizX4mGDqOLbUogbgSZxHPTcRRwuDOUT3eycWzomDVYQ+EbQkJeUToxTaYTaOATThw2wwI58VowXbIAAcAAZOKI4BU+Lz8YTRkU0pwYFSmSy2UgAEycQLOAAqVLqxRhcHM1Na7VaVmE00CBLgADEIKIRgtfGMVhAQAwGEA) <!-- prettier-ignore --> ```sh --parser babel ``` **Input:** <!-- prettier-ignore --> ```jsx const foo = { "foo": 3 }; ``` **Output:** <!-- prettier-ignore --> ```jsx const foo = { foo: 3 }; ``` I think it's similar to object expression. Only need quotes for special characters like `-` Ah sorry, I misunderstood that output and expected were the opposite. understood. thank you. @nicolo-ribaudo Is it safe to remove quotes from Import Attributes keys using the exact same algorithm as for object literal keys? Yes, except for numeric keys like `"0"`. ... What about `"0n"`? Also not safe — the only valid keys are strings and identifiers.
"2024-01-07T14:44:10Z"
3.3
[]
[ "tests/format/js/import-attributes/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBLAtgBwgJxgAmAF98AzHCdfAcmvwHdUYALQ-AHRBgE9M5OknAFYBnaJ3xEQAGhARMMVNBHJQAQxwV6ABQ0IVKNQBt6a7itkAjHGrABrODADKa9HAAyqKHGSljIuCsbe0cnTFsvAHNkGBwAV0CQAPRUGPjEkSijOABFOIh4X39E0QAPJyzc-MKkPyMA2QBHarhtCkwDEDURAFpvOAATQZkuG1QjKIBhSnQ1ZC6jIxHMqEjsgEEYWNRLOPhtOBxPbyL6xOYYdCMAdWYmOBFwsDgnfSZUADcmbnmwEQsQB8EgBJKBDWBOMA4VAKdZgpw8bJpBKyTAUALXGyYeZoh6HD4+WReAJ4NpqSKzU4NEDhHAk+aWNSWOBLVHQ2DXVADFjIAAcAAZZDg4M1UMKyRS5rVirIYEzOdzmMgAEyyOIBAAqTIMdWpcHQzIGQwG7jUqzi5LgADFcLMtlF5mo9hAQEQiEA", "https://prettier.io/playground-redirect" ]
prettier/prettier
15,915
prettier__prettier-15915
[ "15912" ]
12f91dd1a9bbcd0a93f9f5bf91bf99f1af5f4bb9
diff --git a/src/language-js/utils/index.js b/src/language-js/utils/index.js --- a/src/language-js/utils/index.js +++ b/src/language-js/utils/index.js @@ -405,6 +405,16 @@ function isTestCall(node, parent) { /** @return {(node: Node) => boolean} */ const skipChainExpression = (fn) => (node) => { if (node?.type === "ChainExpression") { + // @ts-expect-error + if (!node.object) { + // @ts-expect-error + node.object = node.expression.object; + } + // @ts-expect-error + if (!node.property) { + // @ts-expect-error + node.property = node.expression.property; + } node = node.expression; }
diff --git a/tests/format/js/chain-expression/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/chain-expression/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/js/chain-expression/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/chain-expression/__snapshots__/jsfmt.spec.js.snap @@ -81,6 +81,22 @@ logger.log( ================================================================================ `; +exports[`issue-15912.js format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript", "flow"] +printWidth: 80 + | printWidth +=====================================input====================================== +test() + .test2() + .test2(thing?.something); + +=====================================output===================================== +test().test2().test2(thing?.something); + +================================================================================ +`; + exports[`test.js format 1`] = ` ====================================options===================================== parsers: ["babel", "typescript", "flow"] diff --git a/tests/format/js/chain-expression/issue-15912.js b/tests/format/js/chain-expression/issue-15912.js new file mode 100644 --- /dev/null +++ b/tests/format/js/chain-expression/issue-15912.js @@ -0,0 +1,3 @@ +test() + .test2() + .test2(thing?.something);
TypeError: Cannot read properties of undefined (reading 'type') **Prettier 3.2.0** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuE8DOMAUBKAOlXGAOnRgCYd9CS4MKYALASygHMB+ItCAWzkZatsAbnwgANCAgAHGE2hpkoAIYAnVRADuABTUJFKZQBtNygJ6LJAI1XKwAa34BlZXwAyLOMgBmxtHGtbB2dpO0FkGFUAVwCQfx4mCOjYuAAPaThVJj5YYwAVTKg1JlofP1i0QSM4AEUoiHgyo39JACs0VKcq2vrGpF9m2IBHXrhtDWkDEGU0AFooODgAE2WJVFsmI0EAYV4eZWRpoyM1yrZqgEEYSKYrKPhtTI8FppaQBhgeIwB1ZnRQsBwJz6JhyABuoLMhzAaEsIDBMQAklAVrAnGAsrILiinDAzNVXrFpBp-N9bNJDsTaJkwV5JCx-KoYONlKx9oTJKFVIzDniMmgMUxZGtiSwYN8mEtGMgABwABkkqjgIyYSpZbIO-XKkhgyisEqlDGQZEkUX8eT1BgGbzgPCsyxWSzcyjYUVZcAAYhBVPtruFDPcICAAL7BoA) <!-- prettier-ignore --> ```sh --parser typescript ``` **Input:** <!-- prettier-ignore --> ```tsx test() .test2() .test2(thing?.something); ``` **Output:** <!-- prettier-ignore --> ```tsx TypeError: Cannot read properties of undefined (reading 'type') at Jn (https://prettier.io/lib/plugins/estree.js:7:16595) at be (https://prettier.io/lib/plugins/estree.js:9:605) at be (https://prettier.io/lib/plugins/estree.js:10:289) at https://prettier.io/lib/plugins/estree.js:36:14282 at Array.every (<anonymous>) at https://prettier.io/lib/plugins/estree.js:36:14273 at Array.some (<anonymous>) at Oi (https://prettier.io/lib/plugins/estree.js:36:14252) at Kr (https://prettier.io/lib/plugins/estree.js:36:14852) at Ta (https://prettier.io/lib/plugins/estree.js:36:58423) ``` **Expected output:** Not exactly sure, it's an error. **Why?** This was not an error in 3.1.x.
Thank you! I'll look into this
"2024-01-12T18:50:31Z"
3.3
[]
[ "tests/format/js/chain-expression/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuE8DOMAUBKAOlXGAOnRgCYd9CS4MKYALASygHMB+ItCAWzkZatsAbnwgANCAgAHGE2hpkoAIYAnVRADuABTUJFKZQBtNygJ6LJAI1XKwAa34BlZXwAyLOMgBmxtHGtbB2dpO0FkGFUAVwCQfx4mCOjYuAAPaThVJj5YYwAVTKg1JlofP1i0QSM4AEUoiHgyo39JACs0VKcq2vrGpF9m2IBHXrhtDWkDEGU0AFooODgAE2WJVFsmI0EAYV4eZWRpoyM1yrZqgEEYSKYrKPhtTI8FppaQBhgeIwB1ZnRQsBwJz6JhyABuoLMhzAaEsIDBMQAklAVrAnGAsrILiinDAzNVXrFpBp-N9bNJDsTaJkwV5JCx-KoYONlKx9oTJKFVIzDniMmgMUxZGtiSwYN8mEtGMgABwABkkqjgIyYSpZbIO-XKkhgyisEqlDGQZEkUX8eT1BgGbzgPCsyxWSzcyjYUVZcAAYhBVPtruFDPcICAAL7BoA" ]
prettier/prettier
15,920
prettier__prettier-15920
[ "15916" ]
4ce96dd530613b99bb4a682ec93f719f3d4109f5
diff --git a/src/language-js/utils/index.js b/src/language-js/utils/index.js --- a/src/language-js/utils/index.js +++ b/src/language-js/utils/index.js @@ -405,16 +405,6 @@ function isTestCall(node, parent) { /** @return {(node: Node) => boolean} */ const skipChainExpression = (fn) => (node) => { if (node?.type === "ChainExpression") { - // @ts-expect-error - if (!node.object) { - // @ts-expect-error - node.object = node.expression.object; - } - // @ts-expect-error - if (!node.property) { - // @ts-expect-error - node.property = node.expression.property; - } node = node.expression; } @@ -429,6 +419,22 @@ const isMemberExpression = skipChainExpression( createTypeCheckFunction(["MemberExpression", "OptionalMemberExpression"]), ); +/** + * Retrieves a property from a node, considering any ChainExpression. + * If the node is a ChainExpression, the property is obtained from its expression. + * Otherwise, the property is obtained directly from the node. + * + * @param {Node} node - The AST node to be processed. + * @param {string} property - The property name to retrieve. + * @returns The property value from the node or its expression. + */ +function getChainProp(node, property) { + if (node.type === "ChainExpression") { + return node.expression[property]; + } + return node[property]; +} + /** * * @param {any} node @@ -769,7 +775,7 @@ function isSimpleCallArgument(node, depth = 2) { if (isCallLikeExpression(node)) { if ( node.type === "ImportExpression" || - isSimpleCallArgument(node.callee, depth) + isSimpleCallArgument(getChainProp(node, "callee"), depth) ) { const args = getCallArguments(node); return args.length <= depth && args.every(isChildSimple); @@ -779,8 +785,8 @@ function isSimpleCallArgument(node, depth = 2) { if (isMemberExpression(node)) { return ( - isSimpleCallArgument(node.object, depth) && - isSimpleCallArgument(node.property, depth) + isSimpleCallArgument(getChainProp(node, "object"), depth) && + isSimpleCallArgument(getChainProp(node, "property"), depth) ); } @@ -1232,6 +1238,7 @@ export { createTypeCheckFunction, getCallArguments, getCallArgumentSelector, + getChainProp, getComments, getFunctionParameters, getLeftSide,
diff --git a/tests/format/js/chain-expression/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/chain-expression/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/js/chain-expression/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/chain-expression/__snapshots__/jsfmt.spec.js.snap @@ -97,6 +97,35 @@ test().test2().test2(thing?.something); ================================================================================ `; +exports[`issue-15916.js format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript", "flow"] +printWidth: 80 + | printWidth +=====================================input====================================== +const randomFuncion = (value) => { + if (value.a) { + funcA( + "", + funcB( + dayjs(value.a?.toString()) + .add(1, "day") + .toISOString() + ) + ); + } +}; + +=====================================output===================================== +const randomFuncion = (value) => { + if (value.a) { + funcA("", funcB(dayjs(value.a?.toString()).add(1, "day").toISOString())); + } +}; + +================================================================================ +`; + exports[`test.js format 1`] = ` ====================================options===================================== parsers: ["babel", "typescript", "flow"] diff --git a/tests/format/js/chain-expression/issue-15916.js b/tests/format/js/chain-expression/issue-15916.js new file mode 100644 --- /dev/null +++ b/tests/format/js/chain-expression/issue-15916.js @@ -0,0 +1,12 @@ +const randomFuncion = (value) => { + if (value.a) { + funcA( + "", + funcB( + dayjs(value.a?.toString()) + .add(1, "day") + .toISOString() + ) + ); + } +};
TypeError: Cannot read properties of undefined (reading 'type') **Prettier 3.2.1** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEACdrJQM41QJwEMoATCAWwDEBXKMAS2lQF5UAKAN0IBtq4BKJKg4R6JFgD5UwADpQMC1PQBm7LrzgA6Qv2lzFB1MtpgAgm32GrMkDYA0lqweN0AQhflOvJQgE8AVticPHzaAPyaMBAAyjD49FAA5mz8-I5eijIwWdokJGwAjHaoNj6+NmmeGZnZMJEQAJLRAPKx8Ukp6dWV3QDcXRgAvumD-VAgdiAQAA4wjDjIoIT4+BAA7gAKywjYyCA8a367kwBGRGAA1nAw0YTkcAAyCXDIyjzYcKfnVzfThAxJZBxPiTD7kehA-AgkBwAAe0zg8XusB4ABVEVBlvQ4LskG9uB9QQlEtw4ABFagQeCvd6fECBWHRYmkilUl542mTACOlPgG1W01x+2wAFooHA4CRJRMQHFCPRuMSAMIUciEPY8bgy7DMuCmGBxegnah8xFPcU0gl0gAWMHI3AA6tb6PBsH8wHBojsXfQOC7fHswNhjiAOHwGqQEDcwPFZqZSLFfKTLYSQNNVh8HURpnt0zjERwXpMEh98DB+YREmqU3S-vhS3sYL4EdgY-RZjL0wkYA6xDBrcgABwABkm+DgPPo44rVfVHKtkxghBOvZI-eQACZJtQPqjl7j8am4OQTpKpSQHsREtRK3BKBB8GqDcSNSaICBBoMgA) <!-- prettier-ignore --> ```sh --parser typescript ``` **Input:** <!-- prettier-ignore --> ```tsx const randomFuncion = (value): void => { if (value.a) { funcA( "", funcB( dayjs(value.a?.toString()) .add(1, "day") .toISOString() ) ); } }; ``` **Output:** <!-- prettier-ignore --> ```tsx TypeError: Cannot read properties of undefined (reading 'type') at Jn (https://prettier.io/lib/plugins/estree.js:7:16595) at be (https://prettier.io/lib/plugins/estree.js:9:605) at be (https://prettier.io/lib/plugins/estree.js:10:209) at https://prettier.io/lib/plugins/estree.js:36:14282 at Array.every (<anonymous>) at https://prettier.io/lib/plugins/estree.js:36:14273 at Array.some (<anonymous>) at Oi (https://prettier.io/lib/plugins/estree.js:36:14252) at Kr (https://prettier.io/lib/plugins/estree.js:36:14852) at da (https://prettier.io/lib/plugins/estree.js:36:58423) ``` **Expected output:** <!-- prettier-ignore --> ```tsx const randomFuncion = (value): void => { if (value.a) { funcA( "", funcB(dayjs(value.a?.toString()) .add(1, "day") .toISOString() ) ); } }; ``` **Why?** That was not an Error in 3.1.1 here the error in version 3.2.0 which should be fixed in #15912 If I remove the question mark behind the `funcB(dayjs(value.a? ...` the error is gone. <!-- short explanation of expected output -->
I'm getting the same error with `[email protected]` in my project, here is the minimal reproduction example : ```js a(() => {}, c?.d); ``` The workaround is to introduce an additional variable: ```js const b = c?.d; a(() => {}, b); ```
"2024-01-14T02:29:51Z"
3.3
[]
[ "tests/format/js/chain-expression/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEACdrJQM41QJwEMoATCAWwDEBXKMAS2lQF5UAKAN0IBtq4BKJKg4R6JFgD5UwADpQMC1PQBm7LrzgA6Qv2lzFB1MtpgAgm32GrMkDYA0lqweN0AQhflOvJQgE8AVticPHzaAPyaMBAAyjD49FAA5mz8-I5eijIwWdokJGwAjHaoNj6+NmmeGZnZMJEQAJLRAPKx8Ukp6dWV3QDcXRgAvumD-VAgdiAQAA4wjDjIoIT4+BAA7gAKywjYyCA8a367kwBGRGAA1nAw0YTkcAAyCXDIyjzYcKfnVzfThAxJZBxPiTD7kehA-AgkBwAAe0zg8XusB4ABVEVBlvQ4LskG9uB9QQlEtw4ABFagQeCvd6fECBWHRYmkilUl542mTACOlPgG1W01x+2wAFooHA4CRJRMQHFCPRuMSAMIUciEPY8bgy7DMuCmGBxegnah8xFPcU0gl0gAWMHI3AA6tb6PBsH8wHBojsXfQOC7fHswNhjiAOHwGqQEDcwPFZqZSLFfKTLYSQNNVh8HURpnt0zjERwXpMEh98DB+YREmqU3S-vhS3sYL4EdgY-RZjL0wkYA6xDBrcgABwABkm+DgPPo44rVfVHKtkxghBOvZI-eQACZJtQPqjl7j8am4OQTpKpSQHsREtRK3BKBB8GqDcSNSaICBBoMgA" ]
prettier/prettier
15,926
prettier__prettier-15926
[ "15897" ]
c2e20fbae8ce1800ac0c8242c176d9379db5c001
diff --git a/src/language-html/embed.js b/src/language-html/embed.js --- a/src/language-html/embed.js +++ b/src/language-html/embed.js @@ -114,7 +114,6 @@ function embed(path, options) { }; if (options.parser === "angular") { textToDocOptions.parser = "__ng_interpolation"; - textToDocOptions.trailingComma = "none"; } else if (options.parser === "vue") { textToDocOptions.parser = isVueSfcWithTypescriptScript( path, diff --git a/src/language-html/embed/angular-attributes.js b/src/language-html/embed/angular-attributes.js --- a/src/language-html/embed/angular-attributes.js +++ b/src/language-html/embed/angular-attributes.js @@ -18,11 +18,7 @@ function createAngularPrinter({ parser }) { formatAttributeValue( getUnescapedAttributeValue(path.node), textToDoc, - { - parser, - // angular does not allow trailing comma - trailingComma: "none", - }, + { parser }, shouldHugJsExpression, ); } diff --git a/src/language-html/embed/angular-control-flow-block-parameters.js b/src/language-html/embed/angular-control-flow-block-parameters.js --- a/src/language-html/embed/angular-control-flow-block-parameters.js +++ b/src/language-html/embed/angular-control-flow-block-parameters.js @@ -24,7 +24,6 @@ function printAngularControlFlowBlockParameters( { parser: "__ng_directive", __isInHtmlAttribute: false, - trailingComma: "none", }, shouldHugJsExpression, ); diff --git a/src/language-html/embed/angular-interpolation.js b/src/language-html/embed/angular-interpolation.js --- a/src/language-html/embed/angular-interpolation.js +++ b/src/language-html/embed/angular-interpolation.js @@ -19,7 +19,6 @@ async function printAngularInterpolation(text, textToDoc) { await formatAttributeValue(part, textToDoc, { parser: "__ng_interpolation", __isInHtmlInterpolation: true, // to avoid unexpected `}}` - trailingComma: "none", }), ]), line, diff --git a/src/language-js/print/call-arguments.js b/src/language-js/print/call-arguments.js --- a/src/language-js/print/call-arguments.js +++ b/src/language-js/print/call-arguments.js @@ -82,7 +82,12 @@ function printCallArguments(path, options, print) { const isDynamicImport = node.type === "ImportExpression" || node.callee.type === "Import"; const maybeTrailingComma = - !isDynamicImport && shouldPrintComma(options, "all") ? "," : ""; + // Angular does not allow trailing comma + !options.parser.startsWith("__ng_") && + !isDynamicImport && + shouldPrintComma(options, "all") + ? "," + : ""; function allArgsBrokenOut() { return group(
diff --git a/tests/format/angular/angular/__snapshots__/format.test.js.snap b/tests/format/angular/angular/__snapshots__/format.test.js.snap --- a/tests/format/angular/angular/__snapshots__/format.test.js.snap +++ b/tests/format/angular/angular/__snapshots__/format.test.js.snap @@ -451,10 +451,10 @@ printWidth: 80 [target]="{a: 1}" [target]="{a: 1}" [target]="{ - trailingComma: 'notAllowed' + trailingComma: 'notAllowed', }" [target]="[ - longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong + longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong, ]" [target]="true" [target]="undefined" @@ -540,14 +540,14 @@ printWidth: 80 listRow.NextScheduledSendStatus == 3 " [target]="{ - longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong: true + longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong: true, }" [error]="'We couldn\\\\\\'t find anything with that name.'" *ngIf="form.controls.details?.controls.amount?.errors.min" [ngClass]="{ 'btn-success': (dialog$ | async).level === dialogLevelEnum.SUCCESS, 'btn-warning': (dialog$ | async).level === dialogLevelEnum.WARNING, - 'btn-svg': (dialog$ | async).level === dialogLevelEnum.DANGER + 'btn-svg': (dialog$ | async).level === dialogLevelEnum.DANGER, }" [stickout]="+toolAssembly.stickoutMm" test="{{ 'test' | translate }}" @@ -730,10 +730,10 @@ printWidth: 80 [target]="{ a: 1 }" [target]="{ a: 1 }" [target]="{ - trailingComma: 'notAllowed' + trailingComma: 'notAllowed', }" [target]="[ - longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong + longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong, ]" [target]="true" [target]="undefined" @@ -819,14 +819,14 @@ printWidth: 80 listRow.NextScheduledSendStatus == 3 " [target]="{ - longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong: true + longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong: true, }" [error]="'We couldn\\\\\\'t find anything with that name.'" *ngIf="form.controls.details?.controls.amount?.errors.min" [ngClass]="{ 'btn-success': (dialog$ | async).level === dialogLevelEnum.SUCCESS, 'btn-warning': (dialog$ | async).level === dialogLevelEnum.WARNING, - 'btn-svg': (dialog$ | async).level === dialogLevelEnum.DANGER + 'btn-svg': (dialog$ | async).level === dialogLevelEnum.DANGER, }" [stickout]="+toolAssembly.stickoutMm" test="{{ 'test' | translate }}" @@ -1053,20 +1053,20 @@ printWidth: 1 ] " [target]="[ - 1 + 1, ]" [target]="{ - a: 1 + a: 1, }" [target]="{ - a: 1 + a: 1, }" [target]="{ trailingComma: - 'notAllowed' + 'notAllowed', }" [target]="[ - longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong + longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong, ]" [target]=" true @@ -1210,7 +1210,7 @@ printWidth: 1 1, 2, 3, - 666666666666666666666666666666666666 + 666666666666666666666666666666666666, ]; let i = index " @@ -1320,7 +1320,7 @@ printWidth: 1 3 " [target]="{ - longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong: true + longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong: true, }" [error]=" 'We couldn\\\\\\'t find anything with that name.' @@ -1355,7 +1355,7 @@ printWidth: 1 | async ) .level === - dialogLevelEnum.DANGER + dialogLevelEnum.DANGER, }" [stickout]=" +toolAssembly.stickoutMm @@ -1636,10 +1636,10 @@ trailingComma: "es5" [target]="{ a: 1 }" [target]="{ a: 1 }" [target]="{ - trailingComma: 'notAllowed' + trailingComma: 'notAllowed', }" [target]="[ - longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong + longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong, ]" [target]="true" [target]="undefined" @@ -1725,14 +1725,14 @@ trailingComma: "es5" listRow.NextScheduledSendStatus == 3 " [target]="{ - longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong: true + longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong: true, }" [error]="'We couldn\\\\\\'t find anything with that name.'" *ngIf="form.controls.details?.controls.amount?.errors.min" [ngClass]="{ 'btn-success': (dialog$ | async).level === dialogLevelEnum.SUCCESS, 'btn-warning': (dialog$ | async).level === dialogLevelEnum.WARNING, - 'btn-svg': (dialog$ | async).level === dialogLevelEnum.DANGER + 'btn-svg': (dialog$ | async).level === dialogLevelEnum.DANGER, }" [stickout]="+toolAssembly.stickoutMm" test="{{ 'test' | translate }}" @@ -3395,21 +3395,21 @@ printWidth: 1 <div> {{ [ - 1 + 1, ] }} </div> <div> {{ { - a: 1 + a: 1, } }} </div> <div> {{ { - a: 1 + a: 1, } }} </div> @@ -3599,8 +3599,8 @@ printWidth: 1 | translate : { count: - array.length - }) + array.length, + }), } }} </p> @@ -3609,7 +3609,7 @@ printWidth: 1 { a: 1 + - {} + {}, } }} </p> @@ -3618,14 +3618,14 @@ printWidth: 1 { a: a === - {} + {}, } }} </p> <p> {{ { - a: !{} + a: !{}, } }} </p> @@ -3634,7 +3634,7 @@ printWidth: 1 { a: a ? b - : {} + : {}, } }} </p> @@ -8391,7 +8391,7 @@ can be found in the LICENSE file at http://angular.io/license <div [ngClass]="{ special: - isSpecial + isSpecial, }" ></div> </div> @@ -9371,7 +9371,7 @@ bindon-ngModel [ngClass]="{ bad: false, curly: true, - special: true + special: true, }" > Curly diff --git a/tests/format/angular/trailing-comma/__snapshots__/format.test.js.snap b/tests/format/angular/trailing-comma/__snapshots__/format.test.js.snap new file mode 100644 --- /dev/null +++ b/tests/format/angular/trailing-comma/__snapshots__/format.test.js.snap @@ -0,0 +1,622 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`trailing-comma.html - {"trailingComma":"all"} format 1`] = ` +====================================options===================================== +parsers: ["angular"] +printWidth: 80 +trailingComma: "all" + | printWidth +=====================================input====================================== +<div + (action)=" + {long, long, long, long, long, long, long, long, long, long, + object, + property, + } + " + (action)=" + [long, long, long, long, long, long, long, long, long, long, + array, + element, + ] + " + (action)=" + call(long, long, long, long, long, long, long, long, long, long, + call, + argument + ) + " + [binding]=" + {long, long, long, long, long, long, long, long, long, long, + object, + property, + } + " + [binding]=" + [long, long, long, long, long, long, long, long, long, long, + array, + element, + ] + " + [binding]=" + call(long, long, long, long, long, long, long, long, long, long, + call, + argument + ) + " + *directive=" + {long, long, long, long, long, long, long, long, long, long, + object, + property, + } + " + *directive=" + [long, long, long, long, long, long, long, long, long, long, + array, + element, + ] + " + *directive=" + call(long, long, long, long, long, long, long, long, long, long, + call, + argument + ) + " +></div> + +=====================================output===================================== +<div + (action)=" + ({ + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + object, + property, + }) + " + (action)=" + ([ + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + array, + element, + ]) + " + (action)=" + call( + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + call, + argument + ) + " + [binding]="{ + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + object, + property, + }" + [binding]="[ + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + array, + element, + ]" + [binding]=" + call( + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + call, + argument + ) + " + *directive="{ + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + object, + property, + }" + *directive="[ + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + array, + element, + ]" + *directive=" + call( + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + call, + argument + ) + " +></div> + +================================================================================ +`; + +exports[`trailing-comma.html - {"trailingComma":"es5"} format 1`] = ` +====================================options===================================== +parsers: ["angular"] +printWidth: 80 +trailingComma: "es5" + | printWidth +=====================================input====================================== +<div + (action)=" + {long, long, long, long, long, long, long, long, long, long, + object, + property, + } + " + (action)=" + [long, long, long, long, long, long, long, long, long, long, + array, + element, + ] + " + (action)=" + call(long, long, long, long, long, long, long, long, long, long, + call, + argument + ) + " + [binding]=" + {long, long, long, long, long, long, long, long, long, long, + object, + property, + } + " + [binding]=" + [long, long, long, long, long, long, long, long, long, long, + array, + element, + ] + " + [binding]=" + call(long, long, long, long, long, long, long, long, long, long, + call, + argument + ) + " + *directive=" + {long, long, long, long, long, long, long, long, long, long, + object, + property, + } + " + *directive=" + [long, long, long, long, long, long, long, long, long, long, + array, + element, + ] + " + *directive=" + call(long, long, long, long, long, long, long, long, long, long, + call, + argument + ) + " +></div> + +=====================================output===================================== +<div + (action)=" + ({ + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + object, + property, + }) + " + (action)=" + ([ + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + array, + element, + ]) + " + (action)=" + call( + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + call, + argument + ) + " + [binding]="{ + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + object, + property, + }" + [binding]="[ + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + array, + element, + ]" + [binding]=" + call( + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + call, + argument + ) + " + *directive="{ + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + object, + property, + }" + *directive="[ + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + array, + element, + ]" + *directive=" + call( + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + call, + argument + ) + " +></div> + +================================================================================ +`; + +exports[`trailing-comma.html - {"trailingComma":"none"} format 1`] = ` +====================================options===================================== +parsers: ["angular"] +printWidth: 80 +trailingComma: "none" + | printWidth +=====================================input====================================== +<div + (action)=" + {long, long, long, long, long, long, long, long, long, long, + object, + property, + } + " + (action)=" + [long, long, long, long, long, long, long, long, long, long, + array, + element, + ] + " + (action)=" + call(long, long, long, long, long, long, long, long, long, long, + call, + argument + ) + " + [binding]=" + {long, long, long, long, long, long, long, long, long, long, + object, + property, + } + " + [binding]=" + [long, long, long, long, long, long, long, long, long, long, + array, + element, + ] + " + [binding]=" + call(long, long, long, long, long, long, long, long, long, long, + call, + argument + ) + " + *directive=" + {long, long, long, long, long, long, long, long, long, long, + object, + property, + } + " + *directive=" + [long, long, long, long, long, long, long, long, long, long, + array, + element, + ] + " + *directive=" + call(long, long, long, long, long, long, long, long, long, long, + call, + argument + ) + " +></div> + +=====================================output===================================== +<div + (action)=" + ({ + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + object, + property + }) + " + (action)=" + ([ + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + array, + element + ]) + " + (action)=" + call( + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + call, + argument + ) + " + [binding]="{ + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + object, + property + }" + [binding]="[ + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + array, + element + ]" + [binding]=" + call( + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + call, + argument + ) + " + *directive="{ + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + object, + property + }" + *directive="[ + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + array, + element + ]" + *directive=" + call( + long, + long, + long, + long, + long, + long, + long, + long, + long, + long, + call, + argument + ) + " +></div> + +================================================================================ +`; diff --git a/tests/format/angular/trailing-comma/format.test.js b/tests/format/angular/trailing-comma/format.test.js new file mode 100644 --- /dev/null +++ b/tests/format/angular/trailing-comma/format.test.js @@ -0,0 +1,3 @@ +runFormatTest(import.meta, ["angular"], { trailingComma: "none" }); +runFormatTest(import.meta, ["angular"], { trailingComma: "es5" }); +runFormatTest(import.meta, ["angular"], { trailingComma: "all" }); diff --git a/tests/format/angular/trailing-comma/trailing-comma.html b/tests/format/angular/trailing-comma/trailing-comma.html new file mode 100644 --- /dev/null +++ b/tests/format/angular/trailing-comma/trailing-comma.html @@ -0,0 +1,56 @@ +<div + (action)=" + {long, long, long, long, long, long, long, long, long, long, + object, + property, + } + " + (action)=" + [long, long, long, long, long, long, long, long, long, long, + array, + element, + ] + " + (action)=" + call(long, long, long, long, long, long, long, long, long, long, + call, + argument + ) + " + [binding]=" + {long, long, long, long, long, long, long, long, long, long, + object, + property, + } + " + [binding]=" + [long, long, long, long, long, long, long, long, long, long, + array, + element, + ] + " + [binding]=" + call(long, long, long, long, long, long, long, long, long, long, + call, + argument + ) + " + *directive=" + {long, long, long, long, long, long, long, long, long, long, + object, + property, + } + " + *directive=" + [long, long, long, long, long, long, long, long, long, long, + array, + element, + ] + " + *directive=" + call(long, long, long, long, long, long, long, long, long, long, + call, + argument + ) + " +></div>
Object literals in Angular templates are missing trailing commas **Prettier 3.1.1** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAJgSwG4B0oAEBAVFAOYCSAZgLy4jD5FEDOADgIZiblIHtceZACQEAPgQ4sAnlDAAaJswCuLOACc+qjaIlTZCpQF9JLAmBgAPekoDa5AMIAbKSwC6dBkqIByNpYBaJzIfPgtLADoBbnICGhoCH2CfRUJmP0CAW3RQ8ysozhiyOISfbJTvRP8AyxZc8ILBWPjE2oq0oxsoAD4lAAlMAgAFdTgYGEwNAgBCfFQAeixsbpB5EAg2CegWZFAOdXUIAHch-YQdlA4nI45pHbWAI3UuAGsxgGUOTLgAGR44ZBUK5qR7PMBvGDvQpCZAwdTKOBrNSZTCw+GIkBwSxsDSYb6wK4AFQ0UH2kwuQKcIJALCETjgAEVlBB4IDgRiAFYsSzvOmM5mspCU6kARwFcBGGwuICkASgcDg6EVqxAcI4mCcQgcEEymQ4yBlTicKtp5HpAEFxupMA9lPAhho-vK2VSMQALGCZJwAdTdmHg0Tg73O-pw-ukBrALHuIGwCIoUCVsHeYGtm3NifeMGk9Jd1LYhzU3uebANBbganU2ABax4lZgIw4ZD1eYxnHUlYNHHIyhc6hVBZ4MG9mHQMDdyAAjAAmAAMa1GYswo0bzf1QvZaxgHAeI7HE6Q07W2kJO4pm8xmQeiqV6B+3bIyibcAAYhB1HrxjDLnaICAjEYQA) <!-- prettier-ignore --> ```sh --parser angular --trailing-comma all ``` **Input:** <!-- prettier-ignore --> ```html <div *ngIf="{ spacing: spacing$ | async, user: user$ | async, } as ctx" [ngClass]="{ 'px-lg': ctx.spacing == 'lg', 'px-md': ctx.spacing == 'md', 'px-xs': ctx.spacing == 'xs', }" > Hi Prettier ! </div> ``` **Output:** <!-- prettier-ignore --> ```html <div *ngIf="{ spacing: spacing$ | async, user: user$ | async } as ctx" [ngClass]="{ 'px-lg': ctx.spacing == 'lg', 'px-md': ctx.spacing == 'md', 'px-xs': ctx.spacing == 'xs' }" > Hi Prettier ! </div> ``` **Expected behavior:** Trailing commas should be kept/inserted in object literals. This used to work on 2.8. <!-- prettier-ignore --> ```html <div *ngIf="{ spacing: spacing$ | async, user: user$ | async, } as ctx" [ngClass]="{ 'px-lg': ctx.spacing == 'lg', 'px-md': ctx.spacing == 'md', 'px-xs': ctx.spacing == 'xs', }" > Hi Prettier ! </div> ```
It's indented to not support `trailingComma`, https://github.com/prettier/prettier/blob/b4ed91bffb0a9140259f4190b77cce1b77284ca0/src/language-html/embed/angular-attributes.js#L23 But maybe it's supportted now? Ah, supported since May, 2023. https://github.com/angular/angular/pull/49535 It seems still not supported in call arguments. **Prettier 3.2.2** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAJgSwG4B0oAEBAVFAOYCSAZgLy7gCGANkwBREMCU9+AfPqgD0WbLxAAaEBAAOMTNADOyUAwBOqiAHcACmoRKUzTQwCeSyQCNVDMAGs4MAMoMAtnAAymKHGRVmCuEtrOwdHaRsvMmQYVQBXQJAAl0xouIS4AA9pOFVMN1hmABUcqDVMOAM-JgDJBUimOABFWIh4X38EgCsFDMd6ppa2pCqakABHQbhtDWkDEAYFAFpvOHRViRAYhkwmSIBhCBcXBmR5lg268gaAQRgYzAtY+G0cz2926oSACxgXJgB1L6YeAKcJgOCOfTAnDAkynMAKcwgbDxChQNawRxgXKya7oxwwEwND6jaQaAL-azSU5kio5bA+SReAKqGDTBhkY4khLhVQs04McixJhqDZkrwwf6YdAwL7IACMACYAAySVRwCaYdXszknYYdSQwBgWKUyuVIRWSWIBQrGyoGkBwFwWVZrdDuQVkWIcuAAMQgqmOd0iAqeEBAAF8I0A) <!-- prettier-ignore --> ```sh --parser angular --print-width 120 ``` **Input:** <!-- prettier-ignore --> ```html <div *ngIf="call( a)" > </div> ``` **Output:** <!-- prettier-ignore --> ```html <div *ngIf="call(a)"></div> ``` **Prettier 3.2.2** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAJgSwG4B0oAEBAVFAOYCSAZgLy7gCGANkwBREMA0AlPfgHz5UAeizZ+ITiAgAHGJmgBnZKAYAnNRADuABXUJlKZloYBPZVIBGahmADWcGAGUGAWzgAZTFDjIqzRTgrG3tHJxlbbzJkGDUAVyCQQNdMGPjEuAAPGTg1THdYZgAVXKh1TDhDfyZAqUUopjgARTiIeD8AxIArRUynBubW9qRq2pAARyG4HU0ZQxAGRQBaHzh0NckQWIZMJiiAYQhXVwZkBZZN+vJGgEEYWMxLOPgdXK8fDprEgAsYVyYAOrfTDwRQRMBwJwGEE4EGmM5gRQWEDYBIUKDrWBOMB5OQ3DFOGCmRqfMYyTSBAE2GRncmVXLYXxSbyBNQwGYMMgnUmJCJqVlnBjkOJMdSbcneGAAzDoGDfZAARgATAAGKRqOCTTAajlc04jTpSGAMSzS2XypBKqRxQJFE1VQ0gOCuSxrdboDxCshxTlwABiEDUJ3uUUFzwgIAAvpGgA) <!-- prettier-ignore --> ```sh --parser angular --print-width 120 ``` **Input:** <!-- prettier-ignore --> ```html <div *ngIf="call( a,)" > </div> ``` **Output:** <!-- prettier-ignore --> ```html SyntaxError: Unexpected token ) ```
"2024-01-15T12:29:28Z"
3.3
[]
[ "tests/format/angular/angular/format.test.js", "tests/format/angular/trailing-comma/format.test.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAJgSwG4B0oAEBAVFAOYCSAZgLy4jD5FEDOADgIZiblIHtceZACQEAPgQ4sAnlDAAaJswCuLOACc+qjaIlTZCpQF9JLAmBgAPekoDa5AMIAbKSwC6dBkqIByNpYBaJzIfPgtLADoBbnICGhoCH2CfRUJmP0CAW3RQ8ysozhiyOISfbJTvRP8AyxZc8ILBWPjE2oq0oxsoAD4lAAlMAgAFdTgYGEwNAgBCfFQAeixsbpB5EAg2CegWZFAOdXUIAHch-YQdlA4nI45pHbWAI3UuAGsxgGUOTLgAGR44ZBUK5qR7PMBvGDvQpCZAwdTKOBrNSZTCw+GIkBwSxsDSYb6wK4AFQ0UH2kwuQKcIJALCETjgAEVlBB4IDgRiAFYsSzvOmM5mspCU6kARwFcBGGwuICkASgcDg6EVqxAcI4mCcQgcEEymQ4yBlTicKtp5HpAEFxupMA9lPAhho-vK2VSMQALGCZJwAdTdmHg0Tg73O-pw-ukBrALHuIGwCIoUCVsHeYGtm3NifeMGk9Jd1LYhzU3uebANBbganU2ABax4lZgIw4ZD1eYxnHUlYNHHIyhc6hVBZ4MG9mHQMDdyAAjAAmAAMa1GYswo0bzf1QvZaxgHAeI7HE6Q07W2kJO4pm8xmQeiqV6B+3bIyibcAAYhB1HrxjDLnaICAjEYQA" ]
prettier/prettier
15,947
prettier__prettier-15947
[ "15945" ]
6c6a332171f590a38c369673662d1a5baf765167
diff --git a/src/language-json/languages.evaluate.js b/src/language-json/languages.evaluate.js --- a/src/language-json/languages.evaluate.js +++ b/src/language-json/languages.evaluate.js @@ -14,10 +14,26 @@ const languages = [ parsers: ["json"], vscodeLanguageIds: ["json"], extensions: data.extensions.filter((extension) => extension !== ".jsonl"), + filenames: [ + ...data.filenames, + ".babelrc", + ".jscsrc", + ".jshintrc", + ".jslintrc", + ".swcrc", + ], })), createLanguage(linguistLanguages["JSON with Comments"], () => ({ parsers: ["jsonc"], vscodeLanguageIds: ["jsonc"], + // Too many filenames from `linguist-languages` are not a valid JSONC files. + // https://github.com/prettier/prettier/issues/15945#issuecomment-1895371835 + filenames: [ + "devcontainer.json", + "jsconfig.json", + "language-configuration.json", + "tsconfig.json", + ], })), createLanguage(linguistLanguages.JSON5, () => ({ parsers: ["json5"],
diff --git a/tests/integration/__tests__/__snapshots__/support-info.js.snap b/tests/integration/__tests__/__snapshots__/support-info.js.snap --- a/tests/integration/__tests__/__snapshots__/support-info.js.snap +++ b/tests/integration/__tests__/__snapshots__/support-info.js.snap @@ -488,7 +488,12 @@ exports[`CLI --support-info (stdout) 1`] = ` "Pipfile.lock", "composer.lock", "flake.lock", - "mcmod.info" + "mcmod.info", + ".babelrc", + ".jscsrc", + ".jshintrc", + ".jslintrc", + ".swcrc" ], "linguistLanguageId": 174, "name": "JSON", @@ -522,19 +527,10 @@ exports[`CLI --support-info (stdout) 1`] = ` ".sublime_session" ], "filenames": [ - ".babelrc", - ".devcontainer.json", - ".eslintrc.json", - ".jscsrc", - ".jshintrc", - ".jslintrc", - ".swcrc", - "api-extractor.json", "devcontainer.json", "jsconfig.json", "language-configuration.json", - "tsconfig.json", - "tslint.json" + "tsconfig.json" ], "group": "JSON", "linguistLanguageId": 423, diff --git a/tests/integration/__tests__/with-parser-inference.js b/tests/integration/__tests__/with-parser-inference.js --- a/tests/integration/__tests__/with-parser-inference.js +++ b/tests/integration/__tests__/with-parser-inference.js @@ -66,8 +66,8 @@ describe("infers parser from filename", () => { { "jsc": { // Requires v1.2.50 or upper and requires target to be es2016 or upper. - "keepClassNames": false, - }, + "keepClassNames": false + } } ` + "\n", );
Prettier 3.2.3 incorrectly formats `.estlintrc.json` I'll check how it's loaded.
Confirmed, we should not treat it as jsonc. https://github.com/eslint/eslintrc/blob/a61384731aff386a8260a80d9710c912e4f62aaa/lib/config-array-factory.js#L188-L203 Before we work on it, let's double check and make sure [these files](https://github.com/prettier/prettier/blob/6c6a332171f590a38c369673662d1a5baf765167/tests/integration/__tests__/__snapshots__/support-info.js.snap#L524-L538) are valid jsonc files. - [x] `.babelrc`, JSON5 https://github.com/babel/babel/blob/218faee4351345415b40b23a9e0102f628d45108/packages/babel-core/src/config/files/configuration.ts#L158 - [ ] `.devcontainer.json` - [x] `.eslintrc.json`, JSON https://github.com/eslint/eslintrc/blob/a61384731aff386a8260a80d9710c912e4f62aaa/lib/config-array-factory.js#L188-L203 - [x] `.jscsrc`, uses jsonlint https://github.com/jscs-dev/node-jscs/blob/38d33a0e455d965106ad3c8948c870f8f4e5dda9/lib/cli-config.js#L81 - [x] `.jshintrc`, JSON https://github.com/jshint/jshint/blob/0a5644f8f529e252e7dd0c0d54334ae435b13de0/src/cli.js#L538 - [x] `.jslintrc`, JSON https://github.com/reid/node-jslint/blob/1eefcc48116fe4fbc3b585ebd2922b3509f4f4de/lib/options.js#L31C49-L31C49 - [ ] `.swcrc` - [x] `api-extractor.json`, it uses [jju](https://github.com/microsoft/rushstack/blob/fa6fbb1284cc4cfa4f2da6ec6c6cffc63fdc9822/libraries/node-core-library/src/JsonFile.ts#L218) not sure about the format. - [x] `devcontainer.json` JSONC, https://github.com/devcontainers/cli/blob/e50dad80c154cdc23d4b371a2117b4ba46cc02a3/src/spec-node/featuresCLI/resolveDependencies.ts#L71C44-L71C44 - [x] `jsconfig.json`, JSONC - [x] `language-configuration.json`, JSONC - [x] `tsconfig.json`, JSONC - [x] `tslint.json`, JSON https://github.com/palantir/tslint/blob/285fc1db18d1fd24680d6a2282c6445abf1566ee/src/configuration.ts#L268
"2024-01-17T09:29:19Z"
3.3
[]
[ "tests/integration/__tests__/support-info.js" ]
JavaScript
[]
[]
prettier/prettier
15,968
prettier__prettier-15968
[ "15934" ]
4b1965ae45dcaeb4208e8c7ee366f54372b69256
diff --git a/src/language-js/embed/utils.js b/src/language-js/embed/utils.js --- a/src/language-js/embed/utils.js +++ b/src/language-js/embed/utils.js @@ -30,15 +30,25 @@ const angularComponentObjectExpressionPredicates = [ * }) */ function isAngularComponentStyles(path) { - return path.match( - (node) => node.type === "TemplateLiteral", - (node, name) => isArrayOrTupleExpression(node) && name === "elements", - (node, name) => - isObjectProperty(node) && - node.key.type === "Identifier" && - node.key.name === "styles" && - name === "value", - ...angularComponentObjectExpressionPredicates, + const isTemplateLiteral = (node) => node.type === "TemplateLiteral"; + const isObjectPropertyNamedStyles = (node, key) => + isObjectProperty(node) && + !node.computed && + node.key.type === "Identifier" && + node.key.name === "styles" && + key === "value"; + return ( + path.match( + isTemplateLiteral, + (node, name) => isArrayOrTupleExpression(node) && name === "elements", + isObjectPropertyNamedStyles, + ...angularComponentObjectExpressionPredicates, + ) || + path.match( + isTemplateLiteral, + isObjectPropertyNamedStyles, + ...angularComponentObjectExpressionPredicates, + ) ); } function isAngularComponentTemplate(path) {
diff --git a/tests/format/typescript/angular-component-examples/15934-computed.component.ts b/tests/format/typescript/angular-component-examples/15934-computed.component.ts new file mode 100644 --- /dev/null +++ b/tests/format/typescript/angular-component-examples/15934-computed.component.ts @@ -0,0 +1,13 @@ +import { Component } from '@angular/core'; + +const styles = "foobar"; + +@Component({ + selector: 'app-root', + template: ` + <h1>My App</h1> + <app-todo-list></app-todo-list> + `, + [styles]: `h1 { color: blue }` +}) +export class AppComponent {} diff --git a/tests/format/typescript/angular-component-examples/15934.component.ts b/tests/format/typescript/angular-component-examples/15934.component.ts new file mode 100644 --- /dev/null +++ b/tests/format/typescript/angular-component-examples/15934.component.ts @@ -0,0 +1,11 @@ +import { Component } from '@angular/core'; + +@Component({ + selector: 'app-root', + template: ` + <h1>My App</h1> + <app-todo-list></app-todo-list> + `, + styles: `h1 { color: blue }` +}) +export class AppComponent {} diff --git a/tests/format/typescript/angular-component-examples/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/angular-component-examples/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/typescript/angular-component-examples/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/typescript/angular-component-examples/__snapshots__/jsfmt.spec.js.snap @@ -1,5 +1,161 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP +exports[`15934.component.ts - {"trailingComma":"es5"} format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 +trailingComma: "es5" + | printWidth +=====================================input====================================== +import { Component } from '@angular/core'; + +@Component({ + selector: 'app-root', + template: \` + <h1>My App</h1> + <app-todo-list></app-todo-list> + \`, + styles: \`h1 { color: blue }\` +}) +export class AppComponent {} + +=====================================output===================================== +import { Component } from "@angular/core"; + +@Component({ + selector: "app-root", + template: \` + <h1>My App</h1> + <app-todo-list></app-todo-list> + \`, + styles: \` + h1 { + color: blue; + } + \`, +}) +export class AppComponent {} + +================================================================================ +`; + +exports[`15934.component.ts - {"trailingComma":"none"} format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 +trailingComma: "none" + | printWidth +=====================================input====================================== +import { Component } from '@angular/core'; + +@Component({ + selector: 'app-root', + template: \` + <h1>My App</h1> + <app-todo-list></app-todo-list> + \`, + styles: \`h1 { color: blue }\` +}) +export class AppComponent {} + +=====================================output===================================== +import { Component } from "@angular/core"; + +@Component({ + selector: "app-root", + template: \` + <h1>My App</h1> + <app-todo-list></app-todo-list> + \`, + styles: \` + h1 { + color: blue; + } + \` +}) +export class AppComponent {} + +================================================================================ +`; + +exports[`15934-computed.component.ts - {"trailingComma":"es5"} format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 +trailingComma: "es5" + | printWidth +=====================================input====================================== +import { Component } from '@angular/core'; + +const styles = "foobar"; + +@Component({ + selector: 'app-root', + template: \` + <h1>My App</h1> + <app-todo-list></app-todo-list> + \`, + [styles]: \`h1 { color: blue }\` +}) +export class AppComponent {} + +=====================================output===================================== +import { Component } from "@angular/core"; + +const styles = "foobar"; + +@Component({ + selector: "app-root", + template: \` + <h1>My App</h1> + <app-todo-list></app-todo-list> + \`, + [styles]: \`h1 { color: blue }\`, +}) +export class AppComponent {} + +================================================================================ +`; + +exports[`15934-computed.component.ts - {"trailingComma":"none"} format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 +trailingComma: "none" + | printWidth +=====================================input====================================== +import { Component } from '@angular/core'; + +const styles = "foobar"; + +@Component({ + selector: 'app-root', + template: \` + <h1>My App</h1> + <app-todo-list></app-todo-list> + \`, + [styles]: \`h1 { color: blue }\` +}) +export class AppComponent {} + +=====================================output===================================== +import { Component } from "@angular/core"; + +const styles = "foobar"; + +@Component({ + selector: "app-root", + template: \` + <h1>My App</h1> + <app-todo-list></app-todo-list> + \`, + [styles]: \`h1 { color: blue }\` +}) +export class AppComponent {} + +================================================================================ +`; + exports[`test.component.ts - {"trailingComma":"es5"} format 1`] = ` ====================================options===================================== parsers: ["typescript"]
Angular inline styles are not formatted if specified as single string (new in v17) **Prettier 3.2.2** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBLAtgBwgJxgAmAGEItoEYBffAMx1PwHIABAQygHMBXAG1ZwD0kHHEYBuADpQpzEmSgUAFMCn58AZzg84YGLiRNWmTAFp6EGIwA0q-PCx94BgAYAJLTwjObUNepgAntrqLrZqSAAWEP4qvmrxkJ44SABGPFxwYpS23lKUAJRScAAe2Hj4YHzq6vgAgsZy2AqwhNlQIFYgEJgwqNDqyKD89ADuAAr8CAMorDwjrAEDnSk4rGAA1nAwAMqs6HAAMqgKyDSzmsurG1vbmGvHHMgwOBmdmuioTy9wnSWYcDgMBRZgAVAFQfioODTM48C4gdQPbQARS4Fjgp3OPxAACt1MVtki4Kj0Zi4diAI5o+BjeiYaYgVjqEwKOAAE3ZHRAz1YqB4Dzk6FYyEZPB4XMRnG0tRgz1QKS4NIBRxOSFh8IiMHQPAA6hFUPB1HcwHBtlMDagAG4GgIisDVLmWjIASSgHNg2zAgJ6tTd20C2jJ8Mw9E0OtWmBFIehAMtGM6x00eFprA4QqD2LuOCTIpSrBSWi5IeOMB1qDZMAiyAAHAAGToiKmoEQptPCtVYzowfNlitVpAAJk6XE0IPzMM7IDg6ALbI5bIO7G4qbgADFcELZQ8RaxFRAQJRKEA) <!-- prettier-ignore --> ```sh --parser babel ``` **Input:** <!-- prettier-ignore --> ```jsx import {Component} from '@angular/core'; @Component({ selector: 'app-root', template: `Hello`, styles: ` :host{ color:blue;} `, }) export class AppComponent {} ``` **Output:** <!-- prettier-ignore --> ```jsx import { Component } from "@angular/core"; @Component({ selector: "app-root", template: `Hello`, styles: ` :host{ color:blue;} `, }) export class AppComponent {} ``` **Expected output:** <!-- prettier-ignore --> ```jsx ``` **Why?** Since Angular v17 it is possible to specify an inline style with a single string rather than an array of strings. If specified as array prettier formats the css. If specified as string prettier does nothing with the css.
"2024-01-21T04:30:49Z"
3.3
[]
[ "tests/format/typescript/angular-component-examples/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBLAtgBwgJxgAmAGEItoEYBffAMx1PwHIABAQygHMBXAG1ZwD0kHHEYBuADpQpzEmSgUAFMCn58AZzg84YGLiRNWmTAFp6EGIwA0q-PCx94BgAYAJLTwjObUNepgAntrqLrZqSAAWEP4qvmrxkJ44SABGPFxwYpS23lKUAJRScAAe2Hj4YHzq6vgAgsZy2AqwhNlQIFYgEJgwqNDqyKD89ADuAAr8CAMorDwjrAEDnSk4rGAA1nAwAMqs6HAAMqgKyDSzmsurG1vbmGvHHMgwOBmdmuioTy9wnSWYcDgMBRZgAVAFQfioODTM48C4gdQPbQARS4Fjgp3OPxAACt1MVtki4Kj0Zi4diAI5o+BjeiYaYgVjqEwKOAAE3ZHRAz1YqB4Dzk6FYyEZPB4XMRnG0tRgz1QKS4NIBRxOSFh8IiMHQPAA6hFUPB1HcwHBtlMDagAG4GgIisDVLmWjIASSgHNg2zAgJ6tTd20C2jJ8Mw9E0OtWmBFIehAMtGM6x00eFprA4QqD2LuOCTIpSrBSWi5IeOMB1qDZMAiyAAHAAGToiKmoEQptPCtVYzowfNlitVpAAJk6XE0IPzMM7IDg6ALbI5bIO7G4qbgADFcELZQ8RaxFRAQJRKEA" ]
prettier/prettier
15,972
prettier__prettier-15972
[ "15969" ]
91a2e2513e11df4c89bca14199868b2e1b8f6777
diff --git a/src/language-js/embed/utils.js b/src/language-js/embed/utils.js --- a/src/language-js/embed/utils.js +++ b/src/language-js/embed/utils.js @@ -56,6 +56,7 @@ function isAngularComponentTemplate(path) { (node) => node.type === "TemplateLiteral", (node, name) => isObjectProperty(node) && + !node.computed && node.key.type === "Identifier" && node.key.name === "template" && name === "value",
diff --git a/tests/format/typescript/angular-component-examples/15969-computed.component.ts b/tests/format/typescript/angular-component-examples/15969-computed.component.ts new file mode 100644 --- /dev/null +++ b/tests/format/typescript/angular-component-examples/15969-computed.component.ts @@ -0,0 +1,8 @@ +import { Component } from '@angular/core'; + +const template = "foobar"; + +@Component({ + [template]: `<h1>{{ hello }}</h1>`, +}) +export class AppComponent {} diff --git a/tests/format/typescript/angular-component-examples/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/angular-component-examples/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/typescript/angular-component-examples/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/typescript/angular-component-examples/__snapshots__/jsfmt.spec.js.snap @@ -156,6 +156,64 @@ export class AppComponent {} ================================================================================ `; +exports[`15969-computed.component.ts - {"trailingComma":"es5"} format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 +trailingComma: "es5" + | printWidth +=====================================input====================================== +import { Component } from '@angular/core'; + +const template = "foobar"; + +@Component({ + [template]: \`<h1>{{ hello }}</h1>\`, +}) +export class AppComponent {} + +=====================================output===================================== +import { Component } from "@angular/core"; + +const template = "foobar"; + +@Component({ + [template]: \`<h1>{{ hello }}</h1>\`, +}) +export class AppComponent {} + +================================================================================ +`; + +exports[`15969-computed.component.ts - {"trailingComma":"none"} format 1`] = ` +====================================options===================================== +parsers: ["typescript"] +printWidth: 80 +trailingComma: "none" + | printWidth +=====================================input====================================== +import { Component } from '@angular/core'; + +const template = "foobar"; + +@Component({ + [template]: \`<h1>{{ hello }}</h1>\`, +}) +export class AppComponent {} + +=====================================output===================================== +import { Component } from "@angular/core"; + +const template = "foobar"; + +@Component({ + [template]: \`<h1>{{ hello }}</h1>\` +}) +export class AppComponent {} + +================================================================================ +`; + exports[`test.component.ts - {"trailingComma":"es5"} format 1`] = ` ====================================options===================================== parsers: ["typescript"]
Unexpected embedded formatting for Angular template **Prettier 3.2.4** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuc0DOMAE8C2AHAGwEN5MBeTAHRADMIIAjIgJ2oG5KpOABAYQnzQEMABTBOmTAG1chEnAC6STAAMAPAAsAjAD5gwSYcka4BAhEwBfS2oD02nSoA0nSwEpOcAB54IzLGDEaGiYAIJ4ePyCUMKYwJacIE4gEHgwAJboyKAszBAA7gAKLAhoyCBEBPlEAJ5lyQzMRGAA1nAwAMpEOHAAMukxyDSVaHANTa3tHXjNAwDmyDDMAK5jIKM46Ysra954cMzpPbCVACoHUCzpcGVIwwSjyWjzBHAAissQ8EMjawBWaC8HRe70+3zuv2SAEcwXBCnk8LcKmgALQxOAAE0xSRASyI6QI8yiOCI5UqBBxzygc1eoRgS3SDGW8EKB36gwhDzWGhgOAIAHUNOl4GgZmA4B1SsL0gA3YU1cpgYI4mWrACSUCxsA6YEOaVCmo6MBqrx+XOSeDyo35TTw5UtNwOMrgOIGo388KIcxJZseIBmzHd5SYDFMOMtAxg-PSGJgGmQAA4AAzJZhwGHpNOe72kzl+mBEBjR2PxpAAJmSy1Gp0Lt3ufrgOFDGKxGN6RGpyy9cAAYn4SfT5mTmRAQNYgA) <!-- prettier-ignore --> ```sh --parser babel ``` **Input:** <!-- prettier-ignore --> ```jsx const template = "foobar"; @Component({ [template]: `<h1>{{ hello }}</h1>`, }) export class AppComponent {} ``` **Output:** <!-- prettier-ignore --> ```jsx const template = "foobar"; @Component({ [template]: `<h1>{{ hello }}</h1>`, }) export class AppComponent {} ``` **Expected output:** <!-- prettier-ignore --> ```jsx const template = "foobar"; @Component({ [template]: `<h1>{{ hello }}</h1>`, }) export class AppComponent {} ``` **Why?** <!-- short explanation of expected output --> Prettier formats the content of the `template` field in Angular's `@Component` decorator as HTML. However, it now also formats the content of a different field named `template` as HTML. This isn't expected. I think adding `!node.computed` to https://github.com/prettier/prettier/blob/4b1965ae45dcaeb4208e8c7ee366f54372b69256/src/language-js/embed/utils.js#L47-L51 will fix this.
Seems easy to fix.
"2024-01-22T13:16:28Z"
3.3
[]
[ "tests/format/typescript/angular-component-examples/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuc0DOMAE8C2AHAGwEN5MBeTAHRADMIIAjIgJ2oG5KpOABAYQnzQEMABTBOmTAG1chEnAC6STAAMAPAAsAjAD5gwSYcka4BAhEwBfS2oD02nSoA0nSwEpOcAB54IzLGDEaGiYAIJ4ePyCUMKYwJacIE4gEHgwAJboyKAszBAA7gAKLAhoyCBEBPlEAJ5lyQzMRGAA1nAwAMpEOHAAMukxyDSVaHANTa3tHXjNAwDmyDDMAK5jIKM46Ysra954cMzpPbCVACoHUCzpcGVIwwSjyWjzBHAAissQ8EMjawBWaC8HRe70+3zuv2SAEcwXBCnk8LcKmgALQxOAAE0xSRASyI6QI8yiOCI5UqBBxzygc1eoRgS3SDGW8EKB36gwhDzWGhgOAIAHUNOl4GgZmA4B1SsL0gA3YU1cpgYI4mWrACSUCxsA6YEOaVCmo6MBqrx+XOSeDyo35TTw5UtNwOMrgOIGo388KIcxJZseIBmzHd5SYDFMOMtAxg-PSGJgGmQAA4AAzJZhwGHpNOe72kzl+mBEBjR2PxpAAJmSy1Gp0Lt3ufrgOFDGKxGN6RGpyy9cAAYn4SfT5mTmRAQNYgA" ]
prettier/prettier
15,993
prettier__prettier-15993
[ "9503", "9847" ]
6d2418f637279998963d6e0cabcd3c63a313e707
diff --git a/src/language-markdown/print-paragraph.js b/src/language-markdown/print-paragraph.js new file mode 100644 --- /dev/null +++ b/src/language-markdown/print-paragraph.js @@ -0,0 +1,20 @@ +import { fill } from "../document/builders.js"; +import { normalizeDoc } from "../document/utils.js"; + +/** + * @typedef {import("../common/ast-path.js").default} AstPath + * @typedef {import("../document/builders.js").Doc} Doc + */ + +/** + * @param {AstPath} path + * @param {*} options + * @param {*} print + * @returns {Doc} + */ +function printParagraph(path, options, print) { + const parts = path.map(print, "children"); + return normalizeDoc(fill(parts)); +} + +export { printParagraph }; diff --git a/src/language-markdown/printer-markdown.js b/src/language-markdown/printer-markdown.js --- a/src/language-markdown/printer-markdown.js +++ b/src/language-markdown/printer-markdown.js @@ -2,7 +2,6 @@ import collapseWhiteSpace from "collapse-white-space"; import { align, - fill, group, hardline, indent, @@ -11,7 +10,7 @@ import { markAsRoot, softline, } from "../document/builders.js"; -import { normalizeDoc, replaceEndOfLine } from "../document/utils.js"; +import { replaceEndOfLine } from "../document/utils.js"; import getMaxContinuousCount from "../utils/get-max-continuous-count.js"; import getMinNotPresentContinuousCount from "../utils/get-min-not-present-continuous-count.js"; import getPreferredQuote from "../utils/get-preferred-quote.js"; @@ -23,6 +22,7 @@ import getVisitorKeys from "./get-visitor-keys.js"; import { locEnd, locStart } from "./loc.js"; import { insertPragma } from "./pragma.js"; import { printTable } from "./print/table.js"; +import { printParagraph } from "./print-paragraph.js"; import preprocess from "./print-preprocess.js"; import { printWhitespace } from "./print-whitespace.js"; import { @@ -71,11 +71,9 @@ function genericPrint(path, options, print) { if (node.children.length === 0) { return ""; } - return [normalizeDoc(printRoot(path, options, print)), hardline]; + return [printRoot(path, options, print), hardline]; case "paragraph": - return printChildren(path, options, print, { - postprocessor: fill, - }); + return printParagraph(path, options, print); case "sentence": return printChildren(path, options, print); case "word": { @@ -559,8 +557,7 @@ function printRoot(path, options, print) { } function printChildren(path, options, print, events = {}) { - const { postprocessor = (parts) => parts, processor = () => print() } = - events; + const { processor = print } = events; const parts = []; @@ -586,7 +583,7 @@ function printChildren(path, options, print, events = {}) { } }, "children"); - return postprocessor(parts); + return parts; } function printIgnoreComment(node) {
diff --git a/tests/format/markdown/code/__snapshots__/jsfmt.spec.js.snap b/tests/format/markdown/code/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/markdown/code/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/markdown/code/__snapshots__/jsfmt.spec.js.snap @@ -339,9 +339,9 @@ const createCredentialDefaultArgs = { timeout: 60000, challenge: new Uint8Array([ // must be a cryptographically random number sent from a server - 0x8c, 0x0a, 0x26, 0xff, 0x22, 0x91, 0xc1, 0xe9, 0xb9, 0x4e, 0x2e, 0x17, 0x1a, - 0x98, 0x6a, 0x73, 0x71, 0x9d, 0x43, 0x48, 0xd5, 0xa7, 0x6a, 0x15, 0x7e, 0x38, - 0x94, 0x52, 0x77, 0x97, 0x0f, 0xef, + 0x8c, 0x0a, 0x26, 0xff, 0x22, 0x91, 0xc1, 0xe9, 0xb9, 0x4e, 0x2e, 0x17, + 0x1a, 0x98, 0x6a, 0x73, 0x71, 0x9d, 0x43, 0x48, 0xd5, 0xa7, 0x6a, 0x15, + 0x7e, 0x38, 0x94, 0x52, 0x77, 0x97, 0x0f, 0xef, ]).buffer, }, }; @@ -381,7 +381,8 @@ proseWrap: "always" 105deg, rgb(255 255 255 / 20%) 39%, rgb(51 56 57 / 100%) 96% - ) center center / 400px 200px no-repeat, + ) + center center / 400px 200px no-repeat, url(big-star.png) center no-repeat, rebeccapurple; } @@ -415,7 +416,8 @@ background-image: linear-gradient( to bottom, rgb(255 255 0 / 50%), rgb(0 0 255 / 50%) - ), url("catfront.png"); + ), + url("catfront.png"); \`\`\` ================================================================================ @@ -455,7 +457,8 @@ width: 400px; rgb(131 58 180 / 100%) 0%, rgb(253 29 29 / 60%) 60%, rgb(252 176 69 / 100%) 100% - ), radial-gradient(circle, rgb(255 255 255 / 100%) 0%, rgb(0 0 0 / 100%) 28%); + ), + radial-gradient(circle, rgb(255 255 255 / 100%) 0%, rgb(0 0 0 / 100%) 28%); border: 20px dashed black; padding: 20px; width: 400px; @@ -495,8 +498,8 @@ background-position: .multi-bg-example { width: 100%; height: 400px; - background-image: url(firefox.png), url(bubbles.png), linear-gradient(to right, rgb(30 - 75 115 / 100%), rgb(255 255 255 / 0%)); + background-image: url(firefox.png), url(bubbles.png), + linear-gradient(to right, rgb(30 75 115 / 100%), rgb(255 255 255 / 0%)); background-repeat: no-repeat, no-repeat, no-repeat; background-position: bottom right, @@ -536,7 +539,8 @@ proseWrap: "always" 217deg, rgb(255 0 0 / 80%), rgb(255 0 0 / 0%) 70.71% - ), linear-gradient(127deg, rgb(0 255 0 / 80%), rgb(0 255 0 / 0%) 70.71%), + ), + linear-gradient(127deg, rgb(0 255 0 / 80%), rgb(0 255 0 / 0%) 70.71%), linear-gradient(336deg, rgb(0 0 255 / 80%), rgb(0 0 255 / 0%) 70.71%); } \`\`\` @@ -595,7 +599,8 @@ proseWrap: "always" circle at 93.3% 75%, rgb(0 255 0 / 50%), rgb(0 255 0 / 0%) 70.71% - ) beige; + ) + beige; border-radius: 50%; } \`\`\` @@ -653,7 +658,8 @@ rgb(255 255 0 / 50%) 120px, rgb(75 0 130 / 50%) 240px, rgb(238 130 238 / 50%) 280px, rgb(255 0 0 / 50%) 300px - ), repeating-linear-gradient( + ), + repeating-linear-gradient( -190deg, rgb(255 0 0 / 50%) 30px, rgb(255 153 0 / 50%) 60px, @@ -663,8 +669,18 @@ rgb(255 255 0 / 50%) 120px, rgb(75 0 130 / 50%) 180px, rgb(238 130 238 / 50%) 210px, rgb(255 0 0 / 50%) 230px - ), repeating-linear-gradient(23deg, red 50px, orange 100px, yellow 150px, green - 200px, blue 250px, indigo 300px, violet 350px, red 370px); + ), + repeating-linear-gradient( + 23deg, + red 50px, + orange 100px, + yellow 150px, + green 200px, + blue 250px, + indigo 300px, + violet 350px, + red 370px + ); } \`\`\` @@ -763,7 +779,8 @@ transparent 69px, transparent 116px, rgb(255 206 0 / 25%) 116px, rgb(255 206 0 / 25%) 166px - ), repeating-linear-gradient( + ), + repeating-linear-gradient( 0deg, transparent, transparent 50px, @@ -777,15 +794,21 @@ transparent 69px, transparent 116px, rgb(255 206 0 / 25%) 116px, rgb(255 206 0 / 25%) 166px - ), repeating-linear-gradient( + ), + repeating-linear-gradient( -45deg, transparent, transparent 5px, rgb(143 77 63 / 25%) 5px, rgb(143 77 63 / 25%) 10px - ), repeating-linear-gradient(45deg, transparent, transparent 5px, rgb( - 143 77 63 / 25% - ) 5px, rgb(143 77 63 / 25%) 10px); + ), + repeating-linear-gradient( + 45deg, + transparent, + transparent 5px, + rgb(143 77 63 / 25%) 5px, + rgb(143 77 63 / 25%) 10px + ); background: repeating-linear-gradient( 90deg, @@ -795,7 +818,8 @@ transparent 69px, rgb(255 127 0 / 25%) 63px 69px, transparent 69px 116px, rgb(255 206 0 / 25%) 116px 166px - ), repeating-linear-gradient( + ), + repeating-linear-gradient( 0deg, transparent 0 50px, rgb(255 127 0 / 25%) 50px 56px, @@ -803,12 +827,17 @@ transparent 69px, rgb(255 127 0 / 25%) 63px 69px, transparent 69px 116px, rgb(255 206 0 / 25%) 116px 166px - ), repeating-linear-gradient( + ), + repeating-linear-gradient( -45deg, transparent 0 5px, rgb(143 77 63 / 25%) 5px 10px - ), repeating-linear-gradient(45deg, transparent 0 5px, rgb(143 77 63 / 25%) 5px - 10px); + ), + repeating-linear-gradient( + 45deg, + transparent 0 5px, + rgb(143 77 63 / 25%) 5px 10px + ); } \`\`\` @@ -845,7 +874,8 @@ div { #000 0.25turn 0.5turn, #fff 0.5turn 0.75turn, #000 0.75turn - ) top left / 25% 25% repeat; + ) + top left / 25% 25% repeat; border: 1px solid; } \`\`\` @@ -877,12 +907,10 @@ filter: none; =====================================output===================================== \`\`\`css img { - filter: drop-shadow(2px 2px 0 hsl(300deg 100% 50%)) drop-shadow( - -2px -2px 0 hsl(210deg 100% 50%) - ) - drop-shadow(2px 2px 0 hsl(120deg 100% 50%)) drop-shadow( - -2px -2px 0 hsl(30deg 100% 50%) - ); + filter: drop-shadow(2px 2px 0 hsl(300deg 100% 50%)) + drop-shadow(-2px -2px 0 hsl(210deg 100% 50%)) + drop-shadow(2px 2px 0 hsl(120deg 100% 50%)) + drop-shadow(-2px -2px 0 hsl(30deg 100% 50%)); } img + img { filter: none; @@ -915,8 +943,8 @@ border: 1px solid blue; \`\`\`css #MDN-logo { border: 1px solid blue; - filter: drop-shadow(5px 5px 0 red) hue-rotate(180deg) drop-shadow(5px 5px 0 - red); + filter: drop-shadow(5px 5px 0 red) hue-rotate(180deg) + drop-shadow(5px 5px 0 red); } \`\`\` @@ -953,7 +981,8 @@ font-style: normal; font-family: "HeydingsControlsRegular"; src: url("fonts/heydings_controls-webfont.eot"); src: - url("fonts/heydings_controls-webfont.eot?#iefix") format("embedded-opentype"), + url("fonts/heydings_controls-webfont.eot?#iefix") + format("embedded-opentype"), url("fonts/heydings_controls-webfont.woff") format("woff"), url("fonts/heydings_controls-webfont.ttf") format("truetype"); font-weight: normal; @@ -991,7 +1020,8 @@ proseWrap: "always" @font-face { font-family: "Bungee Spice"; src: - url("https://fonts.googleapis.com/css2?family=Bungee+Spice") tech(color-COLRv1), + url("https://fonts.googleapis.com/css2?family=Bungee+Spice") + tech(color-COLRv1), url("Bungee-fallback.otf") format("opentype"); } \`\`\` @@ -1025,7 +1055,8 @@ grid-auto-columns: min-content max-content auto; grid-auto-columns: 100px 150px 390px; grid-auto-columns: 10% 33.3%; grid-auto-columns: 0.5fr 3fr 1fr; -grid-auto-columns: minmax(100px, auto) minmax(max-content, 2fr) minmax(20%, 80vmax); +grid-auto-columns: minmax(100px, auto) minmax(max-content, 2fr) + minmax(20%, 80vmax); grid-auto-columns: 100px minmax(100px, auto) 10% 0.5fr fit-content(400px); \`\`\` @@ -1053,10 +1084,10 @@ proseWrap: "always" =====================================output===================================== \`\`\`css @import url("gridy.css") supports(display: grid) screen and (max-width: 400px); -@import url("flexy.css") supports(not (display: grid) and (display: flex)) screen - and (max-width: 400px); -@import url("whatever.css") supports((selector(h2 > p)) and - (font-tech(color-COLRv1))); +@import url("flexy.css") supports(not (display: grid) and (display: flex)) + screen and (max-width: 400px); +@import url("whatever.css") +supports((selector(h2 > p)) and (font-tech(color-COLRv1))); \`\`\` ================================================================================ @@ -1079,7 +1110,8 @@ mask-image: image(url(mask.png), skyblue), linear-gradi =====================================output===================================== \`\`\`css /* Multiple values */ -mask-image: image(url(mask.png), skyblue), linear-gradient(rgb(0 0 0 / 100%), transparent); +mask-image: image(url(mask.png), skyblue), + linear-gradient(rgb(0 0 0 / 100%), transparent); \`\`\` ================================================================================ @@ -1107,10 +1139,8 @@ padding: env(safe-area-inset-top, 20px) env(safe-area-inset-right, 20px) env( =====================================output===================================== \`\`\`css body { - padding: env(safe-area-inset-top, 20px) env(safe-area-inset-right, 20px) env( - safe-area-inset-bottom, - 20px - ) env(safe-area-inset-left, 20px); + padding: env(safe-area-inset-top, 20px) env(safe-area-inset-right, 20px) + env(safe-area-inset-bottom, 20px) env(safe-area-inset-left, 20px); } \`\`\` @@ -1143,10 +1173,8 @@ p { p { width: 300px; border: 2px solid red; - padding: env(safe-area-inset-top, 50px) env(safe-area-inset-right, 50px) env( - safe-area-inset-bottom, - 50px - ) env(SAFE-AREA-INSET-LEFT, 50px); + padding: env(safe-area-inset-top, 50px) env(safe-area-inset-right, 50px) + env(safe-area-inset-bottom, 50px) env(SAFE-AREA-INSET-LEFT, 50px); } \`\`\` @@ -1188,24 +1216,8 @@ proseWrap: "always" =====================================output===================================== \`\`\`css #example-element:focus { - transform: rotate3d(1, 1, 1, 30deg) matrix3d( - 1, - 0, - 0, - 0, - 0, - 1, - 6, - 0, - 0, - 0, - 1, - 0, - 50, - 100, - 0, - 1.1 - ); + transform: rotate3d(1, 1, 1, 30deg) + matrix3d(1, 0, 0, 0, 0, 1, 6, 0, 0, 0, 1, 0, 50, 100, 0, 1.1); } \`\`\` @@ -1257,9 +1269,9 @@ U+0152-0153, U+02BB-02BC, U+02C6, local("Montserrat Regular"), local("Montserrat-Regular"), url("fonts/montserrat-regular.woff2") format("woff2"); - unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, - U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, - U+2212, U+2215, U+FEFF, U+FFFD; + unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, + U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, + U+2215, U+FEFF, U+FFFD; } } \`\`\` diff --git a/tests/format/mdx/mdx/__snapshots__/jsfmt.spec.js.snap b/tests/format/mdx/mdx/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/mdx/mdx/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/mdx/mdx/__snapshots__/jsfmt.spec.js.snap @@ -345,6 +345,37 @@ and as you can see_ once you close the italics, it will break incorrectly when p ================================================================================ `; +exports[`issue-9503.mdx - {"semi":false} format 1`] = ` +====================================options===================================== +parsers: ["mdx"] +printWidth: 80 +semi: false + | printWidth +=====================================input====================================== +<ExternalLink href="http://example.com">Prettier</ExternalLink> is an opinionated-code-formatter-that-support-many-languages-and-integrate-with-most-editors + +=====================================output===================================== +<ExternalLink href="http://example.com">Prettier</ExternalLink> is an +opinionated-code-formatter-that-support-many-languages-and-integrate-with-most-editors + +================================================================================ +`; + +exports[`issue-9503.mdx format 1`] = ` +====================================options===================================== +parsers: ["mdx"] +printWidth: 80 + | printWidth +=====================================input====================================== +<ExternalLink href="http://example.com">Prettier</ExternalLink> is an opinionated-code-formatter-that-support-many-languages-and-integrate-with-most-editors + +=====================================output===================================== +<ExternalLink href="http://example.com">Prettier</ExternalLink> is an +opinionated-code-formatter-that-support-many-languages-and-integrate-with-most-editors + +================================================================================ +`; + exports[`jsx.mdx - {"semi":false} format 1`] = ` ====================================options===================================== parsers: ["mdx"] @@ -416,7 +447,8 @@ A {/* JS-style comment */} comment. </Hello> <Hello> test <World /> test -</Hello>123 +</Hello> +123 --- @@ -518,7 +550,8 @@ A {/* JS-style comment */} comment. </Hello> <Hello> test <World /> test -</Hello>123 +</Hello> +123 --- diff --git a/tests/format/mdx/mdx/issue-9503.mdx b/tests/format/mdx/mdx/issue-9503.mdx new file mode 100644 --- /dev/null +++ b/tests/format/mdx/mdx/issue-9503.mdx @@ -0,0 +1 @@ +<ExternalLink href="http://example.com">Prettier</ExternalLink> is an opinionated-code-formatter-that-support-many-languages-and-integrate-with-most-editors
Inline React components in MDX cause line lengths to exceed print-width <!-- BEFORE SUBMITTING AN ISSUE: 1. Search for your issue on GitHub: https://github.com/prettier/prettier/issues A large number of opened issues are duplicates of existing issues. If someone has already opened an issue for what you are experiencing, you do not need to open a new issue — please add a 👍 reaction to the existing issue instead. 2. We get a lot of requests for adding options, but Prettier is built on the principle of being opinionated about code formatting. This means we have a very high bar for adding new options. Find out more: https://prettier.io/docs/en/option-philosophy.html Tip! Don't write this stuff manually. 1. Go to https://prettier.io/playground 2. Paste your code and set options 3. Press the "Report issue" button in the lower right --> **Prettier 2.1.2** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAogD3gJygQwBsAZASygGsACACxzgDMBeAHRBphgAckB6X-AHcAzgDp8AW3wAvaKMgTekACZwupLnELk4vNgD4AggHUAylQDCEVQAUNWnal5ZcBEuQr6qpYVXxVIWHIAVwhg31VtADc4HABPPyhlKnpCOHxhOD9gmAgpGFJoKkycKNIwLJgafBg-UmVfYQkICCqqVS5CCDiJBBgxKgBNMID8KG9YOABzHBqsgGYcZK58HBgE3IhCX3JcxITheC4qCAYqOLCcFK10zKouHAgK4V8IK4vg0fHwrKtbe20UCyGUSVAQygAtLkIeDilscoUoAAaCZgQjBZTkKZUADiNAghyoAEkoMJNGBcld4IdfGNksJgqRqaIQEiQBAuAVoMJkKBVo9BDZVggeSgiIJ8HEeWyAEazMAUOAwUwrMBY5AwHDBOBsuASGVwZSqZTEMZTYL4KZwABib3yBSgU2QIHwOQgrPYMAkhGMNCZcDJ+AqphFTNIZXWzrALw95BKMBssymUmQDCImTZACthJgAELyxXKyRwMhA1PpnUgbOYUxYtIARVC8HL20rKxwJWdEmUmA9DwJcGMsy4zoeAdiMQ9AEcm3BExzRS7hBCgYbDR76DPSPRE5aU0g0622ZkJKQNVrK8I63BG604C2MyAYPgZcZ6lVkAAmNma-CkQFTFYEj7iAAYAKwej8AAqL6ioej5RNqJKqLAphgDgGgwIYSSmOsaQPm2GGwG+ygfkgACMAAMlEAL40UAA) ```sh --parser mdx --print-width 100 ``` **Input:** ```mdx <ExternalLink href="http://aws.amazon.com/codepipeline/">AWS CodePipeline</ExternalLink> is a continuous delivery and release automation service that aids smooth deployments. You can integrate 3rd party tools into any step of your release process or you can use CodePipeline as an end-to-end solution, including Ghost Inspector tests and suites. ``` **Output:** ```mdx <ExternalLink href="http://aws.amazon.com/codepipeline/">AWS CodePipeline</ExternalLink> is a continuous delivery and release automation service that aids smooth deployments. You can integrate 3rd party tools into any step of your release process or you can use CodePipeline as an end-to-end solution, including Ghost Inspector tests and suites. ``` **Expected behavior:** Here the output optically looks correct, however if you view it in the playground or any editor that has a line length “ruler” you can see that each line is actually longer than 100 characters. ``` ❯ echo '<ExternalLink href="http://aws.amazon.com/codepipeline/">AWS CodePipeline</ExternalLink> is a continuous' | wc 1 6 105 ``` This causes a bit of a problem if you have word wrapping on in your editor. <img width="1014" alt="Screen Shot 2020-10-26 at 1 58 54 PM" src="https://user-images.githubusercontent.com/4727/97228071-9c9b8000-1793-11eb-94c5-2669e9d7b01c.png"> If I remove the inline component it works fine, so the bug seems to have something to do with inline React components. Thanks! Refactor markdown `paragraph` print ## Description <!-- Please provide a brief summary of your changes: --> Fix #9503 ## Checklist <!-- Please ensure you’ve done all of these things (if applicable). --> <!-- You can replace the `[ ]` with `[x]` to mark each task as done. --> - [x] I’ve added tests to confirm my change works. - [ ] (If changing the API or CLI) I’ve documented the changes I’ve made (in the `docs/` directory). - [x] (If the change is user-facing) I’ve added my changes to `changelog_unreleased/*/XXXX.md` file following `changelog_unreleased/TEMPLATE.md`. - [x] I’ve read the [contributing guidelines](https://github.com/prettier/prettier/blob/master/CONTRIBUTING.md). <!-- Please DO NOT remove the playground link --> **✨[Try the playground for this PR](https://prettier.io/playground-redirect)✨**
Thanks for reporting this. If you're interested in fixing it, use the "show doc" checkbox in the playground to check the intermediate representation that Prettier builds. It's described [here](https://github.com/prettier/prettier/blob/master/commands.md). The `fill` command has [certain expectations](https://github.com/prettier/prettier/blob/099c5fb7302021c894e38f53bb09909d45870502/src/document/doc-printer.js#L366-L367) about its arguments, a violation of which may be the cause of this bug. You can play with the IR in this [modified playground](https://prettier-doc.netlify.app/playground/#N4Igxg9gdgLgprEAuc0wEMYAoDaAdKAgMwEsAbM3AgAmoHMAnCAVwActIoNt8pba8IADwBnCAFs4MABYkodALRkSAazgK5yqOsjjW0BDEEAaGvy1xTffoID0APkFmAugEpXVgSGpkIDOOImZhae1IIkrCLMgSAEbqEE0ugMACYhBMTklLy0jCzsnNxU1l6iElKy8kqq6ppyOhL62rBBJT71oV4OTtZuHsEdZoK+-jGh6dbhkdE98UNQbiDGIBCsMCTQIsigyUwA7gAKyQhbKOhke+gAnlvLAEYM6GBqMADKrE9ydMgwDMyWIACdzgKRSIIAMuh5Mx0HQ4AAxPziTDreTIEDoZgwCBLEDSGDiMgAdVk8BEHzAcFeJxI6wAbrSruiwCJbiA5CI4AwYAdHnRkcgiOdOcsAFYiAAeACFHs8pK90JJwfVBcKAeKJa8vmQ4ABFZgQeCqsgikAfBichjo1j+GDrLkKFIQMC4m1yGBEkgpGTIAAsAFZljaIJyiY9WNb-Ja6XBcQBHA3wXmrU4YkQKbQgkG4-wJkj+XmwgVIIUmgGc8QkH5-cvavWJ2MltXLGDoO6e73SZAAJhbj3IXwAwhJi4CRP7ccxOQAVNunUumun-ACSUDBsFeYAYERgAEE168YFcdcbOQBfM9AA). I have a little bit of experience with ASTs/AST-like things so I took a look. I simplifed down the example and maybe noticed some things… it’s hard to tell because I’m not exactly what “normal” is supposed to look like. I used two strings: ``` <em>hey</em> <em>hey</em> is a continuous ``` <img width="568" alt="Screen Shot 2020-10-27 at 4 49 34 PM" src="https://user-images.githubusercontent.com/4727/97374390-67675e80-1875-11eb-9d5c-468e831aebec.png"> The HTML definitely seems to be parsed differently when there is markdown after it. It could be a concidence but those extra empty strings seem to match up to the amount of characters that the print width is exceeded by… I guess the prefixed space is the culprit. It should be `line, "is"` instead. @thorn0 You are right about this, https://github.com/prettier/prettier/pull/9736#discussion_r527917647, it's bug in `normalizeDoc`. @thorn0 Can you review this, when you got time? This is actually quite big change, because it called unsafe `normalizeDoc` on "Root", and I removed it. But maybe `normalizeDoc` was safe before we extract to `doc-utils.js` Ooops, I keep forgetting about this one... The doc for #9503 still doesn't look right: ```js [ fill([ conditionalGroup([ group([/*...*/]), group([/*...*/]), ]), " ", // <--- should be `line` "is", line, // ... ``` Yes, this is a big one. My research plan so far: ## MDX: line break inserted between elements and text in JSX blocks ```<asdf/>zxcv``` - Prettier 2.2.1 parses it all as JSX (not Markdown) and prints line breaks the way it normally does for JSX. - That's probably not the expected output. That's why #6961 was opened. - Also there is a `fill` bug that causes v2.2.1 to print `<Hello></Hello><Hello></Hello>123` without that break. ```js [ fill([ group(["<Hello", indent([]), ">"]), "</Hello>", // <--- Problem! Odd-indexed elements must be line breaks. hardlineWithoutBreakParent, breakParent, group(["<Hello", indent([]), ">"]), "</Hello>", softline, "123" ]), hardline, ] ``` - Things to look into: 1. The `fill` bug 1. Is the bug in #9503 same or different? 2. How did it work in older versions? 3. Was `normalizeDoc` safe before it got extracted to `doc-utils`? 4. Manipulations with `normalizeDoc` and `cleanDoc` (in particular, PR #9847) look like they might affect more things in Markdown than just MDX. What else can be affected? 2. What actually is the expected output? 1. Is the whitespace between the tag and the text significant? 2. Should the text be parsed as JSX or as Markdown?
"2024-01-27T23:34:51Z"
3.3
[]
[ "tests/format/mdx/mdx/jsfmt.spec.js", "tests/format/markdown/code/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground", "https://prettier.io/playground-redirect", "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAeAogD3gJygQwBsAZASygGsACACxzgDMBeAHRBphgAckB6X-AHcAzgDp8AW3wAvaKMgTekACZwupLnELk4vNgD4AggHUAylQDCEVQAUNWnal5ZcBEuQr6qpYVXxVIWHIAVwhg31VtADc4HABPPyhlKnpCOHxhOD9gmAgpGFJoKkycKNIwLJgafBg-UmVfYQkICCqqVS5CCDiJBBgxKgBNMID8KG9YOABzHBqsgGYcZK58HBgE3IhCX3JcxITheC4qCAYqOLCcFK10zKouHAgK4V8IK4vg0fHwrKtbe20UCyGUSVAQygAtLkIeDilscoUoAAaCZgQjBZTkKZUADiNAghyoAEkoMJNGBcld4IdfGNksJgqRqaIQEiQBAuAVoMJkKBVo9BDZVggeSgiIJ8HEeWyAEazMAUOAwUwrMBY5AwHDBOBsuASGVwZSqZTEMZTYL4KZwABib3yBSgU2QIHwOQgrPYMAkhGMNCZcDJ+AqphFTNIZXWzrALw95BKMBssymUmQDCImTZACthJgAELyxXKyRwMhA1PpnUgbOYUxYtIARVC8HL20rKxwJWdEmUmA9DwJcGMsy4zoeAdiMQ9AEcm3BExzRS7hBCgYbDR76DPSPRE5aU0g0622ZkJKQNVrK8I63BG604C2MyAYPgZcZ6lVkAAmNma-CkQFTFYEj7iAAYAKwej8AAqL6ioej5RNqJKqLAphgDgGgwIYSSmOsaQPm2GGwG+ygfkgACMAAMlEAL40UAA" ]
prettier/prettier
16,031
prettier__prettier-16031
[ "15904" ]
d467987b4adbae803a62f7707c613f31769c2df9
diff --git a/src/language-js/needs-parens.js b/src/language-js/needs-parens.js --- a/src/language-js/needs-parens.js +++ b/src/language-js/needs-parens.js @@ -567,8 +567,20 @@ function needsParens(path, options) { } // fallthrough case "TSInferType": - if (node.type === "TSInferType" && parent.type === "TSRestType") { - return false; + if (node.type === "TSInferType") { + if (parent.type === "TSRestType") { + return false; + } + + if ( + key === "types" && + (parent.type === "TSUnionType" || + parent.type === "TSIntersectionType") && + node.typeParameter.type === "TSTypeParameter" && + node.typeParameter.constraint + ) { + return true; + } } // fallthrough case "TSTypeOperator":
diff --git a/tests/format/typescript/infer-extends/__snapshots__/jsfmt.spec.js.snap b/tests/format/typescript/infer-extends/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/typescript/infer-extends/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/typescript/infer-extends/__snapshots__/jsfmt.spec.js.snap @@ -13,6 +13,8 @@ type X6<T> = T extends [infer U, infer U extends number] ? MustBeNumber<U> : nev type X7<T> = T extends [infer U extends string, infer U extends number] ? U : never; type X8<U, T> = T extends infer U extends number ? U : T; type X9<U, T> = T extends (infer U extends number ? U : T) ? U : T; +type X10<T> = T extends (infer U extends number) | { a: infer U extends number } ? U : never +type X11<T> = T extends (infer U extends number) & { a: infer U extends number } ? U : never =====================================output===================================== type X3<T> = T extends [infer U extends number] ? MustBeNumber<U> : never; @@ -30,6 +32,12 @@ type X7<T> = T extends [infer U extends string, infer U extends number] : never; type X8<U, T> = T extends infer U extends number ? U : T; type X9<U, T> = T extends (infer U extends number ? U : T) ? U : T; +type X10<T> = T extends (infer U extends number) | { a: infer U extends number } + ? U + : never; +type X11<T> = T extends (infer U extends number) & { a: infer U extends number } + ? U + : never; ================================================================================ `; diff --git a/tests/format/typescript/infer-extends/basic.ts b/tests/format/typescript/infer-extends/basic.ts --- a/tests/format/typescript/infer-extends/basic.ts +++ b/tests/format/typescript/infer-extends/basic.ts @@ -5,3 +5,5 @@ type X6<T> = T extends [infer U, infer U extends number] ? MustBeNumber<U> : nev type X7<T> = T extends [infer U extends string, infer U extends number] ? U : never; type X8<U, T> = T extends infer U extends number ? U : T; type X9<U, T> = T extends (infer U extends number ? U : T) ? U : T; +type X10<T> = T extends (infer U extends number) | { a: infer U extends number } ? U : never +type X11<T> = T extends (infer U extends number) & { a: infer U extends number } ? U : never
TS: Removal of necessary parentheses when using `infer U extends` syntax with multiple conditional checks **Prettier 3.1.1** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEMCeAHOACAYhCAHgBUA+bAXm2OzgA94oATAZ2wAoBLKAMzgCdsAVVoMErbFACuAWwBGAgJTYAPtmDYAhkmzc+gkfUYTp8gdgC+2APzDsOqHABuAkABoQEDDE7QWyUE1+fggAdwAFIIR-FE0AG1DNNH8POX5NMABrOBgAZU0ZOAAZbjhkHniWOFT0rJzcjAzuAHNkGH4papAqmU42jq76LH5OQth44gEoIM44GIq4qo8WFri4AEUpCHhyyq6AKxY6XNWNrZ2kBaWQAEdzuHCQjBiQTRYAWkc4Jm-3VHTOHEWgBhCAyGSaZCvOJxP4rKDNNYAQRg7U4cik8HCAhKjl2iy6AAsYDI4gB1QmceAsRpgOC5aJUzhOKloKFgFgpEBOToASWYCDyYBG3iRzFy6DW+OuGBCVTJ6QwUNlcwELj+3Cq-Bgj00zQh0q6jX4Wqh6CwLGFnG8f1l3BgZM4TBghOQAA4AAwefhwO6cH26-WQy57DwwTRyR3O11IABMHikVWIEfmoZAcDMTB+TCKmgRUj1cHw-AhqJaUM0mIgIAsFiAA) <!-- prettier-ignore --> ```sh --parser typescript ``` **Input:** <!-- prettier-ignore --> ```tsx type Foo<T> = T extends (infer U extends number) | { a: infer U extends number } ? U : never ``` **Output:** <!-- prettier-ignore --> ```tsx type Foo<T> = T extends infer U extends number | { a: infer U extends number } ? U : never; ``` **Expected behavior:** Same as input. Removal of the parentheses will break the code as the second condition gets treated as a part of union along with `number`, rather than a separate condition to be checked against. [TS Playground](https://www.typescriptlang.org/play?ssl=3&ssc=91&pln=1&pc=1#code/C4TwDgpgBAYg9nAPAFQHxQLxWVCAPYCAOwBMBnKACgEsiAzCAJygFVcDjyoiBXAWwBGTAJRQAPlADeUAIYAuKLQbM2+QqQq9BTKAF8oAflZQFRCADcmAKCuhIUAEIzGKdFhxrOFJTtUcN3PxCzBLS8or0vuzqXFrBeobGphZMQA)
"2024-02-04T10:55:26Z"
3.3
[]
[ "tests/format/typescript/infer-extends/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEMCeAHOACAYhCAHgBUA+bAXm2OzgA94oATAZ2wAoBLKAMzgCdsAVVoMErbFACuAWwBGAgJTYAPtmDYAhkmzc+gkfUYTp8gdgC+2APzDsOqHABuAkABoQEDDE7QWyUE1+fggAdwAFIIR-FE0AG1DNNH8POX5NMABrOBgAZU0ZOAAZbjhkHniWOFT0rJzcjAzuAHNkGH4papAqmU42jq76LH5OQth44gEoIM44GIq4qo8WFri4AEUpCHhyyq6AKxY6XNWNrZ2kBaWQAEdzuHCQjBiQTRYAWkc4Jm-3VHTOHEWgBhCAyGSaZCvOJxP4rKDNNYAQRg7U4cik8HCAhKjl2iy6AAsYDI4gB1QmceAsRpgOC5aJUzhOKloKFgFgpEBOToASWYCDyYBG3iRzFy6DW+OuGBCVTJ6QwUNlcwELj+3Cq-Bgj00zQh0q6jX4Wqh6CwLGFnG8f1l3BgZM4TBghOQAA4AAwefhwO6cH26-WQy57DwwTRyR3O11IABMHikVWIEfmoZAcDMTB+TCKmgRUj1cHw-AhqJaUM0mIgIAsFiAA", "https://www.typescriptlang.org/play?ssl=3&ssc=91&pln=1&pc=1#code/C4TwDgpgBAYg9nAPAFQHxQLxWVCAPYCAOwBMBnKACgEsiAzCAJygFVcDjyoiBXAWwBGTAJRQAPlADeUAIYAuKLQbM2+QqQq9BTKAF8oAflZQFRCADcmAKCuhIUAEIzGKdFhxrOFJTtUcN3PxCzBLS8or0vuzqXFrBeobGphZMQA" ]
prettier/prettier
16,058
prettier__prettier-16058
[ "16057" ]
99bc9d0b6d3a9bcc0de6e99786502fba2d29b4fe
diff --git a/src/language-js/print/property.js b/src/language-js/print/property.js --- a/src/language-js/print/property.js +++ b/src/language-js/print/property.js @@ -44,8 +44,7 @@ function isStringKeySafeToUnquote(node, options) { options.parser === "json" || options.parser === "jsonc" || !isStringLiteral(node.key) || - // TODO[@fisker]: Use `printString` instead - rawText(node.key).slice(1, -1) !== node.key.value + printString(rawText(node.key), options).slice(1, -1) !== node.key.value ) { return false; }
diff --git a/tests/format/js/quote-props/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/quote-props/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/js/quote-props/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/quote-props/__snapshots__/jsfmt.spec.js.snap @@ -293,32 +293,32 @@ printWidth: 80 quoteProps: "as-needed" | printWidth =====================================input====================================== -const a = { +a = { a: "a" }; -const b = { +a = { 'b': "b" }; -const b2 = { +a = { // Escapes should stay as escapes and not be unquoted. '\\u0062': "b", '\\u0031': "1" }; -const c = { +a = { c1: "c1", 'c2': "c2" }; -const d = { +a = { d1: "d1", 'd-2': "d2" }; // None of these should become quoted, regardless of the quoteProps value. -const e = { +a = { NaN: null, 1: null, 1.5: null, @@ -336,7 +336,7 @@ const e = { 2n: null, } -const f = { +a = { // These should be unquoted for quoteProps=as-needed. "NaN": null, "1": null, @@ -391,33 +391,38 @@ Object.entries({ "-1.5": null, } +a = { + "\\a": 1, + "b": 2 +} + =====================================output===================================== -const a = { +a = { a: "a", }; -const b = { +a = { b: "b", }; -const b2 = { +a = { // Escapes should stay as escapes and not be unquoted. "\\u0062": "b", "\\u0031": "1", }; -const c = { +a = { c1: "c1", c2: "c2", }; -const d = { +a = { d1: "d1", "d-2": "d2", }; // None of these should become quoted, regardless of the quoteProps value. -const e = { +a = { NaN: null, 1: null, 1.5: null, @@ -435,7 +440,7 @@ const e = { 2n: null, }; -const f = { +a = { // These should be unquoted for quoteProps=as-needed. NaN: null, 1: null, @@ -490,6 +495,11 @@ Object.entries({ "-1.5": null, }; +a = { + a: 1, + b: 2, +}; + ================================================================================ `; @@ -501,32 +511,32 @@ quoteProps: "consistent" singleQuote: true | printWidth =====================================input====================================== -const a = { +a = { a: "a" }; -const b = { +a = { 'b': "b" }; -const b2 = { +a = { // Escapes should stay as escapes and not be unquoted. '\\u0062': "b", '\\u0031': "1" }; -const c = { +a = { c1: "c1", 'c2': "c2" }; -const d = { +a = { d1: "d1", 'd-2': "d2" }; // None of these should become quoted, regardless of the quoteProps value. -const e = { +a = { NaN: null, 1: null, 1.5: null, @@ -544,7 +554,7 @@ const e = { 2n: null, } -const f = { +a = { // These should be unquoted for quoteProps=as-needed. "NaN": null, "1": null, @@ -599,33 +609,38 @@ Object.entries({ "-1.5": null, } +a = { + "\\a": 1, + "b": 2 +} + =====================================output===================================== -const a = { +a = { a: 'a', }; -const b = { +a = { b: 'b', }; -const b2 = { +a = { // Escapes should stay as escapes and not be unquoted. '\\u0062': 'b', '\\u0031': '1', }; -const c = { +a = { c1: 'c1', c2: 'c2', }; -const d = { +a = { 'd1': 'd1', 'd-2': 'd2', }; // None of these should become quoted, regardless of the quoteProps value. -const e = { +a = { NaN: null, 1: null, 1.5: null, @@ -643,7 +658,7 @@ const e = { 2n: null, }; -const f = { +a = { // These should be unquoted for quoteProps=as-needed. 'NaN': null, '1': null, @@ -698,6 +713,11 @@ Object.entries({ '-1.5': null, }; +a = { + a: 1, + b: 2, +}; + ================================================================================ `; @@ -708,32 +728,32 @@ printWidth: 80 quoteProps: "consistent" | printWidth =====================================input====================================== -const a = { +a = { a: "a" }; -const b = { +a = { 'b': "b" }; -const b2 = { +a = { // Escapes should stay as escapes and not be unquoted. '\\u0062': "b", '\\u0031': "1" }; -const c = { +a = { c1: "c1", 'c2': "c2" }; -const d = { +a = { d1: "d1", 'd-2': "d2" }; // None of these should become quoted, regardless of the quoteProps value. -const e = { +a = { NaN: null, 1: null, 1.5: null, @@ -751,7 +771,7 @@ const e = { 2n: null, } -const f = { +a = { // These should be unquoted for quoteProps=as-needed. "NaN": null, "1": null, @@ -806,33 +826,38 @@ Object.entries({ "-1.5": null, } +a = { + "\\a": 1, + "b": 2 +} + =====================================output===================================== -const a = { +a = { a: "a", }; -const b = { +a = { b: "b", }; -const b2 = { +a = { // Escapes should stay as escapes and not be unquoted. "\\u0062": "b", "\\u0031": "1", }; -const c = { +a = { c1: "c1", c2: "c2", }; -const d = { +a = { "d1": "d1", "d-2": "d2", }; // None of these should become quoted, regardless of the quoteProps value. -const e = { +a = { NaN: null, 1: null, 1.5: null, @@ -850,7 +875,7 @@ const e = { 2n: null, }; -const f = { +a = { // These should be unquoted for quoteProps=as-needed. "NaN": null, "1": null, @@ -905,6 +930,11 @@ Object.entries({ "-1.5": null, }; +a = { + a: 1, + b: 2, +}; + ================================================================================ `; @@ -915,32 +945,32 @@ printWidth: 80 quoteProps: "preserve" | printWidth =====================================input====================================== -const a = { +a = { a: "a" }; -const b = { +a = { 'b': "b" }; -const b2 = { +a = { // Escapes should stay as escapes and not be unquoted. '\\u0062': "b", '\\u0031': "1" }; -const c = { +a = { c1: "c1", 'c2': "c2" }; -const d = { +a = { d1: "d1", 'd-2': "d2" }; // None of these should become quoted, regardless of the quoteProps value. -const e = { +a = { NaN: null, 1: null, 1.5: null, @@ -958,7 +988,7 @@ const e = { 2n: null, } -const f = { +a = { // These should be unquoted for quoteProps=as-needed. "NaN": null, "1": null, @@ -1013,33 +1043,38 @@ Object.entries({ "-1.5": null, } +a = { + "\\a": 1, + "b": 2 +} + =====================================output===================================== -const a = { +a = { a: "a", }; -const b = { +a = { "b": "b", }; -const b2 = { +a = { // Escapes should stay as escapes and not be unquoted. "\\u0062": "b", "\\u0031": "1", }; -const c = { +a = { c1: "c1", "c2": "c2", }; -const d = { +a = { d1: "d1", "d-2": "d2", }; // None of these should become quoted, regardless of the quoteProps value. -const e = { +a = { NaN: null, 1: null, 1.5: null, @@ -1057,7 +1092,7 @@ const e = { 2n: null, }; -const f = { +a = { // These should be unquoted for quoteProps=as-needed. "NaN": null, "1": null, @@ -1112,6 +1147,11 @@ Object.entries({ "-1.5": null, }; +a = { + "a": 1, + "b": 2, +}; + ================================================================================ `; diff --git a/tests/format/js/quote-props/jsfmt.spec.js b/tests/format/js/quote-props/jsfmt.spec.js --- a/tests/format/js/quote-props/jsfmt.spec.js +++ b/tests/format/js/quote-props/jsfmt.spec.js @@ -1,22 +1,7 @@ -const errors = {}; - -runFormatTest(import.meta, ["babel"], { - quoteProps: "as-needed", - errors, -}); - -runFormatTest(import.meta, ["babel"], { - quoteProps: "preserve", - errors, -}); - -runFormatTest(import.meta, ["babel"], { - quoteProps: "consistent", - errors, -}); - +runFormatTest(import.meta, ["babel"], { quoteProps: "as-needed" }); +runFormatTest(import.meta, ["babel"], { quoteProps: "preserve" }); +runFormatTest(import.meta, ["babel"], { quoteProps: "consistent" }); runFormatTest(import.meta, ["babel"], { quoteProps: "consistent", singleQuote: true, - errors, }); diff --git a/tests/format/js/quote-props/objects.js b/tests/format/js/quote-props/objects.js --- a/tests/format/js/quote-props/objects.js +++ b/tests/format/js/quote-props/objects.js @@ -1,29 +1,29 @@ -const a = { +a = { a: "a" }; -const b = { +a = { 'b': "b" }; -const b2 = { +a = { // Escapes should stay as escapes and not be unquoted. '\u0062': "b", '\u0031': "1" }; -const c = { +a = { c1: "c1", 'c2': "c2" }; -const d = { +a = { d1: "d1", 'd-2': "d2" }; // None of these should become quoted, regardless of the quoteProps value. -const e = { +a = { NaN: null, 1: null, 1.5: null, @@ -41,7 +41,7 @@ const e = { 2n: null, } -const f = { +a = { // These should be unquoted for quoteProps=as-needed. "NaN": null, "1": null, @@ -95,3 +95,8 @@ Object.entries({ "-1": null, "-1.5": null, } + +a = { + "\a": 1, + "b": 2 +}
Unstable property key print **Prettier 3.2.5** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBDABAXncAOlddXEAMwgmKXQEYAafQ4gI111QCdL0AmeqAXxC0QEAA4wAltADOyUB3YQA7gAUOCWSlQAbJagCes4U3aowAazgwAyqgC2cADISocZCR3S4x0xavXRMxcAc2QYdgBXbxAvOwkwyOi4AA9ROHYJB1gdABV0qA4JOE0PbS9haRDtOABFCIh4d09ogCtpZOsq2vrGpFLykABHHrgVRVFNcBkJaXhEYXDUCW0QgGEIOztUZDRtbSEYroBBGHCJJgj4FXTnVyay6IALGDttAHVHiXhpQLA4aw0XwkADcvvodmBpEYQMCogBJKAAEwQNjAGXERyR1hg+mq9wGokUXjeplEO0JxXSwLcwhcXnYMDGqGCW3x0UC7HpOyYqCYcH2wkJLhgbwkiJgj2QAA4AAzCdhwYYSBVMlnbPrNBa80XiyVIXggCJeHK8kqakBwOx8xHIxGOVBQYIRZlwABiEHYW1OIR2qEuEBA-H4QA) <!-- prettier-ignore --> ```sh --parser babel --quote-props consistent ``` **Input:** <!-- prettier-ignore --> ```jsx a = { "foo": 1, "b\ar": 2, } ``` **Output:** <!-- prettier-ignore --> ```jsx a = { "foo": 1, "bar": 2, }; ``` **Second Output:** <!-- prettier-ignore --> ```jsx a = { foo: 1, bar: 2, }; ``` **Expected output:** <!-- prettier-ignore --> ```jsx a = { foo: 1, bar: 2, }; ``` **Why?** <!-- short explanation of expected output --> Should be stable
"2024-02-07T08:55:53Z"
3.3
[]
[ "tests/format/js/quote-props/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBDABAXncAOlddXEAMwgmKXQEYAafQ4gI111QCdL0AmeqAXxC0QEAA4wAltADOyUB3YQA7gAUOCWSlQAbJagCes4U3aowAazgwAyqgC2cADISocZCR3S4x0xavXRMxcAc2QYdgBXbxAvOwkwyOi4AA9ROHYJB1gdABV0qA4JOE0PbS9haRDtOABFCIh4d09ogCtpZOsq2vrGpFLykABHHrgVRVFNcBkJaXhEYXDUCW0QgGEIOztUZDRtbSEYroBBGHCJJgj4FXTnVyay6IALGDttAHVHiXhpQLA4aw0XwkADcvvodmBpEYQMCogBJKAAEwQNjAGXERyR1hg+mq9wGokUXjeplEO0JxXSwLcwhcXnYMDGqGCW3x0UC7HpOyYqCYcH2wkJLhgbwkiJgj2QAA4AAzCdhwYYSBVMlnbPrNBa80XiyVIXggCJeHK8kqakBwOx8xHIxGOVBQYIRZlwABiEHYW1OIR2qEuEBA-H4QA" ]
prettier/prettier
16,063
prettier__prettier-16063
[ "8301" ]
7250556e287922508d9f28c12a82165a60bab5d7
diff --git a/src/language-markdown/printer-markdown.js b/src/language-markdown/printer-markdown.js --- a/src/language-markdown/printer-markdown.js +++ b/src/language-markdown/printer-markdown.js @@ -41,11 +41,7 @@ import { * @typedef {import("../document/builders.js").Doc} Doc */ -const SIBLING_NODE_TYPES = new Set([ - "listItem", - "definition", - "footnoteDefinition", -]); +const SIBLING_NODE_TYPES = new Set(["listItem", "definition"]); function genericPrint(path, options, print) { const { node } = path; @@ -405,7 +401,6 @@ function genericPrint(path, options, print) { isFirst ? group([softline, print()]) : print(), }), ), - path.next?.type === "footnoteDefinition" ? softline : "", ]), ]; }
diff --git a/tests/format/markdown/footnoteDefinition/__snapshots__/format.test.js.snap b/tests/format/markdown/footnoteDefinition/__snapshots__/format.test.js.snap --- a/tests/format/markdown/footnoteDefinition/__snapshots__/format.test.js.snap +++ b/tests/format/markdown/footnoteDefinition/__snapshots__/format.test.js.snap @@ -37,6 +37,7 @@ proseWrap: "never" =====================================output===================================== [^hello]: this is a long long long long long long long long long long long long long paragraph. + [^world]: this is a long long long long long long long long long long long long long paragraph. this is a long long long long long long long long long long long long long paragraph. ================================================================================ @@ -55,6 +56,7 @@ proseWrap: "preserve" =====================================output===================================== [^hello]: this is a long long long long long long long long long long long long long paragraph. + [^world]: this is a long long long long long long long long long long long long long paragraph. this is a long long long long long long long long long long long long long paragraph. @@ -75,6 +77,7 @@ tabWidth: 3 =====================================output===================================== [^hello]: this is a long long long long long long long long long long long long long paragraph. + [^world]: this is a long long long long long long long long long long long long long paragraph. this is a long long long long long long long long long long long long long paragraph. @@ -352,31 +355,45 @@ proseWrap: "always" =====================================output===================================== [^a]: a + [^a]: a + [^a]: a + [^a]: > 123 + [^a]: a + [^a]: > 123 + [^a]: a + [^a]: a + [^a]: a --- [^a]: a + [^a]: a + [^a]: a + [^a]: > 123\\ > 456 [^a]: a + [^a]: > 123\\ > 456 [^a]: a + [^a]: a + [^a]: a ================================================================================ @@ -415,31 +432,45 @@ proseWrap: "never" =====================================output===================================== [^a]: a + [^a]: a + [^a]: a + [^a]: > 123 + [^a]: a + [^a]: > 123 + [^a]: a + [^a]: a + [^a]: a --- [^a]: a + [^a]: a + [^a]: a + [^a]: > 123\\ > 456 [^a]: a + [^a]: > 123\\ > 456 [^a]: a + [^a]: a + [^a]: a ================================================================================ @@ -478,31 +509,45 @@ proseWrap: "preserve" =====================================output===================================== [^a]: a + [^a]: a + [^a]: a + [^a]: > 123 + [^a]: a + [^a]: > 123 + [^a]: a + [^a]: a + [^a]: a --- [^a]: a + [^a]: a + [^a]: a + [^a]: > 123\\ > 456 [^a]: a + [^a]: > 123\\ > 456 [^a]: a + [^a]: a + [^a]: a ================================================================================ @@ -541,31 +586,45 @@ tabWidth: 3 =====================================output===================================== [^a]: a + [^a]: a + [^a]: a + [^a]: > 123 + [^a]: a + [^a]: > 123 + [^a]: a + [^a]: a + [^a]: a --- [^a]: a + [^a]: a + [^a]: a + [^a]: > 123\\ > 456 [^a]: a + [^a]: > 123\\ > 456 [^a]: a + [^a]: a + [^a]: a ================================================================================
Whitespace is removed from between footnotes **Prettier 2.0.5** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBtAegRgLpIAQCyAhmACbREA2pANHgBIB0BjdATAAyYDMjeAwtBgAnAJYAjAK4xR0AM54IAMzxzJUSqIDmACxh4iUUnlKi4+mBDwA3UTCIBbUVDwARVfZiS5fflTCiSnwAKqJyanB4AJKwrHgAnGwAFGwAlHQADhmMmABs3AC0mADsuYwAOlCVGGy4hETCMlBwRJJ0AIKMAEpxAFIQlJpKSnB0royddPQQEBlwwnQ9ADJxAOLCcAji81p0Kx2UEKJEdL2MAGJxAEI7DoZ0AApxrpLiUBDWBV1EAF50q3EAKJyDIQOR2CB0ADKa0MdxObjWzlIozwnU6BiMeFWM1IVEodEBjH4cU4JT4ADU7I5nG5VJIspQ4A4EJ5ZC5LHgMhtrKyDGBpJENiDRMIiJZhABPPAiEj6ZwjMAyeT4OSSuTwO4yMB4HlmADumOMLPsBUMVHVYUUKmRolspEkVC5DW1ogyhn0ePsfCuBF6dG4AFZcplGKJcoGABy8SrVdDcOpXBobGAwU5xJYkADWez4hmMBAgwjEcjoLDomHi8V4eGCOkiciZcAyBTg1ggWbgxhRYA2RDkkWUeHEEFI0s1czFXg2fChTYyFdyKXSXOy1YKVcYIBoIFmyqgcmQoGTEH1DwaCEPKCo+qI6u3IHEYrAnZgUPdASgWmQIkkoxAegOJQADqOh2HAIIkHAUKXnYdp2JKyDgOED7OAOjQPGKWh3MgShUAOO4AFZyAAHlcz6vlCjhwEszhwLh+H-sRJFQs4WhMgAipIEDwAxlAESA7rCOhSF3MIWbkPqUAPtyzgwMBoikDAOjIJGHA7tyYJwMBYoZEh3IQfMvIPgAjtx8CYbMV4gP2BTNF2XYPhsZminAmFENhRB8QJA5OD+wh-ju4Jfpx5n0UgeH8f+9jiApSkqUgbA7rKoiaF+ggODhKAQYGD7eHAwREOIV6RQJ1h-jEKKwFCvZujA7RGFCMCSky3lwAAvu1QA) ```sh --parser markdown ``` **Input:** ```markdown [^1]: Macdonald, H.M., 2013. Contributions of sunlight and diet to vitamin D status. Calcif. Tissue Int., 92(2), pp.163-176. [^2]: Martineau, A.R., Jolliffe, D.A., Hooper, R.L., Greenberg, L., Aloia, J.F., Bergman, P., Dubnov-Raz, G., Esposito, S., Ganmaa, D., Ginde, A.A. and Goodall, E.C., 2017. Vitamin D supplementation to prevent acute respiratory tract infections: systematic review and meta-analysis of individual participant data. BMJ, 356, p.i6583. [^3]: Barrett, J., Lack, L. and Morris, M., 1993. The sleep-evoked decrease of body temperature. Sleep, 16(2), pp.93-99. ``` **Output:** ```markdown [^1]: Macdonald, H.M., 2013. Contributions of sunlight and diet to vitamin D status. Calcif. Tissue Int., 92(2), pp.163-176. [^2]: Martineau, A.R., Jolliffe, D.A., Hooper, R.L., Greenberg, L., Aloia, J.F., Bergman, P., Dubnov-Raz, G., Esposito, S., Ganmaa, D., Ginde, A.A. and Goodall, E.C., 2017. Vitamin D supplementation to prevent acute respiratory tract infections: systematic review and meta-analysis of individual participant data. BMJ, 356, p.i6583. [^3]: Barrett, J., Lack, L. and Morris, M., 1993. The sleep-evoked decrease of body temperature. Sleep, 16(2), pp.93-99. ``` **Expected behavior:** Blocks should be respected.
Indeed, seems to be a bug. From https://pandoc.org/MANUAL.html#footnotes: > Each footnote should be separated from surrounding content (including other footnotes) by blank lines. @Undistraction Work is currently underway to update the Markdown parser that Prettier uses. See #8140. Could you probably help with testing that PR against your Markdown documents? I'm particularly interested in testing footnotes-related issues. This behavior hasn't changed. I guess it may be intentional? Re: Pandoc, fortunately, I've found that it's tolerant of the absence of a blank line between footnotes. I still experience this bug.
"2024-02-08T14:30:04Z"
3.3
[]
[ "tests/format/markdown/footnoteDefinition/format.test.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBtAegRgLpIAQCyAhmACbREA2pANHgBIB0BjdATAAyYDMjeAwtBgAnAJYAjAK4xR0AM54IAMzxzJUSqIDmACxh4iUUnlKi4+mBDwA3UTCIBbUVDwARVfZiS5fflTCiSnwAKqJyanB4AJKwrHgAnGwAFGwAlHQADhmMmABs3AC0mADsuYwAOlCVGGy4hETCMlBwRJJ0AIKMAEpxAFIQlJpKSnB0royddPQQEBlwwnQ9ADJxAOLCcAji81p0Kx2UEKJEdL2MAGJxAEI7DoZ0AApxrpLiUBDWBV1EAF50q3EAKJyDIQOR2CB0ADKa0MdxObjWzlIozwnU6BiMeFWM1IVEodEBjH4cU4JT4ADU7I5nG5VJIspQ4A4EJ5ZC5LHgMhtrKyDGBpJENiDRMIiJZhABPPAiEj6ZwjMAyeT4OSSuTwO4yMB4HlmADumOMLPsBUMVHVYUUKmRolspEkVC5DW1ogyhn0ePsfCuBF6dG4AFZcplGKJcoGABy8SrVdDcOpXBobGAwU5xJYkADWez4hmMBAgwjEcjoLDomHi8V4eGCOkiciZcAyBTg1ggWbgxhRYA2RDkkWUeHEEFI0s1czFXg2fChTYyFdyKXSXOy1YKVcYIBoIFmyqgcmQoGTEH1DwaCEPKCo+qI6u3IHEYrAnZgUPdASgWmQIkkoxAegOJQADqOh2HAIIkHAUKXnYdp2JKyDgOED7OAOjQPGKWh3MgShUAOO4AFZyAAHlcz6vlCjhwEszhwLh+H-sRJFQs4WhMgAipIEDwAxlAESA7rCOhSF3MIWbkPqUAPtyzgwMBoikDAOjIJGHA7tyYJwMBYoZEh3IQfMvIPgAjtx8CYbMV4gP2BTNF2XYPhsZminAmFENhRB8QJA5OD+wh-ju4Jfpx5n0UgeH8f+9jiApSkqUgbA7rKoiaF+ggODhKAQYGD7eHAwREOIV6RQJ1h-jEKKwFCvZujA7RGFCMCSky3lwAAvu1QA" ]
prettier/prettier
16,064
prettier__prettier-16064
[ "16007" ]
572452b89d3ccdad70f2b99de4af5d5c84be944a
diff --git a/src/language-js/embed/utils.js b/src/language-js/embed/utils.js --- a/src/language-js/embed/utils.js +++ b/src/language-js/embed/utils.js @@ -80,6 +80,8 @@ function hasLanguageComment({ node, parent }, languageName) { return ( hasLeadingBlockCommentWithName(node, languageName) || (isAsConstExpression(parent) && + hasLeadingBlockCommentWithName(parent, languageName)) || + (parent.type === "ExpressionStatement" && hasLeadingBlockCommentWithName(parent, languageName)) ); }
diff --git a/tests/format/js/multiparser-graphql/__snapshots__/jsfmt.spec.js.snap b/tests/format/js/multiparser-graphql/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/js/multiparser-graphql/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/js/multiparser-graphql/__snapshots__/jsfmt.spec.js.snap @@ -16,6 +16,17 @@ const query = /* GraphQL */\` } \`; +/* GraphQL */\` + { + user( id : 5 , type: + "without variable assignment" ) { + firstName + + lastName + } + } +\`; + =====================================output===================================== const query = /* GraphQL */ \` { @@ -27,6 +38,16 @@ const query = /* GraphQL */ \` } \`; +/* GraphQL */ \` + { + user(id: 5, type: "without variable assignment") { + firstName + + lastName + } + } +\`; + ================================================================================ `; diff --git a/tests/format/js/multiparser-graphql/comment-tag.js b/tests/format/js/multiparser-graphql/comment-tag.js --- a/tests/format/js/multiparser-graphql/comment-tag.js +++ b/tests/format/js/multiparser-graphql/comment-tag.js @@ -7,3 +7,14 @@ const query = /* GraphQL */` } } `; + +/* GraphQL */` + { + user( id : 5 , type: + "without variable assignment" ) { + firstName + + lastName + } + } +`;
Bare embedded GQL string in e.g. JS is not formatted **Prettier 3.2.4** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuc0DOMAEAzCFMC8mA9AFSYDiATgIYAOAFgIoAympxmABgDpSaYAjgFc4VAJ448mYJgCWAE0wBfPlwDcfPmUq1Grdp178hoiVPyzFKtepAAaEBDow56ZKBpUqEAO4AFLwQ0ZBAaABtfGnEQxwAjWjAAazgYAGUaAFs4FjkoOGRsCLQ4eMSU9LoaMDyAc2QYKlFHEsy5BqbSkDgADzoxOWzYCIAVMSgvOTgQpCLwkpa68LgmYQh4QuKugCs0HrSllbWN2a3HEXW4fx86GbC0AFp8uAUXhxBGmjlwuoBhCEymRooQi4XeaEOAEEYI05HFhPB-GJcvlNvMugwYJlwgB1BhyeBoKpgOBpYIEuQANwJ4lCYDQsRAlNEAEkoK9YGkwFQ5C5Iey0jBxMs0QsQHQfCUcXpQhLpmJKQVHHkSlQYNcaLUgaKulUqKrQnEaHE4GDHBK8jAcYoYAxkAAOAAMjiocBEcldGq1wNO6McMGN1oUtuQACZHMISiNjTM5mK4JkTQpXgoWDQoLVhJq4AAxCBUIEwuoghEQEDKZRAA) <!-- prettier-ignore --> ```sh --parser babel ``` **Input:** <!-- prettier-ignore --> ```jsx const foo = /* GraphQL */ ` query foo { id } `; foo(/* GraphQL */ ` query foo { id } `); /* GraphQL */ ` query foo { id } `; ``` **Output:** <!-- prettier-ignore --> ```jsx const foo = /* GraphQL */ ` query foo { id } `; foo(/* GraphQL */ ` query foo { id } `); /* GraphQL */ ` query foo { id } `; ``` **Expected output:** <!-- prettier-ignore --> ```jsx const foo = /* GraphQL */ ` query foo { id } `; foo(/* GraphQL */ ` query foo { id } `); /* GraphQL */ ` query foo { id }`; ``` **Why?** We use GQL snippets in TS sometimes purely for codegen - these strings get stripped out during build. We don't need or want to assign to variables, so it would be nice to get these formatted by prettier. I'd consider this to be a nice-to-have feature. I have no idea if this was a conscious decision, or if it's some kind of design limitation. I'd be willing to implement if this feature would be considered and somebody pointed me in the right direction.
To the best of my recollection, I don't believe this is either an intentional design or a limitation. If that's a real-world use case, I think we can accept it. Thanks - this may be trivial for someone who knows the codebase and has time to look at it, but otherwise, any pointers on where to look? I confess I haven't looked yet. Also, I'm not clear on the scope of what I've requested - is this a generic thing that applies across embedded languages somehow, or limited to embedding languages in JS/TS, or specific to JS/TS/GQL? I know I need to do some reading of docs and code, but again, any pointers are welcome. This function https://github.com/prettier/prettier/blob/99bc9d0b6d3a9bcc0de6e99786502fba2d29b4fe/src/language-js/embed/graphql.js#L108-L122 decides if the template should format as graphql. All you need to do is make it match your case.
"2024-02-08T19:35:18Z"
3.3
[]
[ "tests/format/js/multiparser-graphql/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuc0DOMAEAzCFMC8mA9AFSYDiATgIYAOAFgIoAympxmABgDpSaYAjgFc4VAJ448mYJgCWAE0wBfPlwDcfPmUq1Grdp178hoiVPyzFKtepAAaEBDow56ZKBpUqEAO4AFLwQ0ZBAaABtfGnEQxwAjWjAAazgYAGUaAFs4FjkoOGRsCLQ4eMSU9LoaMDyAc2QYKlFHEsy5BqbSkDgADzoxOWzYCIAVMSgvOTgQpCLwkpa68LgmYQh4QuKugCs0HrSllbWN2a3HEXW4fx86GbC0AFp8uAUXhxBGmjlwuoBhCEymRooQi4XeaEOAEEYI05HFhPB-GJcvlNvMugwYJlwgB1BhyeBoKpgOBpYIEuQANwJ4lCYDQsRAlNEAEkoK9YGkwFQ5C5Iey0jBxMs0QsQHQfCUcXpQhLpmJKQVHHkSlQYNcaLUgaKulUqKrQnEaHE4GDHBK8jAcYoYAxkAAOAAMjiocBEcldGq1wNO6McMGN1oUtuQACZHMISiNjTM5mK4JkTQpXgoWDQoLVhJq4AAxCBUIEwuoghEQEDKZRAA" ]
prettier/prettier
16,158
prettier__prettier-16158
[ "15877" ]
d970deed6b6cabe21fdb35249265d766932b5718
diff --git a/src/document/utils.js b/src/document/utils.js --- a/src/document/utils.js +++ b/src/document/utils.js @@ -337,10 +337,11 @@ function cleanDocFn(doc) { return doc; } -// A safer version of `normalizeDoc` -// - `normalizeDoc` concat strings and flat array in `fill`, while `cleanDoc` don't -// - On array, `normalizeDoc` always return object with `parts`, `cleanDoc` may return strings -// - `cleanDoc` also remove nested `group`s and empty `fill`/`align`/`indent`/`line-suffix`/`if-break` if possible + +// - concat strings +// - flat arrays except for parts of `fill` +// - merge arrays of strings into single strings +// - remove nested `group`s and empty `fill`/`align`/`indent`/`line-suffix`/`if-break` if possible function cleanDoc(doc) { return mapDoc(doc, (currentDoc) => cleanDocFn(currentDoc)); } @@ -376,21 +377,6 @@ function normalizeParts(parts) { return newParts; } -function normalizeDoc(doc) { - return mapDoc(doc, (currentDoc) => { - if (Array.isArray(currentDoc)) { - return normalizeParts(currentDoc); - } - if (!currentDoc.parts) { - return currentDoc; - } - return { - ...currentDoc, - parts: normalizeParts(currentDoc.parts), - }; - }); -} - function replaceEndOfLine(doc, replacement = literalline) { return mapDoc(doc, (currentDoc) => typeof currentDoc === "string" @@ -422,7 +408,6 @@ export { getDocType, inheritLabel, mapDoc, - normalizeDoc, normalizeParts, propagateBreaks, removeLines, diff --git a/src/language-markdown/print-paragraph.js b/src/language-markdown/print-paragraph.js --- a/src/language-markdown/print-paragraph.js +++ b/src/language-markdown/print-paragraph.js @@ -1,5 +1,6 @@ import { fill } from "../document/builders.js"; -import { normalizeDoc } from "../document/utils.js"; +import { DOC_TYPE_ARRAY, DOC_TYPE_FILL } from "../document/constants.js"; +import { getDocType } from "../document/utils.js"; /** * @typedef {import("../common/ast-path.js").default} AstPath @@ -14,7 +15,41 @@ import { normalizeDoc } from "../document/utils.js"; */ function printParagraph(path, options, print) { const parts = path.map(print, "children"); - return normalizeDoc(fill(parts)); + return flattenFill(parts); +} + +/** + * @param {Doc[]} docs + * @returns {Doc} + */ +function flattenFill(docs) { + /* + * We assume parts always meet following conditions: + * - parts.length is odd + * - odd elements are line-like doc that comes from odd element off inner fill + */ + /** @type {Doc[]} */ + const parts = [""]; + + (function rec(/** @type {*} */ docArray) { + for (const doc of docArray) { + const docType = getDocType(doc); + if (docType === DOC_TYPE_ARRAY) { + rec(doc); + continue; + } + + let head = doc; + let rest = []; + if (docType === DOC_TYPE_FILL) { + [head, ...rest] = doc.parts; + } + + parts.push([parts.pop(), head], ...rest); + } + })(docs); + + return fill(parts); } export { printParagraph }; diff --git a/src/language-markdown/print-sentence.js b/src/language-markdown/print-sentence.js new file mode 100644 --- /dev/null +++ b/src/language-markdown/print-sentence.js @@ -0,0 +1,37 @@ +/** + * @typedef {import("../common/ast-path.js").default} AstPath + * @typedef {import("../document/builders.js").Doc} Doc + */ + +import { fill } from "../document/builders.js"; +import { DOC_TYPE_STRING } from "../document/constants.js"; +import { getDocType } from "../document/utils.js"; + +/** + * @param {AstPath} path + * @param {*} print + * @returns {Doc} + */ +function printSentence(path, print) { + /** @type {Doc[]} */ + const parts = [""]; + + path.each(() => { + const { node } = path; + const doc = print(); + switch (node.type) { + case "whitespace": + if (getDocType(doc) !== DOC_TYPE_STRING) { + parts.push(doc, ""); + break; + } + // fallthrough + default: + parts.push([parts.pop(), doc]); + } + }, "children"); + + return fill(parts); +} + +export { printSentence }; diff --git a/src/language-markdown/printer-markdown.js b/src/language-markdown/printer-markdown.js --- a/src/language-markdown/printer-markdown.js +++ b/src/language-markdown/printer-markdown.js @@ -2,6 +2,7 @@ import collapseWhiteSpace from "collapse-white-space"; import { align, + fill, group, hardline, indent, @@ -10,7 +11,8 @@ import { markAsRoot, softline, } from "../document/builders.js"; -import { replaceEndOfLine } from "../document/utils.js"; +import { DOC_TYPE_STRING } from "../document/constants.js"; +import { getDocType, replaceEndOfLine } from "../document/utils.js"; import getMaxContinuousCount from "../utils/get-max-continuous-count.js"; import getMinNotPresentContinuousCount from "../utils/get-min-not-present-continuous-count.js"; import getPreferredQuote from "../utils/get-preferred-quote.js"; @@ -24,6 +26,7 @@ import { insertPragma } from "./pragma.js"; import { printTable } from "./print/table.js"; import { printParagraph } from "./print-paragraph.js"; import preprocess from "./print-preprocess.js"; +import { printSentence } from "./print-sentence.js"; import { printWhitespace } from "./print-whitespace.js"; import { getFencedCodeBlockValue, @@ -48,16 +51,27 @@ function genericPrint(path, options, print) { const { node } = path; if (shouldRemainTheSameContent(path)) { - return splitText( + /** @type {Doc} */ + const parts = [""]; + const textsNodes = splitText( options.originalText.slice( node.position.start.offset, node.position.end.offset, ), - ).map((node) => - node.type === "word" - ? node.value - : printWhitespace(path, node.value, options.proseWrap, true), ); + for (const node of textsNodes) { + if (node.type === "word") { + parts.push([parts.pop(), node.value]); + continue; + } + const doc = printWhitespace(path, node.value, options.proseWrap, true); + if (getDocType(doc) === DOC_TYPE_STRING) { + parts.push([parts.pop(), doc]); + continue; + } + parts.push(doc); + } + return fill(parts); } switch (node.type) { @@ -75,7 +89,7 @@ function genericPrint(path, options, print) { case "paragraph": return printParagraph(path, options, print); case "sentence": - return printChildren(path, options, print); + return printSentence(path, print); case "word": { let escapedValue = node.value .replaceAll("*", "\\*") // escape all `*`
diff --git a/tests/format/markdown/break/__snapshots__/jsfmt.spec.js.snap b/tests/format/markdown/break/__snapshots__/jsfmt.spec.js.snap --- a/tests/format/markdown/break/__snapshots__/jsfmt.spec.js.snap +++ b/tests/format/markdown/break/__snapshots__/jsfmt.spec.js.snap @@ -28,3 +28,29 @@ proseWrap: "always" ================================================================================ `; + +exports[`wrap.md - {"proseWrap":"always"} format 1`] = ` +====================================options===================================== +parsers: ["markdown"] +printWidth: 80 +proseWrap: "always" + | printWidth +=====================================input====================================== +a + very-very-very-very-very-very-very-very-very-very-long-word very-very-very-very-very-very-very-very-very-very-long-word very-very-very-very-very-very-very-very-very-very-long-word + +\\ +word very-very-very-very-very-very-very-very-very-very-long-word very-very-very-very-very-very-very-very-very-very-long-word + +=====================================output===================================== +a + very-very-very-very-very-very-very-very-very-very-long-word +very-very-very-very-very-very-very-very-very-very-long-word +very-very-very-very-very-very-very-very-very-very-long-word + +\\ +word very-very-very-very-very-very-very-very-very-very-long-word +very-very-very-very-very-very-very-very-very-very-long-word + +================================================================================ +`; diff --git a/tests/format/markdown/break/wrap.md b/tests/format/markdown/break/wrap.md new file mode 100644 --- /dev/null +++ b/tests/format/markdown/break/wrap.md @@ -0,0 +1,5 @@ +a + very-very-very-very-very-very-very-very-very-very-long-word very-very-very-very-very-very-very-very-very-very-long-word very-very-very-very-very-very-very-very-very-very-long-word + +\ +word very-very-very-very-very-very-very-very-very-very-long-word very-very-very-very-very-very-very-very-very-very-long-word diff --git a/tests/integration/__tests__/normalize-doc.js b/tests/integration/__tests__/normalize-doc.js deleted file mode 100644 --- a/tests/integration/__tests__/normalize-doc.js +++ /dev/null @@ -1,36 +0,0 @@ -import { fill, group } from "../../../src/document/builders.js"; -import { normalizeDoc } from "../../../src/document/utils.js"; - -describe("normalizeDoc", () => { - test.each([ - [ - "removes empty strings", - ["", "foo", fill(["", "bar", ""]), ""], - ["foo", fill(["bar"])], - ], - [ - "flattens nested concat", - ["foo ", "", ["bar ", "", ["baz", ""]]], - ["foo bar baz"], - ], - [ - "flattens nested concat in other docs", - group(["foo ", ["bar ", "", ["baz", ""]]]), - group(["foo bar baz"]), - ], - [ - "keeps groups", - [group("foo"), group("bar"), group("baz")], - [group("foo"), group("bar"), group("baz")], - ], - [ - "keeps fills", - fill(["foo", fill(["bar", fill(["baz"])])]), - fill(["foo", fill(["bar", fill(["baz"])])]), - ], - ])("%s", (_, doc, expected) => { - const result = normalizeDoc(doc); - - expect(result).toEqual(expected); - }); -});
Doc of paragraph in markdown violates a rule of `fill()` **Prettier 3.1.1** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBDABB9AdK6BGB6OeY6ZJuxIANCBAA4wCW0AzsqKgE7cQDuABR4IOKVABt+qAJ4c6+bqjABrODADKqALZwAMsyhxkAM0ls4CpavUaGywwHNkMbgFdLIC9uYv3nuAAPBjhuZl1YSQAVUKgeZjgxMwkLOjYnCTgARTcIeFNzTwArNkCNDOzc-KRk1JAARyq4QT4GMTQ2AFojOAATPtoQV1RmCScAYQhtbVRkNAkJQfSoR0yAQRhXZnw3eEFQgyMClM8ACxhtCQB1U+Z4NnswOA1RO+YANzuZObA2eRB3h4AJJQfqwDRgMJMNagjQwGSZY51Bh8CxXJQMOaSaRyQaGCzcGAtVCOGZIzz2bgEuYzbgqXoCKCDFGGGBXZi9GCnZAADgADHRuHBGswhcTSbMaoU6DBUPh2ZzuUgACx0NwWKJypLSkBwbT4Pr9Xp6VArNwkuAAMQg3BmmycWN2EBAAF8XUA) <!-- prettier-ignore --> ```sh --parser markdown --tab-width 4 --prose-wrap always ``` **Input:** <!-- prettier-ignore --> ```markdown a a b b c c ``` **Doc:** <!-- prettier-ignore --> ```markdown [ fill([ "a", line, "a ", markAsRoot(literalline), line, "b", line, "b ", markAsRoot(literalline), line, "c", line, "c", ]), hardline, ] ``` **Expected behavior:** The result doc should preserve the following invaliant: https://github.com/prettier/prettier/blob/bab892242a1f9d8fcae50514b9304bf03f2e25ab/src/document/printer.js#L442-L443 I haven't found user-facing problem yet. I found it investigating https://github.com/prettier/prettier/discussions/15836#discussioncomment-7917975.
Oh it can be reproduced without `--prose-wrap: always`. I changed the issue title. **Prettier 3.1.1** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBDABKgOlARu3HMdMEAGhAgAcYBLaAZ2VFQCdWIB3ABTYSZSoANp1QBPJhVytUYANZwYAZVQBbOABlaUOMgBmwhnCkz5ipVVnaA5shisArsZBHVtO4+dwAHlTitadVhhABV-KDZaOAEDISMKBhshOABFBwh4fUNnACsGbyUk1PTMpFj4kABHErhuDioBNAYAWh04ABMO8hB7VFohGwBhCFVVVGQ0ISFuxKhrZIBBGHtaXAd4bn8tHSy45wALGFUhAHV92ngGSzA4JX4L2gA3C7EJsAZJEEenAEkoTtgSjAARoC3+ShgYmSuwqVA4RhOMioEzh0X8j10FG0RlYMDqqGsYxhzksrBxEzGrDk7S4UG6cO0MBOtHaMH2yAAHAAGCisODVWh8-GE8ZlbIUGCoXDM1nspAAFgoDiMISlMXFIDgqlwHU67Q0qDmDgJcAAYhBWGNljYJqh1hAQABfR1AA) <!-- prettier-ignore --> ```sh --parser markdown --tab-width 4 ``` **Input:** <!-- prettier-ignore --> ```markdown a a b b c c ``` **Doc:** ``` [ fill([ "a a", hardlineWithoutBreakParent, breakParent, "b b", hardlineWithoutBreakParent, breakParent, "c c", ]), hardline, ] ``` I found I've misunderstood something. This should be one of the user-facing problems. **Prettier 3.1.1** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEACVBDV8AeNtx4FG76nFmGUlUV3kO2NGoA6U6ARvU7zf9UE8Bwoc3xsOqMKNni5fMYoUt26ACYqlI+buV6Rk9HC2mD2i6ckgANCAgAHGAEtoAZ2SgMAJ28QA7gAKPggeKBgANv4YAJ4edpzeGGAA1nAwAMoYALZwADLOUHDIAGaRbnAJSanpGQ7JhQDmyDDeAK6VIBXZzi3tnYQOcN7OubCRACrDUD7OcGFlERV2bk0RcACKbRDwpeWdAFZuOBlrm9u7SIvLIACOF3CBfg5hIBhuALRFcOo-tiCtDDOCJNADCEGy2QwyDeEQi-1WUEa6wAgjBWs5OG14IFhgUinslp0ABYwbIRADqxOc8Dc9TAcAyoRpzgAbjSYjCwG54iBWR0AJJQX6wDJgEZOFHCjIwGLrQk3Bx+CoUpIOGGRaJxf6FCreGBPDCNKEKzr1bx6mFQ7wpdQBKD-JWFGAU5zqGDE5AADgADHZvHB7s4A4bjdCrvs7DAMJxXe7PUgACx2NoVCYxhaRkBwbKcH6-dR5DBItpGuAAMQg3ih6KaGuxEBAAF8m0A) <!-- prettier-ignore --> ```sh --parser markdown --tab-width 4 --prose-wrap always ``` **Input:** <!-- prettier-ignore --> ```markdown a text text text text text text text text text text text text text text text text b text text text text text text text text text text text text text text text text c text text text text text text text text text text text text text text text text d text text text text text text text text text text text text text text text text e text text text text text text text text text text text text text text text text ``` **Output:** <!-- prettier-ignore --> ```markdown a text text text text text text text text text text text text text text text text b text text text text text text text text text text text text text text text text c text text text text text text text text text text text text text text text text d text text text text text text text text text text text text text text text text e text text text text text text text text text text text text text text text text ``` **Expected behavior:** Maybe following? <!-- prettier-ignore --> ```markdown a text text text text text text text text text text text text text text text text b text text text text text text text text text text text text text text text text c text text text text text text text text text text text text text text text text d text text text text text text text text text text text text text text text text e text text text text text text text text text text text text text text text text ``` `normalizeDoc()` is suspicious. https://github.com/prettier/prettier/blob/81efe72536d11ee673cca57e3bbc2117198f0f1f/src/document/utils.js#L392-L405 As `cleanDoc()` comment implies, `normalizeDoc()` is dangerous. https://github.com/prettier/prettier/blob/81efe72536d11ee673cca57e3bbc2117198f0f1f/src/document/utils.js#L353-L359 Feel free to kill it, it's known dangerous. https://github.com/prettier/prettier/pull/9736#discussion_r527916210 Yeah, I'm trying. It might be hard because Markdown printer seems to rely on this bug. Fixing Markdown printer, we will be able to erase it🧹. The originally version was for markdown, there might be difference with current one. https://github.com/prettier/prettier/pull/8496/files I also tried to move it back, didn't finish https://github.com/prettier/prettier/pull/13701
"2024-03-20T07:05:54Z"
3.3
[]
[ "tests/format/markdown/break/jsfmt.spec.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBDABB9AdK6BGB6OeY6ZJuxIANCBAA4wCW0AzsqKgE7cQDuABR4IOKVABt+qAJ4c6+bqjABrODADKqALZwAMsyhxkAM0ls4CpavUaGywwHNkMbgFdLIC9uYv3nuAAPBjhuZl1YSQAVUKgeZjgxMwkLOjYnCTgARTcIeFNzTwArNkCNDOzc-KRk1JAARyq4QT4GMTQ2AFojOAATPtoQV1RmCScAYQhtbVRkNAkJQfSoR0yAQRhXZnw3eEFQgyMClM8ACxhtCQB1U+Z4NnswOA1RO+YANzuZObA2eRB3h4AJJQfqwDRgMJMNagjQwGSZY51Bh8CxXJQMOaSaRyQaGCzcGAtVCOGZIzz2bgEuYzbgqXoCKCDFGGGBXZi9GCnZAADgADHRuHBGswhcTSbMaoU6DBUPh2ZzuUgACx0NwWKJypLSkBwbT4Pr9Xp6VArNwkuAAMQg3BmmycWN2EBAAF8XUA" ]
prettier/prettier
16,267
prettier__prettier-16267
[ "16266" ]
708bb1fe70263549cf7c85508e09b959d623b1de
diff --git a/src/language-js/print/call-expression.js b/src/language-js/print/call-expression.js --- a/src/language-js/print/call-expression.js +++ b/src/language-js/print/call-expression.js @@ -45,7 +45,7 @@ function printCallExpression(path, options, print) { if (!(isTemplateLiteralSingleArg && printed[0].label?.embed)) { return [ isNew ? "new " : "", - print("callee"), + isDynamicImport ? printDynamicImportCallee(node) : print("callee"), optional, printFunctionTypeParameters(path, options, print), "(",
diff --git a/tests/format/js/dynamic-import/__snapshots__/format.test.js.snap b/tests/format/js/dynamic-import/__snapshots__/format.test.js.snap --- a/tests/format/js/dynamic-import/__snapshots__/format.test.js.snap +++ b/tests/format/js/dynamic-import/__snapshots__/format.test.js.snap @@ -45,6 +45,106 @@ import("./foo.json", { assert: { type: "json" } }); ================================================================================ `; +exports[`import-phase.js [acorn] format 1`] = ` +"The only valid meta property for import is 'import.meta' (1:8) +> 1 | import.source(\`data:text/javascript, + | ^ + 2 | console.log("RUN"); + 3 | \`) + 4 | +Cause: The only valid meta property for import is 'import.meta' (1:7)" +`; + +exports[`import-phase.js [espree] format 1`] = ` +"The only valid meta property for import is 'import.meta' (1:8) +> 1 | import.source(\`data:text/javascript, + | ^ + 2 | console.log("RUN"); + 3 | \`) + 4 | +Cause: The only valid meta property for import is 'import.meta'" +`; + +exports[`import-phase.js [flow] format 1`] = ` +"Unexpected identifier, expected the identifier \`meta\` (1:8) +> 1 | import.source(\`data:text/javascript, + | ^^^^^^ + 2 | console.log("RUN"); + 3 | \`) + 4 |" +`; + +exports[`import-phase.js [meriyah] format 1`] = ` +"Unexpected token: 'identifier' (1:13) +> 1 | import.source(\`data:text/javascript, + | ^ + 2 | console.log("RUN"); + 3 | \`) + 4 | +Cause: [1:13]: Unexpected token: 'identifier'" +`; + +exports[`import-phase.js format 1`] = ` +====================================options===================================== +parsers: ["babel", "flow", "typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +import.source(\`data:text/javascript, + console.log("RUN"); +\`) + +import.source(String.raw\`data:text/javascript, + console.log("RUN"); +\`) + +=====================================output===================================== +import.source(\`data:text/javascript, + console.log("RUN"); +\`); + +import.source(String.raw\`data:text/javascript, + console.log("RUN"); +\`); + +================================================================================ +`; + +exports[`template-literal.js [flow] format 1`] = ` +"Unexpected token \`import\`, expected the end of an expression statement (\`;\`) (1:20) +> 1 | module = await import(\`data:text/javascript, + | ^^^^^^ + 2 | console.log("RUN"); + 3 | \`); + 4 |" +`; + +exports[`template-literal.js format 1`] = ` +====================================options===================================== +parsers: ["babel", "flow", "typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +module = await import(\`data:text/javascript, + console.log("RUN"); +\`); + +module = await import(String.raw\`data:text/javascript, + console.log("RUN"); +\`); + +=====================================output===================================== +module = await import(\`data:text/javascript, + console.log("RUN"); +\`); + +module = await import(String.raw\`data:text/javascript, + console.log("RUN"); +\`); + +================================================================================ +`; + exports[`test.js format 1`] = ` ====================================options===================================== parsers: ["babel", "flow", "typescript"] diff --git a/tests/format/js/dynamic-import/format.test.js b/tests/format/js/dynamic-import/format.test.js --- a/tests/format/js/dynamic-import/format.test.js +++ b/tests/format/js/dynamic-import/format.test.js @@ -1,8 +1,8 @@ runFormatTest(import.meta, ["babel", "flow", "typescript"], { errors: { - flow: ["assertions.js"], - acorn: ["assertions.js"], - espree: ["assertions.js"], - meriyah: ["assertions.js"], + flow: ["assertions.js", "template-literal.js", "import-phase.js"], + acorn: ["assertions.js", "import-phase.js"], + espree: ["assertions.js", "import-phase.js"], + meriyah: ["assertions.js", "import-phase.js"], }, }); diff --git a/tests/format/js/dynamic-import/import-phase.js b/tests/format/js/dynamic-import/import-phase.js new file mode 100644 --- /dev/null +++ b/tests/format/js/dynamic-import/import-phase.js @@ -0,0 +1,7 @@ +import.source(`data:text/javascript, + console.log("RUN"); +`) + +import.source(String.raw`data:text/javascript, + console.log("RUN"); +`) diff --git a/tests/format/js/dynamic-import/template-literal.js b/tests/format/js/dynamic-import/template-literal.js new file mode 100644 --- /dev/null +++ b/tests/format/js/dynamic-import/template-literal.js @@ -0,0 +1,7 @@ +module = await import(`data:text/javascript, + console.log("RUN"); +`); + +module = await import(String.raw`data:text/javascript, + console.log("RUN"); +`);
dynamic import keyword is removed when given multiline template string <!-- BEFORE SUBMITTING AN ISSUE: 1. Search for your issue on GitHub: https://github.com/prettier/prettier/issues A large number of opened issues are duplicates of existing issues. If someone has already opened an issue for what you are experiencing, you do not need to open a new issue — please add a 👍 reaction to the existing issue instead. 2. We get a lot of requests for adding options, but Prettier is built on the principle of being opinionated about code formatting. This means we add options only in the case of strict technical necessity. Find out more: https://prettier.io/docs/en/option-philosophy.html Don't fill the form below manually! Let a program create a report for you: 1. Go to https://prettier.io/playground 2. Paste your code and set options 3. Press the "Report issue" button in the lower right --> **Prettier 3.2.5** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuc0DOMAEBbCATAVwBs5MBeTAQwHdKBLLO7ABwgCcYAKAAz0pkpJ4ADxgB6AFaUAbpTRg2dZjAA0AHSiYtmSFDQQSAOiIQA5pzUgASgFUAcpYCUAbg3cXIFSAjK66ZKCUbGwQ1AAKQQhoyCCURLQAntFeAEZslGAA1nAwAMqU2HAAMnRQcMgAZnFocKnpWTm5zBmlpsgwbAS1IDXYdO2d3XDCzHCKhbBxACpjUEF0cNFIVUQ1XmitJACKBBDwldXdEmjCuZtwO3vly4deAI678GEhzEuxaAC0ZXB4P54gHXoRFaAGEINhsJQYnEiP8NlBTCQAIIwDp0FIEJ5jEplA6rboACxg2CIAHUCQxFs0wHBclEGHRpAwEjEwGhkiBpF0AJJQX6wXIKJQwJF83IwBIkPFrEDMEI1UnpZgxOWLMbScpeUo1DjPSimSHS7rNNg6mIS0byRTKf5y0owUl0PAwAnIAAcAAYvGw4A86D69QaoTd8V4BClHc7XUgAExeAg1KaUFJLFYyuDYFI-X54IqUBEEfVwABi7EhqNa0MxEBAAF9a0A) **Input:** ```ts const module = await import(`data:text/javascript, console.log("RUN"); `); ``` **Output:** ```jsx const module = await (`data:text/javascript, console.log("RUN"); `); ``` **Expected output:** ```jsx const module = await import(`data:text/javascript, console.log("RUN"); `); ``` **Why?** The `import` keyword is deleted for no discernable reason.
"2024-05-08T07:37:47Z"
3.3
[]
[ "tests/format/js/dynamic-import/format.test.js" ]
JavaScript
[]
[ "https://prettier.io/playground", "https://prettier.io/playground/#N4Igxg9gdgLgprEAuc0DOMAEBbCATAVwBs5MBeTAQwHdKBLLO7ABwgCcYAKAAz0pkpJ4ADxgB6AFaUAbpTRg2dZjAA0AHSiYtmSFDQQSAOiIQA5pzUgASgFUAcpYCUAbg3cXIFSAjK66ZKCUbGwQ1AAKQQhoyCCURLQAntFeAEZslGAA1nAwAMqU2HAAMnRQcMgAZnFocKnpWTm5zBmlpsgwbAS1IDXYdO2d3XDCzHCKhbBxACpjUEF0cNFIVUQ1XmitJACKBBDwldXdEmjCuZtwO3vly4deAI678GEhzEuxaAC0ZXB4P54gHXoRFaAGEINhsJQYnEiP8NlBTCQAIIwDp0FIEJ5jEplA6rboACxg2CIAHUCQxFs0wHBclEGHRpAwEjEwGhkiBpF0AJJQX6wXIKJQwJF83IwBIkPFrEDMEI1UnpZgxOWLMbScpeUo1DjPSimSHS7rNNg6mIS0byRTKf5y0owUl0PAwAnIAAcAAYvGw4A86D69QaoTd8V4BClHc7XUgAExeAg1KaUFJLFYyuDYFI-X54IqUBEEfVwABi7EhqNa0MxEBAAF9a0A" ]
prettier/prettier
16,347
prettier__prettier-16347
[ "16342" ]
b26f56bd316a3ed11c33f50cd4a3dac44a4ee529
diff --git a/src/document/utils.js b/src/document/utils.js --- a/src/document/utils.js +++ b/src/document/utils.js @@ -212,7 +212,6 @@ function stripTrailingHardlineFromParts(parts) { function stripTrailingHardlineFromDoc(doc) { switch (getDocType(doc)) { - case DOC_TYPE_ALIGN: case DOC_TYPE_INDENT: case DOC_TYPE_INDENT_IF_BREAK: case DOC_TYPE_GROUP: @@ -238,6 +237,7 @@ function stripTrailingHardlineFromDoc(doc) { case DOC_TYPE_STRING: return doc.replace(/[\n\r]*$/, ""); + case DOC_TYPE_ALIGN: case DOC_TYPE_CURSOR: case DOC_TYPE_TRIM: case DOC_TYPE_LINE_SUFFIX_BOUNDARY:
diff --git a/tests/format/misc/embedded_language_formatting/in-markdown/__snapshots__/format.test.js.snap b/tests/format/misc/embedded_language_formatting/in-markdown/__snapshots__/format.test.js.snap --- a/tests/format/misc/embedded_language_formatting/in-markdown/__snapshots__/format.test.js.snap +++ b/tests/format/misc/embedded_language_formatting/in-markdown/__snapshots__/format.test.js.snap @@ -106,6 +106,71 @@ Hello world! ================================================================================ `; +exports[`issue-16342.md - {"embeddedLanguageFormatting":"off"} format 1`] = ` +====================================options===================================== +embeddedLanguageFormatting: "off" +parsers: ["markdown"] +printWidth: 80 + | printWidth +=====================================input====================================== +--- +foo: + - bar1 + + - bar2 + + - bar3 +--- + +Markdown + +=====================================output===================================== +--- +foo: + - bar1 + + - bar2 + + - bar3 +--- + +Markdown + +================================================================================ +`; + +exports[`issue-16342.md format 1`] = ` +====================================options===================================== +parsers: ["markdown"] +printWidth: 80 + | printWidth +=====================================input====================================== +--- +foo: + - bar1 + + - bar2 + + - bar3 +--- + +Markdown + +=====================================output===================================== +--- +foo: + - bar1 + + - bar2 + + - bar3 +--- + +Markdown + +================================================================================ +`; + exports[`test.md - {"embeddedLanguageFormatting":"off"} format 1`] = ` ====================================options===================================== embeddedLanguageFormatting: "off" diff --git a/tests/format/misc/embedded_language_formatting/in-markdown/issue-16342.md b/tests/format/misc/embedded_language_formatting/in-markdown/issue-16342.md new file mode 100644 --- /dev/null +++ b/tests/format/misc/embedded_language_formatting/in-markdown/issue-16342.md @@ -0,0 +1,10 @@ +--- +foo: + - bar1 + + - bar2 + + - bar3 +--- + +Markdown
Some empty lines is being removed in markdown YAML frontmatter **Prettier 3.3.0** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBadAdWBLGAbOJAAgCU4BDPIgBQCcIArOMGAZy20imNYAc8IMMAAssEWgBM4tYgEYsYcvADm4gJ5IsRIqiIAROAFsIWLBIhhWmqNt1RyhwkQDqlbFDhbtRKazDEAQSIAZWxDfjgAGhDyADM4IgBhCENHWBC1VnhDADovbQFVYmEYGF4rAHoKgHc3DxyGVhzxZQrCiBzeKGV8ogBXWjxi0vKkKtq8dzgGppaKhAre2jheCGGyyorlXGE+gCMcyEMaurhGk8mPXt5lgDdsOGriCvJWVjg2CrDyZTgLqYavB6UC8dgcTgAXgBrYJqKBgIgAUVo5F6vn8RCCMFofSyBDeRBuggsECoMGESn671YRDAtDUvBgEGUKN4wk4RFubgkuDUhPoEFiNKZ-Ig9ykRD8lHIewIRHIUAkRAE1VQkCyRGxCtY5BY2GgNOgSPJ0jgfUMvXa61GVXMlhy0NYcLAOX1FUdzoA+u1PbLdVCcqxbsDvP1BtbNnamh74a6IIsbN5lqsI2Mtjt9ocUhVDEp4LRUHgZax3VCnfDUNU4HtUNJyKgo9c7g8nkQXm8PiXvr9S+WXQwgaYoKtaDBYqT9VZQUR7I5iIlhAhlCEKd1egMhkQShs0yIl6hWKvlDlHE24PdHqmqnvugejye-iOxxOOuR7rElis1luRpttuTMyOCoAFlsCyaRUAACQgXg-hvZQ7wVBCn3HSYTBBRMwTnJJF26FckPXcMfx3a9cIQw8kIfM8L1bbcbQqeDEO6B8KhQl8cjfbAP0TbRk2-Oi-wzA4gNA8CC2g2CGLIpjkPEZ80KHWVmSnTCZ3BYhgNoHIJLgAByGkACFCjROA-GIZxF2WTVLISMDlWwZQSmiE0rLs4QYM8HjlWZfjfzTQwwPzVB3NgrNjnaQNg0IzcBP8wKIJC6Yjk-FNiPo-9dmE7NRKCnSQPi8SPJyDLM31aiW2eV53k+bs-kMWhEsBYFp1nJxgIgAB2fSiCM5kTLMkIUg+dk8OqaApFoWI+ioOyZQgPoYE1CAt3IXhYKgPIvKtNLNlibACBPTrDjACosiUTg2gAD2ET1tliK6bo62Riq46KrwqJTj2MDrjvmKAE1DPj3pKrLjm+sATt65Rgnm2gwGmf9ysvHa0z2g7vt+nlWChD7Ck9G5zxbT0EE6NcMNsNTsIAcT6CBuuoH5PNDdFiDoRhmEWu1zQQGBzqNBUlSyPoJD5KBBFMy0fOB2nLs4MiciZXg2h80mQ28DdpYgWX4IVmC-pS3ySPTADQYqGmIAADWwBcly2GW5aXF6TbjJHW3baqu1zHtlFpg9UF4Rnaw2rpgXQVAhxASIQBgmB9SgVhkFAchaHoaoGeWePkBAShakySOQD2FEwChD5gnBAAZKZkFiSh3ijwv-VLgOwHcZRkGxPoohAd4AvbnEu7gS7YNoMIecoAAVaR7BH0zq9rrvWFbggAEVafgOe8DrkBGku0JuhXte4A3reAEdD7Z8os9eVAPDgKQJHzrV9tb5JUnIK+8DwfPF-3uAAlKEeewFpwGoNISuHhj5dxKIYPAFlcCmWbnAYICBF6x3uDANQWdLAJyjrcTuABJRUPNgh0mwIyAIipggYIIJAqORJ3jOFZFnAm7xaC3CPlHdwrCYB0B+LmWhIAA60FYVnXMtAoTmGqFAfONx3AwGcNgCQ5JkAAA4AAMUdlhn2wMsXhyh+FIBrpvLuvM9gKKUcIZAAAmKOuI4Dj2LAIowew7733LkhPojMABi4hcylFblfBaEAQAAF8QlAA) <!-- prettier-ignore --> ```sh --parser markdown ``` **Input:** <!-- prettier-ignore --> ```markdown --- title: Real Projects icon: splotch order: 1 category: - Demo docs: - name: Waline desc: A Simple, Safe Comment System. logo: https://waline.js.org/logo.png url: https://waline.js.org/en/ repo: https://github.com/walinejs/waline preview: /assets/image/waline.jpg - name: zkSync Era desc: A trustless protocol that uses cryptographic validity proofs to provide scalable and low-cost transactions on Ethereum logo: https://docs.zksync.io/zksync_logo_black.svg url: https://docs.zksync.io/ repo: https://github.com/matter-labs/zksync-web-era-docs preview: /assets/image/zksync.jpg portfolios: - name: Cheng Shang url: https://cheng-shang.me preview: https://cheng-shang.me/portfolio.avif repo: https://github.com/Mister-Hope/cheng-shang-portfolio - name: Cheng Shang url: https://cheng-shang.me preview: https://cheng-shang.me/portfolio.avif repo: https://github.com/Mister-Hope/cheng-shang-portfolio blogs: - name: Mr.Hope's Blog desc: Where there is light, there is hope logo: https://mister-hope.com/logo.svg url: https://mister-hope.com repo: https://github.com/Mister-Hope/Mister-Hope.github.io preview: /assets/image/mrhope.jpg - name: Mo7's Blog desc: Something wonderful is about to happen. logo: https://file.mo7.cc/static/lxh_gif/lxh_71.gif url: https://blog.mo7.cc/en/ repo: https://github.com/mo7cc/BlogSource.git preview: https://file.mo7.cc/disk/blog_preview_en.png - name: Guo's Page desc: Project documentation and study notes logo: https://guoxicheng.top/logo.png url: https://guoxicheng.top/en repo: https://github.com/GuoXiCheng/guoxicheng.github.io preview: /assets/image/guo-s-page-en.png --- ``` **Output:** <!-- prettier-ignore --> ```markdown --- title: Real Projects icon: splotch order: 1 category: - Demo docs: - name: Waline desc: A Simple, Safe Comment System. logo: https://waline.js.org/logo.png url: https://waline.js.org/en/ repo: https://github.com/walinejs/waline preview: /assets/image/waline.jpg - name: zkSync Era desc: A trustless protocol that uses cryptographic validity proofs to provide scalable and low-cost transactions on Ethereum logo: https://docs.zksync.io/zksync_logo_black.svg url: https://docs.zksync.io/ repo: https://github.com/matter-labs/zksync-web-era-docs preview: /assets/image/zksync.jpg portfolios: - name: Cheng Shang url: https://cheng-shang.me preview: https://cheng-shang.me/portfolio.avif repo: https://github.com/Mister-Hope/cheng-shang-portfolio - name: Cheng Shang url: https://cheng-shang.me preview: https://cheng-shang.me/portfolio.avif repo: https://github.com/Mister-Hope/cheng-shang-portfolio blogs: - name: Mr.Hope's Blog desc: Where there is light, there is hope logo: https://mister-hope.com/logo.svg url: https://mister-hope.com repo: https://github.com/Mister-Hope/Mister-Hope.github.io preview: /assets/image/mrhope.jpg - name: Mo7's Blog desc: Something wonderful is about to happen. logo: https://file.mo7.cc/static/lxh_gif/lxh_71.gif url: https://blog.mo7.cc/en/ repo: https://github.com/mo7cc/BlogSource.git preview: https://file.mo7.cc/disk/blog_preview_en.png - name: Guo's Page desc: Project documentation and study notes logo: https://guoxicheng.top/logo.png url: https://guoxicheng.top/en repo: https://github.com/GuoXiCheng/guoxicheng.github.io preview: /assets/image/guo-s-page-en.png --- ``` **Expected output:** Empty lines in `blogs` not being removed **Why?** ......
Interesting, thanks for reporting! A few shorter examples: ## Line gaps in the last list are removed **Prettier 3.3.0** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBadAdKAzCECMSWABMasQEYCGATvvliWZbfgEyNSnnV0DMnXBDZEuzXmwZQmPWmw7SxsmmwGKhfUdxY0+UmTr4KDvPmvSpOAWVoBrACYQA7lBAAaEBAAOMAJbQAZ2RQWhpnAAVaBCCUKgAbJyoATyCPChoqMFs4GABlKgBbOAAZXyg4ZGx4gLg0jKyc3K9MsoBzZBgaAFdakBqC3w7u3rgADy84Gl8i2HiAFUmoWl84GKq4mo8Atri4AEUuiHhK6t6AKwDR3J39w+Okdc2QAEc7uHCwrxiQKgDUcrg9kB7hAnSovjibQAwhACgUqMgfnE4iDtlBWrsAIIwTq+ChdeDhSalconDa9AAWMAKcQA6hTfPAAs0wHBctFGb4AG6MpKIsABVIgLk9ACSUCBsFyYCmPkxEtyMCSuzJTy8YRqtIyXkR6tWky5FQ8ZRqNBgHyorXhqt6zRopsR8JoDmcrg86rKMFpvnsMApyAAHAAGDw0OCvXxhi1WhEPU4eGBUCje33+pBsDxdGpzJNreMgOAFCiAoH2YpUdFdS1wABiEBo8JxbURVAJEBAAF8O0A) <!-- prettier-ignore --> ```sh --parser markdown ``` **Input:** <!-- prettier-ignore --> ```markdown --- foo1: - bar11 - bar12 - bar13 foo2: - bar21 - bar22 - bar23 foo3: - bar31 - bar32 - bar33 --- Markdown ``` **Output:** <!-- prettier-ignore --> ```markdown --- foo1: - bar11 - bar12 - bar13 foo2: - bar21 - bar22 - bar23 foo3: - bar31 - bar32 - bar33 --- Markdown ``` ### Line gaps in last list are _not_ removed if followed by a comment **Prettier 3.3.0** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBadAdKAzCECMSWABMasQEYCGATvvliWZbfgEyNSnnV0DMnXBDZEuzXmwZQmPWmw7SxsmmwGKhfUdxY0+UmTr4KDvPmqwBiYgGcIAWzjFIdh7E7pUnALK0A1gBMIAHcoEAAaEAgABxgAS2hrZFBaGmCABVoERJQqABsgqgBPRIiKGiowXzgYAGUqBwAZWKg4ZGw86zhS8srqmqiK5oBzZBgaAFcukE67WNGJqbgADyi4GljXGDyAFTWoWli4bPbczojrYdy4AEVxiHg2jqmAK2slmsubu4ekE7OQACO3zgaVSUWyICo1lQLTg-jh4RAYyosVywwAwvY7FRkJDcrlERcoEMrgBBGBjWIUcbwNJrJotR6nKYACxgdlyAHUWbF4NYBmA4DUsrzYgA3XmFXFgawlEBiyYASSg8NgNTA6xipJVNRghSuTP+UVSnU55SiuONRzWYtaEWanRoMFBVCG2MNUwGNEduOxNACwVCEWNzRgnNi-hgLOQAA4AAwRGhwIGxJMut0435PCJbCjhyPRpBsCLjTrbKgUY7ZkBwOwUOHw-wNKjE8auuAAMQgNGxFOGuKoNIgIAAviOgA) <!-- prettier-ignore --> ```sh --parser markdown ``` **Input:** <!-- prettier-ignore --> ```markdown --- foo1: - bar11 - bar12 - bar13 foo2: - bar21 - bar22 - bar23 foo3: - bar31 - bar32 - bar33 # some comment --- Markdown ``` **Output:** <!-- prettier-ignore --> ```markdown --- foo1: - bar11 - bar12 - bar13 foo2: - bar21 - bar22 - bar23 foo3: - bar31 - bar32 - bar33 # some comment --- Markdown ``` ### Line gaps in last list are _not_ removed if followed by another key **Prettier 3.3.0** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBadAdKAzCECMSWABMasQEYCGATvvliWZbfgEyNSnnV0DMnXBDZEuzXmwZQmPWmw7SxsmmwGKhfUdxY0+UmTr4KDvPmqxCALEmKXjUdKk4BZWgGsAJhADuUEABoQCAAHGABLaABnZFBaGh8ABVoEaJQqABtvKgBPaMCKGiowNzgYAGUqAFs4ABkwqDhkbAzIuHzC4tKy4KL6gHNkGBoAVzaQVsqwwZGxuAAPYLgaMOrYDIAVJahaMLhU5vTWwMj+9LgARWGIeCaWsYArSLmy04urm6QDo5AAR3e4BLxYKpEBUSKoBpwDxQgIgIZUMLpfoAYQglUqVGQoPS6VhJygfTOAEEYEMwhRhvAEks6g1bocxgALGCVdIAdUZYXgkR6YDgZRSXLCADcudksWBInkQMLRgBJKDQ2BlMDLUJExVlGDZM7077BeKtNmFYJYg17JbCxqBeqtGgwQFUPoYvVjHo0O1YjE0Tw+PyBA31GBssIeGCM5AADgADIEaHA-mF447nZjPndAjAqBQQ2GI0g2IFhq11tn9hmQHBKhQodCPDUqAThk64AAxCA0DGk-pYqiUiAgAC+g6AA) <!-- prettier-ignore --> ```sh --parser markdown ``` **Input:** <!-- prettier-ignore --> ```markdown --- foo1: - bar11 - bar12 - bar13 foo2: - bar21 - bar22 - bar23 foo3: - bar31 - bar32 - bar33 foo4: 42 --- Markdown ``` **Output:** <!-- prettier-ignore --> ```markdown --- foo1: - bar11 - bar12 - bar13 foo2: - bar21 - bar22 - bar23 foo3: - bar31 - bar32 - bar33 foo4: 42 --- Markdown ``` ### Line gaps in last list are _not_ removed if it has duplicate key **Prettier 3.3.0** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBadAdKAzCECMSWABMasQEYCGATvvliWZbfgEyNSnnV0DMnXBDZEuzXmwZQmPWmw7SxsmmwGKhI4gGItxACYBXAA4AbAJZgq8YgGs4ATxksafKU958F72nzXpUnACytDZ6EADuUCAANCAQRjBm0ADOyKC0NBEACrQIqShUJuFU9qmxFDRUYHYwAMpUALZwADJmUHDI2IXJcOWV1XB1RlVtAObIMDQGvSA9DWYTUzNwAB5GcDRmTbCFACobULRmcPldJj2xyWMmcACKBhDwnd0zAFbJK7XXdw9PSGcXEAAR1+cCymSM+RAVGSqHacD0CJiIEmVDM5igowAwhAGg0qMhoSYTMirpibgBBGCTMwUAzwLIbVrtZ7nGYACxgDRMAHV2WZ4MlhmA4LU8gKzAA3AX2QlgZJlECS6YASSgiNgtTAmwSFPVtRg9hurMBRkyPR5lSMhLNJw2ko6sTaPRoMHBVFG+JNM2GNBdhPxNFCESisTNbRgPLMehg7OQAA4AAyxGhwEFmVPuz0E-4vWIwKgUKMxuNINixAw9XaF055kBwBoUBGIvTNKiYgweuAAMQgNHx1LGhKo9IgIAAvuOgA) <!-- prettier-ignore --> ```sh --parser markdown ``` **Input:** <!-- prettier-ignore --> ```markdown --- foo1: - bar11 - bar12 - bar13 foo2: - bar21 - bar22 - bar23 foo2: ## duplicate key - bar31 - bar32 - bar33 --- Markdown ``` **Output:** <!-- prettier-ignore --> ```markdown --- foo1: - bar11 - bar12 - bar13 foo2: - bar21 - bar22 - bar23 foo2: ## duplicate key - bar31 - bar32 - bar33 --- Markdown ``` ### Line breaks are _not_ removed in plain yaml **Prettier 3.3.0** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEAzCECMSA6UAE+AtPgEYCGATppnnoSRdQEx0HFlWYDMb6EzXO0ZVmtKPQ5NmrCcM6VmvOf25CGC7uMkjK3WTs3KQAGhAQADjACW0AM7JQVShADuABSoIHKcgBtXcgBPBzNSSnIwAGs4GABlcgBbOAAZayg4ZFR-OzgwiOjYuItI9IBzZBhKAFc8kFzE60qaurgADws4Smtk2H8AFS6oKms4H2y-XLM7cr84AEVqiHgsnLqAKzs2uNmFpZWkCamQAEd9uHcXCx8QcjsiDLgAE2fTECryaz9ygGEIRMS5GQtz8fjeMygZTmAEEYFVrKRqvB3F00hlVpM6gALGCJPwAdSx1ngdhKYDgcW8xOsADdiUFgWA7KEQDTagBJKAvWBxMDdKzQrlxGBBOYY44WFy5fERCzAyVjLo0zJmdK5SgwS7kMqA8V1EqUdXAoJJMFmSXpGD46xPGBY5AADgADGZKHAztY3VqdUDDmszDByKRrbb7UhmGZqrl+kHxv6QHBEqRni8nilyJDqtq4AAxCCUQFw8rA8hIiAgAC+FaAA) <!-- prettier-ignore --> ```sh --parser yaml ``` **Input:** <!-- prettier-ignore --> ```yaml foo1: - bar11 - bar12 - bar13 foo2: - bar21 - bar22 - bar23 foo3: - bar31 - bar32 - bar33 ``` **Output:** <!-- prettier-ignore --> ```yaml foo1: - bar11 - bar12 - bar13 foo2: - bar21 - bar22 - bar23 foo3: - bar31 - bar32 - bar33 ``` I flicked between markdown and mdx parser, did not find any difference. Looks like a bug in frontmatter to me. A Note: this only happens in 3.3.0, while the previous versions are good. I think this can help you locating the issue It seems there is bug in [`stripTrailingHardline`](https://github.com/prettier/prettier/blob/b26f56bd316a3ed11c33f50cd4a3dac44a4ee529/src/document/utils.js#L256)
"2024-06-04T07:41:01Z"
3.4
[]
[ "tests/format/misc/embedded_language_formatting/in-markdown/format.test.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEBadAdWBLGAbOJAAgCU4BDPIgBQCcIArOMGAZy20imNYAc8IMMAAssEWgBM4tYgEYsYcvADm4gJ5IsRIqiIAROAFsIWLBIhhWmqNt1RyhwkQDqlbFDhbtRKazDEAQSIAZWxDfjgAGhDyADM4IgBhCENHWBC1VnhDADovbQFVYmEYGF4rAHoKgHc3DxyGVhzxZQrCiBzeKGV8ogBXWjxi0vKkKtq8dzgGppaKhAre2jheCGGyyorlXGE+gCMcyEMaurhGk8mPXt5lgDdsOGriCvJWVjg2CrDyZTgLqYavB6UC8dgcTgAXgBrYJqKBgIgAUVo5F6vn8RCCMFofSyBDeRBuggsECoMGESn671YRDAtDUvBgEGUKN4wk4RFubgkuDUhPoEFiNKZ-Ig9ykRD8lHIewIRHIUAkRAE1VQkCyRGxCtY5BY2GgNOgSPJ0jgfUMvXa61GVXMlhy0NYcLAOX1FUdzoA+u1PbLdVCcqxbsDvP1BtbNnamh74a6IIsbN5lqsI2Mtjt9ocUhVDEp4LRUHgZax3VCnfDUNU4HtUNJyKgo9c7g8nkQXm8PiXvr9S+WXQwgaYoKtaDBYqT9VZQUR7I5iIlhAhlCEKd1egMhkQShs0yIl6hWKvlDlHE24PdHqmqnvugejye-iOxxOOuR7rElis1luRpttuTMyOCoAFlsCyaRUAACQgXg-hvZQ7wVBCn3HSYTBBRMwTnJJF26FckPXcMfx3a9cIQw8kIfM8L1bbcbQqeDEO6B8KhQl8cjfbAP0TbRk2-Oi-wzA4gNA8CC2g2CGLIpjkPEZ80KHWVmSnTCZ3BYhgNoHIJLgAByGkACFCjROA-GIZxF2WTVLISMDlWwZQSmiE0rLs4QYM8HjlWZfjfzTQwwPzVB3NgrNjnaQNg0IzcBP8wKIJC6Yjk-FNiPo-9dmE7NRKCnSQPi8SPJyDLM31aiW2eV53k+bs-kMWhEsBYFp1nJxgIgAB2fSiCM5kTLMkIUg+dk8OqaApFoWI+ioOyZQgPoYE1CAt3IXhYKgPIvKtNLNlibACBPTrDjACosiUTg2gAD2ET1tliK6bo62Riq46KrwqJTj2MDrjvmKAE1DPj3pKrLjm+sATt65Rgnm2gwGmf9ysvHa0z2g7vt+nlWChD7Ck9G5zxbT0EE6NcMNsNTsIAcT6CBuuoH5PNDdFiDoRhmEWu1zQQGBzqNBUlSyPoJD5KBBFMy0fOB2nLs4MiciZXg2h80mQ28DdpYgWX4IVmC-pS3ySPTADQYqGmIAADWwBcly2GW5aXF6TbjJHW3baqu1zHtlFpg9UF4Rnaw2rpgXQVAhxASIQBgmB9SgVhkFAchaHoaoGeWePkBAShakySOQD2FEwChD5gnBAAZKZkFiSh3ijwv-VLgOwHcZRkGxPoohAd4AvbnEu7gS7YNoMIecoAAVaR7BH0zq9rrvWFbggAEVafgOe8DrkBGku0JuhXte4A3reAEdD7Z8os9eVAPDgKQJHzrV9tb5JUnIK+8DwfPF-3uAAlKEeewFpwGoNISuHhj5dxKIYPAFlcCmWbnAYICBF6x3uDANQWdLAJyjrcTuABJRUPNgh0mwIyAIipggYIIJAqORJ3jOFZFnAm7xaC3CPlHdwrCYB0B+LmWhIAA60FYVnXMtAoTmGqFAfONx3AwGcNgCQ5JkAAA4AAMUdlhn2wMsXhyh+FIBrpvLuvM9gKKUcIZAAAmKOuI4Dj2LAIowew7733LkhPojMABi4hcylFblfBaEAQAAF8QlAA" ]
prettier/prettier
16,349
prettier__prettier-16349
[ "16340" ]
ddce4fb95ccfaaf4435ab5c1e052bf04704c9e3c
diff --git a/src/language-js/print/assignment.js b/src/language-js/print/assignment.js --- a/src/language-js/print/assignment.js +++ b/src/language-js/print/assignment.js @@ -138,6 +138,7 @@ function chooseLayout(path, options, print, leftDoc, rightPropertyName) { } if ( + node.type === "ImportAttribute" || (rightNode.type === "CallExpression" && rightNode.callee.name === "require") || // do not put values on a separate line from the key in json
diff --git a/tests/format/js/import-attributes/__snapshots__/format.test.js.snap b/tests/format/js/import-attributes/__snapshots__/format.test.js.snap --- a/tests/format/js/import-attributes/__snapshots__/format.test.js.snap +++ b/tests/format/js/import-attributes/__snapshots__/format.test.js.snap @@ -159,6 +159,97 @@ export * from "./test.json" /* with */ /* with */ assert { type: "json" }; ================================================================================ `; +exports[`long-sources.js [acorn] format 1`] = ` +"Unexpected token (1:37) +> 1 | import a10 from "./aaaaaaaaaa.json" with { + | ^ + 2 | type: "json" }; + 3 | import a20 from "./aaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; + 4 | import a30 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; +Cause: Unexpected token (1:36)" +`; + +exports[`long-sources.js [espree] format 1`] = ` +"Unexpected token with (1:37) +> 1 | import a10 from "./aaaaaaaaaa.json" with { + | ^ + 2 | type: "json" }; + 3 | import a20 from "./aaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; + 4 | import a30 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; +Cause: Unexpected token with" +`; + +exports[`long-sources.js [meriyah] format 1`] = ` +"Unexpected token: 'with' (1:40) +> 1 | import a10 from "./aaaaaaaaaa.json" with { + | ^ + 2 | type: "json" }; + 3 | import a20 from "./aaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; + 4 | import a30 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; +Cause: [1:40]: Unexpected token: 'with'" +`; + +exports[`long-sources.js format 1`] = ` +====================================options===================================== +parsers: ["babel", "typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +import a10 from "./aaaaaaaaaa.json" with { +type: "json" }; +import a20 from "./aaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; +import a30 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; +import a40 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; +import a50 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; +import a60 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; +import a70 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" with { +type: "json" }; +import a80 +from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; + +import("./aaaaaaaaaa.json", {with: { type: "json" }}) +import("./aaaaaaaaaaaaaaaaaaaa.json", {with: { type: "json" }}) +import("./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", {with: { type: "json" }}) +import("./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", {with: { type: "json" }}) +import("./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", {with: { type: "json" }}) +import("./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", {with: { type: "json" }}) +import("./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", {with: { type: "json" }}) +import("./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", {with: { type: "json" }}) + +=====================================output===================================== +import a10 from "./aaaaaaaaaa.json" with { type: "json" }; +import a20 from "./aaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; +import a30 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; +import a40 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; +import a50 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; +import a60 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; +import a70 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; +import a80 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; + +import("./aaaaaaaaaa.json", { with: { type: "json" } }); +import("./aaaaaaaaaaaaaaaaaaaa.json", { with: { type: "json" } }); +import("./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", { with: { type: "json" } }); +import("./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", { + with: { type: "json" }, +}); +import("./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", { + with: { type: "json" }, +}); +import("./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", { + with: { type: "json" }, +}); +import( + "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", + { with: { type: "json" } } +); +import( + "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", + { with: { type: "json" } } +); + +================================================================================ +`; + exports[`multi-types.js [acorn] format 1`] = ` "Unexpected token (1:31) > 1 | import json from "./foo.json" with { type: "json", type: "bar" }; diff --git a/tests/format/js/import-attributes/format.test.js b/tests/format/js/import-attributes/format.test.js --- a/tests/format/js/import-attributes/format.test.js +++ b/tests/format/js/import-attributes/format.test.js @@ -8,6 +8,7 @@ const errors = { "without-from.js", "non-type.js", "keyword-detect.js", + "long-sources.js", ], espree: [ "dynamic-import.js", @@ -18,6 +19,7 @@ const errors = { "without-from.js", "non-type.js", "keyword-detect.js", + "long-sources.js", ], meriyah: [ "dynamic-import.js", @@ -28,6 +30,7 @@ const errors = { "without-from.js", "non-type.js", "keyword-detect.js", + "long-sources.js", ], }; runFormatTest(import.meta, ["babel", "typescript"], { errors }); diff --git a/tests/format/js/import-attributes/long-sources.js b/tests/format/js/import-attributes/long-sources.js new file mode 100644 --- /dev/null +++ b/tests/format/js/import-attributes/long-sources.js @@ -0,0 +1,20 @@ +import a10 from "./aaaaaaaaaa.json" with { +type: "json" }; +import a20 from "./aaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; +import a30 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; +import a40 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; +import a50 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; +import a60 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; +import a70 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" with { +type: "json" }; +import a80 +from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" with { type: "json" }; + +import("./aaaaaaaaaa.json", {with: { type: "json" }}) +import("./aaaaaaaaaaaaaaaaaaaa.json", {with: { type: "json" }}) +import("./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", {with: { type: "json" }}) +import("./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", {with: { type: "json" }}) +import("./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", {with: { type: "json" }}) +import("./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", {with: { type: "json" }}) +import("./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", {with: { type: "json" }}) +import("./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json", {with: { type: "json" }})
Unexpected line break in `assert { type: "json" }` **Prettier 3.3.0** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEB6VACL2e7-gwo4rADgAYMwALAQwCcBnDQZMIMAdKASwFsAHCPRgZaARkoAzehB4cQAOlS1lK1fIBWjaOxAjGjOEIzAMMAJ584SOZu26AvgG5OvAUdoAmSdNk7FqgMCAjS0oHT0DIxNzS2sdWzCHZ25+QWFaAGZvGTl-IPyC4ITw2n1DYWiLKxtQ8KcXVPcAFmzfBSVCzq7AkLsI8uNTKriQYqSGt3SAVlbcju6FxZ6x-qih2Jq++pTJkQA2Wb95pZPT5drdUsiK9er4i4xt1zSRAHZD9rOv78LexNWbjE7qMHk9GukKBgpDkjj84fDOn8SmU1kCRisnCAADQgCB8GBcaCMZCgBjSADuAAUGAhiShaAAbcm0MzEnEAI3otDAAGs4DAAMq0HhwAAyXCgcGQEkZBg5XN5-IFfG5EoA5sgYPQAK5wHEGHhcTU6vUgOAAD0s9F4CBgjIAKoYoAwuHA6TKGXKQIx1Qy4ABFbUQeDS2WmzTmgW+gNBkNID1egCOsbglOkfDpIFKAFpJXAACYF7EgLW0LgM9UAYRkPFoyCzDIZxZ9UDVfoAgjAtVx2dr4JTDOLJaHPabqDAeAyAOrULjwRgqsBwAW0udcABuc7M9bA+mL691AEkoIXYAKwNb8e2TwLzH6R16+NIDFOuXx60+3YZ11KcRLrmmtBqrWD6miqTCGPW7K0OycBNjiT4SjAU5cPmMDUMgFA4vQcDJlwOGAcBdbxmGOJ2uyKFoRhSAeDi2oGPaMHuqRZo8LB+aFvmoq0K22pAXAABigi1l26r1rQfYQCA9j2EAA) <!-- prettier-ignore --> ```sh --parser babel ``` **Input:** <!-- prettier-ignore --> ```ts // 80 chars ↓ import a10 from "./aaaaaaaaaa.json" assert { type: "json" }; import a20 from "./aaaaaaaaaaaaaaaaaaaa.json" assert { type: "json" }; import a30 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" assert { type: "json" }; import a40 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" assert { type: "json" }; import a50 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" assert { type: "json" }; import a60 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" assert { type: "json" }; import a70 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" assert { type: "json" }; import a80 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" assert { type: "json" }; ``` **Output:** <!-- prettier-ignore --> ```ts // 80 chars ↓ import a10 from "./aaaaaaaaaa.json" assert { type: "json" }; import a20 from "./aaaaaaaaaaaaaaaaaaaa.json" assert { type: "json" }; import a30 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" assert { type: "json" }; import a40 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" assert { type: "json" }; import a50 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" assert { type: "json" }; import a60 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" assert { type: "json" }; import a70 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" assert { type: "json" }; import a80 from "./aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json" assert { type: "json" }; ``` **Expected output:** same as input **Why?** Newline after `type:` breaks the rhythm of the import statements. There was no line break in 3.2 and below. The behavior changed in 3.3 via https://github.com/prettier/prettier/pull/15888. Newline is consistently added after `type:` after reaching `--print-width`, even if `assert` does not fit too. @sosukesuzuki I suggest to enforce a single line here. WDYT?
"2024-06-04T08:54:03Z"
3.4
[]
[ "tests/format/js/import-attributes/format.test.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEB6VACL2e7-gwo4rADgAYMwALAQwCcBnDQZMIMAdKASwFsAHCPRgZaARkoAzehB4cQAOlS1lK1fIBWjaOxAjGjOEIzAMMAJ584SOZu26AvgG5OvAUdoAmSdNk7FqgMCAjS0oHT0DIxNzS2sdWzCHZ25+QWFaAGZvGTl-IPyC4ITw2n1DYWiLKxtQ8KcXVPcAFmzfBSVCzq7AkLsI8uNTKriQYqSGt3SAVlbcju6FxZ6x-qih2Jq++pTJkQA2Wb95pZPT5drdUsiK9er4i4xt1zSRAHZD9rOv78LexNWbjE7qMHk9GukKBgpDkjj84fDOn8SmU1kCRisnCAADQgCB8GBcaCMZCgBjSADuAAUGAhiShaAAbcm0MzEnEAI3otDAAGs4DAAMq0HhwAAyXCgcGQEkZBg5XN5-IFfG5EoA5sgYPQAK5wHEGHhcTU6vUgOAAD0s9F4CBgjIAKoYoAwuHA6TKGXKQIx1Qy4ABFbUQeDS2WmzTmgW+gNBkNID1egCOsbglOkfDpIFKAFpJXAACYF7EgLW0LgM9UAYRkPFoyCzDIZxZ9UDVfoAgjAtVx2dr4JTDOLJaHPabqDAeAyAOrULjwRgqsBwAW0udcABuc7M9bA+mL691AEkoIXYAKwNb8e2TwLzH6R16+NIDFOuXx60+3YZ11KcRLrmmtBqrWD6miqTCGPW7K0OycBNjiT4SjAU5cPmMDUMgFA4vQcDJlwOGAcBdbxmGOJ2uyKFoRhSAeDi2oGPaMHuqRZo8LB+aFvmoq0K22pAXAABigi1l26r1rQfYQCA9j2EAA" ]
prettier/prettier
16,358
prettier__prettier-16358
[ "16356" ]
13163d9b7543021d1f24edadbc0e5a2b1598d478
diff --git a/src/language-handlebars/clean.js b/src/language-handlebars/clean.js --- a/src/language-handlebars/clean.js +++ b/src/language-handlebars/clean.js @@ -32,6 +32,10 @@ function clean(original, cloned /*, parent*/) { if (original.type === "AttrNode" && original.name.toLowerCase() === "class") { delete cloned.value; } + + if (original.type === "PathExpression") { + cloned.head = original.head.original; + } } clean.ignoredProperties = new Set(["loc", "selfClosing"]); diff --git a/src/language-handlebars/printer-glimmer.js b/src/language-handlebars/printer-glimmer.js --- a/src/language-handlebars/printer-glimmer.js +++ b/src/language-handlebars/printer-glimmer.js @@ -366,10 +366,7 @@ function print(path, options, print) { ]; } case "PathExpression": - return printPathExpression(node, print); - - case "AtHead": - return node.name; + return printPathExpression(node); case "BooleanLiteral": return String(node.value); @@ -389,6 +386,7 @@ function print(path, options, print) { case "NullLiteral": return "null"; + case "AtHead": // Handled in `printPathExpression` case "VarHead": // Handled in `printPathExpression` case "ThisHead": // Handled in `printPathExpression` default: @@ -784,21 +782,23 @@ const PATH_EXPRESSION_FORBIDDEN_IN_FIRST_PART = new Set([ "null", "undefined", ]); -const isPathExpressionPartNeedBrackets = (part, index) => - (index !== 0 && PATH_EXPRESSION_FORBIDDEN_IN_FIRST_PART.has(part)) || - /\s/.test(part) || - /^\d/.test(part) || - Array.prototype.some.call(part, (character) => - PATH_EXPRESSION_FORBIDDEN_CHARACTERS.has(character), - ); -function printPathExpression(node, print) { - if (node.head.type === "AtHead") { - return print("head"); +const isPathExpressionPartNeedBrackets = (part, index) => { + if (index === 0 && part.startsWith("@")) { + return false; } + return ( + (index !== 0 && PATH_EXPRESSION_FORBIDDEN_IN_FIRST_PART.has(part)) || + /\s/.test(part) || + /^\d/.test(part) || + Array.prototype.some.call(part, (character) => + PATH_EXPRESSION_FORBIDDEN_CHARACTERS.has(character), + ) + ); +}; +function printPathExpression(node) { + // check if node is a legacy path expression and leave it alone if (node.tail.length === 0 && node.original.includes("/")) { - // check if node has data, or - // check if node is a legacy path expression (and leave it alone) return node.original; } diff --git a/src/language-handlebars/visitor-keys.evaluate.js b/src/language-handlebars/visitor-keys.evaluate.js --- a/src/language-handlebars/visitor-keys.evaluate.js +++ b/src/language-handlebars/visitor-keys.evaluate.js @@ -1,11 +1 @@ -import { visitorKeys as glimmerVisitorKeys } from "@glimmer/syntax"; - -const visitorKeys = { - VarHead: [], - ThisHead: [], - AtHead: [], - ...glimmerVisitorKeys, - PathExpression: [...glimmerVisitorKeys.PathExpression, "head"], -}; - -export default visitorKeys; +export { visitorKeys as default } from "@glimmer/syntax";
diff --git a/tests/format/handlebars/path-expressions/__snapshots__/format.test.js.snap b/tests/format/handlebars/path-expressions/__snapshots__/format.test.js.snap --- a/tests/format/handlebars/path-expressions/__snapshots__/format.test.js.snap +++ b/tests/format/handlebars/path-expressions/__snapshots__/format.test.js.snap @@ -42,6 +42,10 @@ printWidth: 80 {{array.2.[@#].[1]}} {{array.2.[a b]}} {{this.test}} + {{@x.y.z}} + {{@array.[true]}} + {{@array.2.[@#].[1]}} + {{@array.2.[a b]}} {{#if @foo}} {{/if}} <!-- legacy path format, which glimmer does not parse - we don't want to wrap with brackets --> @@ -54,6 +58,10 @@ printWidth: 80 {{array.[2].[@#].[1]}} {{array.[2].[a b]}} {{this.test}} + {{@x.y.z}} + {{@array.[true]}} + {{@array.[2].[@#].[1]}} + {{@array.[2].[a b]}} {{#if @foo}}{{/if}} <!-- legacy path format, which glimmer does not parse - we don't want to wrap with brackets --> {{foo/bar/baz ab=cd}} diff --git a/tests/format/handlebars/path-expressions/literal-expressions.hbs b/tests/format/handlebars/path-expressions/literal-expressions.hbs --- a/tests/format/handlebars/path-expressions/literal-expressions.hbs +++ b/tests/format/handlebars/path-expressions/literal-expressions.hbs @@ -3,6 +3,10 @@ {{array.2.[@#].[1]}} {{array.2.[a b]}} {{this.test}} + {{@x.y.z}} + {{@array.[true]}} + {{@array.2.[@#].[1]}} + {{@array.2.[a b]}} {{#if @foo}} {{/if}} <!-- legacy path format, which glimmer does not parse - we don't want to wrap with brackets --> diff --git a/tests/unit/__snapshots__/visitor-keys.js.snap b/tests/unit/__snapshots__/visitor-keys.js.snap --- a/tests/unit/__snapshots__/visitor-keys.js.snap +++ b/tests/unit/__snapshots__/visitor-keys.js.snap @@ -1165,7 +1165,6 @@ exports[`visitor keys estree-json 1`] = ` exports[`visitor keys glimmer 1`] = ` { - "AtHead": [], "AttrNode": [ "value", ], @@ -1209,9 +1208,7 @@ exports[`visitor keys glimmer 1`] = ` ], "NullLiteral": [], "NumberLiteral": [], - "PathExpression": [ - "head", - ], + "PathExpression": [], "StringLiteral": [], "SubExpression": [ "path", @@ -1222,9 +1219,7 @@ exports[`visitor keys glimmer 1`] = ` "body", ], "TextNode": [], - "ThisHead": [], "UndefinedLiteral": [], - "VarHead": [], } `;
handlebars attrbutes changed: {{@x.y.z}} becomes {{@x}} **Prettier 3.3.1** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuEACVAeAJgSwG7qFgA2AhgM7kC8AOiAjAE4CedhqAfDVOhgBYBGDsGDoYOGMTjsAvjIwB6QVx6ZcBdCQrU6AIwhZWIFexEABAB4A6ZlYBec7u2eERhfYZeFHUReo6YCv4gADQgEAAO4tDkyKCkjIwQAO4ACgkIsSikxMmkzLFhuoykYADWcDAAyqQAtnAAMjhQcMgAZjnkcEUl5ZVVEaXNAObITACu3SBdtThjjJNhcBYRcIw49bA5ACprUAk4cFkdxF1h5CNSAIrjEPDtnVMAVuQWVZdwN3etSCdnIABHW7wVJJCJZEAUAC0LTgWDhoRATFIOGIIwAwhBarVSMhIcRiIiLlBhlIAIIwJg4XTjEFrJotB6nKZ8GC1YgAdT4EiOgzAcCqmQk+AkzDxYEoiLwkwAklB4bAqmB1lEyfKqjBmFImf8IkkuhyShE8Xqjms8K0ws0uowYKDSMMcTqpoNGDa8aSNvVGIi9c0YBycFgYHxkAAOAAMYUYcCBOBj9sduN+jzCMFIukDwdDSAATGFxl1thnjqn6LVdHD4VgGqQSeMHXAAGIQRg4ykjPGkWkQEByIA) <!-- prettier-ignore --> ```sh --parser glimmer ``` **Input:** <!-- prettier-ignore --> ```hbs <div class="entry" > <h1>{{ title }}</h1> <div class="body"> {{@x.y.z}} {{ body }} </div> </div> ``` **Output:** <!-- prettier-ignore --> ```hbs <div class="entry"> <h1>{{title}}</h1> <div class="body"> {{@x}} {{body}} </div> </div> ``` **Expected behavior:** Starting with 3.3.1 {{@x.y.z}} is output as {{@x}} , if I add `--debug-check` it will catch that the output is different
Sorry for breaking your code, it's caused by #16346, print `node.tail` [here](https://github.com/prettier/prettier/blob/13163d9b7543021d1f24edadbc0e5a2b1598d478/src/language-handlebars/printer-glimmer.js#L796) should be able to fix it. Do you want work on it?
"2024-06-06T06:35:03Z"
3.4
[]
[ "tests/unit/visitor-keys.js", "tests/format/handlebars/path-expressions/format.test.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuEACVAeAJgSwG7qFgA2AhgM7kC8AOiAjAE4CedhqAfDVOhgBYBGDsGDoYOGMTjsAvjIwB6QVx6ZcBdCQrU6AIwhZWIFexEABAB4A6ZlYBec7u2eERhfYZeFHUReo6YCv4gADQgEAAO4tDkyKCkjIwQAO4ACgkIsSikxMmkzLFhuoykYADWcDAAyqQAtnAAMjhQcMgAZjnkcEUl5ZVVEaXNAObITACu3SBdtThjjJNhcBYRcIw49bA5ACprUAk4cFkdxF1h5CNSAIrjEPDtnVMAVuQWVZdwN3etSCdnIABHW7wVJJCJZEAUAC0LTgWDhoRATFIOGIIwAwhBarVSMhIcRiIiLlBhlIAIIwJg4XTjEFrJotB6nKZ8GC1YgAdT4EiOgzAcCqmQk+AkzDxYEoiLwkwAklB4bAqmB1lEyfKqjBmFImf8IkkuhyShE8Xqjms8K0ws0uowYKDSMMcTqpoNGDa8aSNvVGIi9c0YBycFgYHxkAAOAAMYUYcCBOBj9sduN+jzCMFIukDwdDSAATGFxl1thnjqn6LVdHD4VgGqQSeMHXAAGIQRg4ykjPGkWkQEByIA" ]
prettier/prettier
16,391
prettier__prettier-16391
[ "4873" ]
d6daeec0a382ffb9471075f839d12568a4e57100
diff --git a/src/language-js/needs-parens.js b/src/language-js/needs-parens.js --- a/src/language-js/needs-parens.js +++ b/src/language-js/needs-parens.js @@ -11,6 +11,7 @@ import { isBitwiseOperator, isCallExpression, isMemberExpression, + isNullishCoalescing, isObjectOrRecordExpression, isObjectProperty, shouldFlatten, @@ -366,7 +367,7 @@ function needsParens(path, options) { return !isBinaryCastExpression(node); case "ConditionalExpression": - return isBinaryCastExpression(node); + return isBinaryCastExpression(node) || isNullishCoalescing(node); case "CallExpression": case "NewExpression": diff --git a/src/language-js/utils/index.js b/src/language-js/utils/index.js --- a/src/language-js/utils/index.js +++ b/src/language-js/utils/index.js @@ -140,6 +140,14 @@ const isObjectOrRecordExpression = createTypeCheckFunction([ "RecordExpression", ]); +/** + * @param {Node} node + * @returns {boolean} + */ +function isNullishCoalescing(node) { + return node.type === "LogicalExpression" && node.operator === "??"; +} + /** * @param {Node} node * @returns {boolean} @@ -1143,6 +1151,7 @@ export { isMemberish, isMethod, isNextLineEmpty, + isNullishCoalescing, isNumericLiteral, isObjectOrRecordExpression, isObjectProperty,
diff --git a/tests/format/js/nullish-coalescing/__snapshots__/format.test.js.snap b/tests/format/js/nullish-coalescing/__snapshots__/format.test.js.snap --- a/tests/format/js/nullish-coalescing/__snapshots__/format.test.js.snap +++ b/tests/format/js/nullish-coalescing/__snapshots__/format.test.js.snap @@ -29,12 +29,16 @@ foo || (baz ?? baz); (foo && baz) ?? baz; foo && (baz ?? baz); +foo ?? bar ? a : b; +a ? foo ?? bar : b; +a ? b : foo ?? bar; + =====================================output===================================== obj.foo ?? "default"; const x = (foo, bar = foo ?? bar) => {}; -foo ? bar ?? foo : baz; +foo ? (bar ?? foo) : baz; foo ?? bar ?? baz; foo ?? bar ?? baz; @@ -53,5 +57,9 @@ foo || (baz ?? baz); (foo && baz) ?? baz; foo && (baz ?? baz); +(foo ?? bar) ? a : b; +a ? (foo ?? bar) : b; +a ? b : (foo ?? bar); + ================================================================================ `; diff --git a/tests/format/js/nullish-coalescing/nullish_coalesing_operator.js b/tests/format/js/nullish-coalescing/nullish_coalesing_operator.js --- a/tests/format/js/nullish-coalescing/nullish_coalesing_operator.js +++ b/tests/format/js/nullish-coalescing/nullish_coalesing_operator.js @@ -20,3 +20,7 @@ foo || (baz ?? baz); (foo && baz) ?? baz; foo && (baz ?? baz); + +foo ?? bar ? a : b; +a ? foo ?? bar : b; +a ? b : foo ?? bar;
Parentheses around nullish coalescing operator within conditional expression **Prettier 1.13.5** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuc0DOMAEA3AhgGwFc5MBeTSKAEwEsYbpMB+TACikP31wCN84AagWLMWAMwL4euMAGshROAEpMSTFGgA5Ttz6DhcANwgANCAgAHeumShcAJ3sQA7gAUHCNMhC5sEGlSmIDz2MrJwMADKFjI0UADmyDD2xGZxaHD2MK6h8QC2uMgS+BlmAFZoAB4AQqFyEZG4eXAAMnFwRQSlIDH2Gfbe0jwAnvjQQRb2cTAA6gEwABbIABwADGaTEBkzoRbek3D92B1m9nAAjoQ0Zzm4+YVIxd0ZeTRJKXBmaHHx-ACKhAg8E6JU+IBgvDmVEWyAATGZkrgaPgfgBhCB5AreDRQE4gQgZAAqvC8jy6cAAvhSgA) ```sh --parser babylon ``` **Input:** ```jsx const value = condition ? (nullableValue ?? fallbackValue) : nonNullableValue; ``` **Output:** ```jsx const value = condition ? nullableValue ?? fallbackValue : nonNullableValue; ``` **Expected behavior:** I think it would be better if Prettier preserved the parentheses around the arguments of the nullish coalescing operator if nested within a conditional expression: ```jsx const value = condition ? (nullableValue ?? fallbackValue) : nonNullableValue; ``` My concern is that the precedence of `??` isn't immediately obvious, and I think that parentheses would improve readability here.
We don't do this for other operators, like `||`. I'm not sure it makes sense to do this for `??`. I've considered this argument as well, but I come to a different conclusion: I do think it's valuable to make the precedence clearer by adding explicit parentheses here — clarity trumps brevity. IMO this case is a little different because the operator contains a `?`, which could be confused with a nested ternary, which parens would clarify. However, we also add parens for actual ternaries, so my point may be moot: **Prettier 1.13.7** [Playground link](https://prettier.io/playground/#N4Igxg9gdgLgprEAuc0DOMAEA3AhgGwFc5MBeTSKAEwEsYbpMB+TKZ1zJTAMwPwCNcYANYA1AsU6toAOUL58ufvjjiicANwgANCAgAHeumShcAJzMQA7gAVzCNMhC5sEGlR0h+ZocLgwAZX0hGigAc2QYM2JdULQ4MxgbHzCAW1xkXnx43QArNAAPACEfEX8A3FS4ABlQuEyCHJBgs3izJ0F+AE98aE99M1CYAHV3GAALZAAOAAZdAYh44Z99JwG4Nux63TM4AEdCGl3k3DSMpCym+NSaSOi4XTRQsJUARUIIeAbsh5AYJVGVAmyAATLoorgaPhngBhCCpdJOKDQbYgQjxAAqSkcF0acAAvvigA) ```sh --parser babylon ``` **Input:** ```jsx const value = condition ? n ? n : fallbackValue : nonNullableValue; ``` **Output:** ```jsx const value = condition ? (n ? n : fallbackValue) : nonNullableValue; ``` @vjeux @cpojer I know facebook started using the nullish coalescing operator recently, do you have any insight into people's reactions with reading it? It’s likely a very niche use case, so whichever decision we make isn’t going to impact a lot of code. I’m not against adding parenthesis there personally. To expand on my comment. This is only an issue if the entire line fits in 80 column. Otherwise it would break at the beginning of the `?` and the indentation would make it obvious what precedence is. It’s unlikely that you have an assignment, condition, fallback and else value that all fits. I can see there's some visual effort needed to separate the alternatives of a ternary but I don't think the specific operator makes much difference: ```js const value = condition ? nullableValue ?? fallbackValue : nonNullableValue; ``` ```js const value = condition ? nullableValue || fallbackValue : nonNullableValue; ``` ```js const value = condition ? nullableValue % fallbackValue : nonNullableValue; ``` IMO the debate should be wether or not to use parenthesis in binary expressions inside ternaries rather than making an exception for this one. This change was [already done for some mathematical expressions](https://prettier.io/blog/2018/05/27/1.13.0.html#insert-more-parentheses-in-math-expressions-4413-and-4407-by-duailibe), so it might make sense to revisit this case too. I agree, it's not so much about the specific operator. IMO it would be a good idea to add/preserve parentheses around binary expressions within conditional expressions. 👍 I'm fine adding them as long as we're consistent across binary expressions I helped debug some code today where the dev had written something like this: ``` const value = valueOrNull ?? condition ? value1 : value2; ``` javascript sees this as ``` const value = (valueOrNull ?? condition) ? value1 : value2; ``` but the dev thought it would mean this: ``` const value = valueOrNull ?? (condition ? value1 : value2); ``` If prettier would insert the paranthesis there, then the dev could have seen his error earlier. (with format on save) A somewhat similar problem came up ```typescript if (maybeValue ?? defaultValue > 2) ``` this was assumed to work like ```typescript if ((maybeValue ?? defaultValue) > 2) ``` but it actually works like ```typescript if (maybeValue ?? (defaultValue > 2)) ``` My suggestion for code style here would be to always use parens with nullish coalescing since there is no consistent instinct around how tightly it binds, but prettier will remove the parens in the latter case when that behavior is desired I can't tell if this issue is supported or not. I've been burned many times by the precedence problem, and would _love_ if prettier added explicit parentheses to help indicate the problem for me. I also hit this recently, with a `??` operator in the second branch of a ternary. Would love to see Prettier add parens here! **Input:** ``` const alwaysConfusing = someCondition ? val1 : val2 ?? val3; const goodBeforePrettier = someCondition ? val1 : (val2 ?? val3); const alwaysFine = (someCondition ? val1 : val2) ?? val3; ``` **Output:** ``` const alwaysConfusing = someCondition ? val1 : val2 ?? val3 const goodBeforePrettier = someCondition ? val1 : val2 ?? val3 const alwaysFine = (someCondition ? val1 : val2) ?? val3 ``` This issue is nearly 5 years old, but still relevant, and it's actually a bug… Let me know if I should open a separate issue. Parentheses around nullish coalescing operators aren't merely cosmetic or for readability alone. In this example, the parentheses help TypeScript with narrowing the type of the variable that's being assigned: ```ts export function myFunc( config: { throughDate?: string } & ( | { baseDate: string; trackedStartDate?: never } | { baseDate?: never; trackedStartDate: string } | { baseDate: string; trackedStartDate: string } ), ) { const { baseDate, throughDate, trackedStartDate } = config const wrong = throughDate ?? baseDate ?? trackedStartDate // --> string | undefined const right = throughDate ?? (baseDate ?? trackedStartDate) // --> string } ``` [Try it on TS Playground](https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBAMwK4DsDGMCWEVwLYCeAYqmgBQCwAUHHGjgpgOYBccA3tbbTABZQQkTXgBEAhjGAB+NgGcYUTCiZc4AXzgAyOJRrcAPhzgAjMbODjJchUqYBuOArFoA1sAAmAZRhjYl6WwowABuwFDqqrSG7CZmFhIBcEGhUA5Orh7evjD+1orKEXpRRqbmuXDy+faOUM5uXj5+CXm2hbQAlAA01O0cqvQo8iVx-p2O-ILCozV1mY05CepwALx0DMzU-ThDAO4CBat8AkKii1JSsWVnF+n1WU2ScAD0T3AAtG8AfBU2BYao7mAjCC7i2g3gimE8EOExO-jg5x0pXij0Rtzm2X8vRe7y+Pyq1DUmyoQA) But, prettier is removing the parentheses, which then breaks the code. I'd say parentheses should be left alone unless they're extraneous, like unnecessary double parentheses: This is ok: ```diff - const right = throughDate ?? ((baseDate ?? trackedStartDate)) + const right = throughDate ?? (baseDate ?? trackedStartDate) ``` This is NOT ok: ```diff - const right = throughDate ?? (baseDate ?? trackedStartDate) + const right = throughDate ?? baseDate ?? trackedStartDate ``` That feels like a TypeScript bug, @Merott — I confirmed that Prettier does seem to intentionally change the AST here (as it does with every other logical expression, including `&&` and `||`). If you swap the types in your function from `string` (which can be falsy) to `"a"` (which will always be truthy), and then swap the operator from `??` to `||`, [you’ll find that both `wrong` and `right` are typed as `"a"`](https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBAMwK4DsDGMCWEVwLYCeAYqmgBQCwAUHHGjgpgOYBccA3tbbTABZQQkTXgBEAhjGAB+NgCIxsrnAC+cAGRxKNbgB8OcAEZiAzsHGS5CgNxwYUMWgDWwACYBlGGNjnpbFMAA3YCgVJVo9dkMTMwlfOH8gqBs7B2d3T29Yy1lQ7XD9I1MfbOT7J1cPLxhiuHkc5SUASgAaakaOJXoUY3hIwpjJZtt+QWEfIZTy9KqfFTgAXjoGZmpOnB64AHcBFCYF4YEhUVi4HT1+2bPbMrTKzMk4AHpHuABaV4A+OB6oTF217rwX7CeCLPiHMYnK5kC5QvSTW4ZaqxdrPN6fb52P5MagNKjUIA). Additionally, I tried out all the possible valid parameters to that function that I could think of and neither `wrong` nor `right` ever returned `undefined` with your original code, so I’m fairly confident this is a deficiency in the type checker. Logically, there’s no behavior difference between `(a ?? b) ?? c` (which is what you get if you don’t use parens) and `a ?? (b ?? c)`.
"2024-06-12T17:55:55Z"
3.4
[]
[ "tests/format/js/nullish-coalescing/format.test.js" ]
JavaScript
[]
[ "https://prettier.io/playground/#N4Igxg9gdgLgprEAuc0DOMAEA3AhgGwFc5MBeTSKAEwEsYbpMB+TACikP31wCN84AagWLMWAMwL4euMAGshROAEpMSTFGgA5Ttz6DhcANwgANCAgAHeumShcAJ3sQA7gAUHCNMhC5sEGlSmIDz2MrJwMADKFjI0UADmyDD2xGZxaHD2MK6h8QC2uMgS+BlmAFZoAB4AQqFyEZG4eXAAMnFwRQSlIDH2Gfbe0jwAnvjQQRb2cTAA6gEwABbIABwADGaTEBkzoRbek3D92B1m9nAAjoQ0Zzm4+YVIxd0ZeTRJKXBmaHHx-ACKhAg8E6JU+IBgvDmVEWyAATGZkrgaPgfgBhCB5AreDRQE4gQgZAAqvC8jy6cAAvhSgA" ]
prettier/prettier
6,644
prettier__prettier-6644
[ "5501" ]
433d3303c169e8a2927580b3df7b1f443bb7f4a5
diff --git a/src/common/common-options.js b/src/common/common-options.js --- a/src/common/common-options.js +++ b/src/common/common-options.js @@ -54,4 +54,11 @@ module.exports = { description: "Put > of opening tags on the last line instead of on a new line.", }, + singleAttributePerLine: { + since: "2.3.3", + category: CATEGORY_COMMON, + type: "boolean", + default: false, + description: "Enforce single attribute per line in HTML, Vue and JSX.", + }, }; diff --git a/src/language-html/options.js b/src/language-html/options.js --- a/src/language-html/options.js +++ b/src/language-html/options.js @@ -28,6 +28,7 @@ module.exports = { }, ], }, + singleAttributePerLine: commonOptions.singleAttributePerLine, vueIndentScriptAndStyle: { since: "1.19.0", category: CATEGORY_HTML, diff --git a/src/language-html/print/tag.js b/src/language-html/print/tag.js --- a/src/language-html/print/tag.js +++ b/src/language-html/print/tag.js @@ -7,7 +7,7 @@ const assert = require("assert"); const { isNonEmptyArray } = require("../../common/util.js"); const { - builders: { indent, join, line, softline }, + builders: { indent, join, line, softline, hardline }, utils: { replaceTextEndOfLine }, } = require("../../document/index.js"); const { locStart, locEnd } = require("../loc.js"); @@ -251,11 +251,14 @@ function printAttributes(path, options, print) { node.attrs[0].fullName === "src" && node.children.length === 0; + const attributeLine = + options.singleAttributePerLine && node.attrs.length > 1 ? hardline : line; + /** @type {Doc[]} */ const parts = [ indent([ forceNotToBreakAttrContent ? " " : line, - join(line, printedAttributes), + join(attributeLine, printedAttributes), ]), ]; diff --git a/src/language-js/options.js b/src/language-js/options.js --- a/src/language-js/options.js +++ b/src/language-js/options.js @@ -98,4 +98,5 @@ module.exports = { }, ], }, + singleAttributePerLine: commonOptions.singleAttributePerLine, }; diff --git a/src/language-js/print/jsx.js b/src/language-js/print/jsx.js --- a/src/language-js/print/jsx.js +++ b/src/language-js/print/jsx.js @@ -605,12 +605,17 @@ function printJsxOpeningElement(path, options, print) { attr.value.value.includes("\n") ); + const attributeLine = + options.singleAttributePerLine && node.attributes.length > 1 + ? hardline + : line; + return group( [ "<", print("name"), print("typeParameters"), - indent(path.map(() => [line, print()], "attributes")), + indent(path.map(() => [attributeLine, print()], "attributes")), node.selfClosing ? line : bracketSameLine ? ">" : softline, node.selfClosing ? "/>" : bracketSameLine ? "" : ">", ],
diff --git a/tests/format/html/single-attribute-per-line/__snapshots__/jsfmt.spec.js.snap b/tests/format/html/single-attribute-per-line/__snapshots__/jsfmt.spec.js.snap new file mode 100644 --- /dev/null +++ b/tests/format/html/single-attribute-per-line/__snapshots__/jsfmt.spec.js.snap @@ -0,0 +1,135 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`single-attribute-per-line.html - {"singleAttributePerLine":true} format 1`] = ` +====================================options===================================== +parsers: ["html"] +printWidth: 80 +singleAttributePerLine: true + | printWidth +=====================================input====================================== +<div data-a="1"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. +</div> + +<div data-a="1" data-b="2" data-c="3"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. +</div> + +<div data-a="Lorem ipsum dolor sit amet" data-b="Lorem ipsum dolor sit amet" data-c="Lorem ipsum dolor sit amet"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. +</div> + +<div data-long-attribute-a="1" data-long-attribute-b="2" data-long-attribute-c="3"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. +</div> + +<img src="/images/foo.png" /> + +<img src="/images/foo.png" alt="bar" /> + +<img src="/images/foo.png" alt="Lorem ipsum dolor sit amet, consectetur adipiscing elit." /> + +=====================================output===================================== +<div data-a="1">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div> + +<div + data-a="1" + data-b="2" + data-c="3" +> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. +</div> + +<div + data-a="Lorem ipsum dolor sit amet" + data-b="Lorem ipsum dolor sit amet" + data-c="Lorem ipsum dolor sit amet" +> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. +</div> + +<div + data-long-attribute-a="1" + data-long-attribute-b="2" + data-long-attribute-c="3" +> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. +</div> + +<img src="/images/foo.png" /> + +<img + src="/images/foo.png" + alt="bar" +/> + +<img + src="/images/foo.png" + alt="Lorem ipsum dolor sit amet, consectetur adipiscing elit." +/> + +================================================================================ +`; + +exports[`single-attribute-per-line.html format 1`] = ` +====================================options===================================== +parsers: ["html"] +printWidth: 80 + | printWidth +=====================================input====================================== +<div data-a="1"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. +</div> + +<div data-a="1" data-b="2" data-c="3"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. +</div> + +<div data-a="Lorem ipsum dolor sit amet" data-b="Lorem ipsum dolor sit amet" data-c="Lorem ipsum dolor sit amet"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. +</div> + +<div data-long-attribute-a="1" data-long-attribute-b="2" data-long-attribute-c="3"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. +</div> + +<img src="/images/foo.png" /> + +<img src="/images/foo.png" alt="bar" /> + +<img src="/images/foo.png" alt="Lorem ipsum dolor sit amet, consectetur adipiscing elit." /> + +=====================================output===================================== +<div data-a="1">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div> + +<div data-a="1" data-b="2" data-c="3"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. +</div> + +<div + data-a="Lorem ipsum dolor sit amet" + data-b="Lorem ipsum dolor sit amet" + data-c="Lorem ipsum dolor sit amet" +> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. +</div> + +<div + data-long-attribute-a="1" + data-long-attribute-b="2" + data-long-attribute-c="3" +> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. +</div> + +<img src="/images/foo.png" /> + +<img src="/images/foo.png" alt="bar" /> + +<img + src="/images/foo.png" + alt="Lorem ipsum dolor sit amet, consectetur adipiscing elit." +/> + +================================================================================ +`; diff --git a/tests/format/html/single-attribute-per-line/jsfmt.spec.js b/tests/format/html/single-attribute-per-line/jsfmt.spec.js new file mode 100644 --- /dev/null +++ b/tests/format/html/single-attribute-per-line/jsfmt.spec.js @@ -0,0 +1,2 @@ +run_spec(__dirname, ["html"]); +run_spec(__dirname, ["html"], { singleAttributePerLine: true }); diff --git a/tests/format/html/single-attribute-per-line/single-attribute-per-line.html b/tests/format/html/single-attribute-per-line/single-attribute-per-line.html new file mode 100644 --- /dev/null +++ b/tests/format/html/single-attribute-per-line/single-attribute-per-line.html @@ -0,0 +1,21 @@ +<div data-a="1"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. +</div> + +<div data-a="1" data-b="2" data-c="3"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. +</div> + +<div data-a="Lorem ipsum dolor sit amet" data-b="Lorem ipsum dolor sit amet" data-c="Lorem ipsum dolor sit amet"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. +</div> + +<div data-long-attribute-a="1" data-long-attribute-b="2" data-long-attribute-c="3"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. +</div> + +<img src="/images/foo.png" /> + +<img src="/images/foo.png" alt="bar" /> + +<img src="/images/foo.png" alt="Lorem ipsum dolor sit amet, consectetur adipiscing elit." /> diff --git a/tests/format/jsx/single-attribute-per-line/__snapshots__/jsfmt.spec.js.snap b/tests/format/jsx/single-attribute-per-line/__snapshots__/jsfmt.spec.js.snap new file mode 100644 --- /dev/null +++ b/tests/format/jsx/single-attribute-per-line/__snapshots__/jsfmt.spec.js.snap @@ -0,0 +1,163 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`single-attribute-per-line.js - {"singleAttributePerLine":true} format 1`] = ` +====================================options===================================== +parsers: ["flow", "babel", "typescript"] +printWidth: 80 +singleAttributePerLine: true + | printWidth +=====================================input====================================== +import React from "react"; + +const Component = () => ( + <div> + <div data-a="1"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div data-a="1" data-b="2" data-c="3"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div data-a="Lorem ipsum dolor sit amet" data-b="Lorem ipsum dolor sit amet" data-c="Lorem ipsum dolor sit amet"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div data-long-attribute-a="1" data-long-attribute-b="2" data-long-attribute-c="3"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <img src="/images/foo.png" /> + + <img src="/images/foo.png" alt="bar" /> + + <img src="/images/foo.png" alt="Lorem ipsum dolor sit amet, consectetur adipiscing elit." /> + </div> +); + +=====================================output===================================== +import React from "react"; + +const Component = () => ( + <div> + <div data-a="1"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div + data-a="1" + data-b="2" + data-c="3" + > + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div + data-a="Lorem ipsum dolor sit amet" + data-b="Lorem ipsum dolor sit amet" + data-c="Lorem ipsum dolor sit amet" + > + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div + data-long-attribute-a="1" + data-long-attribute-b="2" + data-long-attribute-c="3" + > + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <img src="/images/foo.png" /> + + <img + src="/images/foo.png" + alt="bar" + /> + + <img + src="/images/foo.png" + alt="Lorem ipsum dolor sit amet, consectetur adipiscing elit." + /> + </div> +); + +================================================================================ +`; + +exports[`single-attribute-per-line.js format 1`] = ` +====================================options===================================== +parsers: ["flow", "babel", "typescript"] +printWidth: 80 + | printWidth +=====================================input====================================== +import React from "react"; + +const Component = () => ( + <div> + <div data-a="1"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div data-a="1" data-b="2" data-c="3"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div data-a="Lorem ipsum dolor sit amet" data-b="Lorem ipsum dolor sit amet" data-c="Lorem ipsum dolor sit amet"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div data-long-attribute-a="1" data-long-attribute-b="2" data-long-attribute-c="3"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <img src="/images/foo.png" /> + + <img src="/images/foo.png" alt="bar" /> + + <img src="/images/foo.png" alt="Lorem ipsum dolor sit amet, consectetur adipiscing elit." /> + </div> +); + +=====================================output===================================== +import React from "react"; + +const Component = () => ( + <div> + <div data-a="1"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div data-a="1" data-b="2" data-c="3"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div + data-a="Lorem ipsum dolor sit amet" + data-b="Lorem ipsum dolor sit amet" + data-c="Lorem ipsum dolor sit amet" + > + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div + data-long-attribute-a="1" + data-long-attribute-b="2" + data-long-attribute-c="3" + > + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <img src="/images/foo.png" /> + + <img src="/images/foo.png" alt="bar" /> + + <img + src="/images/foo.png" + alt="Lorem ipsum dolor sit amet, consectetur adipiscing elit." + /> + </div> +); + +================================================================================ +`; diff --git a/tests/format/jsx/single-attribute-per-line/jsfmt.spec.js b/tests/format/jsx/single-attribute-per-line/jsfmt.spec.js new file mode 100644 --- /dev/null +++ b/tests/format/jsx/single-attribute-per-line/jsfmt.spec.js @@ -0,0 +1,4 @@ +run_spec(__dirname, ["flow", "babel", "typescript"]); +run_spec(__dirname, ["flow", "babel", "typescript"], { + singleAttributePerLine: true, +}); diff --git a/tests/format/jsx/single-attribute-per-line/single-attribute-per-line.js b/tests/format/jsx/single-attribute-per-line/single-attribute-per-line.js new file mode 100644 --- /dev/null +++ b/tests/format/jsx/single-attribute-per-line/single-attribute-per-line.js @@ -0,0 +1,27 @@ +import React from "react"; + +const Component = () => ( + <div> + <div data-a="1"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div data-a="1" data-b="2" data-c="3"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div data-a="Lorem ipsum dolor sit amet" data-b="Lorem ipsum dolor sit amet" data-c="Lorem ipsum dolor sit amet"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div data-long-attribute-a="1" data-long-attribute-b="2" data-long-attribute-c="3"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <img src="/images/foo.png" /> + + <img src="/images/foo.png" alt="bar" /> + + <img src="/images/foo.png" alt="Lorem ipsum dolor sit amet, consectetur adipiscing elit." /> + </div> +); diff --git a/tests/format/vue/single-attribute-per-line/__snapshots__/jsfmt.spec.js.snap b/tests/format/vue/single-attribute-per-line/__snapshots__/jsfmt.spec.js.snap new file mode 100644 --- /dev/null +++ b/tests/format/vue/single-attribute-per-line/__snapshots__/jsfmt.spec.js.snap @@ -0,0 +1,143 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`single-attribute-per-line.vue - {"singleAttributePerLine":true} format 1`] = ` +====================================options===================================== +parsers: ["vue"] +printWidth: 80 +singleAttributePerLine: true + | printWidth +=====================================input====================================== +<template> + <div data-a="1"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div data-a="1" data-b="2" data-c="3"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div data-a="Lorem ipsum dolor sit amet" data-b="Lorem ipsum dolor sit amet" data-c="Lorem ipsum dolor sit amet"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div data-long-attribute-a="1" data-long-attribute-b="2" data-long-attribute-c="3"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <img src="/images/foo.png" /> + + <img src="/images/foo.png" alt="bar" /> + + <img src="/images/foo.png" alt="Lorem ipsum dolor sit amet, consectetur adipiscing elit." /> +</template> + +=====================================output===================================== +<template> + <div data-a="1">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div> + + <div + data-a="1" + data-b="2" + data-c="3" + > + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div + data-a="Lorem ipsum dolor sit amet" + data-b="Lorem ipsum dolor sit amet" + data-c="Lorem ipsum dolor sit amet" + > + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div + data-long-attribute-a="1" + data-long-attribute-b="2" + data-long-attribute-c="3" + > + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <img src="/images/foo.png" /> + + <img + src="/images/foo.png" + alt="bar" + /> + + <img + src="/images/foo.png" + alt="Lorem ipsum dolor sit amet, consectetur adipiscing elit." + /> +</template> + +================================================================================ +`; + +exports[`single-attribute-per-line.vue format 1`] = ` +====================================options===================================== +parsers: ["vue"] +printWidth: 80 + | printWidth +=====================================input====================================== +<template> + <div data-a="1"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div data-a="1" data-b="2" data-c="3"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div data-a="Lorem ipsum dolor sit amet" data-b="Lorem ipsum dolor sit amet" data-c="Lorem ipsum dolor sit amet"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div data-long-attribute-a="1" data-long-attribute-b="2" data-long-attribute-c="3"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <img src="/images/foo.png" /> + + <img src="/images/foo.png" alt="bar" /> + + <img src="/images/foo.png" alt="Lorem ipsum dolor sit amet, consectetur adipiscing elit." /> +</template> + +=====================================output===================================== +<template> + <div data-a="1">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div> + + <div data-a="1" data-b="2" data-c="3"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div + data-a="Lorem ipsum dolor sit amet" + data-b="Lorem ipsum dolor sit amet" + data-c="Lorem ipsum dolor sit amet" + > + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div + data-long-attribute-a="1" + data-long-attribute-b="2" + data-long-attribute-c="3" + > + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <img src="/images/foo.png" /> + + <img src="/images/foo.png" alt="bar" /> + + <img + src="/images/foo.png" + alt="Lorem ipsum dolor sit amet, consectetur adipiscing elit." + /> +</template> + +================================================================================ +`; diff --git a/tests/format/vue/single-attribute-per-line/jsfmt.spec.js b/tests/format/vue/single-attribute-per-line/jsfmt.spec.js new file mode 100644 --- /dev/null +++ b/tests/format/vue/single-attribute-per-line/jsfmt.spec.js @@ -0,0 +1,2 @@ +run_spec(__dirname, ["vue"]); +run_spec(__dirname, ["vue"], { singleAttributePerLine: true }); diff --git a/tests/format/vue/single-attribute-per-line/single-attribute-per-line.vue b/tests/format/vue/single-attribute-per-line/single-attribute-per-line.vue new file mode 100644 --- /dev/null +++ b/tests/format/vue/single-attribute-per-line/single-attribute-per-line.vue @@ -0,0 +1,23 @@ +<template> + <div data-a="1"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div data-a="1" data-b="2" data-c="3"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div data-a="Lorem ipsum dolor sit amet" data-b="Lorem ipsum dolor sit amet" data-c="Lorem ipsum dolor sit amet"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <div data-long-attribute-a="1" data-long-attribute-b="2" data-long-attribute-c="3"> + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + </div> + + <img src="/images/foo.png" /> + + <img src="/images/foo.png" alt="bar" /> + + <img src="/images/foo.png" alt="Lorem ipsum dolor sit amet, consectetur adipiscing elit." /> +</template> diff --git a/tests/integration/__tests__/__snapshots__/early-exit.js.snap b/tests/integration/__tests__/__snapshots__/early-exit.js.snap --- a/tests/integration/__tests__/__snapshots__/early-exit.js.snap +++ b/tests/integration/__tests__/__snapshots__/early-exit.js.snap @@ -86,6 +86,9 @@ Format options: Change when properties in objects are quoted. Defaults to as-needed. --no-semi Do not print semicolons, except at the beginning of lines which may need them. + --single-attribute-per-line + Enforce single attribute per line in HTML, Vue and JSX. + Defaults to false. --single-quote Use single quotes instead of double quotes. Defaults to false. --tab-width <int> Number of spaces per indentation level. @@ -251,6 +254,9 @@ Format options: Change when properties in objects are quoted. Defaults to as-needed. --no-semi Do not print semicolons, except at the beginning of lines which may need them. + --single-attribute-per-line + Enforce single attribute per line in HTML, Vue and JSX. + Defaults to false. --single-quote Use single quotes instead of double quotes. Defaults to false. --tab-width <int> Number of spaces per indentation level. diff --git a/tests/integration/__tests__/__snapshots__/help-options.js.snap b/tests/integration/__tests__/__snapshots__/help-options.js.snap --- a/tests/integration/__tests__/__snapshots__/help-options.js.snap +++ b/tests/integration/__tests__/__snapshots__/help-options.js.snap @@ -541,6 +541,19 @@ Default: true exports[`show detailed usage with --help semi (write) 1`] = `Array []`; +exports[`show detailed usage with --help single-attribute-per-line (stderr) 1`] = `""`; + +exports[`show detailed usage with --help single-attribute-per-line (stdout) 1`] = ` +"--single-attribute-per-line + + Enforce single attribute per line in HTML, Vue and JSX. + +Default: false +" +`; + +exports[`show detailed usage with --help single-attribute-per-line (write) 1`] = `Array []`; + exports[`show detailed usage with --help single-quote (stderr) 1`] = `""`; exports[`show detailed usage with --help single-quote (stdout) 1`] = ` diff --git a/tests/integration/__tests__/__snapshots__/schema.js.snap b/tests/integration/__tests__/__snapshots__/schema.js.snap --- a/tests/integration/__tests__/__snapshots__/schema.js.snap +++ b/tests/integration/__tests__/__snapshots__/schema.js.snap @@ -366,6 +366,11 @@ in order for it to be formatted.", "description": "Print semicolons.", "type": "boolean", }, + "singleAttributePerLine": Object { + "default": false, + "description": "Enforce single attribute per line in HTML, Vue and JSX.", + "type": "boolean", + }, "singleQuote": Object { "default": false, "description": "Use single quotes instead of double quotes.", diff --git a/tests/integration/__tests__/__snapshots__/support-info.js.snap b/tests/integration/__tests__/__snapshots__/support-info.js.snap --- a/tests/integration/__tests__/__snapshots__/support-info.js.snap +++ b/tests/integration/__tests__/__snapshots__/support-info.js.snap @@ -239,6 +239,10 @@ Object { "default": true, "type": "boolean", }, + "singleAttributePerLine": Object { + "default": false, + "type": "boolean", + }, "singleQuote": Object { "default": false, "type": "boolean", @@ -1065,6 +1069,15 @@ exports[`CLI --support-info (stdout) 1`] = ` \\"since\\": \\"1.0.0\\", \\"type\\": \\"boolean\\" }, + { + \\"category\\": \\"Common\\", + \\"default\\": false, + \\"description\\": \\"Enforce single attribute per line in HTML, Vue and JSX.\\", + \\"name\\": \\"singleAttributePerLine\\", + \\"pluginDefaults\\": {}, + \\"since\\": \\"2.3.3\\", + \\"type\\": \\"boolean\\" + }, { \\"category\\": \\"Common\\", \\"default\\": false,
Change HTML/JSX formatting to have one attribute/prop per line Similar to what was done for #3847 I think it best to break some of the discussion from #3101 into a new issue that people can 👍 or 👎. I'm proposing that for HTML and JSX to have Prettier always have one attribute/prop per line (and thus not respect the developer's original preference). Code would then be formatted as shown below. This is in contrast to the current behaviour where we fit as much as possible with the print-width. **Expected behavior:** ```jsx <MyComponent lorem="1"/> <MyComponent lorem="1" ipsum="2" /> <MyComponent lorem="1" ipsum="2" dolor="3" /> ``` This suggestion for one attribute/prop per line was proposed several times in the discussion of #3101 but I think it is clearer if this is pulled into it's own proposal. The original proposal in #3101 is that Prettier would add an option to preserve original formatting which, while I agree with the author with the style that they want, I don't think a) an option, nor b) preserving original formatting follows the aims for Prettier (see also #2068). Instead I think the aims of #3101 are better served by this proposal to ignore the print-width and always place attributes/props on new lines (assuming that there is more than one). This style appears to be the most common formatting for Angular, Vue and React from what I can tell. It style appears to be the style enforced by the rules: * React: [jsx-max-props-per-line](https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-max-props-per-line.md) which [Airbnb set to to 1 in their style guide](https://github.com/airbnb/javascript/blob/master/packages/eslint-config-airbnb/rules/react.js#L89) * Vue: [max-attributes-per-line](https://github.com/vuejs/eslint-plugin-vue/blob/master/docs/rules/max-attributes-per-line.md) which has a default to 1.
While I agree that I'd like to see this being default behavior, I would suggest the following steps: - introduce new config option (`singleAttributePerLine: true` ?) - make default of that option to have attributes on single line (for backwards compatibility) - now we can have it 🎉 - open discussion about changing the default behavior - depending on the outcome: - change default behavior of the option - deprecate option @lydell This probably also should have `lang:vue` as a label 😄
"2019-10-13T16:53:37Z"
2.6
[ "tests/integration/__tests__/help-options.js" ]
[ "tests/integration/__tests__/early-exit.js", "tests/integration/__tests__/support-info.js", "tests/integration/__tests__/schema.js", "tests/format/jsx/single-attribute-per-line/jsfmt.spec.js", "tests/format/html/single-attribute-per-line/jsfmt.spec.js", "tests/format/vue/single-attribute-per-line/jsfmt.spec.js" ]
JavaScript
[]
[]