make VariablesInput detect whether value is JSON or YAML on init

This commit is contained in:
Keith Grant 2019-06-28 14:48:40 -07:00
parent 968cc8c79c
commit da780c9d7c
4 changed files with 44 additions and 7 deletions

View File

@ -3,7 +3,7 @@ import { string, func, bool, number } from 'prop-types';
import { Button, Split, SplitItem } from '@patternfly/react-core';
import styled from 'styled-components';
import ButtonGroup from '@components/ButtonGroup';
import { yamlToJson, jsonToYaml } from '@util/yaml';
import { yamlToJson, jsonToYaml, isJson } from '@util/yaml';
import CodeMirrorInput from './CodeMirrorInput';
const YAML_MODE = 'yaml';
@ -15,8 +15,19 @@ const SmallButton = styled(Button)`
`;
function VariablesInput (props) {
const { id, label, value, readOnly, rows, error, onChange, onError, className } = props;
const [mode, setMode] = useState(YAML_MODE);
const { id, label, readOnly, rows, error, onError, className } = props;
// eslint-disable-next-line react/destructuring-assignment
const [value, setValue] = useState(props.value);
const [mode, setMode] = useState(isJson(value) ? JSON_MODE : YAML_MODE);
// eslint-disable-next-line react/destructuring-assignment
const isControlled = !!props.onChange;
const onChange = (newValue) => {
if (isControlled) {
props.onChange(newValue);
}
setValue(newValue);
};
return (
<div className={`pf-c-form__group ${className || ''}`}>
@ -88,7 +99,7 @@ VariablesInput.propTypes = {
};
VariablesInput.defaultProps = {
readOnly: false,
onChange: () => {},
onChange: null,
rows: 6,
error: null,
onError: () => {},

View File

@ -14,9 +14,13 @@ export function ucFirst(str) {
return `${str[0].toUpperCase()}${str.substr(1)}`;
}
export const toTitleCase = string =>
string
export const toTitleCase = string => {
if (!string) {
return '';
}
return string
.toLowerCase()
.split('_')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
};

View File

@ -1,4 +1,4 @@
import { pluralize, getArticle, ucFirst } from './strings';
import { pluralize, getArticle, ucFirst, toTitleCase } from './strings';
describe('string utils', () => {
describe('pluralize', () => {
@ -31,4 +31,14 @@ describe('string utils', () => {
expect(ucFirst('team')).toEqual('Team');
});
});
describe('toTitleCase', () => {
test('should upper case each word', () => {
expect(toTitleCase('a_string_of_words')).toEqual('A String Of Words');
});
test('should return empty string for undefined', () => {
expect(toTitleCase(undefined)).toEqual('');
});
});
});

View File

@ -21,3 +21,15 @@ export function jsonToYaml(jsonString) {
}
return yaml.safeDump(value);
}
export function isJson (jsonString) {
if (typeof jsonString !== 'string') { return false; }
let value;
try {
value = JSON.parse(jsonString);
} catch (e) {
return false;
}
return typeof value === 'object' && value !== null;
}