Skip to content

Instantly share code, notes, and snippets.

@devinrhode2
Created May 1, 2023 21:47
Show Gist options
  • Save devinrhode2/bf68cc8a284368d882c6be5d5ddd728a to your computer and use it in GitHub Desktop.
Save devinrhode2/bf68cc8a284368d882c6be5d5ddd728a to your computer and use it in GitHub Desktop.
type asdf = HTMLElement;
const validateElement = <
// eslint-disable-next-line @typescript-eslint/ban-types
TInstanceType extends Element,
>(
node: Element | null,
{
nodeNickname,
tagName,
instanceType,
}: {
nodeNickname: string;
tagName: 'head' | 'body';
instanceType: TInstanceType;
},
): node is TInstanceType => {
if (!node) {
throw new Error(`No ${nodeNickname} in html`);
}
if (node.tagName.toLowerCase() !== tagName.toLowerCase()) {
throw new Error(
`${nodeNickname} is not a <${tagName}> tag.`,
);
}
if (!(node instanceof instanceType)) {
throw new Error(
`node is not an instanceof ${instanceType.name}`,
);
}
return true;
};
export const getPrimaryHtmlNodes = (
html: string,
): {
headNode: HTMLHeadElement;
bodyNode: HTMLBodyElement;
} => {
const fullDoc = document.createElement('html');
fullDoc.innerHTML = html;
// TODO: use something better than `firstElementChild` to find `head`?
const headNode = fullDoc.firstElementChild;
if (
validateElement(headNode, {
nodeNickname: 'firstElementChild',
tagName: 'head',
instanceType: HTMLHeadElement,
})
) {
}
if (!headNode) {
throw new Error('No firstElementChild in html');
}
if (
// TODO: use something better than `firstElementChild` to find `head`?
headNode.tagName.toLowerCase() !== 'head'
) {
throw new Error(
'firstElementChild is not a <head> tag. Maybe this is an unhandled browser bug?',
);
}
if (!(headNode instanceof HTMLHeadElement)) {
throw new Error(
'headNode is not an instanceof HTMLHeadElement',
);
}
const bodyNode = fullDoc.lastElementChild;
if (!bodyNode) {
throw new Error('No lastElementChild in html');
}
if (
// TODO: use something better than `lastElementChild` to find `body`
bodyNode.tagName.toLowerCase() !== 'body'
) {
throw new Error(
'lastElementChild is not a <body> tag. Maybe this is an unhandled browser bug?',
);
}
if (!(bodyNode instanceof HTMLBodyElement)) {
throw new Error(
'bodyNode is not an instanceof HTMLBodyElement',
);
}
return { headNode, bodyNode };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment