From 2ce67c74e1f3649bb4dc0ecbe21f26a9a2a8fb02 Mon Sep 17 00:00:00 2001 From: no92 Date: Mon, 12 Feb 2024 19:59:55 +0100 Subject: [PATCH] fix: use the `lineWidth` option for line breaking in flow collections This should address issues #288 and #507. --- src/stringify/stringifyCollection.ts | 2 +- tests/doc/stringify.ts | 32 +++++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/stringify/stringifyCollection.ts b/src/stringify/stringifyCollection.ts index a572718d..0892549c 100644 --- a/src/stringify/stringifyCollection.ts +++ b/src/stringify/stringifyCollection.ts @@ -148,7 +148,7 @@ function stringifyFlowCollection( } else { if (!reqNewline) { const len = lines.reduce((sum, line) => sum + line.length + 2, 2) - reqNewline = len > Collection.maxFlowStringSingleLineLength + reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth } if (reqNewline) { str = start diff --git a/tests/doc/stringify.ts b/tests/doc/stringify.ts index a094203a..c7b7bf28 100644 --- a/tests/doc/stringify.ts +++ b/tests/doc/stringify.ts @@ -616,7 +616,7 @@ describe('scalar styles', () => { y, n ]\n` - expect(String(doc)).toBe(str) + expect(doc.toString({ lineWidth: 1 })).toBe(str) expect(YAML.parse(str)).toEqual([ true, false, @@ -868,6 +868,36 @@ describe('indentSeq: false', () => { }) }) +describe('lineWidth', () => { + const doc = YAML.parseDocument( + "[ 'Sed', 'ut', 'perspiciatis', 'unde', 'omnis', 'iste', 'natus', 'error', 'sit', 'voluptatem', 'accusantium', 'doloremque', 'laudantium,', 'totam' ]" + ) + + test('limit to 80 with overlong flow collection', () => { + expect(doc.toString({lineWidth: 80})).toBe(`[ + 'Sed', + 'ut', + 'perspiciatis', + 'unde', + 'omnis', + 'iste', + 'natus', + 'error', + 'sit', + 'voluptatem', + 'accusantium', + 'doloremque', + 'laudantium,', + 'totam' +] +`) + }) + + test('limit > flow collection length', () => { + expect(doc.toString({lineWidth: 162})).toBe("[ 'Sed', 'ut', 'perspiciatis', 'unde', 'omnis', 'iste', 'natus', 'error', 'sit', 'voluptatem', 'accusantium', 'doloremque', 'laudantium,', 'totam' ]\n") + }) +}) + describe('collectionStyle', () => { test('collectionStyle: undefined', () => { const doc = new YAML.Document({ foo: ['bar'] })