Add checkbox toggle for boolean values (#19714)

* added a checkbox which appears to the right of a value when value is boolean
* checkbox with toggle capability created for boolean props

Co-authored-by: Brian Vaughn <brian.david.vaughn@gmail.com>
This commit is contained in:
Meghnath Pillay 2020-09-03 18:27:12 +05:30 committed by GitHub
parent 99cae887f3
commit 835c11eba7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 13 deletions

View File

@ -1,13 +1,7 @@
.CheckboxLabel {
flex: 1 1 100%;
display: flex;
}
.CheckboxLabel:focus-within {
background-color: var(--color-button-background-focus);
}
.Checkbox:focus {
outline: none;
.Checkbox {
flex: 0 0 auto;
align-self: center;
margin: 0 0.25rem;
}
.Input {

View File

@ -8,7 +8,7 @@
*/
import * as React from 'react';
import {Fragment, useRef} from 'react';
import {Fragment} from 'react';
import styles from './EditableValue.css';
import {useEditableValue} from '../hooks';
@ -27,7 +27,6 @@ export default function EditableValue({
path,
value,
}: EditableValueProps) {
const inputRef = useRef<HTMLInputElement | null>(null);
const [state, dispatch] = useEditableValue(value);
const {editableValue, hasPendingChanges, isValid, parsedValue} = state;
@ -44,6 +43,21 @@ export default function EditableValue({
externalValue: value,
});
const handleCheckBoxToggle = ({target}) => {
dispatch({
type: 'UPDATE',
editableValue: target.checked,
externalValue: value,
});
// Unlike <input type="text"> which has both an onChange and an onBlur,
// <input type="checkbox"> updates state *and* applies changes in a single event.
// So we read from target.checked rather than parsedValue (which has not yet updated).
// We also don't check isValid (because that hasn't changed yet either);
// we don't need to check it anyway, since target.checked is always a boolean.
overrideValueFn(path, target.checked);
};
const handleKeyDown = event => {
// Prevent keydown events from e.g. change selected element in the tree
event.stopPropagation();
@ -73,6 +87,8 @@ export default function EditableValue({
placeholder = 'Enter valid JSON';
}
const isBool = parsedValue === true || parsedValue === false;
return (
<Fragment>
<input
@ -82,10 +98,17 @@ export default function EditableValue({
onChange={handleChange}
onKeyDown={handleKeyDown}
placeholder={placeholder}
ref={inputRef}
type="text"
value={editableValue}
/>
{isBool && (
<input
className={styles.Checkbox}
checked={parsedValue}
type="checkbox"
onChange={handleCheckBoxToggle}
/>
)}
</Fragment>
);
}