Skip to content

Commit f9e67c4

Browse files
committed
Improvements to printing block strings
1 parent 7a7ffe4 commit f9e67c4

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

src/language/__tests__/printer-test.js

+32-1
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,37 @@ describe('Printer', () => {
7171
`);
7272
});
7373

74+
it('correctly prints single-line block strings with leading space', () => {
75+
const mutationAstWithArtifacts = parse(
76+
'{ field(arg: """ space-led value""") }'
77+
);
78+
expect(print(mutationAstWithArtifacts)).to.equal(dedent`
79+
{
80+
field(arg: """ space-led value""")
81+
}
82+
`);
83+
});
84+
85+
it('correctly prints block strings with a first line indentation', () => {
86+
const mutationAstWithArtifacts = parse(`
87+
{
88+
field(arg: """
89+
first
90+
line
91+
indentation
92+
""")
93+
}
94+
`);
95+
expect(print(mutationAstWithArtifacts)).to.equal(dedent`
96+
{
97+
field(arg: """
98+
first
99+
line
100+
indentation
101+
""")
102+
}
103+
`);
104+
});
74105

75106
const kitchenSink = readFileSync(
76107
join(__dirname, '/kitchen-sink.graphql'),
@@ -128,7 +159,7 @@ describe('Printer', () => {
128159
129160
fragment frag on Friend {
130161
foo(size: $size, bar: $b, obj: {key: "value", block: """
131-
block string uses \"""
162+
block string uses \"""
132163
"""})
133164
}
134165

src/language/printer.js

+12-1
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ const printDocASTReducer = {
7474
FloatValue: ({ value }) => value,
7575
StringValue: ({ value, block: isBlockString }) =>
7676
isBlockString ?
77-
`"""\n${value.replace(/"""/g, '\\"""')}\n"""` :
77+
printBlockString(value) :
7878
JSON.stringify(value),
7979
BooleanValue: ({ value }) => JSON.stringify(value),
8080
NullValue: () => 'null',
@@ -204,3 +204,14 @@ function wrap(start, maybeString, end) {
204204
function indent(maybeString) {
205205
return maybeString && maybeString.replace(/\n/g, '\n ');
206206
}
207+
208+
/**
209+
* Print a block string in the indented block form by adding a leading and
210+
* trailing blank line. However, if a block string starts with whitespace and is
211+
* a single-line, adding a leading blank line would strip that whitespace.
212+
*/
213+
function printBlockString(value) {
214+
return (value[0] === ' ' || value[0] === '\t') && value.indexOf('\n') === -1 ?
215+
`"""${value.replace(/"""/g, '\\"""')}"""` :
216+
indent('"""\n' + value.replace(/"""/g, '\\"""')) + '\n"""';
217+
}

0 commit comments

Comments
 (0)