prettier icon indicating copy to clipboard operation
prettier copied to clipboard

Wrong indentation on long ternary operators

Open externuz opened this issue 7 years ago • 4 comments

Prettier 1.15.3 Playground link

Input:

value === 100 ? caseA() ? caseB() : caseC() : value === 200 ? caseD() : caseE()

Output:

value === 100
  ? caseA()
    ? caseB()
    : caseC()
  : value === 200
  ? caseD()
  : caseE();

Expected behavior:

value === 100
  ? caseA()
    ? caseB()
    : caseC()
  : value === 200
    ? caseD()
    : caseE();

externuz avatar Dec 26 '18 08:12 externuz

Hm, this is a case I didn’t think about when we changed the ternary’s formatting.

j-f1 avatar Dec 26 '18 11:12 j-f1

For me it is looks like bug, we should add or remove indent for all nested ternary operators. But if we remove their indent output will be unreadable:

value === 100
  ? caseA()
  ? caseB()
  : caseC()
  : value === 200
  ? caseD()
  : caseE();

More nested ternary operators look very bad:

value === 100
  ? caseA()
    ? value === 100
      ? caseA()
      : caseE()
    : value === 100
    ? caseA()
    : caseE()
  : value === 200
  ? value === 100
    ? caseA()
    : caseE()
  : value === 100
  ? caseA()
  : caseE();

alexander-akait avatar Dec 26 '18 11:12 alexander-akait

I would also like to see this indented. I have the following example to contribute:

Input:

return options.buttonholePlacketStyle === "seamless"
  ? frontLeftSeamless(part)
  : seperateButtonholePlacket
    ? frontLeftClassicSeperate(part)
    : frontLeftClassicCuton(part)

Output:

return options.buttonholePlacketStyle === "seamless"
  ? frontLeftSeamless(part)
  : seperateButtonholePlacket
  ? frontLeftClassicSeperate(part)
  : frontLeftClassicCuton(part);

While we can debate whether nested ternary operators are a good idea, I feel that in this case, readability suffers because of the applied formatting.

FYI: Example from https://github.com/freesewing/simon/blob/master/src/frontleft.js#L18

joostdecock avatar Dec 29 '18 11:12 joostdecock

This is working as intended. Your expected version is how we used to print this before and we had lots of request to change it.

Hm, this is a case we didn’t think about when we changed the ternary’s formatting.

@j-f1 what case exactly? This case is just a nested ternary inside the consequence (instead of alternate) and we did think about it, which is why it's printing correctly.

@joostdecock Your input is how we used to print this and we intentionally changed it after several requests.

duailibe avatar Jan 14 '19 12:01 duailibe