From 5d886acb37ebce8340f1a240522ba320ae45103f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Vasseur?= Date: Mon, 29 Aug 2022 15:44:31 +0200 Subject: [PATCH] Handle template starting with empty line --- README.md | 2 +- index.test.ts | 14 ++++++++++++++ index.ts | 2 +- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 844313e..48d0263 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,6 @@ indentation: - First it treats the start and end of the template to remove the lines that contains the backticks. - Then it removes the indentation of each line base on the indentation of the - first line. + first non-empty line. - Finaly, it indents strings that are passed into the placeholders based of the indentation preceding them. diff --git a/index.test.ts b/index.test.ts index 556c502..e8edb9b 100644 --- a/index.test.ts +++ b/index.test.ts @@ -20,6 +20,20 @@ test('It reindent placeholders', () => { `).toBe('\n test\n value\n'); }); +test('It correctly detect indentation when first line is empty', () => { + expect(indent` + + Test + `).toBe('\nTest'); +}); + +test('It correctly detect indentation when last line is empty', () => { + expect(indent` + Test + + `).toBe('Test\n'); +}); + test('Nested indent test', () => { const list = ['First', 'Second']; diff --git a/index.ts b/index.ts index c726a98..c8dc437 100644 --- a/index.ts +++ b/index.ts @@ -12,7 +12,7 @@ const indentTag = (strings: TemplateStringsArray, ... expressions: any[]) => { parts[strings.length - 1] = parts[parts.length - 1].replace(/\n[ \t]*$/, ''); // Dedent using indent from first part - const indent = parts[0].match(/^[ \t]*/)![0]; + const indent = parts[0].match(/^\n*([ \t]*)/)![1]; const deindent = new RegExp(`(^|\n)${indent}`, 'g');