diff --git a/src/components/cardSelector/CardSelector.tsx b/src/components/cardSelector/CardSelector.tsx index bb265ef..8b0002b 100644 --- a/src/components/cardSelector/CardSelector.tsx +++ b/src/components/cardSelector/CardSelector.tsx @@ -3,6 +3,7 @@ import { StickyNoteButton } from "./StickyNoteButton" import { ImageCardButton } from "./ImageCardButton" import { ExportButton } from "./ExportButton" import { TextButton } from "./TextButton" +import { ImportButton } from "./ImportButton" export function CardSelector() { const containerRef = useRef(null) @@ -21,6 +22,7 @@ export function CardSelector() { + ) } diff --git a/src/components/cardSelector/ImportButton.tsx b/src/components/cardSelector/ImportButton.tsx new file mode 100644 index 0000000..8df6739 --- /dev/null +++ b/src/components/cardSelector/ImportButton.tsx @@ -0,0 +1,64 @@ +import images from "../../signals/images" +import notes from "../../signals/notes" +import { Card } from "../../types" +import { convertBase64ToJson } from "../../utils/convertBase64ToJson" +import { updateLocalStorage } from "../../utils/localStorage" +import { defaultClassName } from "./utils" + +export function ImportButton() { + + function _handleImport() { + const input = document.createElement('input') + input.type = 'file' + input.onchange = (e: any) => { + const file = e.target.files[0] + const reader = new FileReader() + reader.readAsDataURL(file) + reader.onload = function(readerEvent) { + let content = readerEvent.target?.result; + // get only the base64 parts and not any identifiers + content = (content as string).split(',')[1] + const data: Record | Card<'image'>> = convertBase64ToJson(content) + for (let key in data) { + const item = data[key] + if (item.type == 'image') { + const { id, ...rest } = item + images.addImage(rest) + } + + if (item.type == 'note') { + const { id, ...rest } = item + notes.addNote(rest) + } + } + + updateLocalStorage('notes', notes.notes.value) + updateLocalStorage('images', images.images.value) + notes.notes.notify() + images.images.notify() + } + } + input.click() + } + + return ( + + + + + + ) +} diff --git a/src/utils/convertBase64ToJson.ts b/src/utils/convertBase64ToJson.ts new file mode 100644 index 0000000..a128c46 --- /dev/null +++ b/src/utils/convertBase64ToJson.ts @@ -0,0 +1,19 @@ +export function convertBase64ToJson( + data: string | ArrayBuffer | null | undefined +) { + try { + if (!data) throw new Error("no data to decode") + if (data instanceof ArrayBuffer) + throw new Error("cannot decode array buffer yet") + // Decode Base64 to string + const jsonString = atob(data) + + // Parse string to JSON + const jsonObject = JSON.parse(jsonString) + + // Display the JSON object + return jsonObject + } catch (error) { + console.error("Error decoding Base64:", error) + } +}