Skip to content

Commit

Permalink
Displaying errors when parsing json import
Browse files Browse the repository at this point in the history
  • Loading branch information
cohitre committed Apr 14, 2024
1 parent b0ca941 commit cc6d79e
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 12 deletions.
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import React, { useState } from 'react';

import { Button, Dialog, DialogActions, DialogContent, DialogTitle, Input } from '@mui/material';
import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, Input } from '@mui/material';

import { resetDocument } from '../../../documents/editor/EditorContext';

import validateJsonStringValue from './validateJsonStringValue';

type ImportJsonDialogProps = {
onClose: () => void;
};
Expand All @@ -14,28 +16,32 @@ export default function ImportJsonDialog({ onClose }: ImportJsonDialogProps) {
const handleChange: React.ChangeEventHandler<HTMLTextAreaElement | HTMLInputElement> = (ev) => {
const v = ev.currentTarget.value;
setValue(v);
try {
JSON.parse(v);
setError(null);
} catch {
setError('There was a parsing error');
}
const { error } = validateJsonStringValue(v);
setError(error ?? null);
};

let errorAlert = null;
if (error) {
errorAlert = <Alert color="error">{error}</Alert>;
}

return (
<Dialog open onClose={onClose}>
<DialogTitle>Import JSON</DialogTitle>
<form
onSubmit={(ev) => {
ev.preventDefault();
try {
const doc = JSON.parse(value);
resetDocument(doc);
onClose();
} catch {}
const { error, data } = validateJsonStringValue(value);
setError(error ?? null);
if (!data) {
return;
}
resetDocument(data);
onClose();
}}
>
<DialogContent>
{errorAlert}
<Input
error={error !== null}
value={value}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { EditorConfigurationSchema, TEditorConfiguration } from '../../../documents/editor/core';

type TResult = { error: string; data?: undefined } | { data: TEditorConfiguration; error?: undefined };

export default function validateTextAreaValue(value: string): TResult {
let jsonObject = undefined;
try {
jsonObject = JSON.parse(value);
} catch {
return { error: 'Invalid json' };
}

const parseResult = EditorConfigurationSchema.safeParse(jsonObject);
if (!parseResult.success) {
return { error: 'Invalid JSON schema' };
}

if (!parseResult.data.root) {
return { error: 'Missing "root" node' };
}

return { data: parseResult.data };
}

0 comments on commit cc6d79e

Please sign in to comment.