mapcomplete/UI/Base/Title.ts

67 lines
2.2 KiB
TypeScript
Raw Normal View History

import BaseUIElement from "../BaseUIElement";
2021-09-13 01:16:56 +02:00
import {FixedUiElement} from "./FixedUiElement";
import {Utils} from "../../Utils";
export default class Title extends BaseUIElement {
2021-11-25 22:16:00 +01:00
public readonly title: BaseUIElement;
public readonly level: number;
public readonly id : string
private static readonly defaultClassesPerLevel = ["", "text-3xl font-bold","text-2xl font-bold","text-xl font-bold", "text-lg font-bold"]
constructor(embedded: string | BaseUIElement, level: number = 3) {
super()
if(embedded === undefined){
throw "A title should have some content. Undefined is not allowed"
}
2021-11-07 16:34:51 +01:00
if (typeof embedded === "string") {
2021-11-25 22:16:00 +01:00
this.title = new FixedUiElement(embedded)
2021-11-07 16:34:51 +01:00
} else {
2021-11-25 22:16:00 +01:00
this.title = embedded
2021-09-13 01:16:56 +02:00
}
2021-11-25 22:16:00 +01:00
this.level = level;
2021-11-30 22:50:48 +01:00
let innerText : string = undefined;
if(typeof embedded === "string" ) {
innerText = embedded
}else if(embedded instanceof FixedUiElement){
innerText = embedded.content
}else{
if(Utils.runningFromConsole){
console.log("Not constructing an anchor for title with embedded content of "+embedded)
}else{
innerText = embedded.ConstructElement()?.innerText
}
2021-11-30 22:50:48 +01:00
}
this.id = innerText?.replace(/ /g, '-')
?.replace(/[?#.;:/]/, "")
?.toLowerCase() ?? ""
this.SetClass(Title.defaultClassesPerLevel[level] ?? "")
}
AsMarkdown(): string {
2021-11-25 22:16:00 +01:00
const embedded = " " + this.title.AsMarkdown() + " ";
2021-11-25 22:16:00 +01:00
if (this.level == 1) {
2021-11-08 02:36:01 +01:00
return "\n\n" + embedded + "\n" + "=".repeat(embedded.length) + "\n\n"
}
2021-11-25 22:16:00 +01:00
if (this.level == 2) {
2021-11-08 02:36:01 +01:00
return "\n\n" + embedded + "\n" + "-".repeat(embedded.length) + "\n\n"
}
2021-11-25 22:16:00 +01:00
return "\n\n" + "#".repeat(this.level) + embedded + "\n\n";
}
protected InnerConstructElement(): HTMLElement {
2021-11-25 22:16:00 +01:00
const el = this.title.ConstructElement()
if (el === undefined) {
return undefined;
}
2021-11-25 22:16:00 +01:00
const h = document.createElement("h" + this.level)
h.appendChild(el)
el.id = this.id
return h;
}
}