import type { Block, Field } from 'payload' import type { FormAttachmentsOption, ResolvedFormAttachments } from './config.js' import { withShowWhen } from '../builderBlocks.js' import { resolveFormAttachments } from './config.js' import { DEFAULT_FORM_FILE_TYPES } from './fileTypes.js' /** * The "File" field of the form builder. The file a visitor attaches is never * stored: it is checked and sent with the company e-mail (docs/forms.md). * * forms: { attachments: true } // adds the block * forms: { attachments: true, fields: { file: buildFileBlock({ maxSizeMB: 5 }) } } // your own variant */ export function buildFileBlock(option: FormAttachmentsOption | ResolvedFormAttachments | true = true): Block { const o = option !== true && 'types' in option ? option : resolveFormAttachments(option) const half = { width: '50%' } const fields: Field[] = [ { type: 'row', fields: [ { name: 'name', type: 'text', admin: { ...half, description: { en: 'No spaces, e.g. attachment.', pl: 'Bez spacji, np. zalacznik.' } }, label: { en: 'Field key', pl: 'Klucz pola' }, required: true, }, { name: 'label', type: 'text', admin: half, label: { en: 'Label', pl: 'Etykieta' }, localized: true }, ], }, { name: 'help', type: 'text', admin: { description: { en: 'Shown under the field.', pl: 'Widoczny pod polem.' }, placeholder: { en: 'e.g. PDF or DOCX, up to 10 MB', pl: 'np. PDF lub DOCX, do 10 MB' }, }, label: { en: 'Help text', pl: 'Tekst pomocy' }, localized: true, }, { type: 'row', fields: [ { name: 'width', type: 'number', admin: half, label: { en: 'Width (%)', pl: 'Szerokość (%)' } }, { name: 'required', type: 'checkbox', admin: half, label: { en: 'Required', pl: 'Wymagane' } }, ], }, { name: 'allowedTypes', type: 'select', admin: { description: { en: 'The file is sent by e-mail and is not kept on the site.', pl: 'Plik jest wysyłany e-mailem i nie jest przechowywany w witrynie.', }, }, defaultValue: DEFAULT_FORM_FILE_TYPES.filter((key) => o.types[key]), hasMany: true, label: { en: 'Allowed file types', pl: 'Dozwolone typy plików' }, options: Object.entries(o.types).map(([value, type]) => ({ label: type.label, value })), required: true, }, { type: 'row', fields: [ { name: 'maxSizeMB', type: 'number', admin: half, defaultValue: o.maxSizeMB, label: { en: 'Maximum size (MB)', pl: 'Maksymalny rozmiar (MB)' }, max: o.maxSizeMB, min: 1, }, { name: 'maxFiles', type: 'number', admin: half, defaultValue: 1, label: { en: 'Maximum files', pl: 'Maksymalna liczba plików' }, max: o.maxFiles, min: 1, }, ], }, ] return withShowWhen({ slug: 'file', fields, labels: { plural: { en: 'File fields', pl: 'Pola pliku' }, singular: { en: 'File', pl: 'Plik' } }, }) } /** The File block with default limits — `forms.fields.file: fileBlock`, or build your own with buildFileBlock. */ export const fileBlock: Block = buildFileBlock(true)