MCPcopy Create free account
hub / github.com/angular/components / addBodyClass

Function addBodyClass

src/cdk/schematics/utils/html-manipulation.ts:50–87  ·  view source on GitHub ↗
(host: Tree, htmlFilePath: string, className: string)

Source from the content-addressed store, hash-verified

48
49/** Adds a class to the body of the document. */
50export function addBodyClass(host: Tree, htmlFilePath: string, className: string): void {
51 const htmlFileBuffer = host.read(htmlFilePath);
52
53 if (!htmlFileBuffer) {
54 throw new SchematicsException(`Could not read file for path: ${htmlFilePath}`);
55 }
56
57 const htmlContent = htmlFileBuffer.toString();
58 const body = getElementByTagName('body', htmlContent);
59
60 if (!body) {
61 throw Error(`Could not find <body> element in HTML file: ${htmlFileBuffer}`);
62 }
63
64 const classAttribute = body.attrs.find(attribute => attribute.name === 'class');
65
66 if (classAttribute) {
67 const hasClass = classAttribute.value
68 .split(' ')
69 .map(part => part.trim())
70 .includes(className);
71
72 if (!hasClass) {
73 // We have source code location info enabled, and we pre-checked that the element
74 // has attributes, specifically the `class` attribute.
75 const classAttributeLocation = body.sourceCodeLocation!.attrs!['class'];
76 const recordedChange = host
77 .beginUpdate(htmlFilePath)
78 .insertRight(classAttributeLocation.endOffset - 1, ` ${className}`);
79 host.commitUpdate(recordedChange);
80 }
81 } else {
82 const recordedChange = host
83 .beginUpdate(htmlFilePath)
84 .insertRight(body.sourceCodeLocation!.startTag!.endOffset - 1, ` class="${className}"`);
85 host.commitUpdate(recordedChange);
86 }
87}
88
89/** Finds an element by its tag name. */
90function getElementByTagName(tagName: string, htmlContent: string): Element | null {

Callers

nothing calls this directly

Calls 4

getElementByTagNameFunction · 0.85
readMethod · 0.80
toStringMethod · 0.80
insertRightMethod · 0.80

Tested by

no test coverage detected