From 9037593ab811c984ebe3df592cf003872a6c9798 Mon Sep 17 00:00:00 2001 From: Peter Bacon Darwin Date: Mon, 10 Apr 2017 22:14:40 +0100 Subject: [PATCH] fix(aio): left align code in aio-code components --- aio/src/app/embedded/code/code.component.spec.ts | 8 ++++++++ aio/src/app/embedded/code/code.component.ts | 14 +++++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/aio/src/app/embedded/code/code.component.spec.ts b/aio/src/app/embedded/code/code.component.spec.ts index e32c17ca61..94b8ad3ea0 100644 --- a/aio/src/app/embedded/code/code.component.spec.ts +++ b/aio/src/app/embedded/code/code.component.spec.ts @@ -105,6 +105,14 @@ describe('CodeComponent', () => { expect(lis.length).toBe(0, 'should be no linenums'); }); + it('should remove common indentation from the code before rendering', () => { + hostComponent.linenums = false; + hostComponent.code = ' abc\n def\n ghi\n\n jkl\n'; + fixture.detectChanges(); + const codeContent = codeComponentDe.nativeElement.querySelector('code').innerText; + expect(codeContent).toEqual('abc\n def\nghi\n\njkl'); + }); + it('should trim whitespace from the code before rendering', () => { hostComponent.linenums = false; hostComponent.code = '\n\n\n' + multiLineCode + '\n\n\n'; diff --git a/aio/src/app/embedded/code/code.component.ts b/aio/src/app/embedded/code/code.component.ts index 5e66947765..f994c2af6e 100644 --- a/aio/src/app/embedded/code/code.component.ts +++ b/aio/src/app/embedded/code/code.component.ts @@ -70,7 +70,7 @@ export class CodeComponent implements OnChanges { private logger: Logger) {} ngOnChanges() { - this.code = this.code && this.code.trim(); + this.code = this.code && leftAlign(this.code); if (!this.code) { this.setCodeHtml('

The code sample is missing.

'); @@ -118,3 +118,15 @@ export class CodeComponent implements OnChanges { (this.code.match(/\n/g) || []).length > 1 : linenums; } } + +function leftAlign(text) { + let indent = Number.MAX_VALUE; + const lines = text.split('\n'); + lines.forEach(line => { + const lineIndent = line.search(/\S/); + if (lineIndent !== -1) { + indent = Math.min(lineIndent, indent); + } + }); + return lines.map(line => line.substr(indent)).join('\n').trim(); +}