Skip to content

Commit

Permalink
don't rely on json-markup for non-json strings
Browse files Browse the repository at this point in the history
  • Loading branch information
smanolloff committed May 25, 2020
1 parent 3335512 commit 8ba12a1
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ describe('<KeyValuesTable>', () => {
expect(el.length).toBe(data.length);
el.forEach((valueDiv, i) => {
if (data[i].key !== 'jsonkey') {
expect(valueDiv.html()).toMatch(`"${data[i].value}"`);
expect(valueDiv.text()).toBe(data[i].value);
}
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,47 @@ import './KeyValuesTable.css';

const jsonObjectOrArrayStartRegex = /^(\[|\{)/;

function parseIfComplexJson(value: any) {
function tryParseJson(value: string) {
try {
return JSON.parse(value)
} catch (_) {
return value;
}
}

const stringMarkup = (value: string) => (
<div className="json-markup">
<span className="json-markup-string">{value}</span>
</div>
)

function _jsonMarkup(value: any) {
const markup = { __html: jsonMarkup(value) };

return (
// eslint-disable-next-line react/no-danger
<div dangerouslySetInnerHTML={markup} />
);
}

function formatValue(value: any) {
let content;

// if the value is a string representing actual json object or array, then use json-markup
if (typeof value === 'string' && jsonObjectOrArrayStartRegex.test(value)) {
if (typeof value === 'string') {
// otherwise just return as is
try {
return JSON.parse(value);
// eslint-disable-next-line no-empty
} catch (_) {}
content = jsonObjectOrArrayStartRegex.test(value)
? _jsonMarkup(tryParseJson(value))
: stringMarkup(value);
} else {
content = _jsonMarkup(value)
}
return value;

return (
<div className="ub-inline-block">
{content}
</div>
)
}

export const LinkValue = (props: { href: string; title?: string; children: React.ReactNode }) => (
Expand Down Expand Up @@ -71,11 +102,7 @@ export default function KeyValuesTable(props: KeyValuesTableProps) {
<table className="u-width-100">
<tbody className="KeyValueTable--body">
{data.map((row, i) => {
const markup = {
__html: jsonMarkup(parseIfComplexJson(row.value)),
};
// eslint-disable-next-line react/no-danger
const jsonTable = <div className="ub-inline-block" dangerouslySetInnerHTML={markup} />;
const jsonTable = formatValue(row.value);
const links = linksGetter ? linksGetter(data, i) : null;
let valueMarkup;
if (links && links.length === 1) {
Expand Down

0 comments on commit 8ba12a1

Please sign in to comment.