Skip to content

Commit

Permalink
Make print() break arguments over multiple lines (#2797)
Browse files Browse the repository at this point in the history
  • Loading branch information
draperunner authored Sep 21, 2020
1 parent c2f97bb commit b9cf5f3
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 12 deletions.
49 changes: 46 additions & 3 deletions src/language/__tests__/printer-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,45 @@ describe('Printer: Query document', () => {
`);
});

it('keeps arguments on one line if line is short (<= 80 chars)', () => {
const printed = print(
parse('{trip(wheelchair:false arriveBy:false){dateTime}}'),
);

expect(printed).to.equal(
dedent`
{
trip(wheelchair: false, arriveBy: false) {
dateTime
}
}
`,
);
});

it('puts arguments on multiple lines if line is long (> 80 chars)', () => {
const printed = print(
parse(
'{trip(wheelchair:false arriveBy:false includePlannedCancellations:true transitDistanceReluctance:2000){dateTime}}',
),
);

expect(printed).to.equal(
dedent`
{
trip(
wheelchair: false
arriveBy: false
includePlannedCancellations: true
transitDistanceReluctance: 2000
) {
dateTime
}
}
`,
);
});

it('Experimental: prints fragment with variable directives', () => {
const queryASTWithVariableDirective = parse(
'fragment Foo($foo: TestType @test) on TestType @testDirective { id }',
Expand Down Expand Up @@ -158,9 +197,13 @@ describe('Printer: Query document', () => {
}
fragment frag on Friend @onFragmentDefinition {
foo(size: $size, bar: $b, obj: {key: "value", block: """
block string uses \"""
"""})
foo(
size: $size
bar: $b
obj: {key: "value", block: """
block string uses \"""
"""}
)
}
{
Expand Down
21 changes: 12 additions & 9 deletions src/language/printer.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ export function print(ast: ASTNode): string {
return visit(ast, { leave: printDocASTReducer });
}

const MAX_LINE_LENGTH = 80;

// TODO: provide better type coverage in future
const printDocASTReducer: any = {
Name: (node) => node.value,
Expand Down Expand Up @@ -41,15 +43,16 @@ const printDocASTReducer: any = {
wrap(' ', join(directives, ' ')),
SelectionSet: ({ selections }) => block(selections),

Field: ({ alias, name, arguments: args, directives, selectionSet }) =>
join(
[
wrap('', alias, ': ') + name + wrap('(', join(args, ', '), ')'),
join(directives, ' '),
selectionSet,
],
' ',
),
Field: ({ alias, name, arguments: args, directives, selectionSet }) => {
const prefix = wrap('', alias, ': ') + name;
let argsLine = prefix + wrap('(', join(args, ', '), ')');

if (argsLine.length > MAX_LINE_LENGTH) {
argsLine = prefix + wrap('(\n', indent(join(args, '\n')), '\n)');
}

return join([argsLine, join(directives, ' '), selectionSet], ' ');
},

Argument: ({ name, value }) => name + ': ' + value,

Expand Down

0 comments on commit b9cf5f3

Please sign in to comment.