mapcomplete/UI/Input/Toggle.ts

40 lines
1.3 KiB
TypeScript
Raw Normal View History

2021-06-10 01:36:20 +02:00
import {UIEventSource} from "../../Logic/UIEventSource";
import BaseUIElement from "../BaseUIElement";
import {VariableUiElement} from "../Base/VariableUIElement";
import Lazy from "../Base/Lazy";
2021-06-10 01:36:20 +02:00
/**
* The 'Toggle' is a UIElement showing either one of two elements, depending on the state.
* It can be used to implement e.g. checkboxes or collapsible elements
*/
export default class Toggle extends VariableUiElement {
2021-06-10 01:36:20 +02:00
public readonly isEnabled: UIEventSource<boolean>;
2021-06-12 02:58:32 +02:00
constructor(showEnabled: string | BaseUIElement, showDisabled: string | BaseUIElement, isEnabled: UIEventSource<boolean> = new UIEventSource<boolean>(false)) {
2021-06-10 01:36:20 +02:00
super(
2021-06-12 02:58:32 +02:00
isEnabled.map(isEnabled => isEnabled ? showEnabled : showDisabled)
2021-06-10 01:36:20 +02:00
);
2021-06-12 02:58:32 +02:00
this.isEnabled = isEnabled
2021-06-14 02:39:23 +02:00
}
public ToggleOnClick(): Toggle {
2021-06-14 02:39:23 +02:00
const self = this;
2021-06-10 01:36:20 +02:00
this.onClick(() => {
self.isEnabled.setData(!self.isEnabled.data);
2021-06-10 01:36:20 +02:00
})
2021-06-14 02:39:23 +02:00
return this;
2021-06-10 01:36:20 +02:00
}
public static If(condition: UIEventSource<boolean>, constructor: () => BaseUIElement): BaseUIElement {
if(constructor === undefined){
return undefined
}
return new Toggle(
new Lazy(constructor),
undefined,
condition
)
}
2021-06-10 01:36:20 +02:00
}