From 9573ede92cc4f2ecf13f310736d8e9e0c13bb944 Mon Sep 17 00:00:00 2001 From: "Visal .In" Date: Tue, 16 Jul 2024 11:12:25 +0700 Subject: [PATCH] feat: add drop sqlite database file --- src/app/playground/client/page-client.tsx | 13 +++++++++ src/components/screen-dropzone.tsx | 32 +++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 src/components/screen-dropzone.tsx diff --git a/src/app/playground/client/page-client.tsx b/src/app/playground/client/page-client.tsx index 6bf23307..c7c8f69b 100644 --- a/src/app/playground/client/page-client.tsx +++ b/src/app/playground/client/page-client.tsx @@ -7,6 +7,7 @@ import { LucideLoader } from "lucide-react"; import Script from "next/script"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { Database, SqlJsStatic } from "sql.js"; +import ScreenDropZone from "@/components/screen-dropzone"; export default function PlaygroundEditorBody({ preloadDatabase, @@ -62,6 +63,17 @@ export default function PlaygroundEditorBody({ [sqlInit] ); + const onFileDrop = useCallback( + (buffer: ArrayBuffer) => { + if (sqlInit) { + const sqljsDatabase = new sqlInit.Database(new Uint8Array(buffer)); + setRawDb(sqljsDatabase); + setDb(new SqljsDriver(sqljsDatabase)); + } + }, + [sqlInit] + ); + const sidebarMenu = useMemo(() => { return (
@@ -136,6 +148,7 @@ export default function PlaygroundEditorBody({ onChange={onFileChange} multiple={false} /> + {dom} ); diff --git a/src/components/screen-dropzone.tsx b/src/components/screen-dropzone.tsx new file mode 100644 index 00000000..e5cd47fa --- /dev/null +++ b/src/components/screen-dropzone.tsx @@ -0,0 +1,32 @@ +"use client"; + +import { useEffect } from "react"; + +interface Props { + onFileDrop: (buffer: ArrayBuffer) => void; +} + +export default function ScreenDropZone({ onFileDrop }: Props) { + useEffect(() => { + const dropEventHandler = (e: DragEvent) => { + if (!e.dataTransfer) return; + const file = e.dataTransfer.files[0]; + + if (!file) return; + const reader = new FileReader(); + reader.onload = (loadEvent) => { + onFileDrop(loadEvent.target?.result as ArrayBuffer); + }; + + reader.readAsArrayBuffer(file); + }; + + window.document.addEventListener("drop", dropEventHandler); + + return () => { + window.document.removeEventListener("drop", dropEventHandler); + }; + }, [onFileDrop]); + + return <>; +}