(host: Tree, htmlFilePath: string, elementHtml: string)
| 12 | |
| 13 | /** Appends the given element HTML fragment to the `<head>` element of the specified HTML file. */ |
| 14 | export 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. */ |
| 45 | export function getHtmlHeadTagElement(htmlContent: string): Element | null { |
no test coverage detected