@dloizides/marketing-astro-kit 1.7.0 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +132 -115
- package/README.md +24 -0
- package/package.json +30 -4
- package/src/BookingEmbed.astro +53 -0
- package/src/DateField.astro +85 -0
- package/src/MeetingRequestForm.astro +214 -0
- package/src/bookingEmbed/BookingState.ts +6 -0
- package/src/bookingEmbed/BookingTheme.ts +5 -0
- package/src/bookingEmbed/CalLayout.ts +6 -0
- package/src/bookingEmbed/contact.ts +22 -0
- package/src/bookingEmbed/fallbackWatch.ts +37 -0
- package/src/bookingEmbed/index.ts +6 -0
- package/src/bookingEmbed/mount.ts +140 -0
- package/src/bookingEmbed/options.ts +132 -0
- package/src/dateField/DateFieldError.ts +7 -0
- package/src/dateField/attributes.ts +25 -0
- package/src/dateField/index.ts +3 -0
- package/src/dateField/isoDay.ts +35 -0
- package/src/meetingRequest/FieldErrorKind.ts +8 -0
- package/src/meetingRequest/MeetingField.ts +11 -0
- package/src/meetingRequest/SubmitOutcome.ts +6 -0
- package/src/meetingRequest/TimeOfDay.ts +8 -0
- package/src/meetingRequest/dom.ts +60 -0
- package/src/meetingRequest/index.ts +10 -0
- package/src/meetingRequest/labels.ts +17 -0
- package/src/meetingRequest/mount.ts +86 -0
- package/src/meetingRequest/options.ts +72 -0
- package/src/meetingRequest/payload.ts +31 -0
- package/src/meetingRequest/submit.ts +44 -0
- package/src/meetingRequest/validation.ts +99 -0
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** The part of the day the visitor would like to meet in. */
|
|
2
|
+
export const enum TimeOfDay {
|
|
3
|
+
Morning = 'morning',
|
|
4
|
+
Afternoon = 'afternoon',
|
|
5
|
+
Evening = 'evening',
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export const TIME_OF_DAY_VALUES: readonly string[] = [TimeOfDay.Morning, TimeOfDay.Afternoon, TimeOfDay.Evening];
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { FieldErrorKind } from './FieldErrorKind';
|
|
2
|
+
import type { SubmitOutcome } from './SubmitOutcome';
|
|
3
|
+
import type { MeetingRequestErrors } from './validation';
|
|
4
|
+
|
|
5
|
+
const DESCRIBED_BY = 'aria-describedby';
|
|
6
|
+
|
|
7
|
+
function toggleToken(element: Element, attribute: string, token: string, isOn: boolean): void {
|
|
8
|
+
const tokens = (element.getAttribute(attribute) ?? '').split(' ').filter((item) => item !== '' && item !== token);
|
|
9
|
+
if (isOn) tokens.push(token);
|
|
10
|
+
if (tokens.length > 0) element.setAttribute(attribute, tokens.join(' '));
|
|
11
|
+
else element.removeAttribute(attribute);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function markControl(control: Element, isInvalid: boolean, errorId: string): void {
|
|
15
|
+
if (isInvalid) control.setAttribute('aria-invalid', 'true');
|
|
16
|
+
else control.removeAttribute('aria-invalid');
|
|
17
|
+
if (errorId !== '') toggleToken(control, DESCRIBED_BY, errorId, isInvalid);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Shows each field's matching error, marks its control invalid and focuses the first invalid control. */
|
|
21
|
+
export function renderErrors(form: HTMLFormElement, errors: MeetingRequestErrors): void {
|
|
22
|
+
const byField = errors as Record<string, FieldErrorKind | undefined>;
|
|
23
|
+
form.querySelectorAll<HTMLElement>('[data-field-error]').forEach((block) => {
|
|
24
|
+
const field = block.getAttribute('data-field-error') ?? '';
|
|
25
|
+
const kind = byField[field];
|
|
26
|
+
const shownKind: string = kind ?? '';
|
|
27
|
+
block.hidden = kind === undefined;
|
|
28
|
+
block.querySelectorAll<HTMLElement>('[data-error-kind]').forEach((message) => {
|
|
29
|
+
message.hidden = message.getAttribute('data-error-kind') !== shownKind;
|
|
30
|
+
});
|
|
31
|
+
const control = form.elements.namedItem(field);
|
|
32
|
+
if (control instanceof Element) markControl(control, kind !== undefined, block.id);
|
|
33
|
+
});
|
|
34
|
+
form.querySelector<HTMLElement>('[aria-invalid="true"]')?.focus();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Returns true while a request from this form is in flight. */
|
|
38
|
+
export function isLoading(form: HTMLFormElement): boolean {
|
|
39
|
+
return form.getAttribute('aria-busy') === 'true';
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Puts Send in (or out of) the loading state: disabled, aria-busy and data-loading. */
|
|
43
|
+
export function setLoading(form: HTMLFormElement, loading: boolean): void {
|
|
44
|
+
form.setAttribute('aria-busy', String(loading));
|
|
45
|
+
form.querySelectorAll<HTMLButtonElement>('[data-meeting-send]').forEach((button) => {
|
|
46
|
+
button.disabled = loading;
|
|
47
|
+
button.setAttribute('aria-busy', String(loading));
|
|
48
|
+
button.toggleAttribute('data-loading', loading);
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Shows only the outcome's status block, fills its contact links and moves focus to it. */
|
|
53
|
+
export function showOutcome(form: HTMLFormElement, outcome: SubmitOutcome, mailto: string | null): void {
|
|
54
|
+
form.setAttribute('data-meeting-state', outcome);
|
|
55
|
+
form.querySelectorAll<HTMLElement>('[data-meeting-status]').forEach((block) => {
|
|
56
|
+
block.hidden = block.getAttribute('data-meeting-status') !== outcome;
|
|
57
|
+
});
|
|
58
|
+
if (mailto !== null) form.querySelectorAll('a[data-meeting-contact]').forEach((link) => link.setAttribute('href', mailto));
|
|
59
|
+
form.querySelector<HTMLElement>(`[data-meeting-status="${outcome}"]`)?.focus();
|
|
60
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { FieldErrorKind } from './FieldErrorKind';
|
|
2
|
+
export { HONEYPOT_FIELD, MeetingField } from './MeetingField';
|
|
3
|
+
export { SubmitOutcome } from './SubmitOutcome';
|
|
4
|
+
export { TimeOfDay, TIME_OF_DAY_VALUES } from './TimeOfDay';
|
|
5
|
+
export type { MeetingRequestLabels } from './labels';
|
|
6
|
+
export * from './mount';
|
|
7
|
+
export * from './options';
|
|
8
|
+
export * from './payload';
|
|
9
|
+
export * from './submit';
|
|
10
|
+
export * from './validation';
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { FieldErrorKind } from './FieldErrorKind';
|
|
2
|
+
|
|
3
|
+
/** Every visible string of the form; the host site supplies them (the kit holds no copy). */
|
|
4
|
+
export interface MeetingRequestLabels {
|
|
5
|
+
form: string;
|
|
6
|
+
preferredDay: string;
|
|
7
|
+
timeOfDay: string;
|
|
8
|
+
morning: string;
|
|
9
|
+
afternoon: string;
|
|
10
|
+
evening: string;
|
|
11
|
+
name: string;
|
|
12
|
+
email: string;
|
|
13
|
+
company: string;
|
|
14
|
+
message: string;
|
|
15
|
+
send: string;
|
|
16
|
+
errors: Record<FieldErrorKind, string>;
|
|
17
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { contactMailtoHref } from '../bookingEmbed/contact';
|
|
2
|
+
import { isLoading, renderErrors, setLoading, showOutcome } from './dom';
|
|
3
|
+
import { HONEYPOT_FIELD, MeetingField } from './MeetingField';
|
|
4
|
+
import { parseMeetingRequestOptions, type ResolvedMeetingRequestOptions } from './options';
|
|
5
|
+
import { buildMeetingRequestPayload } from './payload';
|
|
6
|
+
import { SubmitOutcome } from './SubmitOutcome';
|
|
7
|
+
import { submitMeetingRequest, type FetchLike } from './submit';
|
|
8
|
+
import { hasErrors, todayIso, validateMeetingRequest, type MeetingRequestValues } from './validation';
|
|
9
|
+
|
|
10
|
+
const MOUNTED_ATTRIBUTE = 'data-meeting-mounted';
|
|
11
|
+
|
|
12
|
+
export interface UmamiWindow extends Window {
|
|
13
|
+
umami?: { track: (event: string, data?: Record<string, string>) => void };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface MeetingRequestDeps {
|
|
17
|
+
fetchFn: FetchLike;
|
|
18
|
+
now: () => Date;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function defaultDeps(): MeetingRequestDeps {
|
|
22
|
+
return { fetchFn: (url, init) => fetch(url, init), now: () => new Date() };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function readValues(form: HTMLFormElement): MeetingRequestValues {
|
|
26
|
+
const data = new FormData(form);
|
|
27
|
+
const read = (name: string): string => {
|
|
28
|
+
const value = data.get(name);
|
|
29
|
+
return typeof value === 'string' ? value : '';
|
|
30
|
+
};
|
|
31
|
+
return {
|
|
32
|
+
preferredDay: read(MeetingField.PreferredDay),
|
|
33
|
+
timeOfDay: read(MeetingField.TimeOfDay),
|
|
34
|
+
name: read(MeetingField.Name),
|
|
35
|
+
email: read(MeetingField.Email),
|
|
36
|
+
company: read(MeetingField.Company),
|
|
37
|
+
message: read(MeetingField.Message),
|
|
38
|
+
website: read(HONEYPOT_FIELD),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function mailtoFor(form: HTMLFormElement): string | null {
|
|
43
|
+
const { local, domain } = form.dataset;
|
|
44
|
+
if (local === undefined || domain === undefined) return null;
|
|
45
|
+
try {
|
|
46
|
+
return contactMailtoHref({ local, domain });
|
|
47
|
+
} catch {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function trackSent(options: ResolvedMeetingRequestOptions): void {
|
|
53
|
+
const tracker = (window as UmamiWindow).umami;
|
|
54
|
+
if (options.analyticsEvent !== null && tracker !== undefined) tracker.track(options.analyticsEvent, { siteId: options.siteId });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Validates and sends one request; returns null when nothing was sent (invalid input or already sending). */
|
|
58
|
+
export async function handleMeetingSubmit(form: HTMLFormElement, deps: MeetingRequestDeps = defaultDeps()): Promise<SubmitOutcome | null> {
|
|
59
|
+
if (isLoading(form)) return null;
|
|
60
|
+
const options = parseMeetingRequestOptions(form.getAttribute('data-meeting-options') ?? '');
|
|
61
|
+
const values = readValues(form);
|
|
62
|
+
const errors = validateMeetingRequest(values, todayIso(deps.now()));
|
|
63
|
+
renderErrors(form, errors);
|
|
64
|
+
if (hasErrors(errors)) return null;
|
|
65
|
+
setLoading(form, true);
|
|
66
|
+
const payload = buildMeetingRequestPayload(values, options.siteId);
|
|
67
|
+
const outcome = await submitMeetingRequest({ endpoint: options.endpoint, payload, timeoutMs: options.timeoutMs }, deps.fetchFn);
|
|
68
|
+
setLoading(form, false);
|
|
69
|
+
showOutcome(form, outcome, mailtoFor(form));
|
|
70
|
+
if (outcome === SubmitOutcome.Sent) trackSent(options);
|
|
71
|
+
return outcome;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Wires every `form[data-meeting-request]` once: day minimum = today, native submit (Enter too) sends. */
|
|
75
|
+
export function mountMeetingRequestForms(root: ParentNode = document, deps: MeetingRequestDeps = defaultDeps()): void {
|
|
76
|
+
root.querySelectorAll<HTMLFormElement>('form[data-meeting-request]').forEach((form) => {
|
|
77
|
+
if (form.hasAttribute(MOUNTED_ATTRIBUTE)) return;
|
|
78
|
+
form.setAttribute(MOUNTED_ATTRIBUTE, 'true');
|
|
79
|
+
const day = form.elements.namedItem(MeetingField.PreferredDay);
|
|
80
|
+
if (day instanceof HTMLInputElement) day.min = todayIso(deps.now());
|
|
81
|
+
form.addEventListener('submit', (event) => {
|
|
82
|
+
event.preventDefault();
|
|
83
|
+
handleMeetingSubmit(form, deps).catch((error: unknown) => console.warn(error));
|
|
84
|
+
});
|
|
85
|
+
});
|
|
86
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
export const DEFAULT_MEETING_REQUEST_TIMEOUT_MS = 10000;
|
|
2
|
+
|
|
3
|
+
const SITE_ID_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
|
|
4
|
+
const HTTPS_PROTOCOL = 'https:';
|
|
5
|
+
const ERROR_PREFIX = 'MeetingRequestForm:';
|
|
6
|
+
|
|
7
|
+
export interface MeetingRequestOptions {
|
|
8
|
+
endpoint: string;
|
|
9
|
+
siteId: string;
|
|
10
|
+
timeoutMs?: number;
|
|
11
|
+
analyticsEvent?: string | null;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface ResolvedMeetingRequestOptions {
|
|
15
|
+
endpoint: string;
|
|
16
|
+
siteId: string;
|
|
17
|
+
timeoutMs: number;
|
|
18
|
+
analyticsEvent: string | null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function isHttpsUrl(value: string): boolean {
|
|
22
|
+
try {
|
|
23
|
+
return new URL(value).protocol === HTTPS_PROTOCOL;
|
|
24
|
+
} catch {
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function resolveEndpoint(value: unknown): string {
|
|
30
|
+
const isPath = typeof value === 'string' && value.startsWith('/') && !value.startsWith('//');
|
|
31
|
+
if (isPath || (typeof value === 'string' && isHttpsUrl(value))) return value;
|
|
32
|
+
throw new Error(`${ERROR_PREFIX} endpoint must be an https URL or a path starting with /`);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function resolveSiteId(value: unknown): string {
|
|
36
|
+
if (typeof value === 'string' && SITE_ID_PATTERN.test(value)) return value;
|
|
37
|
+
throw new Error(`${ERROR_PREFIX} siteId must be lowercase letters, digits and hyphens`);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function resolveTimeout(value: unknown): number {
|
|
41
|
+
const isUsable = typeof value === 'number' && Number.isFinite(value) && value > 0;
|
|
42
|
+
return isUsable ? value : DEFAULT_MEETING_REQUEST_TIMEOUT_MS;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Validates options and fills defaults; unknown keys (a subject, say) are dropped. */
|
|
46
|
+
export function resolveMeetingRequestOptions(raw: unknown): ResolvedMeetingRequestOptions {
|
|
47
|
+
if (typeof raw !== 'object' || raw === null) throw new Error(`${ERROR_PREFIX} options must be an object`);
|
|
48
|
+
const record = raw as Record<string, unknown>;
|
|
49
|
+
const event = record['analyticsEvent'];
|
|
50
|
+
return {
|
|
51
|
+
endpoint: resolveEndpoint(record['endpoint']),
|
|
52
|
+
siteId: resolveSiteId(record['siteId']),
|
|
53
|
+
timeoutMs: resolveTimeout(record['timeoutMs']),
|
|
54
|
+
analyticsEvent: typeof event === 'string' && event !== '' ? event : null,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Parses the serialized options from the form's data attribute; throws on bad JSON or values. */
|
|
59
|
+
export function parseMeetingRequestOptions(serialized: string): ResolvedMeetingRequestOptions {
|
|
60
|
+
let raw: unknown;
|
|
61
|
+
try {
|
|
62
|
+
raw = JSON.parse(serialized);
|
|
63
|
+
} catch {
|
|
64
|
+
throw new Error(`${ERROR_PREFIX} options are not valid JSON`);
|
|
65
|
+
}
|
|
66
|
+
return resolveMeetingRequestOptions(raw);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Returns the validated options as JSON for the form's data attribute, so bad options fail the build. */
|
|
70
|
+
export function serializeMeetingRequestOptions(options: MeetingRequestOptions): string {
|
|
71
|
+
return JSON.stringify(resolveMeetingRequestOptions(options));
|
|
72
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { MeetingRequestValues } from './validation';
|
|
2
|
+
|
|
3
|
+
export interface MeetingRequestPayload {
|
|
4
|
+
name: string;
|
|
5
|
+
email: string;
|
|
6
|
+
message: string;
|
|
7
|
+
company: string | null;
|
|
8
|
+
website: string | null;
|
|
9
|
+
siteId: string;
|
|
10
|
+
preferredDay: string;
|
|
11
|
+
timeOfDay: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function optionalText(value: string): string | null {
|
|
15
|
+
const trimmed = value.trim();
|
|
16
|
+
return trimmed === '' ? null : trimmed;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Returns the `/contact` body; the server picks the subject from `siteId`, so none is sent. */
|
|
20
|
+
export function buildMeetingRequestPayload(values: MeetingRequestValues, siteId: string): MeetingRequestPayload {
|
|
21
|
+
return {
|
|
22
|
+
name: values.name.trim(),
|
|
23
|
+
email: values.email.trim(),
|
|
24
|
+
message: values.message.trim(),
|
|
25
|
+
company: optionalText(values.company),
|
|
26
|
+
website: optionalText(values.website),
|
|
27
|
+
siteId,
|
|
28
|
+
preferredDay: values.preferredDay,
|
|
29
|
+
timeOfDay: values.timeOfDay,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { SubmitOutcome } from './SubmitOutcome';
|
|
2
|
+
import type { MeetingRequestPayload } from './payload';
|
|
3
|
+
|
|
4
|
+
const HTTP_SUCCESS_MIN = 200;
|
|
5
|
+
const HTTP_SUCCESS_MAX = 299;
|
|
6
|
+
const HTTP_TOO_MANY_REQUESTS = 429;
|
|
7
|
+
|
|
8
|
+
export interface FetchResponseLike {
|
|
9
|
+
status: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export type FetchLike = (url: string, init: RequestInit) => Promise<FetchResponseLike>;
|
|
13
|
+
|
|
14
|
+
export interface MeetingSubmitRequest {
|
|
15
|
+
endpoint: string;
|
|
16
|
+
payload: MeetingRequestPayload;
|
|
17
|
+
timeoutMs: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Maps an HTTP status to sent (2xx), rate limited (429) or failed (anything else). */
|
|
21
|
+
export function outcomeForStatus(status: number): SubmitOutcome {
|
|
22
|
+
if (status >= HTTP_SUCCESS_MIN && status <= HTTP_SUCCESS_MAX) return SubmitOutcome.Sent;
|
|
23
|
+
return status === HTTP_TOO_MANY_REQUESTS ? SubmitOutcome.RateLimited : SubmitOutcome.Failed;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Posts the payload as JSON once, aborting after `timeoutMs`; a network error or timeout is failed. */
|
|
27
|
+
export async function submitMeetingRequest(request: MeetingSubmitRequest, fetchFn: FetchLike): Promise<SubmitOutcome> {
|
|
28
|
+
const controller = new AbortController();
|
|
29
|
+
const timer = setTimeout(() => controller.abort(), request.timeoutMs);
|
|
30
|
+
try {
|
|
31
|
+
const response = await fetchFn(request.endpoint, {
|
|
32
|
+
method: 'POST',
|
|
33
|
+
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
|
34
|
+
body: JSON.stringify(request.payload),
|
|
35
|
+
credentials: 'omit',
|
|
36
|
+
signal: controller.signal,
|
|
37
|
+
});
|
|
38
|
+
return outcomeForStatus(response.status);
|
|
39
|
+
} catch {
|
|
40
|
+
return SubmitOutcome.Failed;
|
|
41
|
+
} finally {
|
|
42
|
+
clearTimeout(timer);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { DateFieldError } from '../dateField/DateFieldError';
|
|
2
|
+
import { checkDateValue, toIsoDay } from '../dateField/isoDay';
|
|
3
|
+
import { FieldErrorKind } from './FieldErrorKind';
|
|
4
|
+
import { MeetingField } from './MeetingField';
|
|
5
|
+
import { TIME_OF_DAY_VALUES } from './TimeOfDay';
|
|
6
|
+
|
|
7
|
+
export const MAX_NAME_LENGTH = 200;
|
|
8
|
+
export const MAX_EMAIL_LENGTH = 320;
|
|
9
|
+
export const MAX_COMPANY_LENGTH = 200;
|
|
10
|
+
export const MAX_MESSAGE_LENGTH = 5000;
|
|
11
|
+
export const MIN_MESSAGE_LENGTH = 10;
|
|
12
|
+
|
|
13
|
+
const EMAIL_PART_COUNT = 2;
|
|
14
|
+
|
|
15
|
+
export interface MeetingRequestValues {
|
|
16
|
+
preferredDay: string;
|
|
17
|
+
timeOfDay: string;
|
|
18
|
+
name: string;
|
|
19
|
+
email: string;
|
|
20
|
+
company: string;
|
|
21
|
+
message: string;
|
|
22
|
+
website: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export type MeetingRequestErrors = Partial<Record<MeetingField, FieldErrorKind>>;
|
|
26
|
+
|
|
27
|
+
export const FIELD_ERROR_KINDS: Readonly<Record<MeetingField, readonly FieldErrorKind[]>> = {
|
|
28
|
+
[MeetingField.PreferredDay]: [FieldErrorKind.Required, FieldErrorKind.Invalid, FieldErrorKind.Past],
|
|
29
|
+
[MeetingField.TimeOfDay]: [FieldErrorKind.Required],
|
|
30
|
+
[MeetingField.Name]: [FieldErrorKind.Required, FieldErrorKind.TooLong],
|
|
31
|
+
[MeetingField.Email]: [FieldErrorKind.Required, FieldErrorKind.Invalid, FieldErrorKind.TooLong],
|
|
32
|
+
[MeetingField.Company]: [FieldErrorKind.TooLong],
|
|
33
|
+
[MeetingField.Message]: [FieldErrorKind.Required, FieldErrorKind.TooShort, FieldErrorKind.TooLong],
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const DAY_ERROR_KINDS: Readonly<Record<DateFieldError, FieldErrorKind>> = {
|
|
37
|
+
[DateFieldError.Required]: FieldErrorKind.Required,
|
|
38
|
+
[DateFieldError.Invalid]: FieldErrorKind.Invalid,
|
|
39
|
+
[DateFieldError.BeforeMin]: FieldErrorKind.Past,
|
|
40
|
+
[DateFieldError.AfterMax]: FieldErrorKind.Invalid,
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/** Returns the local calendar day of `now` as YYYY-MM-DD. */
|
|
44
|
+
export function todayIso(now: Date): string {
|
|
45
|
+
return toIsoDay(now);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function dayError(value: string, today: string): FieldErrorKind | undefined {
|
|
49
|
+
const error = checkDateValue(value, { min: today, required: true });
|
|
50
|
+
return error === undefined ? undefined : DAY_ERROR_KINDS[error];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function textError(value: string, maxLength: number, isRequired: boolean): FieldErrorKind | undefined {
|
|
54
|
+
const trimmed = value.trim();
|
|
55
|
+
if (isRequired && trimmed === '') return FieldErrorKind.Required;
|
|
56
|
+
return trimmed.length > maxLength ? FieldErrorKind.TooLong : undefined;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function isEmailShaped(value: string): boolean {
|
|
60
|
+
const parts = value.split('@');
|
|
61
|
+
if (parts.length !== EMAIL_PART_COUNT || [...value].some((char) => char.trim() === '')) return false;
|
|
62
|
+
const [local = '', domain = ''] = parts;
|
|
63
|
+
const dot = domain.lastIndexOf('.');
|
|
64
|
+
return local !== '' && dot > 0 && dot < domain.length - 1;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function messageError(value: string): FieldErrorKind | undefined {
|
|
68
|
+
const lengthError = textError(value, MAX_MESSAGE_LENGTH, true);
|
|
69
|
+
if (lengthError !== undefined) return lengthError;
|
|
70
|
+
return value.trim().length < MIN_MESSAGE_LENGTH ? FieldErrorKind.TooShort : undefined;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function emailError(value: string): FieldErrorKind | undefined {
|
|
74
|
+
const lengthError = textError(value, MAX_EMAIL_LENGTH, true);
|
|
75
|
+
if (lengthError !== undefined) return lengthError;
|
|
76
|
+
return isEmailShaped(value.trim()) ? undefined : FieldErrorKind.Invalid;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Returns the first error per field; a day before `today` (YYYY-MM-DD) is rejected. */
|
|
80
|
+
export function validateMeetingRequest(values: MeetingRequestValues, today: string): MeetingRequestErrors {
|
|
81
|
+
const checks: [MeetingField, FieldErrorKind | undefined][] = [
|
|
82
|
+
[MeetingField.PreferredDay, dayError(values.preferredDay, today)],
|
|
83
|
+
[MeetingField.TimeOfDay, TIME_OF_DAY_VALUES.includes(values.timeOfDay) ? undefined : FieldErrorKind.Required],
|
|
84
|
+
[MeetingField.Name, textError(values.name, MAX_NAME_LENGTH, true)],
|
|
85
|
+
[MeetingField.Email, emailError(values.email)],
|
|
86
|
+
[MeetingField.Company, textError(values.company, MAX_COMPANY_LENGTH, false)],
|
|
87
|
+
[MeetingField.Message, messageError(values.message)],
|
|
88
|
+
];
|
|
89
|
+
const errors: MeetingRequestErrors = {};
|
|
90
|
+
checks.forEach(([field, kind]) => {
|
|
91
|
+
if (kind !== undefined) errors[field] = kind;
|
|
92
|
+
});
|
|
93
|
+
return errors;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Returns true when any field has an error. */
|
|
97
|
+
export function hasErrors(errors: MeetingRequestErrors): boolean {
|
|
98
|
+
return Object.keys(errors).length > 0;
|
|
99
|
+
}
|