Skip to content
← Public packages

@kentcdodds/photo-portfolio

A fast, photo-first portfolio site you update by chatting with your agent: galleries, about, contact, and one-step rollback.

FollowFork

Files

contact.tsx

253 lines · 6.5 KB · TypeScript
/** @jsxRuntime automatic */
/** @jsxImportSource remix/component */
import { KodyRuntime } from 'kody:runtime'
import type { Controller, RequestContext } from 'remix/router'
import { redirect } from 'remix/response/redirect'
import {
	inquiryFields,
	validateInquiry,
	type InquiryField,
	type InquiryValues,
} from '../../src/domain/inquiry-form.ts'
import type { SiteConfig } from '../../src/domain/types.ts'
import {
	claimNotification,
	saveInquiry,
	type Inquiry,
} from '../../src/store/inquiries.ts'
import { canonicalUrl, loadSite, type Site } from '../data/site.ts'
import { routes } from '../routes.ts'
import { contactLinks } from '../ui/contact-links.tsx'
import { render } from '../ui/render.tsx'

type FormState = {
	values: InquiryValues
	errors: Partial<Record<InquiryField, string>>
}

const emptyForm: FormState = {
	values: Object.fromEntries(
		inquiryFields.map((field) => [field, '']),
	) as InquiryValues,
	errors: {},
}

type FieldOptions = {
	type?: 'text' | 'email' | 'tel'
	required?: boolean
	autocomplete?: string
	multiline?: boolean
}

function field(
	state: FormState,
	name: InquiryField,
	label: string,
	input: FieldOptions,
) {
	const error = state.errors[name]
	const id = `field-${name}`
	const inputProps = {
		id,
		name,
		value: state.values[name],
		required: input.required,
		autocomplete: input.autocomplete,
		'aria-invalid': error ? ('true' as const) : undefined,
		'aria-describedby': error ? `${id}-error` : undefined,
	}
	return (
		<div class={`field${error ? ' has-error' : ''}`}>
			<label for={id}>
				{label}
				{input.required ? null : <span class="optional"> (optional)</span>}
			</label>
			{input.multiline ? (
				<textarea rows={6} {...inputProps} />
			) : input.type === 'email' ? (
				<input type="email" {...inputProps} />
			) : input.type === 'tel' ? (
				<input type="tel" {...inputProps} />
			) : (
				<input type="text" {...inputProps} />
			)}
			{error ? (
				<p class="field-error" id={`${id}-error`}>
					{error}
				</p>
			) : null}
		</div>
	)
}

function contactPage(
	site: Site,
	state: FormState,
	sent: boolean,
	status = 200,
) {
	const { config } = site.content
	return render(
		site,
		{
			title: 'Contact',
			description: `Get in touch with ${config.photographerName}${config.bookingUrl ? ' or book a session' : ''}.`,
			canonical: canonicalUrl(site, routes.contact.index.href()),
			nav: 'contact',
			noindex: sent || status !== 200,
		},
		<section class="wrap section contact">
			<header class="page-head">
				<h1>Let's talk</h1>
				<p class="lede">
					Tell me a little about what you have in mind. I usually reply within
					two days.
				</p>
			</header>
			<div class="contact-grid">
				{sent ? (
					<div class="notice" role="status">
						<h2>Thank you!</h2>
						<p>Your message is on its way. I'll get back to you soon.</p>
						<p>
							<a href={routes.galleries.href()}>Keep browsing galleries</a>
						</p>
					</div>
				) : (
					<form
						class="contact-form"
						method="post"
						action={routes.contact.action.href()}
						novalidate
					>
						{field(state, 'name', 'Name', {
							required: true,
							autocomplete: 'name',
						})}
						{field(state, 'email', 'Email', {
							type: 'email',
							required: true,
							autocomplete: 'email',
						})}
						{field(state, 'phone', 'Phone', {
							type: 'tel',
							autocomplete: 'tel',
						})}
						{field(state, 'sessionType', 'What kind of session?', {})}
						{field(state, 'preferredDate', 'Preferred date or season', {})}
						{field(state, 'message', 'Message', {
							required: true,
							multiline: true,
						})}
						<div class="hp" aria-hidden="true">
							<label for="field-website">Leave this empty</label>
							<input
								id="field-website"
								name="website"
								type="text"
								tabindex={-1}
								autocomplete="off"
							/>
						</div>
						<button class="button" type="submit">
							Send message
						</button>
					</form>
				)}
				<aside class="contact-aside" aria-label="Other ways to reach me">
					<h2>Other ways to reach me</h2>
					{contactLinks(config)}
				</aside>
			</div>
		</section>,
		{ status },
	)
}

async function notifyOwner(
	context: RequestContext,
	config: SiteConfig,
	inquiry: Inquiry,
) {
	const { kody } = context.get(KodyRuntime)
	const lines = [
		`New message from your website (${config.siteName}).`,
		'',
		`Name: ${inquiry.name}`,
		`Email: ${inquiry.email}`,
		inquiry.phone ? `Phone: ${inquiry.phone}` : null,
		inquiry.sessionType ? `Session: ${inquiry.sessionType}` : null,
		inquiry.preferredDate ? `Preferred date: ${inquiry.preferredDate}` : null,
		'',
		inquiry.message,
		'',
		'Reply to this email to answer them directly.',
	].filter((line) => line !== null)
	try {
		await kody.emailSend({
			subject: `New inquiry from ${inquiry.name}`,
			text: lines.join('\n'),
			reply_to: inquiry.email,
		})
		return true
	} catch (error) {
		console.error('Inquiry notification failed:', error)
		return false
	}
}

export default {
	actions: {
		async index(context) {
			const site = await loadSite(context)
			return contactPage(
				site,
				emptyForm,
				context.url.searchParams.get('sent') === '1',
			)
		},

		async action(context) {
			const site = await loadSite(context)
			const form = await context.request.formData()
			const raw = Object.fromEntries(
				[...inquiryFields, 'website'].map((name) => [
					name,
					String(form.get(name) ?? ''),
				]),
			)
			const result = validateInquiry(raw)
			const sentUrl = routes.contact.index.href(undefined, {
				searchParams: { sent: '1' },
			})
			// Bots get the same thank-you page and nothing is stored.
			if (result.spam) return redirect(sentUrl, 303)
			if (!result.valid) return contactPage(site, result, false, 400)

			const now = new Date().toISOString()
			const { config } = site.content
			const { values } = result
			const inquiry: Inquiry = {
				id: crypto.randomUUID(),
				receivedAt: now,
				name: values.name,
				email: values.email,
				...(values.phone ? { phone: values.phone } : {}),
				...(values.sessionType ? { sessionType: values.sessionType } : {}),
				...(values.preferredDate
					? { preferredDate: values.preferredDate }
					: {}),
				message: values.message,
				notified: false,
			}
			if (
				config.notifyOnInquiry &&
				(await claimNotification(site.storage, now))
			) {
				inquiry.notified = await notifyOwner(context, config, inquiry)
			}
			await saveInquiry(site.storage, inquiry)
			return redirect(sentUrl, 303)
		},
	},
} satisfies Controller<typeof routes.contact>