fix(aio): left align code in aio-code components
This commit is contained in:
parent
3ced940b5a
commit
9037593ab8
|
@ -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';
|
||||
|
|
|
@ -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('<p class="code-missing">The code sample is missing.</p>');
|
||||
|
@ -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();
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue