|
| 1 | +/* |
| 2 | + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 3 | + * or more contributor license agreements. Licensed under the Elastic License |
| 4 | + * 2.0; you may not use this file except in compliance with the Elastic License |
| 5 | + * 2.0. |
| 6 | + */ |
| 7 | + |
| 8 | +import { text, softline, hardline, group, indent, conditionalGroup, join, layout } from '..'; |
| 9 | + |
| 10 | +describe('conditionalGroup', () => { |
| 11 | + it('uses first state (flat) when it fits', () => { |
| 12 | + const items = [text('alpha'), text('beta'), text('gamma')]; |
| 13 | + |
| 14 | + const doc = conditionalGroup([ |
| 15 | + // Phase 1: flat with spaces — "alpha, beta, gamma" |
| 16 | + group(join(text(', '), items)), |
| 17 | + // Phase 2: compact — "alpha,beta,gamma" |
| 18 | + group(join([text(','), softline], items)), |
| 19 | + // Phase 3: one per line |
| 20 | + group([indent([hardline, join([text(','), hardline], items)]), hardline], { |
| 21 | + shouldBreak: true, |
| 22 | + }), |
| 23 | + ]); |
| 24 | + |
| 25 | + expect(layout(doc, { printWidth: 20 })).toBe('alpha, beta, gamma'); |
| 26 | + expect(layout(doc, { printWidth: 17 })).toBe('alpha,beta,gamma'); |
| 27 | + expect(layout(doc, { printWidth: 10 })).toBe('\n alpha,\n beta,\n gamma\n'); |
| 28 | + }); |
| 29 | + |
| 30 | + it('three-phase list with brackets', () => { |
| 31 | + const items = [text('alpha'), text('beta'), text('gamma'), text('delta')]; |
| 32 | + const sep = text(','); |
| 33 | + |
| 34 | + const doc = conditionalGroup([ |
| 35 | + // Phase 1: all on one line — "(alpha, beta, gamma, delta)" = 27 |
| 36 | + group([text('('), join([sep, text(' ')], items), text(')')]), |
| 37 | + // Phase 2: compact (no spaces) — "(alpha,beta,gamma,delta)" = 24 |
| 38 | + group([text('('), join([sep, softline], items), text(')')]), |
| 39 | + // Phase 3: one per line |
| 40 | + group([text('('), indent([hardline, join([sep, hardline], items)]), hardline, text(')')], { |
| 41 | + shouldBreak: true, |
| 42 | + }), |
| 43 | + ]); |
| 44 | + |
| 45 | + expect(layout(doc, { printWidth: 30 })).toBe('(alpha, beta, gamma, delta)'); |
| 46 | + expect(layout(doc, { printWidth: 25 })).toBe('(alpha,beta,gamma,delta)'); |
| 47 | + expect(layout(doc, { printWidth: 10 })).toBe('(\n alpha,\n beta,\n gamma,\n delta\n)'); |
| 48 | + }); |
| 49 | + |
| 50 | + it('with two states only', () => { |
| 51 | + const doc = conditionalGroup([ |
| 52 | + // Try flat |
| 53 | + join([text(', ')], [text('aaa'), text('bbb'), text('ccc')]), |
| 54 | + // Fallback: broken |
| 55 | + group( |
| 56 | + [indent([hardline, join([text(','), hardline], [text('aaa'), text('bbb'), text('ccc')])])], |
| 57 | + { shouldBreak: true } |
| 58 | + ), |
| 59 | + ]); |
| 60 | + |
| 61 | + expect(layout(doc, { printWidth: 20 })).toBe('aaa, bbb, ccc'); |
| 62 | + expect(layout(doc, { printWidth: 10 })).toBe('\n aaa,\n bbb,\n ccc'); |
| 63 | + }); |
| 64 | +}); |
0 commit comments