import { BinaryFileInput, checkEqualInputBinary, } from "@/components/BinaryInput" import { Modal } from "@/components/Modal" import { useGenericSynchronizeInput } from "@/components/useSynchroniseInput" import { NOTIN } from "@polkadot-api/react-builder" import { Download, FileUp } from "lucide-react" import { ComponentProps, FC, useMemo, useState } from "react" import { twMerge } from "tailwind-merge" // @ts-expect-error save-as typings not available import { saveAs } from "save-as" import { BinaryEdit } from "./Icons" import { ActionButton } from "./ActionButton" import { fromHex, toHex } from "polkadot-api/utils" export interface BinaryEditProps { initialValue?: Uint8Array decode: (value: Uint8Array) => unknown | NOTIN onValueChange: (value: any) => void title?: string fileName?: string } export const BinaryEditButton: FC< BinaryEditProps & { iconProps?: ComponentProps } > = ({ iconProps, ...props }) => { const [open, setOpen] = useState(false) return ( <> setOpen(true)} /> setOpen(false)} /> ) } export const BinaryEditModal: FC< BinaryEditProps & { open: boolean onClose: () => void } > = ({ open, ...props }) => ( {props.title} ) const MAX_DISPLAY_SIZE = 5 * 1024 * 1024 const BinaryEditModalContent: FC< BinaryEditProps & { onClose: () => void } > = ({ fileName, initialValue = new Uint8Array(), decode, onValueChange, onClose, }) => { const [value, setValue] = useState(initialValue) const [error, setError] = useState("") const [inputValue, setInputValue] = useGenericSynchronizeInput( value, setValue as any, parseInput, "" as string | Uint8Array, (value) => { if (value.length > MAX_DISPLAY_SIZE) return "" return toHex(value) }, (input, value) => checkEqualInputBinary(parseInput(input), value), ) const placeholder = value.length > MAX_DISPLAY_SIZE ? "(value is too long to display)" : "" const safeDecode = (value: Uint8Array) => { try { return decode(value) } catch (_) { return NOTIN } } // eslint-disable-next-line react-hooks/exhaustive-deps const isValid = useMemo(() => safeDecode(value) !== NOTIN, [value, decode]) const textareaValue = inputValue instanceof Uint8Array ? "" : inputValue const submit = () => { const decoded = safeDecode(value) if (decoded !== NOTIN) { onValueChange(decoded) onClose() } else { // Shouldn't happen, but it's better than just swallowing that it failed. setError("Couldn't set the binary data 😢") } } const validateFile = (file: File) => { if (file.size > 512 * 1024 * 1024) { setError("File size can't exceed 512MB") return false } return true } const downloadDisabled = value.length === 0 const download = () => { saveAs( new Blob([value as Uint8Array], { type: "application/octet-stream", }), `${fileName ?? new Date().toISOString()}.dat`, ) } return ( <>
Hex data{isValid ? ` (${value.length} bytes)` : ""}