@dloizides/marketing-astro-kit 1.8.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 +11 -0
- package/package.json +12 -5
- package/src/DateField.astro +85 -0
- package/src/MeetingRequestForm.astro +214 -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
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.9.0
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- `<MeetingRequestForm />` (`./MeetingRequestForm.astro`) + `./meetingRequest` helpers: preferred day, time of day, name, email, company, message; validation (past day, bad email), JSON POST with timeout, sent / rate-limited (429) / failed states, mailto assembled in the browser, honeypot `website`, Send loading state, optional Umami event. Labels and endpoint are options; no subject is sent. MOONCUBE-SITE-1 "Moon Cube Technologies site: read and book", AC-07, AC-08, AC-18, AC-20, AC-21, AC-22.
|
|
8
|
+
- `<DateField />` (`./DateField.astro`) + `./dateField` helpers: the shared date input for Astro sites (DATE-INPUT-1 "Every date or date-time field uses the shared input"): native picker, label, min/max, error with `aria-invalid` + `aria-describedby`, 44 px control, themed by `--tmk-df-*`. `MeetingRequestForm` uses it for the day. MOONCUBE-SITE-1, D-SITE-17.
|
|
9
|
+
|
|
10
|
+
### Changed
|
|
11
|
+
|
|
12
|
+
- `MeetingRequestForm`: the message is required, at least 10 characters (matches the `/contact` server validator); new error kind `too-short` in `labels.errors`.
|
|
13
|
+
|
|
3
14
|
## 1.8.0
|
|
4
15
|
|
|
5
16
|
### Added
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dloizides/marketing-astro-kit",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "Reusable, themeable Astro marketing sections for product sites — a Free-vs-Pro pricing comparison table, a trust / credibility section (security cards, customer-logo + testimonial placeholders, discreet built-by), a client-side \"try it\" demo shell, and an SEO guides/content-hub card + frontmatter schema. Data-driven via a shared TypeScript schema; themed entirely through the host site's CSS custom properties.",
|
|
3
|
+
"version": "1.9.0",
|
|
4
|
+
"description": "Reusable, themeable Astro marketing sections for product sites — a Free-vs-Pro pricing comparison table, a trust / credibility section (security cards, customer-logo + testimonial placeholders, discreet built-by), a client-side \"try it\" demo shell, a meeting request form posting to a contact endpoint, and an SEO guides/content-hub card + frontmatter schema. Data-driven via a shared TypeScript schema; themed entirely through the host site's CSS custom properties.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"astro",
|
|
7
7
|
"marketing",
|
|
@@ -21,7 +21,10 @@
|
|
|
21
21
|
"hairline",
|
|
22
22
|
"illustration",
|
|
23
23
|
"booking",
|
|
24
|
-
"cal.com"
|
|
24
|
+
"cal.com",
|
|
25
|
+
"meeting-request",
|
|
26
|
+
"contact-form",
|
|
27
|
+
"date-field"
|
|
25
28
|
],
|
|
26
29
|
"author": "dloizides",
|
|
27
30
|
"license": "MIT",
|
|
@@ -53,11 +56,15 @@
|
|
|
53
56
|
"./BottomSheet.astro": "./src/BottomSheet.astro",
|
|
54
57
|
"./bottomSheet.css": "./src/bottomSheet.css",
|
|
55
58
|
"./BookingEmbed.astro": "./src/BookingEmbed.astro",
|
|
56
|
-
"./bookingEmbed": "./src/bookingEmbed/index.ts"
|
|
59
|
+
"./bookingEmbed": "./src/bookingEmbed/index.ts",
|
|
60
|
+
"./MeetingRequestForm.astro": "./src/MeetingRequestForm.astro",
|
|
61
|
+
"./meetingRequest": "./src/meetingRequest/index.ts",
|
|
62
|
+
"./DateField.astro": "./src/DateField.astro",
|
|
63
|
+
"./dateField": "./src/dateField/index.ts"
|
|
57
64
|
},
|
|
58
65
|
"scripts": {
|
|
59
66
|
"test": "vitest run",
|
|
60
|
-
"lint": "eslint src/bookingEmbed --ext .ts",
|
|
67
|
+
"lint": "eslint src/bookingEmbed src/dateField src/meetingRequest --ext .ts",
|
|
61
68
|
"typecheck": "tsc --noEmit -p ."
|
|
62
69
|
},
|
|
63
70
|
"dependencies": {
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
---
|
|
2
|
+
import { dateErrorId, dateFieldControlAria } from './dateField/attributes';
|
|
3
|
+
|
|
4
|
+
interface Props {
|
|
5
|
+
/** Control id; the error block is `<id>-error`. */
|
|
6
|
+
id: string;
|
|
7
|
+
name: string;
|
|
8
|
+
label: string;
|
|
9
|
+
value?: string;
|
|
10
|
+
/** Earliest day, YYYY-MM-DD, inclusive. */
|
|
11
|
+
min?: string;
|
|
12
|
+
/** Latest day, YYYY-MM-DD, inclusive. */
|
|
13
|
+
max?: string;
|
|
14
|
+
required?: boolean;
|
|
15
|
+
autofocus?: boolean;
|
|
16
|
+
/** Error shown on render; marks the control aria-invalid. The `error` slot replaces it for client-rendered messages. */
|
|
17
|
+
error?: string;
|
|
18
|
+
testId?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const { id, name, label, value, min, max, required = false, autofocus = false, error, testId } = Astro.props;
|
|
22
|
+
const errorId = dateErrorId(id);
|
|
23
|
+
const aria = dateFieldControlAria({ errorId, error });
|
|
24
|
+
const hasError = error !== undefined && error !== '';
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
<div class="tmk-df">
|
|
28
|
+
<label class="tmk-df-label" for={id}>{label}</label>
|
|
29
|
+
<input
|
|
30
|
+
class="tmk-df-control"
|
|
31
|
+
id={id}
|
|
32
|
+
name={name}
|
|
33
|
+
type="date"
|
|
34
|
+
value={value}
|
|
35
|
+
min={min}
|
|
36
|
+
max={max}
|
|
37
|
+
required={required}
|
|
38
|
+
autofocus={autofocus}
|
|
39
|
+
{...aria}
|
|
40
|
+
data-testid={testId}
|
|
41
|
+
/>
|
|
42
|
+
<p class="tmk-df-error" id={errorId} data-field-error={name} hidden={!hasError}>
|
|
43
|
+
<slot name="error">{error}</slot>
|
|
44
|
+
</p>
|
|
45
|
+
</div>
|
|
46
|
+
|
|
47
|
+
<style>
|
|
48
|
+
:where(.tmk-df) {
|
|
49
|
+
display: grid;
|
|
50
|
+
gap: var(--tmk-df-label-gap, 0.375rem);
|
|
51
|
+
min-width: 0;
|
|
52
|
+
}
|
|
53
|
+
:where(.tmk-df-label) {
|
|
54
|
+
color: var(--tmk-df-label-fg, inherit);
|
|
55
|
+
}
|
|
56
|
+
:where(.tmk-df-control) {
|
|
57
|
+
box-sizing: border-box;
|
|
58
|
+
width: 100%;
|
|
59
|
+
min-height: 44px;
|
|
60
|
+
padding: 0.625rem 0.75rem;
|
|
61
|
+
font: inherit;
|
|
62
|
+
color: var(--tmk-df-fg, inherit);
|
|
63
|
+
background: var(--tmk-df-bg, transparent);
|
|
64
|
+
border: 1px solid var(--tmk-df-border, currentColor);
|
|
65
|
+
border-radius: var(--tmk-df-radius, 0.5rem);
|
|
66
|
+
color-scheme: var(--tmk-df-color-scheme, normal);
|
|
67
|
+
}
|
|
68
|
+
:where(.tmk-df-control:focus-visible) {
|
|
69
|
+
outline: 2px solid var(--tmk-df-focus, currentColor);
|
|
70
|
+
outline-offset: 2px;
|
|
71
|
+
}
|
|
72
|
+
:where(.tmk-df-control)::-webkit-calendar-picker-indicator {
|
|
73
|
+
min-width: 24px;
|
|
74
|
+
min-height: 24px;
|
|
75
|
+
cursor: pointer;
|
|
76
|
+
}
|
|
77
|
+
:where(.tmk-df-control[aria-invalid='true']) {
|
|
78
|
+
border-color: var(--tmk-df-error, currentColor);
|
|
79
|
+
}
|
|
80
|
+
:where(.tmk-df-error) {
|
|
81
|
+
margin: 0;
|
|
82
|
+
color: var(--tmk-df-error, inherit);
|
|
83
|
+
overflow-wrap: anywhere;
|
|
84
|
+
}
|
|
85
|
+
</style>
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
---
|
|
2
|
+
import DateField from './DateField.astro';
|
|
3
|
+
import { contactDataAttributes, type BookingContact } from './bookingEmbed/contact';
|
|
4
|
+
import type { MeetingRequestLabels } from './meetingRequest/labels';
|
|
5
|
+
import { HONEYPOT_FIELD, MeetingField } from './meetingRequest/MeetingField';
|
|
6
|
+
import { serializeMeetingRequestOptions, type MeetingRequestOptions } from './meetingRequest/options';
|
|
7
|
+
import { TimeOfDay } from './meetingRequest/TimeOfDay';
|
|
8
|
+
import { FIELD_ERROR_KINDS, MIN_MESSAGE_LENGTH } from './meetingRequest/validation';
|
|
9
|
+
|
|
10
|
+
interface Props {
|
|
11
|
+
/** Unique id; controls are `<id>-<field>`. */
|
|
12
|
+
id: string;
|
|
13
|
+
options: MeetingRequestOptions;
|
|
14
|
+
/** Address parts, joined in the browser only for the error mailto link. */
|
|
15
|
+
contact: BookingContact;
|
|
16
|
+
labels: MeetingRequestLabels;
|
|
17
|
+
autofocusDay?: boolean;
|
|
18
|
+
testId?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const { id, options, contact, labels, autofocusDay = false, testId } = Astro.props;
|
|
22
|
+
const fieldId = (field: string): string => `${id}-${field}`;
|
|
23
|
+
const errorId = (field: string): string => `${id}-${field}-error`;
|
|
24
|
+
const fieldTestId = (field: string): string | undefined => (testId === undefined ? undefined : `${testId}-${field}`);
|
|
25
|
+
const textFields = [
|
|
26
|
+
{ field: MeetingField.Name, label: labels.name, type: 'text', autocomplete: 'name', required: true },
|
|
27
|
+
{ field: MeetingField.Email, label: labels.email, type: 'email', autocomplete: 'email', required: true },
|
|
28
|
+
{ field: MeetingField.Company, label: labels.company, type: 'text', autocomplete: 'organization', required: false },
|
|
29
|
+
];
|
|
30
|
+
const timeOptions = [
|
|
31
|
+
{ value: TimeOfDay.Morning, label: labels.morning },
|
|
32
|
+
{ value: TimeOfDay.Afternoon, label: labels.afternoon },
|
|
33
|
+
{ value: TimeOfDay.Evening, label: labels.evening },
|
|
34
|
+
];
|
|
35
|
+
---
|
|
36
|
+
|
|
37
|
+
<form
|
|
38
|
+
class="tmk-mr"
|
|
39
|
+
id={id}
|
|
40
|
+
aria-label={labels.form}
|
|
41
|
+
method="post"
|
|
42
|
+
action={options.endpoint}
|
|
43
|
+
novalidate
|
|
44
|
+
data-meeting-request
|
|
45
|
+
data-meeting-options={serializeMeetingRequestOptions(options)}
|
|
46
|
+
{...contactDataAttributes(contact)}
|
|
47
|
+
data-testid={testId}
|
|
48
|
+
>
|
|
49
|
+
<div class="tmk-mr-fields">
|
|
50
|
+
<div class="tmk-mr-row">
|
|
51
|
+
<DateField
|
|
52
|
+
id={fieldId(MeetingField.PreferredDay)}
|
|
53
|
+
name={MeetingField.PreferredDay}
|
|
54
|
+
label={labels.preferredDay}
|
|
55
|
+
required
|
|
56
|
+
autofocus={autofocusDay}
|
|
57
|
+
testId={fieldTestId(MeetingField.PreferredDay)}
|
|
58
|
+
>
|
|
59
|
+
<Fragment slot="error">
|
|
60
|
+
{FIELD_ERROR_KINDS[MeetingField.PreferredDay].map((kind) => <span data-error-kind={kind} hidden>{labels.errors[kind]}</span>)}
|
|
61
|
+
</Fragment>
|
|
62
|
+
</DateField>
|
|
63
|
+
<div class="tmk-mr-field">
|
|
64
|
+
<label for={fieldId(MeetingField.TimeOfDay)}>{labels.timeOfDay}</label>
|
|
65
|
+
<select class="tmk-mr-control" id={fieldId(MeetingField.TimeOfDay)} name={MeetingField.TimeOfDay} data-testid={fieldTestId(MeetingField.TimeOfDay)}>
|
|
66
|
+
{timeOptions.map((option) => <option value={option.value}>{option.label}</option>)}
|
|
67
|
+
</select>
|
|
68
|
+
<p class="tmk-mr-error" id={errorId(MeetingField.TimeOfDay)} data-field-error={MeetingField.TimeOfDay} hidden>
|
|
69
|
+
{FIELD_ERROR_KINDS[MeetingField.TimeOfDay].map((kind) => <span data-error-kind={kind} hidden>{labels.errors[kind]}</span>)}
|
|
70
|
+
</p>
|
|
71
|
+
</div>
|
|
72
|
+
</div>
|
|
73
|
+
{textFields.map((item) => (
|
|
74
|
+
<div class="tmk-mr-field">
|
|
75
|
+
<label for={fieldId(item.field)}>{item.label}</label>
|
|
76
|
+
<input
|
|
77
|
+
class="tmk-mr-control"
|
|
78
|
+
id={fieldId(item.field)}
|
|
79
|
+
name={item.field}
|
|
80
|
+
type={item.type}
|
|
81
|
+
autocomplete={item.autocomplete}
|
|
82
|
+
required={item.required}
|
|
83
|
+
data-testid={fieldTestId(item.field)}
|
|
84
|
+
/>
|
|
85
|
+
<p class="tmk-mr-error" id={errorId(item.field)} data-field-error={item.field} hidden>
|
|
86
|
+
{FIELD_ERROR_KINDS[item.field].map((kind) => <span data-error-kind={kind} hidden>{labels.errors[kind]}</span>)}
|
|
87
|
+
</p>
|
|
88
|
+
</div>
|
|
89
|
+
))}
|
|
90
|
+
<div class="tmk-mr-field">
|
|
91
|
+
<label for={fieldId(MeetingField.Message)}>{labels.message}</label>
|
|
92
|
+
<textarea class="tmk-mr-control tmk-mr-message" id={fieldId(MeetingField.Message)} name={MeetingField.Message} rows="4" required minlength={MIN_MESSAGE_LENGTH} data-testid={fieldTestId(MeetingField.Message)}></textarea>
|
|
93
|
+
<p class="tmk-mr-error" id={errorId(MeetingField.Message)} data-field-error={MeetingField.Message} hidden>
|
|
94
|
+
{FIELD_ERROR_KINDS[MeetingField.Message].map((kind) => <span data-error-kind={kind} hidden>{labels.errors[kind]}</span>)}
|
|
95
|
+
</p>
|
|
96
|
+
</div>
|
|
97
|
+
<div class="tmk-mr-hp" aria-hidden="true">
|
|
98
|
+
<input type="text" name={HONEYPOT_FIELD} tabindex="-1" autocomplete="off" />
|
|
99
|
+
</div>
|
|
100
|
+
<button class="tmk-mr-send" type="submit" aria-busy="false" data-meeting-send data-testid={fieldTestId('send')}>{labels.send}</button>
|
|
101
|
+
</div>
|
|
102
|
+
<div class="tmk-mr-status" data-meeting-status="sent" role="status" tabindex="-1" hidden><slot name="sent" /></div>
|
|
103
|
+
<div class="tmk-mr-status" data-meeting-status="rate-limited" role="alert" tabindex="-1" hidden><slot name="rate-limited" /></div>
|
|
104
|
+
<div class="tmk-mr-status" data-meeting-status="failed" role="alert" tabindex="-1" hidden><slot name="failed" /></div>
|
|
105
|
+
</form>
|
|
106
|
+
|
|
107
|
+
<style>
|
|
108
|
+
:where(.tmk-mr) {
|
|
109
|
+
--tmk-df-fg: var(--tmk-mr-field-fg, inherit);
|
|
110
|
+
--tmk-df-bg: var(--tmk-mr-field-bg, transparent);
|
|
111
|
+
--tmk-df-border: var(--tmk-mr-border, currentColor);
|
|
112
|
+
--tmk-df-radius: var(--tmk-mr-radius, 0.5rem);
|
|
113
|
+
--tmk-df-error: var(--tmk-mr-error, currentColor);
|
|
114
|
+
--tmk-df-color-scheme: var(--tmk-mr-color-scheme, normal);
|
|
115
|
+
display: block;
|
|
116
|
+
width: 100%;
|
|
117
|
+
color-scheme: var(--tmk-mr-color-scheme, normal);
|
|
118
|
+
}
|
|
119
|
+
:where(.tmk-mr-fields) {
|
|
120
|
+
display: grid;
|
|
121
|
+
gap: var(--tmk-mr-gap, 1rem);
|
|
122
|
+
}
|
|
123
|
+
:where(.tmk-mr-row) {
|
|
124
|
+
display: grid;
|
|
125
|
+
grid-template-columns: repeat(auto-fit, minmax(min(100%, 14rem), 1fr));
|
|
126
|
+
align-items: start;
|
|
127
|
+
gap: var(--tmk-mr-gap, 1rem);
|
|
128
|
+
}
|
|
129
|
+
:where(.tmk-mr-field) {
|
|
130
|
+
display: grid;
|
|
131
|
+
gap: 0.375rem;
|
|
132
|
+
min-width: 0;
|
|
133
|
+
}
|
|
134
|
+
:where(.tmk-mr-control) {
|
|
135
|
+
box-sizing: border-box;
|
|
136
|
+
width: 100%;
|
|
137
|
+
min-height: 44px;
|
|
138
|
+
padding: 0.625rem 0.75rem;
|
|
139
|
+
font: inherit;
|
|
140
|
+
color: var(--tmk-mr-field-fg, inherit);
|
|
141
|
+
background: var(--tmk-mr-field-bg, transparent);
|
|
142
|
+
border: 1px solid var(--tmk-mr-border, currentColor);
|
|
143
|
+
border-radius: var(--tmk-mr-radius, 0.5rem);
|
|
144
|
+
}
|
|
145
|
+
:where(.tmk-mr-message) {
|
|
146
|
+
resize: vertical;
|
|
147
|
+
}
|
|
148
|
+
:where(.tmk-mr-control[aria-invalid='true']) {
|
|
149
|
+
border-color: var(--tmk-mr-error, currentColor);
|
|
150
|
+
}
|
|
151
|
+
:where(.tmk-mr-error) {
|
|
152
|
+
margin: 0;
|
|
153
|
+
color: var(--tmk-mr-error, inherit);
|
|
154
|
+
overflow-wrap: anywhere;
|
|
155
|
+
}
|
|
156
|
+
:where(.tmk-mr-hp) {
|
|
157
|
+
position: absolute;
|
|
158
|
+
left: -10000px;
|
|
159
|
+
width: 1px;
|
|
160
|
+
height: 1px;
|
|
161
|
+
overflow: hidden;
|
|
162
|
+
}
|
|
163
|
+
:where(.tmk-mr-send) {
|
|
164
|
+
display: inline-flex;
|
|
165
|
+
align-items: center;
|
|
166
|
+
justify-content: center;
|
|
167
|
+
gap: 0.5rem;
|
|
168
|
+
min-height: 44px;
|
|
169
|
+
min-width: 44px;
|
|
170
|
+
padding: 0.625rem 1.25rem;
|
|
171
|
+
font: inherit;
|
|
172
|
+
color: var(--tmk-mr-send-fg, inherit);
|
|
173
|
+
background: var(--tmk-mr-send-bg, transparent);
|
|
174
|
+
border: 1px solid var(--tmk-mr-send-border, currentColor);
|
|
175
|
+
border-radius: var(--tmk-mr-radius, 0.5rem);
|
|
176
|
+
cursor: pointer;
|
|
177
|
+
justify-self: start;
|
|
178
|
+
}
|
|
179
|
+
:where(.tmk-mr-send[data-loading]) {
|
|
180
|
+
cursor: progress;
|
|
181
|
+
opacity: 0.8;
|
|
182
|
+
}
|
|
183
|
+
:where(.tmk-mr-send[data-loading])::after {
|
|
184
|
+
content: '';
|
|
185
|
+
width: 1em;
|
|
186
|
+
height: 1em;
|
|
187
|
+
border: 2px solid currentColor;
|
|
188
|
+
border-right-color: transparent;
|
|
189
|
+
border-radius: 50%;
|
|
190
|
+
animation: tmk-mr-spin 0.8s linear infinite;
|
|
191
|
+
}
|
|
192
|
+
:where(.tmk-mr[data-meeting-state='sent'] .tmk-mr-fields) {
|
|
193
|
+
display: none;
|
|
194
|
+
}
|
|
195
|
+
:where(.tmk-mr-status) {
|
|
196
|
+
overflow-wrap: anywhere;
|
|
197
|
+
}
|
|
198
|
+
@keyframes tmk-mr-spin {
|
|
199
|
+
to {
|
|
200
|
+
transform: rotate(360deg);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
@media (prefers-reduced-motion: reduce) {
|
|
204
|
+
:where(.tmk-mr-send[data-loading])::after {
|
|
205
|
+
animation: none;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
</style>
|
|
209
|
+
|
|
210
|
+
<script>
|
|
211
|
+
import { mountMeetingRequestForms } from './meetingRequest/mount';
|
|
212
|
+
|
|
213
|
+
mountMeetingRequestForms();
|
|
214
|
+
</script>
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export interface DateFieldAriaInput {
|
|
2
|
+
errorId: string;
|
|
3
|
+
hintId?: string;
|
|
4
|
+
error?: string;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export interface DateFieldAria {
|
|
8
|
+
'aria-invalid'?: 'true';
|
|
9
|
+
'aria-describedby'?: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Returns the id of a date field's error block. */
|
|
13
|
+
export function dateErrorId(fieldId: string): string {
|
|
14
|
+
return `${fieldId}-error`;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Returns the control's aria-invalid and aria-describedby for the current error and hint. */
|
|
18
|
+
export function dateFieldControlAria(input: DateFieldAriaInput): DateFieldAria {
|
|
19
|
+
const hasError = input.error !== undefined && input.error !== '';
|
|
20
|
+
const describedBy = [input.hintId, hasError ? input.errorId : undefined].filter((id): id is string => id !== undefined);
|
|
21
|
+
const aria: DateFieldAria = {};
|
|
22
|
+
if (hasError) aria['aria-invalid'] = 'true';
|
|
23
|
+
if (describedBy.length > 0) aria['aria-describedby'] = describedBy.join(' ');
|
|
24
|
+
return aria;
|
|
25
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { DateFieldError } from './DateFieldError';
|
|
2
|
+
|
|
3
|
+
const ISO_DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
|
4
|
+
const MONTH_OFFSET = 1;
|
|
5
|
+
const PAD_WIDTH = 2;
|
|
6
|
+
|
|
7
|
+
export interface DateBounds {
|
|
8
|
+
min?: string;
|
|
9
|
+
max?: string;
|
|
10
|
+
required?: boolean;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function pad(value: number): string {
|
|
14
|
+
return String(value).padStart(PAD_WIDTH, '0');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Returns the local calendar day of `date` as YYYY-MM-DD. */
|
|
18
|
+
export function toIsoDay(date: Date): string {
|
|
19
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + MONTH_OFFSET)}-${pad(date.getDate())}`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Returns true when `value` is a YYYY-MM-DD day that exists on the calendar. */
|
|
23
|
+
export function isIsoDay(value: string): boolean {
|
|
24
|
+
if (!ISO_DAY_PATTERN.test(value)) return false;
|
|
25
|
+
const date = new Date(`${value}T00:00:00Z`);
|
|
26
|
+
return !Number.isNaN(date.getTime()) && date.toISOString().startsWith(value);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Returns why `value` breaks the bounds (min and max are inclusive YYYY-MM-DD), or undefined when it fits. */
|
|
30
|
+
export function checkDateValue(value: string, bounds: DateBounds): DateFieldError | undefined {
|
|
31
|
+
if (value === '') return bounds.required === true ? DateFieldError.Required : undefined;
|
|
32
|
+
if (!isIsoDay(value)) return DateFieldError.Invalid;
|
|
33
|
+
if (bounds.min !== undefined && value < bounds.min) return DateFieldError.BeforeMin;
|
|
34
|
+
return bounds.max !== undefined && value > bounds.max ? DateFieldError.AfterMax : undefined;
|
|
35
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** The form control names of the meeting request form. */
|
|
2
|
+
export const enum MeetingField {
|
|
3
|
+
PreferredDay = 'preferredDay',
|
|
4
|
+
TimeOfDay = 'timeOfDay',
|
|
5
|
+
Name = 'name',
|
|
6
|
+
Email = 'email',
|
|
7
|
+
Company = 'company',
|
|
8
|
+
Message = 'message',
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export const HONEYPOT_FIELD = 'website';
|
|
@@ -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
|
+
}
|