forked from rajun/ar-test
48 lines
2.0 KiB
TypeScript
48 lines
2.0 KiB
TypeScript
import type { ProjectIntent } from '~/data/projects/constants';
|
|
import type { ProjectFormValues } from '~/schemas/projects/project-form';
|
|
|
|
// Encodes the project form (including the logo file) for a multipart clientAction submit
|
|
export function toProjectFormData(intent: ProjectIntent, id: string | undefined, values: ProjectFormValues): FormData {
|
|
const formData = new FormData();
|
|
formData.append('intent', intent);
|
|
if (id) formData.append('id', id);
|
|
formData.append('name', values.name);
|
|
formData.append('logoBg', values.logoBg);
|
|
formData.append('logoBgColor', values.logoBgColor);
|
|
formData.append('brandColor', values.brandColor);
|
|
formData.append('buttonTextColor', values.buttonTextColor);
|
|
formData.append('buttonLabel', values.buttonLabel);
|
|
formData.append('arPage', JSON.stringify(values.arPage));
|
|
formData.append('description', values.description);
|
|
formData.append('status', values.status);
|
|
formData.append('logoExisting', values.logo.existing);
|
|
if (values.logo.file) formData.append('logoFile', values.logo.file);
|
|
return formData;
|
|
}
|
|
|
|
const text = (formData: FormData, key: string) => String(formData.get(key) ?? '');
|
|
|
|
function json(formData: FormData, key: string): unknown {
|
|
try {
|
|
return JSON.parse(text(formData, key));
|
|
} catch {
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
export function fromProjectFormData(formData: FormData) {
|
|
const logoFile = formData.get('logoFile');
|
|
return {
|
|
name: text(formData, 'name'),
|
|
logo: { file: logoFile instanceof File && logoFile.size > 0 ? logoFile : null, existing: text(formData, 'logoExisting') },
|
|
logoBg: text(formData, 'logoBg'),
|
|
logoBgColor: text(formData, 'logoBgColor'),
|
|
brandColor: text(formData, 'brandColor'),
|
|
buttonTextColor: text(formData, 'buttonTextColor'),
|
|
buttonLabel: text(formData, 'buttonLabel'),
|
|
arPage: json(formData, 'arPage'),
|
|
description: text(formData, 'description'),
|
|
status: text(formData, 'status'),
|
|
};
|
|
}
|