mapcomplete/UI/Base/Img.ts

70 lines
2 KiB
TypeScript
Raw Normal View History

2021-01-06 02:21:50 +01:00
import {Utils} from "../../Utils";
2021-06-10 01:36:20 +02:00
import BaseUIElement from "../BaseUIElement";
2021-01-06 02:21:50 +01:00
2021-06-10 01:36:20 +02:00
export default class Img extends BaseUIElement {
private _src: string;
private readonly _rawSvg: boolean;
private _options: { fallbackImage?: string };
constructor(src: string, rawSvg = false, options?: {
fallbackImage?: string
}) {
2021-06-10 01:36:20 +02:00
super();
2021-11-07 16:34:51 +01:00
if (src === undefined || src === "undefined") {
throw "Undefined src for image"
}
2021-06-10 01:36:20 +02:00
this._src = src;
this._rawSvg = rawSvg;
this._options = options;
2021-06-10 01:36:20 +02:00
}
2021-06-10 01:36:20 +02:00
static AsData(source: string) {
if (Utils.runningFromConsole) {
return source;
}
return `data:image/svg+xml;base64,${(btoa(source))}`;
}
2021-06-10 01:36:20 +02:00
static AsImageElement(source: string, css_class: string = "", style = ""): string {
2021-02-20 03:29:55 +01:00
return `<img class="${css_class}" style="${style}" alt="" src="${Img.AsData(source)}">`;
2020-11-05 12:28:02 +01:00
}
2021-06-10 01:36:20 +02:00
2022-01-26 21:40:38 +01:00
AsMarkdown(): string {
if (this._rawSvg === true) {
console.warn("Converting raw svgs to markdown is not supported");
return undefined
}
let src = this._src
if (this._src.startsWith("./")) {
src = "https://mapcomplete.osm.be/" + src
}
return "![](" + src + ")";
}
2021-06-10 01:36:20 +02:00
protected InnerConstructElement(): HTMLElement {
const self = this;
if (this._rawSvg) {
const e = document.createElement("div")
e.innerHTML = this._src
return e;
}
2021-06-10 01:36:20 +02:00
const el = document.createElement("img")
el.src = this._src;
2021-06-12 02:58:32 +02:00
el.onload = () => {
el.style.opacity = "1"
}
el.onerror = () => {
if (self._options?.fallbackImage) {
2021-11-07 16:34:51 +01:00
if (el.src === self._options.fallbackImage) {
// Sigh... nothing to be done anymore
return;
}
el.src = self._options.fallbackImage
}
}
2021-06-10 01:36:20 +02:00
return el;
}
}