partey_workadventure/front/src/WebRtc/HtmlUtils.ts

75 lines
2.6 KiB
TypeScript
Raw Normal View History

export class HtmlUtils {
public static getElementByIdOrFail<T extends HTMLElement>(id: string): T {
const elem = document.getElementById(id);
2021-01-27 18:33:40 +01:00
if (HtmlUtils.isHtmlElement<T>(elem)) {
return elem;
}
throw new Error("Cannot find HTML element with id '" + id + "'");
}
2022-01-05 10:27:40 +01:00
public static getElementById<T extends HTMLElement>(id: string): T | undefined {
const elem = document.getElementById(id);
return HtmlUtils.isHtmlElement<T>(elem) ? elem : undefined;
}
public static querySelectorOrFail<T extends HTMLElement>(selector: string): T {
2021-01-28 21:07:17 +01:00
const elem = document.querySelector<T>(selector);
if (HtmlUtils.isHtmlElement<T>(elem)) {
return elem;
}
throw new Error("Cannot find HTML element with selector '" + selector + "'");
}
public static removeElementByIdOrFail<T extends HTMLElement>(id: string): T {
const elem = document.getElementById(id);
2021-01-27 18:33:40 +01:00
if (HtmlUtils.isHtmlElement<T>(elem)) {
elem.remove();
2021-01-28 15:31:09 +01:00
return elem;
}
throw new Error("Cannot find HTML element with id '" + id + "'");
}
public static escapeHtml(html: string): string {
const text = document.createTextNode(html);
const p = document.createElement("p");
p.appendChild(text);
return p.innerHTML;
2021-02-11 18:03:14 +01:00
}
public static urlify(text: string, style: string = ""): string {
const urlRegex = /(https?:\/\/[^\s]+)/g;
2021-02-11 18:03:14 +01:00
text = HtmlUtils.escapeHtml(text);
return text.replace(urlRegex, (url: string) => {
url = HtmlUtils.htmlDecode(url);
const link = document.createElement("a");
link.href = url;
link.target = "_blank";
const text = document.createTextNode(url);
link.appendChild(text);
link.setAttribute("style", style);
return link.outerHTML;
2021-02-11 14:49:32 +01:00
});
}
2021-01-27 18:33:40 +01:00
private static htmlDecode(input: string): string {
const doc = new DOMParser().parseFromString(input, "text/html");
const text = doc.documentElement.textContent;
if (text === null) {
throw new Error("Unexpected non parseable string");
}
return text;
}
public static isClickedInside(event: MouseEvent, target: HTMLElement): boolean {
return !!event.composedPath().find((et) => et === target);
}
public static isClickedOutside(event: MouseEvent, target: HTMLElement): boolean {
return !this.isClickedInside(event, target);
}
2021-01-27 18:33:40 +01:00
private static isHtmlElement<T extends HTMLElement>(elem: HTMLElement | null): elem is T {
2021-01-28 15:31:09 +01:00
return elem !== null;
2021-01-27 18:33:40 +01:00
}
}