dprint-plugin-typescript icon indicating copy to clipboard operation
dprint-plugin-typescript copied to clipboard

Indentation of function arguments with ternary operator

Open marcesengel opened this issue 2 years ago • 1 comments

Hi!

First of all thank you very much for the nice plugin! I'm having some strange formatting for the use-case mentioned above, where the keys of an inline object align with the opening curly braces of it. Here's a playground link.

Screenshot: image

As you can see the key in line 10 aligns with the curly brace in line 9 which doesn't seem to be in line with the formatting of lines 3 + 4. Is this intended or is it a bug? I can try providing a PR in case it's a bug. Prettier indents everything after the first line of the ternary operator one additional time, to me this seems more natural.

Thanks in advance!

Best regards

marcesengel avatar Jun 07 '23 14:06 marcesengel

This issue was bugging me as well, so I started to look into it. Unfortunately, it doesn't seem to be as trivial as I thought. I assumed you could just add an additional level of indentation, but that's only valid if your indentation width is 2 spaces. If you use 4 or 8, adding one indent will indent two much. Prettier makes it so that myVeryLongVariableName will be one indent width to the right of test, but I couldn't figure out how to make dprint indent by something that isn't a multiple of the indent width.

A potential workaround is to add an indent if the indent width is 2 spaces, otherwise leave it alone. That would result in code that looks like this for 2 space indents:

true
  ? test({
      prop: "some value",
      otherProp: "some value",
    })
  : test({
      prop: "some value",
      otherProp: "some value",
    });

and this for 4 spaces:

true
    ? test({
        prop: "some value",
        otherProp: "some value",
    })
    : test({
        prop: "some value",
        otherProp: "some value",
    });

The solution feels a bit hacky to me, but I think the appearance is a slight improvement.

(But take everything above with a grain of salt. I'm not very familiar with the codebase and may have overlooked some alignment facilities. Just wanted to share in case it helps someone.)

cjpearson avatar Apr 08 '24 18:04 cjpearson