import React, {JSX, ReactNode, useEffect, useRef} from "react"; import {Button, ControlGroup, FileInput, HTMLSelect, InputGroup} from "@blueprintjs/core"; import {BPFileComponentState} from "../bpComponents/BPFileComponent"; import {useLoadingStateKey} from './loadingState' export interface FileComponentProps { state: BPFileComponentState onChange: (state: Partial>)=>Promise previewSlot?: ReactNode, uuid?: string AssetPicker?: (props: { state: BPFileComponentState onChange: (state: Partial>)=>Promise className?: string style?: React.CSSProperties })=>JSX.Element disableFileInput?: boolean // todo } export const FileComponent = ({state, onChange, previewSlot, AssetPicker}: FileComponentProps)=>{ const fileInputRef = useRef() const textInputRef = useRef() // console.log('render file component', state) useEffect(() => { const fileElement = fileInputRef.current; const textElement = textInputRef.current; const val = state.value if(!val) { fileElement && (fileElement.value = '') textElement && (textElement.value = '') return } if(typeof val === 'string') { textElement && (textElement.value = val) return } if(!fileElement) return; // console.log(val) // it can be Blob also because of GLTF loaded... const file = val instanceof File ? val : typeof val === 'string' || typeof (val as any as Blob).arrayBuffer === 'function' ? new File([val as string | Blob], (val as any).name||('file'+((val as any).ext?'.'+(val as any).ext:''))) : null if(!file) return const dataTransfer = new DataTransfer(); dataTransfer.items.add(file); fileElement!.files = dataTransfer.files }, [state.value]); // useEffect(() => { // fileInputRef.current && (fileInputRef.current.placeholder = 'https://example.com/file.png') // }, []); // const hasValue = !!state.value || !!state.preview const dropdownOptions = ['url', 'file'] if(AssetPicker) dropdownOptions.push('asset') const {loadingState, updateLoading} = useLoadingStateKey() return (
{!!state.preview && ( <> {previewSlot} )} {!state.readOnly && !state.value ? ( { onChange({mode: e.target.value as BPFileComponentState['mode']}) }}/>) : null} {state.mode === 'url' ? ( { onChange({mode: 'url', value: textInputRef.current?.value ?? ''}) }}> )} disabled={state.disabled} readOnly={state.readOnly} onChange={(_) => { }} placeholder="https://example.com/file.png"/> ) : state.mode === 'file' ? ( { if (state.readOnly) { e.preventDefault() e.stopPropagation() } }} buttonText={state.readOnly ? '-' : state.value ? 'Change' : 'Choose'} onChange={() => { onChange({mode: 'file', value: fileInputRef.current?.files?.[0] ?? null}) }} className="inputGroupFile"/> ) : state.mode === 'asset' && AssetPicker ? ( ) : null} {!state.readOnly && state.value && !state.preview && ( )}
) }