diff --git a/src/transform/liquid/conditions.ts b/src/transform/liquid/conditions.ts index ad3e8b39..8832fc2c 100644 --- a/src/transform/liquid/conditions.ts +++ b/src/transform/liquid/conditions.ts @@ -78,19 +78,48 @@ function trimResult(content: string, ifTag: IfTag, ifCon: IfCondition | null) { if (!ifCon) { const head = headLinebreak(ifTag.rawStart); const tail = tailLinebreak(ifTag.rawEnd); - return ifTag.isBlock ? '\n' : head + tail; + + let rest = head + tail; + if (rest !== head && rest !== tail) { + // We have extra line break, if condition was placed on individual line + rest = rest.replace('\n', ''); + } + + return ifTag.isBlock ? '\n' : rest; } content = content.substring(ifCon.start, ifCon.end); - const head = ifTag.isBlock ? headLinebreak(ifCon.rawStart) : headLinebreak(ifTag.rawStart); + if (ifTag.isBlock) { + return trimBlockResult(content, ifCon); + } else { + return trimInlineResult(content, ifTag); + } +} + +function trimBlockResult(content: string, ifCon: IfCondition) { + const head = headLinebreak(ifCon.rawStart); + if (head) { + content = '\n' + content; + } + + const tail = tailLinebreak(ifCon.rawEnd); + if (tail) { + content = content + '\n'; + } + + return content; +} + +function trimInlineResult(content: string, ifTag: IfTag) { + const head = headLinebreak(ifTag.rawStart); if (head) { - content = (ifTag.isBlock ? '\n' : head) + content; + content = head + content; } - const tail = ifTag.isBlock ? tailLinebreak(ifCon.rawEnd) : tailLinebreak(ifTag.rawEnd); + const tail = tailLinebreak(ifTag.rawEnd); if (tail) { - content = content + (ifTag.isBlock ? '\n' : tail); + content = content + tail; } return content; @@ -279,6 +308,10 @@ export = function conditions( break; } + default: + // This is not condition. + // Step back last linebreaks to match them on next condition + R_LIQUID.lastIndex -= tailLinebreak(match[1]).length; } } diff --git a/test/liquid/conditions.test.ts b/test/liquid/conditions.test.ts index 548a28f9..dab499e9 100644 --- a/test/liquid/conditions.test.ts +++ b/test/liquid/conditions.test.ts @@ -253,6 +253,59 @@ describe('Conditions', () => { End `); }); + + test('Falsy inline condition after truthly inline condition', () => { + expect( + conditions( + trim` + {% if product == "A" %}A{% endif %} + {% if product == "B" %}B{% endif %} + C + `, + { + product: 'A', + }, + '', + { + sourceMap: {}, + }, + ), + ).toEqual( + trim` + A + C + `, + ); + }); + + test('Around other curly braced structures', () => { + expect( + conditions( + trim` + * Title: + * {% include [A](./A.md) %} + {% if audience != "internal" %} + * {% include [B](./B.md) %} + {% endif %} + * {% include [C](./C.md) %} + `, + { + audience: 'other', + }, + '', + { + sourceMap: {}, + }, + ), + ).toEqual( + trim` + * Title: + * {% include [A](./A.md) %} + * {% include [B](./B.md) %} + * {% include [C](./C.md) %} + `, + ); + }); }); describe('Conditions', () => {