import { 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,
useFormEvent,
useFormState,
useFormValue,
} from '@embedpdf/react/form';
import type { FormField } from '@embedpdf/react/form';
import { localEngine } from '@embedpdf/engine';
import './read.css';
const engine = localEngine();
const plugins = [stagePlugin(), renderPlugin(), interactionPlugin(), formPlugin()];
// [!doc-source forms]
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()) };
};
// [!/doc-source]
/** On load: a name filled in. */
function useFilledInName() {
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' });
}, [form, status]);
}
/** A field's value as text, whatever its kind. */
function valueText(field: FormField): string {
switch (field.kind) {
case 'text':
case 'combobox':
return field.value || '—';
case 'checkbox':
return field.checked ? 'checked' : 'not checked';
case 'radio':
return field.value === 'Off' ? '—' : field.value;
case 'listbox':
return field.selectedValues.join(', ') || '—';
default:
return '';
}
}
function Greeting() {
useFilledInName();
const name = useFormValue(toFieldRef('name'));
const [changed, setChanged] = useState(null);
// Every change, whoever made it: typing, a script, or code.
useFormEvent(
(form) => form.onValueChanged,
({ field }) => setChanged(field.name),
);
return (
{changed && }
);
}
function FieldList() {
const { fields } = useFormState();
return (
{fields.map((field) => (
-
{field.name} {field.kind}
{valueText(field)}
))}
);
}
export default function App() {
return (
Loading…
}>
{() => (
<>
>
)}
);
}