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

Function appendHtmlElementToHead

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

Source from the content-addressed store, hash-verified

12
13/** Appends the given element HTML fragment to the `<head>` element of the specified HTML file. */
14export function appendHtmlElementToHead(host: Tree, htmlFilePath: string, elementHtml: string) {
15 const htmlFileBuffer = host.read(htmlFilePath);
16
17 if (!htmlFileBuffer) {
18 throw new SchematicsException(`Could not read file for path: ${htmlFilePath}`);
19 }
20
21 const htmlContent = htmlFileBuffer.toString();
22
23 if (htmlContent.includes(elementHtml)) {
24 return;
25 }
26
27 const headTag = getHtmlHeadTagElement(htmlContent);
28
29 if (!headTag) {
30 throw Error(`Could not find '<head>' element in HTML file: ${htmlFileBuffer}`);
31 }
32
33 // We always have access to the source code location here because the `getHeadTagElement`
34 // function explicitly has the `sourceCodeLocationInfo` option enabled.
35 const endTagOffset = headTag.sourceCodeLocation!.endTag!.startOffset;
36 const indentationOffset = getChildElementIndentation(headTag);
37 const insertion = `${' '.repeat(indentationOffset)}${elementHtml}`;
38
39 const recordedChange = host.beginUpdate(htmlFilePath).insertRight(endTagOffset, `${insertion}\n`);
40
41 host.commitUpdate(recordedChange);
42}
43
44/** Parses the given HTML file and returns the head element if available. */
45export function getHtmlHeadTagElement(htmlContent: string): Element | null {

Callers 1

addFontsToIndexFunction · 0.90

Calls 5

getHtmlHeadTagElementFunction · 0.85
readMethod · 0.80
toStringMethod · 0.80
insertRightMethod · 0.80

Tested by

no test coverage detected