mapcomplete/UI/Base/TabbedComponent.ts

53 lines
2.1 KiB
TypeScript
Raw Normal View History

2020-07-29 15:05:19 +02:00
import Translations from "../i18n/Translations";
import {UIEventSource} from "../../Logic/UIEventSource";
2021-06-10 01:36:20 +02:00
import Combine from "./Combine";
2021-06-12 02:58:32 +02:00
import BaseUIElement from "../BaseUIElement";
import {VariableUiElement} from "./VariableUIElement";
2020-07-29 15:05:19 +02:00
2021-06-12 02:58:32 +02:00
export class TabbedComponent extends Combine {
2020-07-29 15:05:19 +02:00
2021-11-07 16:34:51 +01:00
constructor(elements: { header: BaseUIElement | string, content: BaseUIElement | string }[],
openedTab: (UIEventSource<number> | number) = 0,
options?: {
leftOfHeader?: BaseUIElement
styleHeader?: (header: BaseUIElement) => void
}) {
2021-06-10 01:36:20 +02:00
2021-06-12 02:58:32 +02:00
const openedTabSrc = typeof (openedTab) === "number" ? new UIEventSource(openedTab) : (openedTab ?? new UIEventSource<number>(0))
2021-11-07 16:34:51 +01:00
const tabs: BaseUIElement[] = [options?.leftOfHeader]
2021-06-12 02:58:32 +02:00
const contentElements: BaseUIElement[] = [];
2020-07-29 15:05:19 +02:00
for (let i = 0; i < elements.length; i++) {
let element = elements[i];
2021-06-12 02:58:32 +02:00
const header = Translations.W(element.header).onClick(() => openedTabSrc.setData(i))
2021-06-14 19:21:33 +02:00
openedTabSrc.addCallbackAndRun(selected => {
2021-11-07 16:34:51 +01:00
if (selected >= elements.length) {
selected = 0
}
if (selected === i) {
2021-06-14 19:21:33 +02:00
header.SetClass("tab-active")
header.RemoveClass("tab-non-active")
} else {
2021-06-14 19:21:33 +02:00
header.SetClass("tab-non-active")
header.RemoveClass("tab-active")
}
})
2020-09-12 23:15:17 +02:00
const content = Translations.W(element.content)
content.SetClass("relative w-full inline-block")
2021-06-12 02:58:32 +02:00
contentElements.push(content);
const tab = header.SetClass("block tab-single-header")
tabs.push(tab)
2020-07-29 15:05:19 +02:00
}
const header = new Combine(tabs).SetClass("tabs-header-bar")
2021-11-07 16:34:51 +01:00
if (options?.styleHeader) {
options.styleHeader(header)
}
2021-06-12 02:58:32 +02:00
const actualContent = new VariableUiElement(
openedTabSrc.map(i => contentElements[i])
).SetStyle("max-height: inherit; height: inherit")
2021-06-12 02:58:32 +02:00
super([header, actualContent])
2020-07-29 15:05:19 +02:00
}
2020-07-29 15:05:19 +02:00
}