From 9a8aa0d28effc6afba7ed8cca986a6360ba8f055 Mon Sep 17 00:00:00 2001 From: no92 Date: Thu, 15 Feb 2024 12:26:38 +0100 Subject: [PATCH] fix: Use the `lineWidth` option for line breaking in flow collections (#522) 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'] })