mapcomplete/UI/Base/SubtleButton.ts

72 lines
2.1 KiB
TypeScript
Raw Normal View History

2022-09-08 21:40:48 +02:00
import BaseUIElement from "../BaseUIElement"
import { Store, UIEventSource } from "../../Logic/UIEventSource"
import { UIElement } from "../UIElement"
import { VariableUiElement } from "./VariableUIElement"
import Lazy from "./Lazy"
import Loading from "./Loading"
2023-01-17 18:31:51 +01:00
import SubtleButtonSvelte from "./SubtleButton.svelte"
import SvelteUIElement from "./SvelteUIElement"
2021-06-12 02:58:32 +02:00
export class SubtleButton extends UIElement {
2022-09-08 21:40:48 +02:00
private readonly imageUrl: string | BaseUIElement
private readonly message: string | BaseUIElement
private readonly options: {
url?: string | Store<string>
newTab?: boolean
2023-03-09 23:19:49 +01:00
imgSize?: string
extraClasses?: string
}
2021-05-30 00:17:31 +02:00
2022-09-08 21:40:48 +02:00
constructor(
imageUrl: string | BaseUIElement,
message: string | BaseUIElement,
options: {
url?: string | Store<string>
newTab?: boolean
2023-03-09 23:19:49 +01:00
imgSize?: "h-11 w-11" | string
extraClasses?: string
2023-01-17 18:31:51 +01:00
} = {}
2022-09-08 21:40:48 +02:00
) {
super()
this.imageUrl = imageUrl
this.message = message
this.options = options
2021-05-30 00:17:31 +02:00
}
protected InnerRender(): string | BaseUIElement {
2023-01-17 18:31:51 +01:00
return new SvelteUIElement(SubtleButtonSvelte, {
imageUrl: this?.imageUrl ?? undefined,
message: this?.message ?? "",
options: this?.options ?? {},
})
}
public OnClickWithLoading(
loadingText: BaseUIElement | string,
2022-09-08 21:40:48 +02:00
action: () => Promise<void>
): BaseUIElement {
const state = new UIEventSource<"idle" | "running">("idle")
2022-09-08 21:40:48 +02:00
const button = this
button.onClick(async () => {
state.setData("running")
2022-09-08 21:40:48 +02:00
try {
await action()
} catch (e) {
console.error(e)
2022-09-08 21:40:48 +02:00
} finally {
state.setData("idle")
}
})
2022-09-08 21:40:48 +02:00
const loading = new Lazy(() => new Loading(loadingText))
2022-11-02 14:44:06 +01:00
return new VariableUiElement(
state.map((st) => {
if (st === "idle") {
return button
}
return loading
})
)
}
2022-09-08 21:40:48 +02:00
}