[Story] Contact page #6
@@ -0,0 +1,72 @@
|
||||
import { buildMailtoUrl } from "./mailto.js";
|
||||
|
||||
/** The address the contact form messages are sent to. */
|
||||
export const MAILTO_TARGET = "hello@example.com";
|
||||
|
||||
/**
|
||||
* Collect form field values by name.
|
||||
* Works with a real DOM form and with the minimal fake form used in tests.
|
||||
*
|
||||
* @param {{querySelectorAll(selector: string): ArrayLike<{name: string, value: string}>}} form
|
||||
* @returns {{name: string, email: string, message: string}}
|
||||
*/
|
||||
export function readFormValues(form) {
|
||||
const values = {};
|
||||
for (const el of form.querySelectorAll("[name]")) {
|
||||
values[el.name] = el.value;
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the mailto: URL for the contact form from the entered values.
|
||||
*
|
||||
* @param {{name: string, email: string, message: string}} values
|
||||
* @param {string} [to]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function buildContactMailto(values, to = MAILTO_TARGET) {
|
||||
const subject = `Contact form submission from ${values.name || "someone"}`;
|
||||
const body = [
|
||||
`Name: ${values.name || ""}`,
|
||||
`Email: ${values.email || ""}`,
|
||||
"",
|
||||
"Message:",
|
||||
values.message || "",
|
||||
].join("\n");
|
||||
return buildMailtoUrl({ to, subject, body });
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a contact form submit: build the mailto: URL and send the
|
||||
* visitor to it so their mail client opens pre-filled.
|
||||
*
|
||||
* @param {HTMLFormElement} form
|
||||
* @param {{to?: string, navigate?: (url: string) => void}} [options]
|
||||
* @returns {string} the mailto: URL that was navigated to
|
||||
*/
|
||||
export function handleContactSubmit(
|
||||
form,
|
||||
{ to = MAILTO_TARGET, navigate = (url) => { window.location.href = url; } } = {}
|
||||
) {
|
||||
const url = buildContactMailto(readFormValues(form), to);
|
||||
navigate(url);
|
||||
return url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wire the submit handler onto a contact form.
|
||||
* @param {HTMLFormElement} form
|
||||
*/
|
||||
export function initContactForm(form) {
|
||||
form.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
handleContactSubmit(form);
|
||||
});
|
||||
}
|
||||
|
||||
// Browser-only wiring — guarded so this module stays importable in Node tests.
|
||||
if (typeof window !== "undefined" && typeof document !== "undefined") {
|
||||
const form = document.getElementById("contact-form");
|
||||
if (form) initContactForm(form);
|
||||
}
|
||||
Reference in New Issue
Block a user