import { useEffect, useRef, useState } from 'react';
import { Viewer, DocumentGate } from '@embedpdf/react/runtime';
import type { OpenInput } from '@embedpdf/react/runtime';
import { Stage, stagePlugin, useStage } 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 { stampPlugin, useStamp, useStampAssetPreviewUrl } from '@embedpdf/react/stamp';
import {
createTestSigner,
signaturePlugin,
useSignature,
useSignatureState,
useSignerRows,
} from '@embedpdf/react/signature';
import { cloudEngine } from '@cloudpdf/engine';
import { localEngine } from '@embedpdf/engine';
import './basic.css';
const engine = cloudEngine();
const assetEngine = localEngine();
// A throwaway key for the demo. Bring your own with `webCryptoSigner`, a
// service with `remoteSigner`, or a person's own with `personalSigner`.
const signer = createTestSigner({ commonName: 'Ada Lovelace' });
const plugins = [
stagePlugin(),
renderPlugin(),
interactionPlugin(),
formPlugin(),
stampPlugin({ assetEngine }),
signaturePlugin({
signingKey: () => signer,
// Trust the demo key itself, so its signatures check out as 'valid'.
trust: { anchors: async () => [(await signer).certificate] },
}),
];
const agreement: OpenInput = { kind: 'grant', grant: 'shr_G5GcxJeEBa2IiwIs0DCNruCL' };
/**
* Start at the agreement's signature field. The browser holds no signatures
* yet: add one person with a typed signature.
*/
function useSetUp() {
const form = useForm();
const stamp = useStamp();
const stage = useStage();
const status = useFormState((state) => state.status);
const done = useRef(false);
useEffect(() => {
if (status !== 'ready' || done.current) return;
done.current = true;
void (async () => {
// Bring the agreement's signature field into view.
const [widget] = form.getWidgets(toFieldRef('approval'));
if (widget) stage.reveal(widget.page, { rect: widget.rect });
const { library } = await stamp.createLibrary('Ada Lovelace', { kind: 'signatures' });
await stamp.createAsset({
libraryId: library.id,
name: 'signature',
label: 'Signature',
mark: { kind: 'text', text: 'Ada Lovelace', fontFamily: 'times-italic', color: '#1d2b53' },
});
})();
}, [form, stamp, stage, status]);
}
function MarkButton({
assetId,
label,
onPick,
}: {
assetId: string;
label: string;
onPick: () => void;
}) {
const url = useStampAssetPreviewUrl(assetId);
return (
);
}
function SignBar() {
useSetUp();
const signature = useSignature();
const [person] = useSignerRows();
const { signatures, target, busy } = useSignatureState();
const field = useFormState((state) =>
state.fields.find((candidate) => candidate.kind === 'signature'),
);
const [error, setError] = useState