Skip to content

Commit

Permalink
Add checkbox toggle for boolean values (facebook#19714)
Browse files Browse the repository at this point in the history
* 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 <[email protected]>
  • Loading branch information
2 people authored and koto committed Jun 15, 2021
1 parent 2e35b61 commit 541aad7
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 13 deletions.
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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;

Expand All @@ -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();
Expand Down Expand Up @@ -73,6 +87,8 @@ export default function EditableValue({
placeholder = 'Enter valid JSON';
}

const isBool = parsedValue === true || parsedValue === false;

return (
<Fragment>
<input
Expand All @@ -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>
);
}

0 comments on commit 541aad7

Please sign in to comment.