mapcomplete/UI/Base/Img.ts

77 lines
2.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 {
2022-07-26 09:56:07 +02:00
private readonly _src: string;
private readonly _rawSvg: boolean;
2022-07-26 09:56:07 +02:00
private readonly _options: { readonly 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;
}
2022-07-26 11:26:27 +02:00
try{
return `data:image/svg+xml;base64,${(btoa(source))}`;
}catch (e){
console.error("Cannot create an image for", source.slice(0, 100))
console.trace("Cannot create an image for the given source string due to ", e)
return ""
}
2021-06-10 01:36:20 +02:00
}
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;
}
}