Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/hokulea/pahu. Agnostic headless form with adapters for frameworks
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899import type { FieldElement, Issue, PathSegment, ValidationResponse } from './definitions';import type { StandardSchemaV1 } from '@standard-schema/spec';
export function isValidationSchema(schema: unknown): schema is StandardSchemaV1 { return ( schema !== undefined && typeof schema === 'object' && (schema as Partial<StandardSchemaV1>)['~standard'] !== undefined );}
export async function validateSchema( data: unknown, schema: StandardSchemaV1): Promise<StandardSchemaV1.Result<unknown>> { return await schema['~standard'].validate(data);}
export function normalizePathSegment(segment: PropertyKey | PathSegment): PropertyKey { return typeof segment === 'object' ? segment.key : segment;}
export function transformSchemaPath( path: (PropertyKey | PathSegment)[] | undefined): string | undefined { return path === undefined ? undefined : path .map((segment) => normalizePathSegment(segment)) .map((segment) => { return typeof segment === 'number' ? `[${segment}]` : segment; }) .join('.') .replaceAll('.[', '[');}
export function transformValidationResponse(response: ValidationResponse): Issue[] { const responses = Array.isArray(response) ? response : [response];
const issues = responses .filter((r) => r !== undefined) .map((r): Issue => { if (typeof r === 'string') { return { message: r }; }
return r; });
return issues;}
export function validateNativeField(element: FieldElement): ValidationResponse { // custom controls (build with aria do not have a validity object to them) // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition if (!element.validity) { return; }
if (element.validity.valid) { return; }
return { element: element, ...('value' in element ? { value: element.value } : {}), path: [element.name], message: element.validationMessage };}
export function validateNativeFields(elements: FieldElement[]): Issue[] { const seenRadioOptions = new Set<string>();
return ( elements // filter out `<input type="radio">` with the same name, as they would all // produce the same error .filter((elem) => { const { type, name } = elem;
if (type !== 'radio') { return true; }
if (!seenRadioOptions.has(name)) { seenRadioOptions.add(name);
return true; }
return false; }) .flatMap((e) => transformValidationResponse(validateNativeField(e))) );}