@meetelise/chat 1.63.0 → 1.64.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.
@@ -78,7 +78,7 @@ import { readGoogleReserveReferral } from "../../googleReserve";
78
78
  import fetchBuildingUnitsSummary, {
79
79
  UnitSummary,
80
80
  } from "../../fetchBuildingUnitsSummary";
81
- import { focusFirstTabStop, trapTabInside } from "../pubnub-chat";
81
+ import { placeFocusInside, trapTabInside } from "../pubnub-chat";
82
82
 
83
83
  @customElement("tour-scheduler")
84
84
  export class TourScheduler extends LitElement {
@@ -167,7 +167,7 @@ export class TourScheduler extends LitElement {
167
167
 
168
168
  updated(): void {
169
169
  if (this.movedFocusInside) return;
170
- if (focusFirstTabStop(this)) {
170
+ if (placeFocusInside(this)) {
171
171
  this.movedFocusInside = true;
172
172
  return;
173
173
  }
@@ -0,0 +1,123 @@
1
+ import { getDefaultLeadSourceAttribution } from "../LeadSourceClient";
2
+ import type { LeadSourceSubmittedListItem } from "../LeadSourceMultitouchClient";
3
+ import { snakify } from "../../utils";
4
+ import type {
5
+ BookingAttribution,
6
+ BookingContact,
7
+ BookingRequest,
8
+ PlanRequest,
9
+ PlanResponse,
10
+ TourTypeId,
11
+ } from "./tourItineraryApi";
12
+
13
+ /** What the prospect has chosen on the schedule step. */
14
+ export interface ItineraryChoice {
15
+ /** New stops, in the prospect's order. */
16
+ buildingIds: number[];
17
+ tourType: TourTypeId;
18
+ date: string;
19
+ /** "HH:mm" picked for the first new stop, or null for the earliest. */
20
+ firstStart: string | null;
21
+ /** ISO starts picked for later new stops, by building id. */
22
+ laterStarts: Record<number, string>;
23
+ /** Booked events this itinerary extends, in order; the last one is fixed first. */
24
+ existingEventIds: number[];
25
+ }
26
+
27
+ export const buildPlanRequest = (choice: ItineraryChoice): PlanRequest => {
28
+ const laterStarts = Object.fromEntries(
29
+ choice.buildingIds
30
+ .slice(1)
31
+ .filter((id) => choice.laterStarts[id])
32
+ .map((id) => [String(id), choice.laterStarts[id]])
33
+ );
34
+ const fixedEventId =
35
+ choice.existingEventIds[choice.existingEventIds.length - 1];
36
+ return {
37
+ building_ids: choice.buildingIds,
38
+ tour_type: choice.tourType,
39
+ date: choice.date,
40
+ start_time: choice.firstStart,
41
+ stop_starts: Object.keys(laterStarts).length > 0 ? laterStarts : null,
42
+ fixed_first:
43
+ fixedEventId === undefined ? null : { calendar_event_id: fixedEventId },
44
+ };
45
+ };
46
+
47
+ /**
48
+ * Lead-source attribution, built the way tour-scheduler.ts builds the same
49
+ * fields for /v2/scheduleMe.
50
+ */
51
+ export const buildAttribution = ({
52
+ orgSlug,
53
+ selectedLeadSource,
54
+ currentLeadSource,
55
+ touchpoints,
56
+ search,
57
+ referrer,
58
+ googleReferral,
59
+ }: {
60
+ orgSlug: string;
61
+ /** Picked in the "How did you hear about us?" dropdown. */
62
+ selectedLeadSource: string | null;
63
+ /** Derived from the referrer and query params. */
64
+ currentLeadSource: string;
65
+ touchpoints: LeadSourceSubmittedListItem[];
66
+ search: string;
67
+ referrer: string;
68
+ googleReferral: {
69
+ rwgToken: string;
70
+ buildingId: number;
71
+ environment: string;
72
+ } | null;
73
+ }): BookingAttribution => {
74
+ const parsedLeadSource = selectedLeadSource || currentLeadSource || null;
75
+ const defaultLeadSource = getDefaultLeadSourceAttribution(orgSlug);
76
+ return {
77
+ lead_sources: [
78
+ ...new Set(
79
+ parsedLeadSource
80
+ ? [parsedLeadSource, defaultLeadSource]
81
+ : [defaultLeadSource]
82
+ ),
83
+ ],
84
+ lead_sources_with_timestamps: touchpoints.map((source) =>
85
+ snakify({ ...source })
86
+ ),
87
+ query_params: Object.fromEntries(new URLSearchParams(search).entries()),
88
+ referrer,
89
+ google_rwg_token: googleReferral?.rwgToken ?? null,
90
+ google_referral_building_id: googleReferral?.buildingId ?? null,
91
+ google_environment: googleReferral?.environment ?? null,
92
+ };
93
+ };
94
+
95
+ export const buildBookingRequest = ({
96
+ choice,
97
+ plan,
98
+ contact,
99
+ attribution,
100
+ conversationTrackingId,
101
+ cancelExistingTours,
102
+ }: {
103
+ choice: ItineraryChoice;
104
+ plan: PlanResponse;
105
+ contact: BookingContact;
106
+ attribution: BookingAttribution;
107
+ conversationTrackingId: string | null;
108
+ cancelExistingTours: boolean;
109
+ }): BookingRequest => ({
110
+ tour_type: choice.tourType,
111
+ stops: [
112
+ ...choice.existingEventIds.map((id) => ({
113
+ existing_calendar_event_id: id,
114
+ })),
115
+ ...plan.stops
116
+ .filter((stop) => !stop.fixed)
117
+ .map((stop) => ({ building_id: stop.building_id, start: stop.start })),
118
+ ],
119
+ contact,
120
+ lead_sources: attribution,
121
+ conversation_tracking_id: conversationTrackingId,
122
+ cancel_existing_tours: cancelExistingTours,
123
+ });
@@ -0,0 +1,256 @@
1
+ import axios, { AxiosError } from "axios";
2
+
3
+ /**
4
+ * Client for the widget tour itinerary endpoints (communities, plan, book).
5
+ * The schemas follow the contract shared with the backend; the server owns
6
+ * ranking, caps, chaining and every prospect-facing reason, and the widget only
7
+ * renders what comes back.
8
+ */
9
+
10
+ export type TourTypeId =
11
+ | "escorted-tour"
12
+ | "self-guided-tour"
13
+ | "live-virtual-tour";
14
+
15
+ export interface CommunityAddress {
16
+ line1: string | null;
17
+ city: string | null;
18
+ state: string | null;
19
+ }
20
+
21
+ export interface Community {
22
+ building_id: number;
23
+ name: string;
24
+ address: CommunityAddress | null;
25
+ timezone: string | null;
26
+ distance_mi: number | null;
27
+ /** In US dollars. */
28
+ price_from: { bedrooms: number; amount: number } | null;
29
+ next_available: { date: string; time: string } | null;
30
+ best_match: boolean;
31
+ image_url: string | null;
32
+ tourable: boolean;
33
+ /** The text to show when the community can't be toured. */
34
+ unavailable_reason: string | null;
35
+ }
36
+
37
+ /**
38
+ * Most stops in one itinerary, counting ones already booked. The server's cap,
39
+ * mirrored here for the picker; booking enforces the real one.
40
+ */
41
+ export const MAX_ITINERARY_STOPS = 3;
42
+
43
+ /** The top communities after filtering; there's no paging. */
44
+ export interface CommunitiesResponse {
45
+ anchor: { building_id: number; name: string; is_general_building: boolean };
46
+ communities: Community[];
47
+ }
48
+
49
+ export interface CommunityFilters {
50
+ bedrooms: number[];
51
+ moveIn: string | null;
52
+ maxBudget: number | null;
53
+ }
54
+
55
+ /** Adding a stop after a booking: the widget sends what it knows of that booking. */
56
+ export interface ExtendQuery {
57
+ /** ISO 8601 with offset: when the last booked stop ends. */
58
+ availableAfter: string;
59
+ tourType: TourTypeId;
60
+ /** The last booked stop's building, which distances are measured from. */
61
+ nearBuildingId: number;
62
+ /** Every building already in the itinerary. */
63
+ excludeBuildingIds: number[];
64
+ }
65
+
66
+ export interface CommunityQuery extends CommunityFilters {
67
+ extend?: ExtendQuery;
68
+ }
69
+
70
+ export interface PlanRequest {
71
+ building_ids: number[];
72
+ tour_type: TourTypeId;
73
+ date: string;
74
+ start_time: string | null;
75
+ stop_starts: Record<string, string> | null;
76
+ fixed_first: { calendar_event_id: number } | null;
77
+ }
78
+
79
+ export interface PlanStop {
80
+ building_id: number;
81
+ start: string;
82
+ end: string;
83
+ timezone: string;
84
+ distance_from_prev_mi: number | null;
85
+ alternatives: string[];
86
+ fixed: boolean;
87
+ }
88
+
89
+ export interface PlanResponse {
90
+ bookable_dates: string[];
91
+ tour_types: TourTypeId[];
92
+ stops: PlanStop[];
93
+ changed: { building_id: number; reason: string; text: string }[];
94
+ unchainable: { building_id: number; reason: string; text: string }[];
95
+ }
96
+
97
+ export type BookingStopRequest =
98
+ | { existing_calendar_event_id: number }
99
+ | { building_id: number; start: string };
100
+
101
+ export interface BookingContact {
102
+ first_name: string;
103
+ last_name: string;
104
+ email: string;
105
+ phone_e164: string;
106
+ bedrooms: number[];
107
+ move_in: string | null;
108
+ notes: string;
109
+ }
110
+
111
+ /** The attribution /v2/scheduleMe takes today, under the same names. */
112
+ export interface BookingAttribution {
113
+ lead_sources: string[];
114
+ lead_sources_with_timestamps: Record<string, unknown>[];
115
+ query_params: Record<string, string>;
116
+ referrer: string;
117
+ google_rwg_token: string | null;
118
+ google_referral_building_id: number | null;
119
+ google_environment: string | null;
120
+ }
121
+
122
+ export interface BookingRequest {
123
+ tour_type: TourTypeId;
124
+ stops: BookingStopRequest[];
125
+ contact: BookingContact;
126
+ lead_sources: BookingAttribution;
127
+ conversation_tracking_id: string | null;
128
+ cancel_existing_tours: boolean;
129
+ }
130
+
131
+ export type BookedStopStatus = "booked" | "existing" | "failed";
132
+
133
+ export interface BookedStop {
134
+ building_id: number;
135
+ calendar_event_id: number | null;
136
+ start: string | null;
137
+ end: string | null;
138
+ status: BookedStopStatus;
139
+ error: { code: string; message: string } | null;
140
+ }
141
+
142
+ export interface BookingResponse {
143
+ itinerary_id: string | null;
144
+ stops: BookedStop[];
145
+ }
146
+
147
+ export type TourApiErrorCode =
148
+ | "SLOT_TAKEN"
149
+ | "EXISTING_TOUR"
150
+ | "MAX_STOPS"
151
+ | "NOT_IN_GROUP"
152
+ | "INVALID_STOPS"
153
+ | "RATE_LIMITED";
154
+
155
+ export class TourApiError extends Error {
156
+ constructor(
157
+ readonly status: number,
158
+ readonly code: TourApiErrorCode | null,
159
+ message: string
160
+ ) {
161
+ super(message);
162
+ this.name = "TourApiError";
163
+ }
164
+ }
165
+
166
+ export interface TourItineraryApi {
167
+ getCommunities(query: CommunityQuery): Promise<CommunitiesResponse>;
168
+ plan(request: PlanRequest): Promise<PlanResponse>;
169
+ book(
170
+ request: BookingRequest,
171
+ idempotencyKey: string
172
+ ): Promise<BookingResponse>;
173
+ }
174
+
175
+ const GENERIC_ERROR = "Something went wrong. Please try again.";
176
+
177
+ const toTourApiError = (e: unknown): TourApiError => {
178
+ const error = e as AxiosError<{
179
+ error?: { code?: TourApiErrorCode; message?: string };
180
+ }>;
181
+ const body = error.response?.data?.error;
182
+ return new TourApiError(
183
+ error.response?.status ?? 0,
184
+ body?.code ?? null,
185
+ body?.message || GENERIC_ERROR
186
+ );
187
+ };
188
+
189
+ /** Query string for GET tour-communities; empty filters are left out. */
190
+ export const communitiesSearchParams = (
191
+ query: CommunityQuery
192
+ ): URLSearchParams => {
193
+ const params = new URLSearchParams();
194
+ query.bedrooms.forEach((n) => params.append("bedrooms", String(n)));
195
+ if (query.moveIn) params.set("move_in", query.moveIn);
196
+ if (query.maxBudget !== null) {
197
+ params.set("max_budget", String(query.maxBudget));
198
+ }
199
+ if (query.extend) {
200
+ params.set("available_after", query.extend.availableAfter);
201
+ params.set("tour_type", query.extend.tourType);
202
+ params.set("near_building_id", String(query.extend.nearBuildingId));
203
+ query.extend.excludeBuildingIds.forEach((id) =>
204
+ params.append("exclude_building_ids", String(id))
205
+ );
206
+ }
207
+ return params;
208
+ };
209
+
210
+ export const createTourItineraryApi = ({
211
+ orgSlug,
212
+ buildingSlug,
213
+ getSessionToken,
214
+ host = "https://app.meetelise.com",
215
+ }: {
216
+ orgSlug: string;
217
+ buildingSlug: string;
218
+ getSessionToken: () => string | null;
219
+ host?: string;
220
+ }): TourItineraryApi => {
221
+ const baseUrl = `${host}/platformApi/webchat`;
222
+ const headers = (): Record<string, string> => ({
223
+ "X-Session-Token": getSessionToken() ?? "",
224
+ "org-slug": orgSlug,
225
+ "building-slug": buildingSlug,
226
+ });
227
+ const call = async <T>(request: () => Promise<{ data: T }>): Promise<T> => {
228
+ try {
229
+ return (await request()).data;
230
+ } catch (e) {
231
+ throw toTourApiError(e);
232
+ }
233
+ };
234
+
235
+ return {
236
+ getCommunities: (query) =>
237
+ call(() =>
238
+ axios.get<CommunitiesResponse>(
239
+ `${baseUrl}/tour-communities?${communitiesSearchParams(query)}`,
240
+ { headers: headers() }
241
+ )
242
+ ),
243
+ plan: (request) =>
244
+ call(() =>
245
+ axios.post<PlanResponse>(`${baseUrl}/tour-itineraries/plan`, request, {
246
+ headers: headers(),
247
+ })
248
+ ),
249
+ book: (request, idempotencyKey) =>
250
+ call(() =>
251
+ axios.post<BookingResponse>(`${baseUrl}/tour-itineraries`, request, {
252
+ headers: { ...headers(), "Idempotency-Key": idempotencyKey },
253
+ })
254
+ ),
255
+ };
256
+ };
@@ -0,0 +1,82 @@
1
+ import format from "date-fns/format";
2
+ import type { TourTypeId } from "./tourItineraryApi";
3
+
4
+ /*
5
+ * The API sends each time as ISO 8601 in its building's own time zone
6
+ * (e.g. "2026-10-15T10:45:00-05:00"), so the wall-clock time a prospect should
7
+ * see is the text of the string itself. Reading it directly avoids converting
8
+ * through the visitor's time zone.
9
+ */
10
+
11
+ /** "2026-10-15T10:45:00-05:00" -> "2026-10-15" */
12
+ export const isoDate = (iso: string): string => iso.slice(0, 10);
13
+
14
+ /** "2026-10-15T10:45:00-05:00" -> "10:45" */
15
+ export const isoHourMinute = (iso: string): string => iso.slice(11, 16);
16
+
17
+ const parts = (hourMinute: string): { hour: number; minute: string } => {
18
+ const [hour, minute] = hourMinute.split(":");
19
+ return { hour: parseInt(hour, 10), minute };
20
+ };
21
+
22
+ const meridiem = (hour: number): string => (hour < 12 ? "am" : "pm");
23
+
24
+ const clock = (hour: number, minute: string): string =>
25
+ `${hour % 12 === 0 ? 12 : hour % 12}:${minute}`;
26
+
27
+ /** "14:30" -> "2:30pm" */
28
+ export const formatHourMinute = (hourMinute: string): string => {
29
+ const { hour, minute } = parts(hourMinute);
30
+ return `${clock(hour, minute)}${meridiem(hour)}`;
31
+ };
32
+
33
+ /** ISO start -> "10:45am" */
34
+ export const formatTime = (iso: string): string =>
35
+ formatHourMinute(isoHourMinute(iso));
36
+
37
+ /** "10:00–10:30am", or "11:30am–12:00pm" across noon. */
38
+ export const formatTimeRange = (startIso: string, endIso: string): string => {
39
+ const start = parts(isoHourMinute(startIso));
40
+ const end = parts(isoHourMinute(endIso));
41
+ const startText =
42
+ meridiem(start.hour) === meridiem(end.hour)
43
+ ? clock(start.hour, start.minute)
44
+ : formatHourMinute(isoHourMinute(startIso));
45
+ return `${startText}–${formatHourMinute(isoHourMinute(endIso))}`;
46
+ };
47
+
48
+ /** A calendar date, read as that date wherever the visitor is. */
49
+ export const dateFromIsoDate = (date: string): Date => {
50
+ const [year, month, day] = date.split("-").map((n) => parseInt(n, 10));
51
+ return new Date(year, month - 1, day);
52
+ };
53
+
54
+ /** "2026-10-15" -> "Thu, Oct 15" */
55
+ export const formatShortDate = (date: string): string =>
56
+ format(dateFromIsoDate(date), "EEE, MMM d");
57
+
58
+ /** "2026-10-15" -> "Oct 15" */
59
+ export const formatMonthDay = (date: string): string =>
60
+ format(dateFromIsoDate(date), "MMM d");
61
+
62
+ /** "2026-10-15" -> "Thu, Oct 15, 2026" */
63
+ export const formatLongDate = (date: string): string =>
64
+ format(dateFromIsoDate(date), "EEE, MMM d, yyyy");
65
+
66
+ /** A Date as the "YYYY-MM-DD" the API uses. */
67
+ export const toIsoDate = (date: Date): string => format(date, "yyyy-MM-dd");
68
+
69
+ export const TOUR_TYPE_COPY: Record<
70
+ TourTypeId,
71
+ { label: string; subtitle: string }
72
+ > = {
73
+ "escorted-tour": { label: "Escorted Tour", subtitle: "With an agent" },
74
+ "live-virtual-tour": { label: "Virtual Tour", subtitle: "Over video" },
75
+ "self-guided-tour": { label: "Self-Guided Tour", subtitle: "On your own" },
76
+ };
77
+
78
+ export const TOUR_TYPE_ORDER: TourTypeId[] = [
79
+ "escorted-tour",
80
+ "live-virtual-tour",
81
+ "self-guided-tour",
82
+ ];
@@ -17,7 +17,7 @@ import {
17
17
  } from "../LeadSourceMultitouchClient";
18
18
 
19
19
  import { getOfficeHourText } from "../OfficeHours";
20
- import { focusFirstTabStop, trapTabInside } from "../pubnub-chat";
20
+ import { placeFocusInside, trapTabInside } from "../pubnub-chat";
21
21
  import {
22
22
  formatToUsPhoneInput,
23
23
  isModifierKey,
@@ -47,13 +47,6 @@ export class CallUsWindow extends LitElement {
47
47
  trapTabInside(event, this);
48
48
  };
49
49
 
50
- private movedFocusInside = false;
51
-
52
- updated(): void {
53
- if (this.movedFocusInside) return;
54
- if (focusFirstTabStop(this)) this.movedFocusInside = true;
55
- }
56
-
57
50
  static styles = [
58
51
  InputStyles,
59
52
  css`
@@ -225,7 +218,18 @@ export class CallUsWindow extends LitElement {
225
218
  | { dayOfWeek: string; startTime: string; endTime: string }
226
219
  )[] = [];
227
220
 
221
+ // Focus moves in once, on open, after details-window has drawn the controls.
228
222
  firstUpdated = async (): Promise<void> => {
223
+ await this.renderRoot.querySelector<LitElement>("details-window")
224
+ ?.updateComplete;
225
+ if (this.isConnected) {
226
+ placeFocusInside(
227
+ this,
228
+ this.renderRoot.querySelector<HTMLElement>(
229
+ "#call-us-window__content-wrapper"
230
+ )
231
+ );
232
+ }
229
233
  if (!this.buildingId || !this.hasCallUsEnabled) return;
230
234
  this.officeHoursTextInfo = await getOfficeHourText(this.buildingId);
231
235
  };
@@ -14,7 +14,7 @@ import axios from "axios";
14
14
  import { FeatureFlagsShowDropdown } from "../../fetchFeatureFlag";
15
15
  import { pushGtmEvent } from "../../gtm";
16
16
  import formDisclaimer from "../../disclaimers";
17
- import { focusFirstTabStop, trapTabInside } from "../pubnub-chat";
17
+ import { placeFocusInside, trapTabInside } from "../pubnub-chat";
18
18
  import { isMobile, isValidEmail, snakify } from "../../utils";
19
19
  import LeadSourceClient, {
20
20
  getDefaultLeadSourceAttribution,
@@ -47,11 +47,17 @@ export class EmailUsWindow extends LitElement {
47
47
  trapTabInside(event, this);
48
48
  };
49
49
 
50
- private movedFocusInside = false;
51
-
52
- updated(): void {
53
- if (this.movedFocusInside) return;
54
- if (focusFirstTabStop(this)) this.movedFocusInside = true;
50
+ // Focus moves in once, on open. The fields render inside details-window, which draws
51
+ // after this element's first update, so wait for it. Later renders (every keystroke)
52
+ // never move focus.
53
+ async firstUpdated(): Promise<void> {
54
+ await this.renderRoot.querySelector<LitElement>("details-window")
55
+ ?.updateComplete;
56
+ if (!this.isConnected) return;
57
+ placeFocusInside(
58
+ this,
59
+ this.renderRoot.querySelector<HTMLElement>("#email-us-form")
60
+ );
55
61
  }
56
62
 
57
63
  static styles = [
@@ -1079,6 +1079,20 @@ export function focusFirstTabStop(container: HTMLElement): boolean {
1079
1079
  return true;
1080
1080
  }
1081
1081
 
1082
+ /**
1083
+ * Move focus into an overlay, to the first control in `preferred` when it has one.
1084
+ * Leaves focus alone when the person is already on a control inside the overlay.
1085
+ */
1086
+ export function placeFocusInside(
1087
+ container: HTMLElement,
1088
+ preferred?: HTMLElement | null
1089
+ ): boolean {
1090
+ const active = activeElementInside(container);
1091
+ if (active && active !== container) return true;
1092
+ if (preferred && focusFirstTabStop(preferred)) return true;
1093
+ return focusFirstTabStop(container);
1094
+ }
1095
+
1082
1096
  /** Wrap Tab inside container when focus is already in it. No effect otherwise. */
1083
1097
  export function trapTabInside(
1084
1098
  event: KeyboardEvent,
@@ -0,0 +1,102 @@
1
+ import { expect } from "@esm-bundle/chai";
2
+ import { sendKeys, sendMouse } from "@web/test-runner-commands";
3
+ import "../public/dist/index";
4
+ import type { EmailUsWindow } from "./WebComponent/actions/email-us-window";
5
+ import type { Launcher } from "./WebComponent/launcher/Launcher";
6
+
7
+ declare const afterEach: (callback: () => void) => void;
8
+
9
+ const deepestActive = (): Element | null => {
10
+ let active: Element | null = document.activeElement;
11
+ while (active?.shadowRoot?.activeElement) {
12
+ active = active.shadowRoot.activeElement;
13
+ }
14
+ return active;
15
+ };
16
+
17
+ // Compare labels, not elements: a failed equal on DOM nodes stalls chai's output.
18
+ const label = (el: Node | null): string =>
19
+ el instanceof Element
20
+ ? `${el.tagName.toLowerCase()} ${
21
+ el.getAttribute("placeholder") ?? el.getAttribute("aria-label") ?? ""
22
+ }`.trim()
23
+ : String(el);
24
+
25
+ const settle = (): Promise<void> =>
26
+ new Promise((resolve) => setTimeout(resolve, 50));
27
+
28
+ // Open the overlay the way a visitor does, through the launcher, which also wires
29
+ // the window's Close button.
30
+ const openFromLauncher = async (
31
+ open: (launcher: Launcher) => void,
32
+ tag: string
33
+ ): Promise<HTMLElement> => {
34
+ const eliseWindow = window as unknown as {
35
+ eliseAi?: Record<string, unknown>;
36
+ };
37
+ eliseWindow.eliseAi = eliseWindow.eliseAi ?? {};
38
+ const launcher = document.createElement("meetelise-launcher") as Launcher;
39
+ document.body.appendChild(launcher);
40
+ await launcher.updateComplete;
41
+ open(launcher);
42
+ await launcher.updateComplete;
43
+ await settle();
44
+ const overlay = launcher.shadowRoot?.querySelector<HTMLElement>(tag);
45
+ if (!overlay) throw new Error(`no ${tag}`);
46
+ return overlay;
47
+ };
48
+
49
+ const openEmailWindow = (): Promise<EmailUsWindow> =>
50
+ openFromLauncher(
51
+ (launcher) => launcher.onClickEmailOption(new MouseEvent("click")),
52
+ "email-us-window"
53
+ ) as Promise<EmailUsWindow>;
54
+
55
+ const field = (emailUs: EmailUsWindow, selector: string): HTMLInputElement => {
56
+ const input = emailUs.shadowRoot?.querySelector<HTMLInputElement>(selector);
57
+ if (!input) throw new Error(`no ${selector}`);
58
+ return input;
59
+ };
60
+
61
+ afterEach(() => {
62
+ document.querySelectorAll("meetelise-launcher").forEach((el) => el.remove());
63
+ });
64
+
65
+ it("puts focus on the first name field when the email window opens", async () => {
66
+ const emailUs = await openEmailWindow();
67
+
68
+ expect(label(deepestActive())).to.equal(
69
+ label(field(emailUs, 'input[placeholder="First name"]'))
70
+ );
71
+ });
72
+
73
+ it("keeps focus in the field the person clicked and is typing in", async () => {
74
+ const emailUs = await openEmailWindow();
75
+ const email = field(emailUs, 'input[type="email"]');
76
+ const box = email.getBoundingClientRect();
77
+
78
+ await sendMouse({
79
+ type: "click",
80
+ position: [Math.round(box.x + 10), Math.round(box.y + box.height / 2)],
81
+ });
82
+ await sendKeys({ type: "jo@example.com" });
83
+ await settle();
84
+
85
+ expect(label(deepestActive())).to.equal(label(email));
86
+ expect(email.value).to.equal("jo@example.com");
87
+ });
88
+
89
+ it("moves focus into the call window when it opens", async () => {
90
+ const callUs = await openFromLauncher(
91
+ (launcher) => launcher.onClickPhoneOption(new MouseEvent("click")),
92
+ "call-us-window"
93
+ );
94
+
95
+ let node: Node | null = deepestActive();
96
+ while (node && node !== callUs) {
97
+ node = node instanceof ShadowRoot ? node.host : node.parentNode;
98
+ }
99
+ expect(node === callUs, `focus is on ${label(deepestActive())}`).to.equal(
100
+ true
101
+ );
102
+ });