import { useCallback, useEffect, useRef, useState } from 'react'; import { Viewer, DocumentGate } from '@embedpdf/react/runtime'; import type { OpenInput } from '@embedpdf/react/runtime'; import { Stage, stagePlugin } from '@embedpdf/react/stage'; import { RenderLayer, renderPlugin } from '@embedpdf/react/render'; import { interactionPlugin } from '@embedpdf/react/interaction'; import { FormLayer, formPlugin, toFieldRef, useForm, useFormState } from '@embedpdf/react/form'; import type { FormValidation } from '@embedpdf/react/form'; import { localEngine } from '@embedpdf/engine'; import './validate.css'; const engine = localEngine(); const plugins = [stagePlugin(), renderPlugin(), interactionPlugin(), formPlugin()]; const forms = async (): Promise => { const response = await fetch('https://www.embedpdf.com/pdfs/forms.pdf'); return { kind: 'bytes', id: 'forms', bytes: new Uint8Array(await response.arrayBuffer()) }; }; /** Fill in a name, then check the form, as if it was submitted. */ function useFilledInName(onReady: () => void) { const form = useForm(); const status = useFormState((state) => state.status); const started = useRef(false); useEffect(() => { if (status !== 'ready' || started.current) return; started.current = true; void form.setValue(toFieldRef('name'), { value: 'Ada Lovelace' }).then(onReady); }, [form, status, onReady]); } function SubmitToolbar() { const form = useForm(); const [check, setCheck] = useState(null); // Check the required fields. const validate = useCallback(() => { const result = form.validate(); setCheck(result); return result; }, [form]); useFilledInName(validate); // Submit: check, and put the cursor in the first empty field. const submit = () => { const first = validate().missing[0]; if (first) form.focus(first.ref); }; return (
{check && (check.valid ? ( Every required field is filled in ) : ( Fill in first: {check.missing.map((field) => field.name).join(', ')} ))}
); } export default function App() { return ( Loading…

}> {() => ( <> )}
); }