47 lines
2.0 KiB
TypeScript
47 lines
2.0 KiB
TypeScript
/**
|
|||
|
|
* Shared contact-form relay wiring for HTML export.
|
||
|
|
*
|
||
|
|
* Any form component that wants to deliver submissions by email (ContactForm,
|
||
|
|
* FormContainer, ...) emits the SAME marker/placeholder/honeypot shape so the
|
||
|
|
* WHP publish step (`fs_rewrite_contact_forms`) can provision a token, rewrite
|
||
|
|
* the action, and strip the marker. Keeping this in one place means the two
|
||
|
|
* components can't drift apart (a drift would leak the recipient into published
|
||
|
|
* HTML — see PR #47 review).
|
||
|
|
*/
|
||
|
|
|
||
|
|
const esc = (s: unknown): string =>
|
||
|
|
String(s ?? '').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||
|
|
|
||
|
|
export interface RelayWiring {
|
||
|
|
/** true when a recipient is set (relay path); false = legacy formAction fallback */
|
||
|
|
useRelay: boolean;
|
||
|
|
/** the `<!--WHP-FORM ...-->` marker (stripped at publish); '' when not relay */
|
||
|
|
marker: string;
|
||
|
|
/** value for the form's `action` attribute (placeholder when relay, else the escaped fallback) */
|
||
|
|
actionAttr: string;
|
||
|
|
/** hidden honeypot `<input>` to render as the form's first child; '' when not relay */
|
||
|
|
honeypot: string;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* @param recipientEmail the "Send submissions to" address (empty/undefined = no relay)
|
||
|
|
* @param thankYouUrl optional post-submit redirect (blank = hosted thank-you page)
|
||
|
|
* @param fallbackAction the form's existing action to use when no recipient is set
|
||
|
|
*/
|
||
|
|
export function relayFormWiring(
|
||
|
|
recipientEmail: string | undefined,
|
||
|
|
thankYouUrl: string | undefined,
|
||
|
|
fallbackAction: string | undefined,
|
||
|
|
): RelayWiring {
|
||
|
|
if (!recipientEmail) {
|
||
|
|
return { useRelay: false, marker: '', actionAttr: esc(fallbackAction || '#'), honeypot: '' };
|
||
|
|
}
|
||
|
|
const fid = 'F' + Math.random().toString(36).slice(2, 8);
|
||
|
|
return {
|
||
|
|
useRelay: true,
|
||
|
|
marker: `<!--WHP-FORM id="${fid}" recipient="${esc(recipientEmail)}" thankyou="${esc(thankYouUrl || '')}"-->`,
|
||
|
|
actionAttr: `__WHP_FORM_ACTION__${fid}__`,
|
||
|
|
honeypot: `<input type="text" name="_gotcha" tabindex="-1" autocomplete="off" style="position:absolute;left:-9999px" aria-hidden="true">`,
|
||
|
|
};
|
||
|
|
}
|