65 lines
2.7 KiB
TypeScript
65 lines
2.7 KiB
TypeScript
import type { SubmitFormResult } from './submitForm.js';
|
|
/** Field values the form tracks. Projects add/remove keys freely. */
|
|
export type ContactFormValues = {
|
|
consent: boolean;
|
|
email: string;
|
|
message: string;
|
|
name: string;
|
|
phone: string;
|
|
topic: string;
|
|
};
|
|
export type ContactFormErrors = Partial<Record<keyof ContactFormValues, boolean>>;
|
|
/**
|
|
* The project's server action that calls submitForm (server-only, holds the
|
|
* Turnstile secret). The hook is a client hook, so it can't call submitForm
|
|
* directly — the project injects its action.
|
|
*/
|
|
export type SubmitAction = (values: ContactFormValues, turnstileToken?: string) => Promise<{
|
|
message?: string;
|
|
success: boolean;
|
|
} | SubmitFormResult>;
|
|
type UseContactFormOptions = {
|
|
/** Generic error message shown when the action throws. */
|
|
errorFallback?: string;
|
|
initialTopic?: string;
|
|
/** Minimum message length. Default 10. */
|
|
minMessageLength?: number;
|
|
/** Whether consent is required (project passes true when consentText shown). */
|
|
requireConsent?: boolean;
|
|
/** Whether a topic must be chosen (project passes this when topics exist). */
|
|
requireTopic?: boolean;
|
|
/** Require a Turnstile token before submit (when the widget is shown). */
|
|
requireTurnstile?: boolean;
|
|
submitAction: SubmitAction;
|
|
};
|
|
/**
|
|
* All contact-form logic (state, validation, Turnstile token, submit, success)
|
|
* WITHOUT any markup — the project owns 100% of the look. Replaces the ~150
|
|
* lines of identical logic copied into every project's ContactForm, while the
|
|
* project keeps full control over field layout and styling.
|
|
*
|
|
* const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),
|
|
* requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })
|
|
* // in JSX — your own fields/classes:
|
|
* <input value={f.values.name} onChange={(e) => f.setField('name', e.target.value)}
|
|
* className={f.errors.name ? 'border-red-500' : '…'} />
|
|
* <Turnstile siteKey={siteKey} onToken={f.setTurnstileToken} />
|
|
* <form onSubmit={f.handleSubmit}>…</form>
|
|
* {f.isSuccess && <YourSuccessPanel onReset={f.reset} />}
|
|
*/
|
|
export declare function useContactForm(options: UseContactFormOptions): {
|
|
errorMessage: string | null;
|
|
errors: Partial<Record<keyof ContactFormValues, boolean>>;
|
|
handleSubmit: (e: {
|
|
preventDefault: () => void;
|
|
}) => Promise<void>;
|
|
isSubmitting: boolean;
|
|
isSuccess: boolean;
|
|
reset: () => void;
|
|
setField: <K extends keyof ContactFormValues>(key: K, value: ContactFormValues[K]) => void;
|
|
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
|
|
turnstileToken: string | null;
|
|
values: ContactFormValues;
|
|
};
|
|
export {};
|