@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,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,22 @@
|
|
|
1
|
+
export interface BookingContact {
|
|
2
|
+
local: string;
|
|
3
|
+
domain: string;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
/** Joins the two parts into an address at runtime, so the served HTML never holds it; throws on a bad part. */
|
|
7
|
+
export function assembleContactEmail(local: string, domain: string): string {
|
|
8
|
+
if (local === '' || local.includes('@')) throw new Error('BookingEmbed: contact local part must be non-empty with no @');
|
|
9
|
+
if (domain === '' || domain.includes('@')) throw new Error('BookingEmbed: contact domain must be non-empty with no @');
|
|
10
|
+
return `${local}@${domain}`;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Returns the mailto link for the contact. */
|
|
14
|
+
export function contactMailtoHref(contact: BookingContact): string {
|
|
15
|
+
return `mailto:${assembleContactEmail(contact.local, contact.domain)}`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Returns the split data attributes the host renders instead of an address. */
|
|
19
|
+
export function contactDataAttributes(contact: BookingContact): Record<string, string> {
|
|
20
|
+
assembleContactEmail(contact.local, contact.domain);
|
|
21
|
+
return { 'data-local': contact.local, 'data-domain': contact.domain };
|
|
22
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { BookingState } from './BookingState';
|
|
2
|
+
|
|
3
|
+
export interface FallbackWatchOptions {
|
|
4
|
+
timeoutMs: number;
|
|
5
|
+
onFallback: () => void;
|
|
6
|
+
onLoaded?: () => void;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface FallbackWatch {
|
|
10
|
+
markLoaded: () => void;
|
|
11
|
+
markFailed: () => void;
|
|
12
|
+
state: () => BookingState;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Shows the fallback once when the embed errors or is not ready within `timeoutMs`; a ready embed cancels it. */
|
|
16
|
+
export function createFallbackWatch(options: FallbackWatchOptions): FallbackWatch {
|
|
17
|
+
let state = BookingState.Loading;
|
|
18
|
+
const fallBack = (): void => {
|
|
19
|
+
if (state !== BookingState.Loading) return;
|
|
20
|
+
state = BookingState.Fallback;
|
|
21
|
+
options.onFallback();
|
|
22
|
+
};
|
|
23
|
+
const timer = setTimeout(fallBack, options.timeoutMs);
|
|
24
|
+
return {
|
|
25
|
+
markLoaded: (): void => {
|
|
26
|
+
if (state !== BookingState.Loading) return;
|
|
27
|
+
state = BookingState.Ready;
|
|
28
|
+
clearTimeout(timer);
|
|
29
|
+
options.onLoaded?.();
|
|
30
|
+
},
|
|
31
|
+
markFailed: (): void => {
|
|
32
|
+
clearTimeout(timer);
|
|
33
|
+
fallBack();
|
|
34
|
+
},
|
|
35
|
+
state: (): BookingState => state,
|
|
36
|
+
};
|
|
37
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { BookingState } from './BookingState';
|
|
2
|
+
import { contactMailtoHref } from './contact';
|
|
3
|
+
import { createFallbackWatch, type FallbackWatch } from './fallbackWatch';
|
|
4
|
+
import {
|
|
5
|
+
buildCalCommands,
|
|
6
|
+
calEmbedScriptUrl,
|
|
7
|
+
parseBookingOptions,
|
|
8
|
+
resolveBookingTimeoutMs,
|
|
9
|
+
resolveCalNamespace,
|
|
10
|
+
} from './options';
|
|
11
|
+
|
|
12
|
+
const HOST_SELECTOR = '[data-booking-embed]';
|
|
13
|
+
const CALENDAR_SELECTOR = '[data-booking-calendar]';
|
|
14
|
+
const FALLBACK_SELECTOR = '[data-booking-fallback]';
|
|
15
|
+
const CONTACT_SELECTOR = '[data-booking-contact]';
|
|
16
|
+
const SCRIPT_SELECTOR = 'script[data-booking-cal-script]';
|
|
17
|
+
const SCRIPT_FAILED = 'failed';
|
|
18
|
+
const SELECTOR_UNSAFE_CHARS = /[^\w-]/g;
|
|
19
|
+
|
|
20
|
+
export interface CalQueue {
|
|
21
|
+
(...args: unknown[]): void;
|
|
22
|
+
q: unknown[][];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface CalApi extends CalQueue {
|
|
26
|
+
ns: Record<string, CalQueue | undefined>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export type CalWindow = Window & { Cal?: CalApi };
|
|
30
|
+
|
|
31
|
+
function createQueue(): CalQueue {
|
|
32
|
+
const queue = ((...args: unknown[]): void => {
|
|
33
|
+
queue.q.push(args);
|
|
34
|
+
}) as CalQueue;
|
|
35
|
+
queue.q = [];
|
|
36
|
+
return queue;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function createCalStub(doc: Document, scriptUrl: string): CalApi {
|
|
40
|
+
const cal = ((...args: unknown[]): void => {
|
|
41
|
+
const namespace = args[1];
|
|
42
|
+
if (args[0] !== 'init' || typeof namespace !== 'string') {
|
|
43
|
+
cal.q.push(args);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
const api = cal.ns[namespace] ?? createQueue();
|
|
47
|
+
cal.ns[namespace] = api;
|
|
48
|
+
api.q.push(args);
|
|
49
|
+
cal.q.push(['initNamespace', namespace]);
|
|
50
|
+
}) as CalApi;
|
|
51
|
+
cal.q = [];
|
|
52
|
+
cal.ns = {};
|
|
53
|
+
const script = doc.createElement('script');
|
|
54
|
+
script.src = scriptUrl;
|
|
55
|
+
script.async = true;
|
|
56
|
+
script.dataset.bookingCalScript = '';
|
|
57
|
+
script.addEventListener('error', () => {
|
|
58
|
+
script.dataset.bookingCalScript = SCRIPT_FAILED;
|
|
59
|
+
});
|
|
60
|
+
doc.head.appendChild(script);
|
|
61
|
+
return cal;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function fillContactLinks(host: HTMLElement): void {
|
|
65
|
+
const { local, domain } = host.dataset;
|
|
66
|
+
if (local === undefined || domain === undefined) return;
|
|
67
|
+
const href = contactMailtoHref({ local, domain });
|
|
68
|
+
host.querySelectorAll<HTMLAnchorElement>(CONTACT_SELECTOR).forEach((link) => {
|
|
69
|
+
link.href = href;
|
|
70
|
+
if ((link.textContent ?? '').trim() === '') link.textContent = href.replace('mailto:', '');
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function showFallback(host: HTMLElement): void {
|
|
75
|
+
host.dataset.bookingState = BookingState.Fallback;
|
|
76
|
+
fillContactLinks(host);
|
|
77
|
+
const calendar = host.querySelector<HTMLElement>(CALENDAR_SELECTOR);
|
|
78
|
+
const fallback = host.querySelector<HTMLElement>(FALLBACK_SELECTOR);
|
|
79
|
+
if (calendar !== null) calendar.hidden = true;
|
|
80
|
+
if (fallback !== null) fallback.hidden = false;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function mountHost(host: HTMLElement, getCal: (scriptUrl: string) => CalApi): FallbackWatch {
|
|
84
|
+
host.dataset.bookingState = BookingState.Loading;
|
|
85
|
+
const parsed = parseBookingOptions(host.dataset.bookingOptions ?? '');
|
|
86
|
+
const options = { ...parsed, namespace: resolveCalNamespace(parsed, host.id) };
|
|
87
|
+
const calendarId = host.querySelector<HTMLElement>(CALENDAR_SELECTOR)?.id ?? '';
|
|
88
|
+
const [init, ...rest] = buildCalCommands(options, `#${calendarId.replace(SELECTOR_UNSAFE_CHARS, '\\$&')}`);
|
|
89
|
+
const cal = getCal(calEmbedScriptUrl(options.origin));
|
|
90
|
+
const watch = createFallbackWatch({
|
|
91
|
+
timeoutMs: resolveBookingTimeoutMs(options.timeoutMs),
|
|
92
|
+
onFallback: () => showFallback(host),
|
|
93
|
+
onLoaded: () => {
|
|
94
|
+
host.dataset.bookingState = BookingState.Ready;
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
if (init !== undefined) cal(...init);
|
|
98
|
+
const api = cal.ns[options.namespace];
|
|
99
|
+
rest.forEach((command) => api?.(...command));
|
|
100
|
+
api?.('on', { action: 'linkReady', callback: () => watch.markLoaded() });
|
|
101
|
+
api?.('on', { action: 'linkFailed', callback: () => watch.markFailed() });
|
|
102
|
+
return watch;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function mountOrFallBack(host: HTMLElement, cal: (scriptUrl: string) => CalApi): FallbackWatch | null {
|
|
106
|
+
try {
|
|
107
|
+
return mountHost(host, cal);
|
|
108
|
+
} catch (error) {
|
|
109
|
+
console.warn(`BookingEmbed: host "${host.id}" shows its fallback: ${String(error)}`);
|
|
110
|
+
showFallback(host);
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function watchScriptFailure(doc: Document, watches: FallbackWatch[]): void {
|
|
116
|
+
const script = doc.querySelector<HTMLScriptElement>(SCRIPT_SELECTOR);
|
|
117
|
+
if (script === null || watches.length === 0) return;
|
|
118
|
+
const failAll = (): void => watches.forEach((watch) => watch.markFailed());
|
|
119
|
+
if (script.dataset.bookingCalScript === SCRIPT_FAILED) failAll();
|
|
120
|
+
else script.addEventListener('error', failAll);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Mounts every not-yet-mounted booking host on the page; adds the Cal.com script only when one exists. */
|
|
124
|
+
export function mountBookingEmbeds(doc: Document = document, win: CalWindow = window): number {
|
|
125
|
+
const hosts = Array.from(doc.querySelectorAll<HTMLElement>(HOST_SELECTOR)).filter(
|
|
126
|
+
(host) => host.dataset.bookingState === undefined,
|
|
127
|
+
);
|
|
128
|
+
if (hosts.length === 0) return 0;
|
|
129
|
+
const watches: FallbackWatch[] = [];
|
|
130
|
+
const cal = (scriptUrl: string): CalApi => {
|
|
131
|
+
win.Cal ??= createCalStub(doc, scriptUrl);
|
|
132
|
+
return win.Cal;
|
|
133
|
+
};
|
|
134
|
+
hosts.forEach((host) => {
|
|
135
|
+
const watch = mountOrFallBack(host, cal);
|
|
136
|
+
if (watch !== null) watches.push(watch);
|
|
137
|
+
});
|
|
138
|
+
watchScriptFailure(doc, watches);
|
|
139
|
+
return hosts.length;
|
|
140
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { BookingTheme } from './BookingTheme';
|
|
2
|
+
import { CalLayout } from './CalLayout';
|
|
3
|
+
|
|
4
|
+
export const DEFAULT_BOOKING_TIMEOUT_MS = 8000;
|
|
5
|
+
export const DEFAULT_CAL_NAMESPACE = 'booking';
|
|
6
|
+
export const DEFAULT_CAL_ORIGIN = 'https://app.cal.com';
|
|
7
|
+
const CAL_EMBED_SCRIPT_PATH = '/embed/embed.js';
|
|
8
|
+
|
|
9
|
+
const CAL_LINK_PATTERN = /^[\w.-]+(\/[\w.-]+)*$/;
|
|
10
|
+
const CAL_VAR_PATTERN = /^cal-[a-z-]+$/;
|
|
11
|
+
const CAL_NAMESPACE_PATTERN = /^[\w-]+$/;
|
|
12
|
+
const NAMESPACE_UNSAFE_CHARS = /[^\w-]/g;
|
|
13
|
+
const HTTPS_PROTOCOL = 'https:';
|
|
14
|
+
const HEX_COLOUR_PATTERN = /^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
|
|
15
|
+
|
|
16
|
+
export type CalCssVars = Record<string, string>;
|
|
17
|
+
export type CalCssVarsPerTheme = Partial<Record<BookingTheme, CalCssVars>>;
|
|
18
|
+
|
|
19
|
+
export interface BookingEmbedOptions {
|
|
20
|
+
calLink: string;
|
|
21
|
+
theme?: BookingTheme;
|
|
22
|
+
layout?: CalLayout;
|
|
23
|
+
hideEventTypeDetails?: boolean;
|
|
24
|
+
cssVarsPerTheme?: CalCssVarsPerTheme;
|
|
25
|
+
timeoutMs?: number;
|
|
26
|
+
namespace?: string;
|
|
27
|
+
origin?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface CalUiConfig {
|
|
31
|
+
theme: BookingTheme;
|
|
32
|
+
hideEventTypeDetails: boolean;
|
|
33
|
+
layout: CalLayout;
|
|
34
|
+
cssVarsPerTheme: CalCssVarsPerTheme;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export type CalCommand = [string, ...unknown[]];
|
|
38
|
+
|
|
39
|
+
/** Returns the timeout in ms, or the 8 s default when the value is missing, not finite or not positive. */
|
|
40
|
+
export function resolveBookingTimeoutMs(value: number | undefined): number {
|
|
41
|
+
const isUsable = value !== undefined && Number.isFinite(value) && value > 0;
|
|
42
|
+
return isUsable ? value : DEFAULT_BOOKING_TIMEOUT_MS;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function parseUrl(value: string): URL | null {
|
|
46
|
+
try {
|
|
47
|
+
return new URL(value);
|
|
48
|
+
} catch {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function hasNoPath(value: string, url: URL): boolean {
|
|
54
|
+
return url.protocol === HTTPS_PROTOCOL && (value === url.origin || value === `${url.origin}/`);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Returns the Cal.com origin, default app.cal.com; throws unless it is an https URL with no path. */
|
|
58
|
+
export function resolveCalOrigin(origin: string | undefined): string {
|
|
59
|
+
const value = origin ?? DEFAULT_CAL_ORIGIN;
|
|
60
|
+
const url = parseUrl(value);
|
|
61
|
+
if (url === null || !hasNoPath(value, url)) throw new Error(`BookingEmbed: "${value}" is not an https origin`);
|
|
62
|
+
return url.origin;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Returns the Cal.com embed script URL on the given origin. */
|
|
66
|
+
export function calEmbedScriptUrl(origin: string | undefined): string {
|
|
67
|
+
return `${resolveCalOrigin(origin)}${CAL_EMBED_SCRIPT_PATH}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Returns the namespace from the options, else the host id with every non `[\w-]` character as `-`, else the default. */
|
|
71
|
+
export function resolveCalNamespace(options: BookingEmbedOptions, hostId: string): string {
|
|
72
|
+
return options.namespace ?? (hostId !== '' ? hostId.replace(NAMESPACE_UNSAFE_CHARS, '-') : DEFAULT_CAL_NAMESPACE);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function checkNamespace(namespace: string): string {
|
|
76
|
+
if (!CAL_NAMESPACE_PATTERN.test(namespace)) throw new Error(`BookingEmbed: "${namespace}" is not a namespace`);
|
|
77
|
+
return namespace;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function checkCssVars(vars: CalCssVars): CalCssVars {
|
|
81
|
+
Object.entries(vars).forEach(([name, colour]) => {
|
|
82
|
+
if (!CAL_VAR_PATTERN.test(name)) throw new Error(`BookingEmbed: "${name}" is not a Cal.com cal-* variable`);
|
|
83
|
+
if (!HEX_COLOUR_PATTERN.test(colour)) throw new Error(`BookingEmbed: colour for "${name}" must be hex`);
|
|
84
|
+
});
|
|
85
|
+
return { ...vars };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function checkCssVarsPerTheme(perTheme: CalCssVarsPerTheme | undefined): CalCssVarsPerTheme {
|
|
89
|
+
const checked: CalCssVarsPerTheme = {};
|
|
90
|
+
Object.entries(perTheme ?? {}).forEach(([theme, vars]) => {
|
|
91
|
+
checked[theme as BookingTheme] = checkCssVars(vars);
|
|
92
|
+
});
|
|
93
|
+
return checked;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Builds the Cal.com `ui` instruction from the options; throws on a non-hex colour or a non `cal-*` variable. */
|
|
97
|
+
export function buildCalUiConfig(options: BookingEmbedOptions): CalUiConfig {
|
|
98
|
+
return {
|
|
99
|
+
theme: options.theme ?? BookingTheme.Dark,
|
|
100
|
+
hideEventTypeDetails: options.hideEventTypeDetails ?? false,
|
|
101
|
+
layout: options.layout ?? CalLayout.Month,
|
|
102
|
+
cssVarsPerTheme: checkCssVarsPerTheme(options.cssVarsPerTheme),
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Builds the ordered Cal.com calls (init, inline, ui) for one embed; throws on an unsafe link, origin or namespace. */
|
|
107
|
+
export function buildCalCommands(options: BookingEmbedOptions, elementOrSelector: string): CalCommand[] {
|
|
108
|
+
if (!CAL_LINK_PATTERN.test(options.calLink)) throw new Error(`BookingEmbed: "${options.calLink}" is not a Cal.com link`);
|
|
109
|
+
const ui = buildCalUiConfig(options);
|
|
110
|
+
return [
|
|
111
|
+
['init', checkNamespace(options.namespace ?? DEFAULT_CAL_NAMESPACE), { origin: resolveCalOrigin(options.origin) }],
|
|
112
|
+
[
|
|
113
|
+
'inline',
|
|
114
|
+
{ elementOrSelector, calLink: options.calLink, layout: ui.layout, config: { layout: ui.layout, theme: ui.theme } },
|
|
115
|
+
],
|
|
116
|
+
['ui', ui],
|
|
117
|
+
];
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Checks the options and serialises them for the embed host's data attribute. */
|
|
121
|
+
export function serializeBookingOptions(options: BookingEmbedOptions): string {
|
|
122
|
+
buildCalCommands(options, '#check');
|
|
123
|
+
return JSON.stringify(options);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Parses the host's data attribute back into options; throws when it is not an options object. */
|
|
127
|
+
export function parseBookingOptions(raw: string): BookingEmbedOptions {
|
|
128
|
+
const parsed: unknown = JSON.parse(raw);
|
|
129
|
+
const hasLink = typeof parsed === 'object' && parsed !== null && typeof (parsed as BookingEmbedOptions).calLink === 'string';
|
|
130
|
+
if (!hasLink) throw new Error('BookingEmbed: options need a calLink');
|
|
131
|
+
return parsed as BookingEmbedOptions;
|
|
132
|
+
}
|
|
@@ -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';
|