forked from rajun/ar-test
feat: add upload or URL model source field
This commit is contained in:
parent
0317387105
commit
ed853200e0
64
app/components/assets/form/model-source-field.tsx
Normal file
64
app/components/assets/form/model-source-field.tsx
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
import { useFormContext, useWatch } from 'react-hook-form';
|
||||||
|
import { Link2 } from 'lucide-react';
|
||||||
|
import { Field } from '~/components/ui/field';
|
||||||
|
import { IconInput } from '~/components/ui/icon-input';
|
||||||
|
import { SegmentedControl } from '~/components/ui/segmented-control';
|
||||||
|
import { FilePicker } from '~/components/assets/form/file-picker';
|
||||||
|
import { MODEL_FIELDS, MODEL_SOURCE_OPTIONS, type ModelFieldName } from '~/data/assets/constants';
|
||||||
|
import type { AssetFormValues } from '~/schemas/assets/asset-form';
|
||||||
|
|
||||||
|
export function ModelSourceField({ name, required }: { name: ModelFieldName; required?: boolean }) {
|
||||||
|
const { control, register, setValue, trigger, formState } = useFormContext<AssetFormValues>();
|
||||||
|
const source = useWatch({ control, name });
|
||||||
|
const config = MODEL_FIELDS[name];
|
||||||
|
const fieldErrors = formState.errors[name];
|
||||||
|
const error = fieldErrors?.file?.message ?? fieldErrors?.url?.message;
|
||||||
|
const inputId = `${name}-source`;
|
||||||
|
|
||||||
|
// Re-validates the whole source once the form has been submitted, so errors for the other mode clear
|
||||||
|
const update = (patch: Partial<AssetFormValues['glb']>) => {
|
||||||
|
setValue(name, { ...source, ...patch });
|
||||||
|
if (formState.isSubmitted) trigger(name);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Field
|
||||||
|
label={config.label}
|
||||||
|
htmlFor={inputId}
|
||||||
|
required={required}
|
||||||
|
hint={config.hint}
|
||||||
|
error={error}
|
||||||
|
action={
|
||||||
|
<SegmentedControl
|
||||||
|
size='sm'
|
||||||
|
surface='sunken'
|
||||||
|
label={`${config.label} source`}
|
||||||
|
value={source.mode}
|
||||||
|
options={MODEL_SOURCE_OPTIONS}
|
||||||
|
onChange={(mode) => update({ mode })}
|
||||||
|
/>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{source.mode === 'file' ? (
|
||||||
|
<FilePicker
|
||||||
|
id={inputId}
|
||||||
|
accept={config.accept}
|
||||||
|
file={source.file}
|
||||||
|
existing={source.existing}
|
||||||
|
invalid={!!error}
|
||||||
|
onFileChange={(file) => update({ file })}
|
||||||
|
onClearExisting={() => update({ existing: '' })}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<IconInput
|
||||||
|
id={inputId}
|
||||||
|
type='url'
|
||||||
|
icon={Link2}
|
||||||
|
placeholder={config.urlPlaceholder}
|
||||||
|
aria-invalid={!!error}
|
||||||
|
{...register(`${name}.url`)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Field>
|
||||||
|
);
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user