Skip to content

Commit

Permalink
Improvements to printing block strings
Browse files Browse the repository at this point in the history
  • Loading branch information
leebyron committed Nov 30, 2017
1 parent 7a7ffe4 commit f9e67c4
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
33 changes: 32 additions & 1 deletion src/language/__tests__/printer-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,37 @@ describe('Printer', () => {
`);
});

it('correctly prints single-line block strings with leading space', () => {
const mutationAstWithArtifacts = parse(
'{ field(arg: """ space-led value""") }'
);
expect(print(mutationAstWithArtifacts)).to.equal(dedent`
{
field(arg: """ space-led value""")
}
`);
});

it('correctly prints block strings with a first line indentation', () => {
const mutationAstWithArtifacts = parse(`
{
field(arg: """
first
line
indentation
""")
}
`);
expect(print(mutationAstWithArtifacts)).to.equal(dedent`
{
field(arg: """
first
line
indentation
""")
}
`);
});

const kitchenSink = readFileSync(
join(__dirname, '/kitchen-sink.graphql'),
Expand Down Expand Up @@ -128,7 +159,7 @@ describe('Printer', () => {
fragment frag on Friend {
foo(size: $size, bar: $b, obj: {key: "value", block: """
block string uses \"""
block string uses \"""
"""})
}
Expand Down
13 changes: 12 additions & 1 deletion src/language/printer.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ const printDocASTReducer = {
FloatValue: ({ value }) => value,
StringValue: ({ value, block: isBlockString }) =>
isBlockString ?
`"""\n${value.replace(/"""/g, '\\"""')}\n"""` :
printBlockString(value) :
JSON.stringify(value),
BooleanValue: ({ value }) => JSON.stringify(value),
NullValue: () => 'null',
Expand Down Expand Up @@ -204,3 +204,14 @@ function wrap(start, maybeString, end) {
function indent(maybeString) {
return maybeString && maybeString.replace(/\n/g, '\n ');
}

/**
* Print a block string in the indented block form by adding a leading and
* trailing blank line. However, if a block string starts with whitespace and is
* a single-line, adding a leading blank line would strip that whitespace.
*/
function printBlockString(value) {
return (value[0] === ' ' || value[0] === '\t') && value.indexOf('\n') === -1 ?
`"""${value.replace(/"""/g, '\\"""')}"""` :
indent('"""\n' + value.replace(/"""/g, '\\"""')) + '\n"""';
}

0 comments on commit f9e67c4

Please sign in to comment.