Skip to content

Commit

Permalink
feat(material/schematics): add fn for adding attrs to templates (#24550)
Browse files Browse the repository at this point in the history
* create and unit test addAttribute fn
  • Loading branch information
wagnermaciel authored and mmalerba committed Jul 15, 2022
1 parent 33c3277 commit 801c23c
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
@@ -1,4 +1,10 @@
import {visitElements, parseTemplate, replaceStartTag, replaceEndTag} from './tree-traversal';
import {
addAttribute,
visitElements,
parseTemplate,
replaceStartTag,
replaceEndTag,
} from './tree-traversal';

function runTagNameDuplicationTest(html: string, result: string): void {
visitElements(
Expand All @@ -13,6 +19,13 @@ function runTagNameDuplicationTest(html: string, result: string): void {
expect(html).toBe(result);
}

function runAddAttributeTest(html: string, result: string): void {
visitElements(parseTemplate(html).nodes, undefined, node => {
html = addAttribute(html, node, 'attr', 'val');
});
expect(html).toBe(result);
}

describe('#visitElements', () => {
describe('tag name replacements', () => {
it('should handle basic cases', async () => {
Expand Down Expand Up @@ -76,4 +89,25 @@ describe('#visitElements', () => {
);
});
});

describe('add attribute tests', () => {
it('should handle single element', async () => {
runAddAttributeTest('<a></a>', '<a attr="val"></a>');
});

it('should handle multiple unnested', async () => {
runAddAttributeTest('<a></a><b></b>', '<a attr="val"></a><b attr="val"></b>');
});

it('should handle multiple nested', async () => {
runAddAttributeTest('<a><b></b></a>', '<a attr="val"><b attr="val"></b></a>');
});

it('should handle multiple nested and unnested', async () => {
runAddAttributeTest(
'<a><b></b><c></c></a>',
'<a attr="val"><b attr="val"></b><c attr="val"></c></a>',
);
});
});
});
Expand Up @@ -80,6 +80,27 @@ export function replaceEndTag(html: string, node: compiler.TmplAstElement, tag:
return replaceAt(html, node.endSourceSpan.start.offset + 2, node.name, tag);
}

/**
* Appends an attribute to the given node of the template html.
*
* @param html The template html to be updated.
* @param node The node to be updated.
* @param name The name of the attribute.
* @param value The value of the attribute.
* @returns The updated template html.
*/
export function addAttribute(
html: string,
node: compiler.TmplAstElement,
name: string,
value: string,
): string {
const index = node.startSourceSpan.start.offset + node.name.length + 1;
const prefix = html.slice(0, index);
const suffix = html.slice(index);
return prefix + ` ${name}="${value}"` + suffix;
}

/**
* Replaces a substring of a given string starting at some offset index.
*
Expand Down

0 comments on commit 801c23c

Please sign in to comment.