Image Pipeline Playground
feat(frontend/inspector): add Load Image file and folder picker
Mohammad Rajaeiabfc4c0bc213
diff --git a/frontend/src/features/inspector/FileParamInput.tsx b/frontend/src/features/inspector/FileParamInput.tsxnew file mode 100644index 0000000..217e1a8--- /dev/null+++ b/frontend/src/features/inspector/FileParamInput.tsx@@ -0,0 +1,151 @@+import { useEffect, useRef, useState } from 'react'+import { Box, Button, Stack, TextField, Typography } from '@mui/material'+import type { ParamField } from '../../types'++interface FileParamInputProps {+ field: ParamField+ value: string+ onChange: (path: string) => void+}++interface UploadResponse {+ path: string+ kind: string+ files: string[]+ count: number+}++function acceptAttr(field: ParamField): string {+ const extensions = field.accept?.length+ ? field.accept+ : ['.png', '.jpg', '.jpeg', '.bmp', '.tif', '.tiff', '.webp', '.gif']+ return extensions.map((ext) => (ext.startsWith('.') ? ext : `.${ext}`)).join(',')+}++function filterImageFiles(fileList: FileList | null, field: ParamField): File[] {+ if (!fileList) return []+ const allowed = new Set(+ (field.accept?.length+ ? field.accept+ : ['.png', '.jpg', '.jpeg', '.bmp', '.tif', '.tiff', '.webp', '.gif']+ ).map((ext) => ext.toLowerCase().replace(/^\./, '')),+ )+ return Array.from(fileList).filter((file) => {+ const ext = file.name.includes('.') ? file.name.split('.').pop()!.toLowerCase() : ''+ return allowed.has(ext)+ })+}++async function uploadFiles(files: File[], asFolder: boolean): Promise<UploadResponse> {+ const body = new FormData()+ for (const file of files) {+ body.append('files', file, file.name)+ }+ const response = await fetch(`/api/uploads?as_folder=${asFolder ? 'true' : 'false'}`, {+ method: 'POST',+ body,+ })+ if (!response.ok) {+ const detail = await response.text()+ throw new Error(detail || 'Upload failed')+ }+ return response.json() as Promise<UploadResponse>+}++export function FileParamInput({ field, value, onChange }: FileParamInputProps) {+ const fileRef = useRef<HTMLInputElement>(null)+ const folderRef = useRef<HTMLInputElement>(null)+ const [busy, setBusy] = useState(false)+ const [error, setError] = useState<string | null>(null)+ const [summary, setSummary] = useState<string | null>(null)++ useEffect(() => {+ const input = folderRef.current+ if (!input) return+ input.setAttribute('webkitdirectory', '')+ input.setAttribute('directory', '')+ }, [])++ const handleFiles = async (fileList: FileList | null, asFolder: boolean) => {+ const files = filterImageFiles(fileList, field)+ if (files.length === 0) {+ setError(`No supported images selected (${acceptAttr(field)})`)+ return+ }+ setBusy(true)+ setError(null)+ try {+ const result = await uploadFiles(files, asFolder)+ onChange(result.path)+ setSummary(+ result.kind === 'folder'+ ? `Folder selected · ${result.count} image${result.count === 1 ? '' : 's'}`+ : `File selected · ${files[0]?.name ?? 'image'}`,+ )+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Upload failed')+ } finally {+ setBusy(false)+ }+ }++ return (+ <Box sx={{ display: 'grid', gap: 1 }}>+ <TextField+ size="small"+ label={field.label}+ value={value}+ onChange={(event) => onChange(event.target.value)}+ helperText={field.description ?? `Allowed: ${acceptAttr(field)}`}+ />+ <Stack direction="row" spacing={1}>+ <Button+ size="small"+ variant="outlined"+ disabled={busy}+ onClick={() => fileRef.current?.click()}+ >+ Choose file+ </Button>+ <Button+ size="small"+ variant="outlined"+ disabled={busy}+ onClick={() => folderRef.current?.click()}+ >+ Choose folder+ </Button>+ </Stack>+ <input+ ref={fileRef}+ type="file"+ hidden+ accept={acceptAttr(field)}+ onChange={(event) => {+ void handleFiles(event.target.files, false)+ event.target.value = ''+ }}+ />+ <input+ ref={folderRef}+ type="file"+ hidden+ multiple+ onChange={(event) => {+ void handleFiles(event.target.files, true)+ event.target.value = ''+ }}+ />+ {summary && (+ <Typography variant="caption" color="text.secondary">+ {summary}+ </Typography>+ )}+ {error && (+ <Typography variant="caption" color="error">+ {error}+ </Typography>+ )}+ </Box>+ )+}diff --git a/frontend/src/features/inspector/NodeInspector.tsx b/frontend/src/features/inspector/NodeInspector.tsxindex f9c2274..900aef0 100644--- a/frontend/src/features/inspector/NodeInspector.tsx+++ b/frontend/src/features/inspector/NodeInspector.tsx@@ -10,6 +10,7 @@ import {} from '@mui/material'import { useGraphStore } from '../../store/graphStore'import type { ParamField } from '../../types'+import { FileParamInput } from './FileParamInput'function buildSchema(fields: ParamField[]) {const shape: Record<string, z.ZodTypeAny> = {}@@ -39,7 +40,7 @@ export function NodeInspector() {const fields = meta?.params ?? []const schema = buildSchema(fields)- const { register, handleSubmit, reset, formState } = useForm({+ const { register, handleSubmit, reset, setValue, formState } = useForm({resolver: zodResolver(schema),defaultValues: selected?.data.params ?? {},})@@ -61,6 +62,8 @@ export function NodeInspector() {)}+ const commit = handleSubmit((values) => updateNodeParams(selected.id, values))+return (<Box sx={{ p: 2, height: '100%', overflow: 'auto' }}><Typography variant="subtitle1" sx={{ fontWeight: 700 }}>@@ -71,7 +74,7 @@ export function NodeInspector() {</Typography><Boxcomponent="form"- onChange={handleSubmit((values) => updateNodeParams(selected.id, values))}+ onChange={() => void commit()}sx={{ display: 'grid', gap: 1.5 }}>{fields.length === 0 && (@@ -79,23 +82,39 @@ export function NodeInspector() {No configurable parameters.</Typography>)}- {fields.map((field) =>- field.type === 'select' && field.options ? (- <TextField- key={field.name}- select- size="small"- label={field.label}- defaultValue={String(selected.data.params[field.name] ?? field.default ?? '')}- {...register(field.name)}- >- {field.options.map((option) => (- <MenuItem key={option} value={option}>- {option}- </MenuItem>- ))}- </TextField>- ) : (+ {fields.map((field) => {+ if (field.type === 'file') {+ return (+ <FileParamInput+ key={field.name}+ field={field}+ value={String(selected.data.params[field.name] ?? '')}+ onChange={(path) => {+ setValue(field.name, path, { shouldDirty: true, shouldValidate: true })+ updateNodeParams(selected.id, { [field.name]: path })+ }}+ />+ )+ }+ if (field.type === 'select' && field.options) {+ return (+ <TextField+ key={field.name}+ select+ size="small"+ label={field.label}+ defaultValue={String(selected.data.params[field.name] ?? field.default ?? '')}+ {...register(field.name)}+ >+ {field.options.map((option) => (+ <MenuItem key={option} value={option}>+ {option}+ </MenuItem>+ ))}+ </TextField>+ )+ }+ return (<TextFieldkey={field.name}size="small"@@ -104,8 +123,8 @@ export function NodeInspector() {helperText={formState.errors[field.name]?.message as string | undefined}{...register(field.name)}/>- ),- )}+ )+ })}</Box></Box>)diff --git a/frontend/src/types/graph.ts b/frontend/src/types/graph.tsindex a268478..440494c 100644--- a/frontend/src/types/graph.ts+++ b/frontend/src/types/graph.ts@@ -17,6 +17,7 @@ export interface ParamField {maximum?: number | nullstep?: number | nulloptions?: string[] | null+ accept?: string[] | nulldescription?: string | null}