fix: improve JSON comparison error reporting and add line numbers

This commit is contained in:
Bhavesh Kshatriya
2025-07-16 00:45:31 +05:30
parent 2c5972023f
commit 91d743bafc
3 changed files with 150 additions and 15 deletions

View File

@@ -0,0 +1,127 @@
import { Box, styled, TextField } from '@mui/material';
import React, { useContext, useRef } from 'react';
import { CustomSnackBarContext } from '../../contexts/CustomSnackBarContext';
import InputHeader from '../InputHeader';
import InputFooter from './InputFooter';
import { useTranslation } from 'react-i18next';
const LineNumberWrapper = styled(Box)(({ theme }) => ({
position: 'relative',
display: 'flex',
backgroundColor: theme.palette.background.paper,
'.line-numbers': {
whiteSpace: 'pre',
position: 'absolute',
left: 0,
top: 0,
bottom: 0,
width: '40px',
backgroundColor: theme.palette.action.hover,
borderRight: `1px solid ${theme.palette.divider}`,
textAlign: 'right',
paddingRight: '8px',
paddingTop: '16px', // Align with TextField content
paddingBottom: '8px',
color: theme.palette.text.secondary,
userSelect: 'none',
fontSize: '14px',
lineHeight: '1.5em',
fontFamily: 'monospace',
zIndex: 1,
overflow: 'hidden'
},
'.MuiTextField-root': {
position: 'relative',
'& .MuiInputBase-root': {
paddingLeft: '48px',
fontFamily: 'monospace',
fontSize: '14px',
lineHeight: '1.5em'
},
'& .MuiInputBase-input': {
lineHeight: '1.5em'
}
}
}));
export default function LineNumberInput({
value,
onChange,
title = 'Input text',
placeholder
}: {
title?: string;
value: string;
onChange: (value: string) => void;
placeholder?: string;
}) {
const { t } = useTranslation();
const { showSnackBar } = useContext(CustomSnackBarContext);
const fileInputRef = useRef<HTMLInputElement>(null);
const handleCopy = () => {
navigator.clipboard
.writeText(value)
.then(() => showSnackBar(t('toolTextInput.copied'), 'success'))
.catch((err) => {
showSnackBar(t('toolTextInput.copyFailed', { error: err }), 'error');
});
};
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
const reader = new FileReader();
reader.onload = (e) => {
const text = e.target?.result;
if (typeof text === 'string') {
onChange(text);
}
};
reader.readAsText(file);
}
};
const handleImportClick = () => {
fileInputRef.current?.click();
};
// Generate line numbers based on the content
const lineCount = value.split('\n').length;
const lineNumbers = Array.from({ length: lineCount }, (_, i) => i + 1).join(
'\n'
);
return (
<Box>
<InputHeader title={title || t('toolTextInput.input')} />
<LineNumberWrapper>
<pre className="line-numbers">{lineNumbers}</pre>
<TextField
value={value}
onChange={(event) => onChange(event.target.value)}
fullWidth
multiline
rows={10}
placeholder={placeholder || t('toolTextInput.placeholder')}
sx={{
'&.MuiTextField-root': {
backgroundColor: 'background.paper'
}
}}
inputProps={{
'data-testid': 'text-input'
}}
/>
</LineNumberWrapper>
<InputFooter handleCopy={handleCopy} handleImport={handleImportClick} />
<input
type="file"
accept="*"
ref={fileInputRef}
style={{ display: 'none' }}
onChange={handleFileChange}
/>
</Box>
);
}

View File

@@ -1,6 +1,6 @@
import { useState, useEffect } from 'react';
import ToolContent from '@components/ToolContent';
import ToolTextInput from '@components/input/ToolTextInput';
import LineNumberInput from '@components/input/LineNumberInput';
import ToolTextResult from '@components/result/ToolTextResult';
import { compareJson } from './service';
import { CardExampleType } from '@components/examples/ToolExamples';
@@ -122,7 +122,7 @@ export default function JsonComparison({ title }: ToolComponentProps) {
<StyledGrid container spacing={2}>
<Grid item xs={4}>
<StyledInputWrapper>
<ToolTextInput
<LineNumberInput
title="First JSON"
value={input1}
onChange={handleInput1Change}
@@ -132,7 +132,7 @@ export default function JsonComparison({ title }: ToolComponentProps) {
</Grid>
<Grid item xs={4}>
<StyledInputWrapper>
<ToolTextInput
<LineNumberInput
title="Second JSON"
value={input2}
onChange={handleInput2Change}

View File

@@ -18,12 +18,20 @@ const tryParseJSON = (
const data = JSON.parse(fixedJson);
return { valid: true, data };
} catch (error) {
const errorMessage =
error instanceof SyntaxError ? error.message : 'Invalid JSON format';
// Extract line and column info from the error message if available
const match = errorMessage.match(/at line (\d+) column (\d+)/);
if (match) {
const [, line, column] = match;
return {
valid: false,
error: `${errorMessage}\nLocation: Line ${line}, Column ${column}`
};
}
return {
valid: false,
error:
error instanceof SyntaxError
? `Invalid JSON: ${error.message}`
: 'Invalid JSON format'
error: errorMessage
};
}
};
@@ -42,14 +50,14 @@ export const compareJson = (
// Handle parsing errors
if (!parsed1.valid || !parsed2.valid) {
throw new Error(
[
parsed1.valid ? null : parsed1.error,
parsed2.valid ? null : parsed2.error
]
.filter(Boolean)
.join('\n')
);
const errors = [];
if (!parsed1.valid) {
errors.push(`First JSON: ${parsed1.error}`);
}
if (!parsed2.valid) {
errors.push(`Second JSON: ${parsed2.error}`);
}
throw new Error(errors.join('\n\n'));
}
// Compare the valid JSON objects