Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add checkbox toggle for boolean values #19714

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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>
);
}