File size: 2,226 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { FormLabel } from '@automattic/components';
import { useCallback, useRef } from 'react';
import * as React from 'react';
import FormInputCheckbox from 'calypso/components/forms/form-checkbox';

import './style.scss';

// eslint-disable-next-line @typescript-eslint/no-empty-function
const noop = () => {};

type OptionValue = number | string;

interface Option< T = OptionValue > {
	value: T;
	label: string;
}

export interface ChangeList< T = OptionValue > {
	value: T[];
}

interface Props< T = OptionValue > {
	options: Option< T >[];
	checked?: T[];
	defaultChecked?: T[];
	onChange?: ( list: ChangeList< T > ) => void;
	disabled?: boolean;
	name?: string;
}

type DivProps = Omit< React.ComponentPropsWithoutRef< 'div' >, 'className' >;

export default function MultiCheckbox< T extends string | number >( props: Props< T > & DivProps ) {
	const {
		checked,
		defaultChecked = [],
		disabled = false,
		onChange = noop,
		name = 'multiCheckbox',
		options,
		...otherProps
	} = props;

	// Used to store the initial value of the `defaultChecked` prop. Never updated.
	// This is done to avoid changing the active items if the defaults change after the initial render.
	const defaultCheckedOnStart = useRef( defaultChecked );

	const handleChange = useCallback(
		( event: React.ChangeEvent< HTMLInputElement > ) => {
			const target = event.target;
			let changeEventValue = checked || defaultCheckedOnStart.current;
			changeEventValue = changeEventValue
				.concat( [ target.value as T ] )
				.filter( ( currentValue ) => {
					return currentValue !== target.value || target.checked;
				} );

			if ( onChange ) {
				onChange( { value: changeEventValue } );
			}

			event.stopPropagation();
		},
		[ checked, onChange ]
	);

	const checkedItems = checked || defaultCheckedOnStart.current;
	return (
		<div className="multi-checkbox" { ...otherProps }>
			{ options.map( ( option ) => (
				<FormLabel key={ option.value }>
					<FormInputCheckbox
						name={ name + '[]' }
						value={ option.value }
						checked={ checkedItems.includes( option.value ) }
						onChange={ handleChange }
						disabled={ disabled }
					/>
					<span>{ option.label }</span>
				</FormLabel>
			) ) }
		</div>
	);
}