Skip to content

Commit

Permalink
[field formatters] improved resiliency of url formatter (#121584)
Browse files Browse the repository at this point in the history
* test url formatter

Co-authored-by: Kibana Machine <[email protected]>
  • Loading branch information
mattkime and kibanamachine authored Dec 23, 2021
1 parent 6c8974f commit f388d99
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
14 changes: 14 additions & 0 deletions src/plugins/field_formats/common/converters/url.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,13 @@ describe('UrlFormat', () => {
'<img src="http://elastic.co" alt="A dynamically-specified image located at http://elastic.co" ' +
'style="width:auto; height:auto; max-width:none; max-height:none;">'
);

const url2 = new UrlFormat({ type: 'img', width: '123not a number' });

expect(url2.convert('http://elastic.co', HTML_CONTEXT_TYPE)).toBe(
'<img src="http://elastic.co" alt="A dynamically-specified image located at http://elastic.co" ' +
'style="width:auto; height:auto; max-width:123px; max-height:none;">'
);
});

test('only accepts valid numbers for height', () => {
Expand All @@ -79,6 +86,13 @@ describe('UrlFormat', () => {
'<img src="http://elastic.co" alt="A dynamically-specified image located at http://elastic.co" ' +
'style="width:auto; height:auto; max-width:none; max-height:none;">'
);

const url2 = new UrlFormat({ type: 'img', height: '123not a number' });

expect(url2.convert('http://elastic.co', HTML_CONTEXT_TYPE)).toBe(
'<img src="http://elastic.co" alt="A dynamically-specified image located at http://elastic.co" ' +
'style="width:auto; height:auto; max-width:none; max-height:123px;">'
);
});
});

Expand Down
10 changes: 6 additions & 4 deletions src/plugins/field_formats/common/converters/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,10 +122,12 @@ export class UrlFormat extends FieldFormat {
}

private generateImgHtml(url: string, imageLabel: string): string {
const isValidWidth = !isNaN(parseInt(this.param('width'), 10));
const isValidHeight = !isNaN(parseInt(this.param('height'), 10));
const maxWidth = isValidWidth ? `${this.param('width')}px` : 'none';
const maxHeight = isValidHeight ? `${this.param('height')}px` : 'none';
const parsedWidth = parseInt(this.param('width'), 10);
const parsedHeight = parseInt(this.param('height'), 10);
const isValidWidth = !isNaN(parsedWidth);
const isValidHeight = !isNaN(parsedHeight);
const maxWidth = isValidWidth ? `${parsedWidth}px` : 'none';
const maxHeight = isValidHeight ? `${parsedHeight}px` : 'none';

return `<img src="${url}" alt="${imageLabel}" style="width:auto; height:auto; max-width:${maxWidth}; max-height:${maxHeight};">`;
}
Expand Down

0 comments on commit f388d99

Please sign in to comment.