All files / js/widgets BooleanInputWidget.tsx

10.53% Statements 2/19
0% Branches 0/13
0% Functions 0/5
12.5% Lines 2/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 561x   1x                                                                                                          
import React, { ChangeEvent, createRef, RefObject } from "react";
import { WidgetProps } from "./types";
import { trans_obj } from "../i18n";
 
function isTrue(value?: string) {
  return value === "true" || value === "yes" || value === "1";
}
 
export class BooleanInputWidget extends React.Component<WidgetProps, unknown> {
  checkbox: RefObject<HTMLInputElement>;
 
  constructor(props: WidgetProps) {
    super(props);
    this.checkbox = createRef();
    this.onChange = this.onChange.bind(this);
  }
 
  onChange(event: ChangeEvent<HTMLInputElement>) {
    this.props.onChange(event.target.checked ? "yes" : "no");
  }
 
  componentDidMount() {
    const checkbox = this.checkbox.current;
    if (checkbox) {
      if (!this.props.value && this.props.placeholder) {
        checkbox.indeterminate = true;
        checkbox.checked = isTrue(this.props.placeholder);
      } else {
        checkbox.indeterminate = false;
      }
    }
  }
 
  render() {
    const { type, value, disabled } = this.props;
 
    return (
      <div className="form-check">
        <label className="form-check-label">
          <input
            type="checkbox"
            className="form-check-input"
            disabled={disabled}
            ref={this.checkbox}
            checked={isTrue(value)}
            onChange={this.onChange}
          />
          {type.checkbox_label_i18n
            ? trans_obj(type.checkbox_label_i18n)
            : null}
        </label>
      </div>
    );
  }
}