feat: add asset form schema

This commit is contained in:
rajun 2026-10-27 16:28:49 +05:30
parent adfa93cc82
commit 2babc57982

View File

@ -0,0 +1,59 @@
import { z } from 'zod';
import { MODEL_SOURCE_MODES } from '~/data/assets/constants';
import { RECORD_ID_PATTERN } from '~/lib/assets/qr';
import type { ArAsset } from '~/types/asset';
const isAbsoluteUrl = (value: string) => URL.canParse(value);
const modelSourceSchema = z.object({
mode: z.enum(MODEL_SOURCE_MODES),
url: z.string().trim(),
file: z.instanceof(File).nullable(),
existing: z.string(),
});
export const assetFormSchema = z
.object({
id: z
.string()
.trim()
.refine((v) => v === '' || RECORD_ID_PATTERN.test(v), 'Use exactly 15 lowercase letters or digits'),
name: z.string().trim().min(1, 'Enter a name'),
project: z.string(),
brandedQr: z.boolean(),
glb: modelSourceSchema,
usdz: modelSourceSchema,
})
.superRefine(({ glb, usdz }, ctx) => {
if (glb.mode === 'url' && !isAbsoluteUrl(glb.url)) {
ctx.addIssue({ code: 'custom', message: 'Enter a valid model URL', path: ['glb', 'url'] });
}
if (glb.mode === 'file' && !glb.file && !glb.existing) {
ctx.addIssue({ code: 'custom', message: 'Choose a GLB file', path: ['glb', 'file'] });
}
if (usdz.mode === 'url' && usdz.url && !isAbsoluteUrl(usdz.url)) {
ctx.addIssue({ code: 'custom', message: 'Enter a valid model URL', path: ['usdz', 'url'] });
}
});
export type AssetFormValues = z.infer<typeof assetFormSchema>;
function toModelSource(file: string, url: string): AssetFormValues['glb'] {
return { mode: url && !file ? 'url' : 'file', url: file ? '' : url, file: null, existing: file };
}
interface NewAssetDefaults {
projectId?: string;
brandedQr: boolean;
}
export function toAssetFormValues(asset: ArAsset | null, defaults: NewAssetDefaults): AssetFormValues {
return {
id: asset?.id ?? '',
name: asset?.name ?? '',
project: asset ? asset.project : (defaults.projectId ?? ''),
brandedQr: asset ? asset.branded_qr : defaults.brandedQr,
glb: toModelSource(asset?.glb_file ?? '', asset?.glb_url ?? ''),
usdz: toModelSource(asset?.usdz_file ?? '', asset?.usdz_url ?? ''),
};
}