| 1 | // This file is part of HFS - Copyright 2021-2023, Massimo Melina <a@rejetto.com> - License https://www.gnu.org/licenses/gpl-3.0.txt |
| 2 | |
| 3 | import { FieldProps, StringField } from '@hfs/mui-grid-form' |
| 4 | import { createElement as h } from 'react' |
| 5 | import { Eject } from '@mui/icons-material' |
| 6 | import { IconBtn, useBreakpoint } from './mui' |
| 7 | import { newDialog, prefix } from '@hfs/shared' |
| 8 | import FilePicker from './FilePicker' |
| 9 | import { apiCall } from './api' |
| 10 | |
| 11 | export default function FileField({ value, onChange, files=true, folders=false, fileMask, defaultPath, title, ...props }: FieldProps<string>) { |
| 12 | const large = useBreakpoint('md') |
| 13 | return h(StringField, { |
| 14 | ...props, |
| 15 | value, |
| 16 | onChange, |
| 17 | wrap: true, |
| 18 | end: h(IconBtn, { |
| 19 | icon: Eject, |
| 20 | title: "Browse files...", |
| 21 | edge: 'end', |
| 22 | sx: { mb: .5 }, |
| 23 | onClick() { |
| 24 | const { close } = newDialog({ |
| 25 | title: title ?? ((files ? "Pick a file" : "Pick a folder") + prefix(': ', fileMask)), |
| 26 | dialogProps: { |
| 27 | fullScreen: !large, |
| 28 | sx: { minWidth: 'min(90vw, 40em)', minHeight: 'calc(100vh - 9em)' } |
| 29 | }, |
| 30 | Content() { |
| 31 | return h(FilePicker, { |
| 32 | multiple: false, |
| 33 | folders, |
| 34 | files, |
| 35 | fileMask, |
| 36 | from: value || defaultPath, |
| 37 | async onSelect(sel) { |
| 38 | let one = sel?.[0] |
| 39 | if (!one) return |
| 40 | const cwd = (await apiCall('get_cwd'))?.path |
| 41 | if (one.startsWith(cwd)) |
| 42 | one = one.slice(cwd.length+1) || '.' |
| 43 | onChange(one, { was: value, event: 'picker' }) |
| 44 | close() |
| 45 | } |
| 46 | }) |
| 47 | }, |
| 48 | }) |
| 49 | }, |
| 50 | }) |
| 51 | }) |
| 52 | } |