clickable-json
Version:
Interactive JSON and JSON CRDT viewer and editor
79 lines • 2.86 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueInput = void 0;
const React = require("react");
const nano_theme_1 = require("nano-theme");
const css = require("../css");
const utils_1 = require("./utils");
const flexible_input_1 = require("flexible-input");
const selectOnFocus_1 = require("../utils/selectOnFocus");
const ValueInput = (props) => {
const { value, onChange } = props;
const inputRef = React.useRef(null);
const theme = (0, nano_theme_1.useTheme)();
const json = React.useMemo(() => value === null
? 'null'
: typeof value === 'boolean'
? value
? 'true'
: 'false'
: typeof value === 'string'
? JSON.stringify(value)
: String(value), [value, theme]);
const [proposed, setProposed] = React.useState(json);
const [focused, setFocused] = React.useState(false);
React.useEffect(() => {
setProposed(json);
}, [json]);
const onSubmit = (e) => {
if (e)
e.preventDefault();
if (e)
e.stopPropagation();
let newValue;
try {
newValue = JSON.parse(proposed);
}
catch (_a) {
newValue = String(proposed);
}
if (onChange)
onChange(newValue);
};
const handleFocus = (e) => {
const input = e.target;
if (input.value === proposed)
(0, selectOnFocus_1.selectOnFocus)(input);
setFocused(true);
};
const handleBlur = () => {
setFocused(false);
};
const handleSubmit = (e) => {
if (inputRef.current)
inputRef.current.blur();
onSubmit(e);
};
const handleCancel = () => {
if (json !== proposed)
setProposed(json);
else if (inputRef.current)
inputRef.current.blur();
};
const handleTab = (e) => {
const ahead = (0, utils_1.typeahead)(proposed);
if (ahead) {
e.preventDefault();
setProposed(proposed + ahead);
}
};
return (React.createElement("span", { className: css.input, style: focused
? (0, utils_1.inputStyle)(theme, !theme.isLight, proposed)
: {
color: (0, utils_1.valueColor)(!theme.isLight, value),
background: (0, utils_1.valueBg)(value),
} },
React.createElement(flexible_input_1.FlexibleInput, { inp: (el) => (inputRef.current = el), value: focused ? proposed : json, typeahead: focused ? (0, utils_1.typeahead)(proposed) : '', onChange: (e) => setProposed(e.target.value), onFocus: handleFocus, onBlur: handleBlur, onSubmit: handleSubmit, onCancel: handleCancel, onTab: handleTab })));
};
exports.ValueInput = ValueInput;
//# sourceMappingURL=ValueInput.js.map
;