import camelCase from 'lodash/camelCase' import startCase from 'lodash/startCase' import {required} from '../validation' import {defineField} from 'sanity' import type {FieldProps, FieldReturn} from '../types' export const getFieldName = (type: string, field?: FieldProps) => { const {name, title} = field || {} return name || camelCase(title) || type } export const getFieldTitle = (type: string, field?: FieldProps) => { const {title} = field || {} return title || startCase(getFieldName(type, field)) } export const getValidation = ({validation, required: isRequired}: FieldProps = {}) => (!!validation || isRequired) && {validation: validation || (isRequired && required)} // TODO: Improve typing with generics in the future. This currently conflicts with // defineField's typing. Check it out in the future. // // export type FieldProps = Omit< // IntrinsicDefinitions[T], // 'type' | 'name' // > & // FieldExtensions // // //... // // export const field = ( // type: T, // props: FieldProps, // ): FieldReturn => { // export const field = (type: string, props?: FieldProps): FieldReturn => { const {validation, required: isRequired, ...fieldProps} = props || {} const name = getFieldName(type, props) const title = getFieldTitle(type, props) const validationProps = getValidation({validation, required: isRequired}) return defineField({ ...fieldProps, ...validationProps, name, title, type, }) }