From cc6d79e4fa5d956f9e23b954bd698eaa6b06b488 Mon Sep 17 00:00:00 2001 From: cohitre Date: Sun, 14 Apr 2024 07:32:51 -0700 Subject: [PATCH] Displaying errors when parsing json import --- .../ImportJson/ImportJsonDialog.tsx | 30 +++++++++++-------- .../ImportJson/validateJsonStringValue.ts | 23 ++++++++++++++ 2 files changed, 41 insertions(+), 12 deletions(-) create mode 100644 packages/editor-sample/src/App/TemplatePanel/ImportJson/validateJsonStringValue.ts diff --git a/packages/editor-sample/src/App/TemplatePanel/ImportJson/ImportJsonDialog.tsx b/packages/editor-sample/src/App/TemplatePanel/ImportJson/ImportJsonDialog.tsx index 0b7c3c4..f663d2d 100644 --- a/packages/editor-sample/src/App/TemplatePanel/ImportJson/ImportJsonDialog.tsx +++ b/packages/editor-sample/src/App/TemplatePanel/ImportJson/ImportJsonDialog.tsx @@ -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; }; @@ -14,28 +16,32 @@ export default function ImportJsonDialog({ onClose }: ImportJsonDialogProps) { const handleChange: React.ChangeEventHandler = (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 = {error}; + } + return ( Import JSON
{ 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(); }} > + {errorAlert}