workadventure/front/src/WebRtc/HtmlUtils.ts

46 lines
1.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)) {
2021-01-28 15:31:09 +01:00
return elem;
}
2021-01-27 18:33:40 +01:00
throw new Error("Cannot find HTML element with id '"+id+"'");
}
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;
}
2021-01-28 21:07:17 +01:00
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;
}
2021-01-27 18:33:40 +01:00
throw new Error("Cannot find HTML element with id '"+id+"'");
}
2021-02-11 14:49:32 +01:00
public static urlify(text: string): HTMLSpanElement {
const textReturn : HTMLSpanElement = document.createElement('span');
textReturn.innerText = text;
const urlRegex = /(https?:\/\/[^\s]+)/g;
2021-02-11 14:49:32 +01:00
text.replace(urlRegex, (url: string) => {
2021-02-11 15:06:12 +01:00
const link : HTMLAnchorElement = document.createElement('a');
2021-02-11 14:49:32 +01:00
link.innerText = ` ${url}`;
link.href = url;
link.target = '_blank';
textReturn.append(link);
return url;
});
return textReturn;
}
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
}
}