Skip to content

A games launcher for GOG, Amazon and Epic Games for Linux, Windows and macOS.

1.8 KB
Raw Blame
import classNames from 'classnames'
import { ChangeEventHandler, ReactNode, useEffect, useRef } from 'react'
import InfoTooltip from '../InfoTooltip'
import SettingRow from '../SettingRow'
import './index.css'

interface Props {
  htmlId: string
  handleChange: ChangeEventHandler<HTMLInputElement>
  value: unknown
  title: string
  disabled?: boolean
  extraClass?: string
  description?: string
  info?: ReactNode
  fading?: boolean
  // Shows the mixed state of a checkbox that controls a list of items.
  indeterminate?: boolean
}

export default function ToggleSwitch({
  handleChange,
  value,
  disabled,
  title,
  htmlId,
  extraClass,
  description,
  info,
  fading,
  indeterminate = false
}: Props) {
  const inputRef = useRef<HTMLInputElement>(null)
  const infoAsDescription = !description && info

  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.indeterminate = indeterminate
    }
  }, [indeterminate])

  return (
    <SettingRow
      label={title}
      labelAfter={
        !infoAsDescription &&
        info && <InfoTooltip content={info} label={title} />
      }
      description={infoAsDescription ? info : description}
      htmlFor={htmlId}
      className={classNames('ToggleSwitch', extraClass, {
        'ToggleSwitch--disabled': disabled,
        fading
      })}
    >
      <input
        ref={inputRef}
        id={htmlId}
        disabled={disabled}
        checked={Boolean(value)}
        type="checkbox"
        onChange={handleChange}
        aria-label={title}
        aria-checked={indeterminate ? 'mixed' : undefined}
        className="ToggleSwitch__input hiddenCheckbox"
      />
      <label className="ToggleSwitch__track" htmlFor={htmlId} tabIndex={-1}>
        <span className="ToggleSwitch__thumb" />
      </label>
    </SettingRow>
  )
}