1// Copyright (C) 2024 The Android Open Source Project 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15import m from 'mithril'; 16import {ProbeSetting} from '../../config/config_interfaces'; 17 18export interface ToggleAttrs { 19 title: string; 20 descr?: string; 21 default?: boolean; 22 cssClass?: string; 23 onChange?: (enabled: boolean) => void; 24} 25 26export class Toggle implements ProbeSetting { 27 private _enabled: boolean; 28 29 constructor(readonly attrs: ToggleAttrs) { 30 this._enabled = this.setEnabled(undefined); 31 } 32 33 setEnabled(enabled: boolean | undefined) { 34 this._enabled = enabled ?? this.attrs.default ?? false; 35 return this._enabled; 36 } 37 38 get enabled(): boolean { 39 return this._enabled; 40 } 41 42 serialize() { 43 return this._enabled; 44 } 45 46 deserialize(state: unknown): void { 47 if (state === true || state === false) { 48 this._enabled = state; 49 } 50 } 51 52 render() { 53 return m( 54 `.toggle${this._enabled ? '.enabled' : ''}${this.attrs.cssClass ?? ''}`, 55 m( 56 'label', 57 m(`input[type=checkbox]`, { 58 checked: this._enabled, 59 oninput: (e: InputEvent) => { 60 this.setEnabled((e.target as HTMLInputElement).checked); 61 this.attrs.onChange?.(this._enabled); 62 }, 63 }), 64 m('span', this.attrs.title), 65 ), 66 m('.descr', this.attrs.descr), 67 ); 68 } 69} 70