diff --git a/src/common/file-input/index.ts b/src/common/file-input/index.ts new file mode 100644 index 00000000..438919f6 --- /dev/null +++ b/src/common/file-input/index.ts @@ -0,0 +1 @@ +export * from './open-file'; diff --git a/src/common/file-input/open-file.ts b/src/common/file-input/open-file.ts new file mode 100644 index 00000000..d3da1be3 --- /dev/null +++ b/src/common/file-input/open-file.ts @@ -0,0 +1,13 @@ +export type OnFileSelectedCallback = (file: File) => void; + +export const FileInput = (onFileSelected: OnFileSelectedCallback) => { + const fileInput = document.createElement('input'); + fileInput.type = 'file'; + fileInput.accept = '.mml'; + fileInput.addEventListener('change', event => { + const target = event.target as HTMLInputElement; + const file = target.files?.[0]; + if (file) onFileSelected(file); + }); + fileInput.click(); +}; diff --git a/src/pods/toolbar/components/open-button/open-button.component.tsx b/src/pods/toolbar/components/open-button/open-button.component.tsx index 89a1d4b0..eb0c5abe 100644 --- a/src/pods/toolbar/components/open-button/open-button.component.tsx +++ b/src/pods/toolbar/components/open-button/open-button.component.tsx @@ -1,17 +1,36 @@ +import React from 'react'; import { OpenIcon } from '@/common/components/icons/open-icon.component'; import { ToolbarButton } from '@/pods/toolbar/components/toolbar-button'; +import { useCanvasSchemaContext } from '@/core/providers'; +import { FileInput, OnFileSelectedCallback } from '@/common/file-input'; import classes from '@/pods/toolbar/toolbar.pod.module.css'; -export const OpenButton = () => { - const handleOpenButtonClick = () => { - console.log('Open button clicked'); +export const OpenButton: React.FC = () => { + const { loadSchema } = useCanvasSchemaContext(); + + const handleFileRead = (fileContent: string) => { + try { + const parsedData = JSON.parse(fileContent); + loadSchema(parsedData); + } catch (error) { + throw new Error('Error opening file' + error); + } + }; + + const handleOpenButtonClick: OnFileSelectedCallback = (file: File) => { + const reader = new FileReader(); + reader.onload = e => { + const fileContent = e.target?.result as string; + if (fileContent) handleFileRead(fileContent); + }; + reader.readAsText(file); }; return ( } label={'Open'} - onClick={handleOpenButtonClick} + onClick={() => FileInput(handleOpenButtonClick)} className={classes.button} /> );