1// Copyright (C) 2023 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 {classNames} from '../classnames'; 17 18export interface SwitchAttrs { 19 // Optional text to show to the right of the switch. 20 // If omitted, no text will be shown. 21 label?: string; 22 // Whether the switch is checked or not. 23 // If omitted, the switch will be uncontrolled. 24 checked?: boolean; 25 // Make the switch appear greyed out block any interaction with it. 26 // No events will be fired when interacting with it. 27 // Defaults to false. 28 disabled?: boolean; 29 // Remaining attributes forwarded to the underlying HTML <label>. 30 [htmlAttrs: string]: any; 31} 32 33export class Switch implements m.ClassComponent<SwitchAttrs> { 34 view({attrs}: m.CVnode<SwitchAttrs>) { 35 const {label, checked, disabled = false, ...htmlAttrs} = attrs; 36 37 const classes = classNames( 38 disabled && 'pf-disabled', 39 ); 40 41 // The default checkbox is removed and an entirely new one created inside 42 // the span element in CSS. 43 return m( 44 'label.pf-switch', 45 {class: classes, ...htmlAttrs}, 46 m('input[type=checkbox]', {disabled, checked}), 47 m('span'), 48 label, 49 ); 50 } 51} 52