@yext/visual-editor 2.0.0-beta.12 → 2.0.0-beta.13

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.
Files changed (69) hide show
  1. package/dist/{SectionLibraryVisualEditorProvider-DJezMczO.js → SectionLibraryVisualEditorProvider-64whofF8.js} +3128 -3105
  2. package/dist/cli/assets/directory-locator-source/components/sections/locator/Filters.test.tsx +1 -0
  3. package/dist/cli/assets/directory-locator-source/components/sections/locator/Filters.tsx +9 -8
  4. package/dist/cli/assets/directory-locator-source/components/sections/locator/Locator.tsx +61 -1
  5. package/dist/cli/assets/directory-locator-source/components/sections/locator/LocatorFields.test.ts +66 -0
  6. package/dist/cli/assets/directory-locator-source/components/sections/locator/LocatorRadius.test.ts +316 -34
  7. package/dist/cli/assets/directory-locator-source/components/sections/locator/LocatorResultCard.tsx +4 -1
  8. package/dist/cli/assets/directory-locator-source/components/sections/locator/LocatorWrapper.test.ts +370 -0
  9. package/dist/cli/assets/directory-locator-source/components/sections/locator/LocatorWrapper.tsx +223 -25
  10. package/dist/cli/assets/directory-locator-source/components/sections/locator/Map.tsx +91 -12
  11. package/dist/cli/assets/directory-locator-source/components/sections/locator/Results.tsx +11 -6
  12. package/dist/cli/assets/directory-locator-source/components/sections/locator/distanceUnits.ts +7 -0
  13. package/dist/cli/yextve.js +1 -1
  14. package/dist/{createYextFieldTransforms-B3f0jVg6.d.ts → createYextFieldTransforms-w-U4b5Zf.d.ts} +5 -2
  15. package/dist/index.d.ts +20 -4
  16. package/dist/locales/platform/cs/visual-editor.json +6 -0
  17. package/dist/locales/platform/da/visual-editor.json +6 -0
  18. package/dist/locales/platform/de/visual-editor.json +6 -0
  19. package/dist/locales/platform/en/visual-editor.json +6 -0
  20. package/dist/locales/platform/en-GB/visual-editor.json +6 -0
  21. package/dist/locales/platform/es/visual-editor.json +6 -0
  22. package/dist/locales/platform/et/visual-editor.json +6 -0
  23. package/dist/locales/platform/fi/visual-editor.json +6 -0
  24. package/dist/locales/platform/fr/visual-editor.json +6 -0
  25. package/dist/locales/platform/hr/visual-editor.json +6 -0
  26. package/dist/locales/platform/hu/visual-editor.json +6 -0
  27. package/dist/locales/platform/it/visual-editor.json +6 -0
  28. package/dist/locales/platform/ja/visual-editor.json +6 -0
  29. package/dist/locales/platform/lt/visual-editor.json +6 -0
  30. package/dist/locales/platform/lv/visual-editor.json +6 -0
  31. package/dist/locales/platform/nb/visual-editor.json +6 -0
  32. package/dist/locales/platform/nl/visual-editor.json +6 -0
  33. package/dist/locales/platform/pl/visual-editor.json +6 -0
  34. package/dist/locales/platform/pt/visual-editor.json +6 -0
  35. package/dist/locales/platform/ro/visual-editor.json +6 -0
  36. package/dist/locales/platform/sk/visual-editor.json +6 -0
  37. package/dist/locales/platform/sv/visual-editor.json +6 -0
  38. package/dist/locales/platform/tr/visual-editor.json +6 -0
  39. package/dist/locales/platform/zh/visual-editor.json +6 -0
  40. package/dist/locales/platform/zh-TW/visual-editor.json +6 -0
  41. package/dist/section-library-support.js +55 -55
  42. package/dist/sectionLibrarySupport.d.ts +2 -2
  43. package/dist/{visual-editor-DuxrpEsM.js → visual-editor-B84T0Hz5.js} +67 -61
  44. package/dist/{visual-editor-bjHpuHcP.js → visual-editor-B8eVGZjZ.js} +6 -0
  45. package/dist/{visual-editor-89bNoCOk.js → visual-editor-BTv1Bren.js} +58 -52
  46. package/dist/{visual-editor-BWDv00Sj.js → visual-editor-BWJvQ6QT.js} +100 -94
  47. package/dist/{visual-editor-BPOG2TRh.js → visual-editor-BWk-Ri1i.js} +69 -63
  48. package/dist/{visual-editor-DuH1uy-p.js → visual-editor-BdM7VUac.js} +57 -51
  49. package/dist/{visual-editor-D_Xqs07E.js → visual-editor-BmM2bYhg.js} +92 -86
  50. package/dist/{visual-editor-CiE_sZgp.js → visual-editor-BuRftlWt.js} +79 -73
  51. package/dist/{visual-editor-BEiQqs_Z.js → visual-editor-BxnbtD_z.js} +59 -53
  52. package/dist/{visual-editor-DVI-AF67.js → visual-editor-C4Nretnd.js} +34 -28
  53. package/dist/{visual-editor-BmfXE4Nt.js → visual-editor-CFE4ijeV.js} +36 -30
  54. package/dist/{visual-editor-CJMynoK2.js → visual-editor-CMfDvLU2.js} +49 -43
  55. package/dist/{visual-editor-DSYNp8sQ.js → visual-editor-CauX7_Ur.js} +23 -17
  56. package/dist/{visual-editor-C5aegP-t.js → visual-editor-D5d9meOo.js} +22 -16
  57. package/dist/{visual-editor-dWLAQOr6.js → visual-editor-D9U8TxD-.js} +47 -41
  58. package/dist/{visual-editor-C_SC4gLo.js → visual-editor-DBZwjDQd.js} +43 -37
  59. package/dist/{visual-editor-TsYZAz_J.js → visual-editor-DI6rS2dP.js} +112 -106
  60. package/dist/{visual-editor-8Okvw03s.js → visual-editor-DOioJ5CW.js} +62 -56
  61. package/dist/{visual-editor-BfzO6vuG.js → visual-editor-D_EvXM08.js} +48 -42
  62. package/dist/{visual-editor-yqgcCbY4.js → visual-editor-DguhAL12.js} +6 -0
  63. package/dist/{visual-editor-C7Ne5NW6.js → visual-editor-DmsRSmAI.js} +54 -48
  64. package/dist/{visual-editor-B-9-8VqT.js → visual-editor-DnNNHiLS.js} +49 -43
  65. package/dist/{visual-editor-Crc50YSl.js → visual-editor-DvksDrGT.js} +36 -30
  66. package/dist/{visual-editor-DcNe0Txh.js → visual-editor-XsBMHUSs.js} +62 -56
  67. package/dist/{visual-editor-d-SdfYpR.js → visual-editor-kiT3ocKi.js} +36 -30
  68. package/dist/visual-editor.js +6727 -6388
  69. package/package.json +1 -1
@@ -106,6 +106,7 @@ const renderFilterModal = (
106
106
  isOpenNowSelected={false}
107
107
  showDistanceOptions={false}
108
108
  selectedDistanceOption={null}
109
+ distanceUnit="kilometer"
109
110
  handleCloseModalClick={vi.fn()}
110
111
  handleOpenNowClick={vi.fn()}
111
112
  handleDistanceClick={vi.fn()}
@@ -18,12 +18,12 @@ import { useCollapse } from "react-collapsed";
18
18
  import { useTranslation } from "react-i18next";
19
19
  import { FaChevronUp, FaDotCircle, FaRegCircle, FaTimes } from "react-icons/fa";
20
20
  import { type TranslatableString } from "../../../types/types.ts";
21
- import { getPreferredDistanceUnit } from "../../../utils/i18n/distance.ts";
22
21
  import { msg } from "../../../utils/i18n/platform.ts";
23
22
  import { LocatorEntityType } from "../../../utils/locatorEntityTypes.ts";
24
23
  import { resolveComponentData } from "../../../utils/resolveComponentData.tsx";
25
24
  import { Body } from "../../atoms/body.tsx";
26
25
  import { translateDistanceUnit } from "./Results.tsx";
26
+ import type { DistanceUnit } from "./distanceUnits.ts";
27
27
 
28
28
  export const LOCATION_FIELD = "builtin.location";
29
29
  export const COUNTRY_CODE_FIELD = "address.countryCode";
@@ -36,12 +36,10 @@ interface FilterModalProps {
36
36
  isOpenNowSelected: boolean; // whether the Open Now filter is currently selected by the user
37
37
  showDistanceOptions: boolean; // whether to show the Distance filter option
38
38
  selectedDistanceOption: number | null;
39
+ distanceUnit: DistanceUnit;
39
40
  handleCloseModalClick: () => void;
40
41
  handleOpenNowClick: (selected: boolean) => void;
41
- handleDistanceClick: (
42
- distance: number,
43
- distanceUnit: "mile" | "kilometer"
44
- ) => void;
42
+ handleDistanceClick: (distance: number, distanceUnit: DistanceUnit) => void;
45
43
  handleClearFiltersClick: () => void;
46
44
  accentColorCssValue: string;
47
45
  closeButtonRef: React.Ref<HTMLButtonElement>;
@@ -54,6 +52,7 @@ export const FilterModal = ({
54
52
  isOpenNowSelected,
55
53
  showDistanceOptions,
56
54
  selectedDistanceOption,
55
+ distanceUnit,
57
56
  handleCloseModalClick,
58
57
  handleOpenNowClick,
59
58
  handleDistanceClick,
@@ -136,6 +135,7 @@ export const FilterModal = ({
136
135
  <DistanceFilter
137
136
  onChange={handleDistanceClick}
138
137
  selectedDistanceOption={selectedDistanceOption}
138
+ unit={distanceUnit}
139
139
  accentColorCssValue={accentColorCssValue}
140
140
  />
141
141
  )}
@@ -212,17 +212,19 @@ const OpenNowFilter = ({ isSelected, onChange }: OpenNowFilterProps) => {
212
212
  };
213
213
 
214
214
  interface DistanceFilterProps {
215
- onChange: (distance: number, unit: "mile" | "kilometer") => void;
215
+ onChange: (distance: number, unit: DistanceUnit) => void;
216
216
  selectedDistanceOption: number | null;
217
+ unit: DistanceUnit;
217
218
  accentColorCssValue: string;
218
219
  }
219
220
 
220
221
  const DistanceFilter = ({
221
222
  onChange,
222
223
  selectedDistanceOption,
224
+ unit,
223
225
  accentColorCssValue,
224
226
  }: DistanceFilterProps) => {
225
- const { t, i18n } = useTranslation();
227
+ const { t } = useTranslation();
226
228
  const { isExpanded, getToggleProps, getCollapseProps } = useCollapse({
227
229
  defaultExpanded: true,
228
230
  });
@@ -230,7 +232,6 @@ const DistanceFilter = ({
230
232
  ? "w-3 text-gray-400"
231
233
  : "w-3 text-gray-400 transform rotate-180";
232
234
  const distanceOptions = [5, 10, 25, 50];
233
- const unit = getPreferredDistanceUnit(i18n.language);
234
235
 
235
236
  return (
236
237
  <div className="flex flex-col gap-4">
@@ -31,6 +31,12 @@ import {
31
31
  } from "./LocatorResultCard.tsx";
32
32
  import { ResultCardPropsField } from "./Results.tsx";
33
33
  import { LocatorWrapper } from "./LocatorWrapper.tsx";
34
+ import {
35
+ BROWSER_LANGUAGE,
36
+ KILOMETER,
37
+ MILE,
38
+ type DefaultDistanceUnit,
39
+ } from "./distanceUnits.ts";
34
40
  import {
35
41
  DEFAULT_LOCATION_STYLE,
36
42
  DEFAULT_MAKI_ICON_NAME,
@@ -44,6 +50,13 @@ const DEFAULT_TITLE = "Find a Location";
44
50
  const DEFAULT_DISTANCE_DISPLAY = "distanceFromUser";
45
51
 
46
52
  export interface LocatorProps {
53
+ /**
54
+ * Search the visible map area 500 ms after the user stops a pan or zoom.
55
+ * If enabled, hide the Search This Area button.
56
+ * @defaultValue false
57
+ */
58
+ autoSearchOnMapMove?: boolean;
59
+
47
60
  /**
48
61
  * The visual theme for the map tiles, chosen from a predefined list of Mapbox styles.
49
62
  * @defaultValue 'mapbox://styles/mapbox/streets-v12'
@@ -102,7 +115,7 @@ export interface LocatorProps {
102
115
 
103
116
  /**
104
117
  * The default radius for nearby-location searches. Leave unset to use Search's
105
- * suggested radius, or 25 in the locale's preferred unit for coordinate searches.
118
+ * suggested radius, or 25 in the configured default distance unit for coordinate searches.
106
119
  * Visitor-selected distances and explicit map/URL search areas take precedence.
107
120
  * Geographic boundary filters are unaffected.
108
121
  */
@@ -140,6 +153,10 @@ export interface LocatorProps {
140
153
  /** Props to customize the locator result card component. */
141
154
  props: LocatorResultCardProps;
142
155
  }>;
156
+ /** Whether visitors can switch the locator between miles and kilometers. */
157
+ showDistanceUnitToggle?: boolean;
158
+ /** Unit used before a visitor selects one. Defaults to the page language. */
159
+ defaultDistanceUnit?: DefaultDistanceUnit;
143
160
  /** Controls which distance value to display on each locator result card. */
144
161
  distanceDisplay?: DistanceDisplayOption;
145
162
  }
@@ -394,6 +411,17 @@ const locatorFields: YextFields<LocatorProps> = {
394
411
  },
395
412
  },
396
413
  },
414
+ autoSearchOnMapMove: {
415
+ type: "radio",
416
+ label: msg(
417
+ "fields.autoSearchOnMapMove",
418
+ "Automatically Search on Map Movement"
419
+ ),
420
+ options: [
421
+ { label: msg("fields.options.yes", "Yes"), value: true },
422
+ { label: msg("fields.options.no", "No"), value: false },
423
+ ],
424
+ },
397
425
  pageHeading: {
398
426
  type: "object",
399
427
  label: msg("fields.pageHeading", "Page Heading"),
@@ -430,9 +458,11 @@ const locatorFields: YextFields<LocatorProps> = {
430
458
  props: DEFAULT_LOCATOR_RESULT_CARD_PROPS,
431
459
  },
432
460
  },
461
+ // Keep saved distance display values working without exposing the old selector.
433
462
  distanceDisplay: {
434
463
  type: "basicSelector",
435
464
  label: msg("fields.distanceDisplay", "Distance Display"),
465
+ visible: false,
436
466
  options: [
437
467
  {
438
468
  label: msg("fields.options.distanceFromUser", "Distance from User"),
@@ -452,6 +482,29 @@ const locatorFields: YextFields<LocatorProps> = {
452
482
  },
453
483
  ],
454
484
  },
485
+ showDistanceUnitToggle: {
486
+ type: "radio",
487
+ label: msg("fields.showDistanceUnitToggle", "Show Distance Unit Toggle"),
488
+ options: [
489
+ { label: msg("fields.options.yes", "Yes"), value: true },
490
+ { label: msg("fields.options.no", "No"), value: false },
491
+ ],
492
+ },
493
+ defaultDistanceUnit: {
494
+ type: "basicSelector",
495
+ label: msg("fields.defaultDistanceUnit", "Default Distance Unit"),
496
+ options: [
497
+ { label: msg("fields.options.miles", "Miles (mi)"), value: MILE },
498
+ {
499
+ label: msg("fields.options.kilometers", "Kilometers (km)"),
500
+ value: KILOMETER,
501
+ },
502
+ {
503
+ label: msg("fields.options.browserLanguage", "Browser language"),
504
+ value: BROWSER_LANGUAGE,
505
+ },
506
+ ],
507
+ },
455
508
  };
456
509
 
457
510
  /**
@@ -497,6 +550,7 @@ export const LocatorComponent: YextComponentConfig<LocatorProps> = {
497
550
  return toPuckFields<LocatorProps>(updatedFields);
498
551
  },
499
552
  defaultProps: {
553
+ autoSearchOnMapMove: false,
500
554
  locationStyles: [],
501
555
  resultCard: [],
502
556
  filters: {
@@ -507,6 +561,8 @@ export const LocatorComponent: YextComponentConfig<LocatorProps> = {
507
561
  title: { defaultValue: DEFAULT_TITLE },
508
562
  },
509
563
  distanceDisplay: DEFAULT_DISTANCE_DISPLAY,
564
+ showDistanceUnitToggle: false,
565
+ defaultDistanceUnit: BROWSER_LANGUAGE,
510
566
  },
511
567
  label: msg("components.locator", "Locator"),
512
568
  /**
@@ -579,6 +635,10 @@ export const LocatorComponent: YextComponentConfig<LocatorProps> = {
579
635
  data = setDeep(data, "props.resultCard", newResultCards);
580
636
  }
581
637
 
638
+ if (data.props.defaultDistanceUnit === undefined) {
639
+ data = setDeep(data, "props.defaultDistanceUnit", BROWSER_LANGUAGE);
640
+ }
641
+
582
642
  return data;
583
643
  },
584
644
  render: (props) => <LocatorWrapper {...props} />,
@@ -21,6 +21,72 @@ const getKeywordsDisplayNameVisibility = (facetValues?: string[]) => {
21
21
  };
22
22
 
23
23
  describe("Locator fields", () => {
24
+ it.each([
25
+ { entityTypes: ["ce_warehouse"] },
26
+ { entityTypes: ["ce_warehouse", "location"] },
27
+ { entityTypes: ["location", "ce_warehouse"] },
28
+ ])(
29
+ "configures cards and styles for $entityTypes",
30
+ async ({ entityTypes }) => {
31
+ const params = {
32
+ metadata: {
33
+ streamDocument: {
34
+ _pageset: JSON.stringify({
35
+ typeConfig: {
36
+ locatorConfig: {
37
+ entityTypeScope: entityTypes.map((entityType) => ({
38
+ entityType,
39
+ })),
40
+ },
41
+ },
42
+ }),
43
+ },
44
+ },
45
+ } as any;
46
+ const customCard = {
47
+ props: {
48
+ entityType: "ce_warehouse",
49
+ primaryHeading: { field: "c_warehouseName" },
50
+ },
51
+ };
52
+ const customStyle = {
53
+ entityType: "ce_warehouse",
54
+ pinIcon: { type: "icon", iconName: "warehouse" },
55
+ };
56
+ const data = {
57
+ props: {
58
+ ...LocatorComponent.defaultProps,
59
+ resultCard: [customCard],
60
+ locationStyles: [customStyle],
61
+ },
62
+ } as any;
63
+ const fields = LocatorComponent.resolveFields?.(data, params) as any;
64
+ expect(fields.resultCard).toMatchObject({
65
+ min: entityTypes.length,
66
+ max: entityTypes.length,
67
+ });
68
+ expect(fields.locationStyles).toMatchObject({
69
+ min: entityTypes.length,
70
+ max: entityTypes.length,
71
+ });
72
+
73
+ const resolved = (await LocatorComponent.resolveData?.(
74
+ data,
75
+ params
76
+ )) as any;
77
+ expect(
78
+ resolved.props.resultCard.map((card: any) => card.props.entityType)
79
+ ).toEqual(entityTypes);
80
+ expect(
81
+ resolved.props.locationStyles.map((style: any) => style.entityType)
82
+ ).toEqual(entityTypes);
83
+ expect(resolved.props.resultCard).toContainEqual(customCard);
84
+ expect(resolved.props.locationStyles).toContainEqual(
85
+ expect.objectContaining(customStyle)
86
+ );
87
+ }
88
+ );
89
+
24
90
  it.each([
25
91
  {
26
92
  name: "shows the display name when Keywords is selected",
@@ -1,5 +1,12 @@
1
1
  import React from "react";
2
- import { act, cleanup, render, screen, waitFor } from "@testing-library/react";
2
+ import {
3
+ act,
4
+ cleanup,
5
+ fireEvent,
6
+ render,
7
+ screen,
8
+ waitFor,
9
+ } from "@testing-library/react";
3
10
  import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4
11
  import {
5
12
  Matcher,
@@ -11,9 +18,11 @@ import type { FilterModal } from "./Filters.tsx";
11
18
  import type { LocatorMap } from "./Map.tsx";
12
19
  import type { LocatorProps } from "./Locator.tsx";
13
20
  import { LocatorWrapper } from "./LocatorWrapper.tsx";
21
+ import type { StreamDocument } from "../../../utils/types/StreamDocument.ts";
14
22
 
15
23
  const mocks = vi.hoisted(() => ({
16
24
  locale: "en",
25
+ streamDocument: {} as StreamDocument,
17
26
  state: {
18
27
  vertical: { results: [], resultsCount: 0, offset: 0 },
19
28
  filters: { static: [] as SelectableStaticFilter[], facets: [] },
@@ -68,7 +77,11 @@ vi.mock("react-i18next", async (importOriginal) => ({
68
77
  }),
69
78
  }));
70
79
  vi.mock("../../../hooks/useDocument.tsx", () => ({
71
- useDocument: () => ({ id: "locator", locale: mocks.locale }),
80
+ useDocument: () => ({
81
+ ...mocks.streamDocument,
82
+ id: "locator",
83
+ locale: mocks.locale,
84
+ }),
72
85
  }));
73
86
  vi.mock("../../../hooks/useViewport.ts", () => ({
74
87
  getViewport: () => ({ isMobile: false }),
@@ -97,6 +110,8 @@ vi.mock("./Results.tsx", () => ({
97
110
  RESULTS_LIMIT: 20,
98
111
  MobileLocatorResultsSection: () => null,
99
112
  ResultsCountSummary: () => null,
113
+ translateDistanceUnit: (_t: unknown, unit: string) =>
114
+ unit === "mile" ? "miles" : "kilometers",
100
115
  }));
101
116
  vi.mock("./LocatorResultCard.tsx", () => ({
102
117
  DEFAULT_LOCATOR_RESULT_CARD_PROPS: {},
@@ -104,6 +119,23 @@ vi.mock("./LocatorResultCard.tsx", () => ({
104
119
  }));
105
120
 
106
121
  const suggestedValue = { lat: 38.9, lng: -77.1, radius: 12000 };
122
+ const searchResponse = {
123
+ sections: [
124
+ {
125
+ results: [
126
+ {
127
+ value: "Arlington",
128
+ filter: {
129
+ kind: "fieldValue" as const,
130
+ fieldId: "builtin.location",
131
+ matcher: Matcher.Near,
132
+ value: suggestedValue,
133
+ },
134
+ },
135
+ ],
136
+ },
137
+ ],
138
+ };
107
139
  const getLocationFilter = () =>
108
140
  mocks.state.filters.static.find(
109
141
  ({ filter }) =>
@@ -111,21 +143,33 @@ const getLocationFilter = () =>
111
143
  )?.filter;
112
144
  const getRadius = () =>
113
145
  (getLocationFilter() as { value: NearFilterValue } | undefined)?.value.radius;
114
- const renderLocator = (radius?: LocatorProps["defaultSearchRadius"]) =>
115
- render(
116
- React.createElement(LocatorWrapper, {
117
- locationStyles: [],
118
- resultCard: [],
119
- filters: { openNowButton: false, showDistanceOptions: true },
120
- defaultSearchRadius: radius,
121
- puck: {
122
- metadata: {},
123
- isEditing: false,
124
- dragRef: null,
125
- renderDropZone: () => null,
126
- },
127
- })
128
- );
146
+ const createLocator = (
147
+ radius?: LocatorProps["defaultSearchRadius"],
148
+ distanceProps?: Pick<
149
+ LocatorProps,
150
+ "defaultDistanceUnit" | "showDistanceUnitToggle"
151
+ >
152
+ ) =>
153
+ React.createElement(LocatorWrapper, {
154
+ locationStyles: [],
155
+ resultCard: [],
156
+ filters: { openNowButton: false, showDistanceOptions: true },
157
+ defaultSearchRadius: radius,
158
+ ...distanceProps,
159
+ puck: {
160
+ metadata: {},
161
+ isEditing: false,
162
+ dragRef: null,
163
+ renderDropZone: () => null,
164
+ },
165
+ });
166
+ const renderLocator = (
167
+ radius?: LocatorProps["defaultSearchRadius"],
168
+ distanceProps?: Pick<
169
+ LocatorProps,
170
+ "defaultDistanceUnit" | "showDistanceUnitToggle"
171
+ >
172
+ ) => render(createLocator(radius, distanceProps));
129
173
  const selectSuggestion = async () =>
130
174
  act(async () => {
131
175
  mocks.filterSearch.onSelect?.({
@@ -148,6 +192,7 @@ beforeEach(() => {
148
192
  new Error("Geolocation unavailable")
149
193
  );
150
194
  mocks.locale = "en";
195
+ mocks.streamDocument = {};
151
196
  mocks.state.filters = { static: [], facets: [] };
152
197
  window.history.replaceState(null, "", "/");
153
198
  mocks.actions.setStaticFilters.mockImplementation(
@@ -155,23 +200,7 @@ beforeEach(() => {
155
200
  mocks.state.filters = { ...mocks.state.filters, static: filters };
156
201
  }
157
202
  );
158
- mocks.actions.executeFilterSearch.mockResolvedValue({
159
- sections: [
160
- {
161
- results: [
162
- {
163
- value: "Arlington",
164
- filter: {
165
- kind: "fieldValue",
166
- fieldId: "builtin.location",
167
- matcher: Matcher.Near,
168
- value: suggestedValue,
169
- },
170
- },
171
- ],
172
- },
173
- ],
174
- });
203
+ mocks.actions.executeFilterSearch.mockResolvedValue(searchResponse);
175
204
  });
176
205
  afterEach(() => {
177
206
  cleanup();
@@ -179,6 +208,259 @@ afterEach(() => {
179
208
  });
180
209
 
181
210
  describe("Locator default search radius", () => {
211
+ it("uses the latest selection when a pending location lookup resolves", async () => {
212
+ window.history.replaceState(null, "", "/?q=Arlington");
213
+ let finishSearch!: (response: typeof searchResponse) => void;
214
+ mocks.actions.executeFilterSearch.mockImplementationOnce(
215
+ () =>
216
+ new Promise<typeof searchResponse>((resolve) => {
217
+ finishSearch = resolve;
218
+ })
219
+ );
220
+ const radius = { value: 50, unit: "mile" } as const;
221
+ const { rerender } = renderLocator(radius, { defaultDistanceUnit: "mile" });
222
+ await waitFor(() =>
223
+ expect(mocks.actions.executeFilterSearch).toHaveBeenCalledTimes(1)
224
+ );
225
+ await act(async () => mocks.filterModal.handleDistanceClick(5, "mile"));
226
+ await act(async () =>
227
+ rerender(createLocator(radius, { defaultDistanceUnit: "kilometer" }))
228
+ );
229
+ await act(async () => finishSearch(searchResponse));
230
+ expect(getRadius()).toBeCloseTo(5000);
231
+ });
232
+
233
+ it.each([
234
+ { name: "automatic coordinates", query: "", expectedBase: 25000 },
235
+ { name: "Search suggestion", query: "?q=Arlington", expectedBase: 12000 },
236
+ {
237
+ name: "explicit map area",
238
+ query: "?q=38.9,-77.1,40233.6",
239
+ expectedBase: 40233.6,
240
+ },
241
+ ])(
242
+ "restores the $name base radius after a unit change",
243
+ async ({ query, expectedBase }) => {
244
+ window.history.replaceState(null, "", `/${query}`);
245
+ const { rerender } = renderLocator(undefined, {
246
+ defaultDistanceUnit: "mile",
247
+ });
248
+ await waitFor(() => expect(getRadius()).toBeDefined());
249
+ await act(async () => mocks.filterModal.handleDistanceClick(5, "mile"));
250
+ await act(async () =>
251
+ rerender(createLocator(undefined, { defaultDistanceUnit: "kilometer" }))
252
+ );
253
+ await act(async () =>
254
+ mocks.filterModal.handleDistanceClick(5, "kilometer")
255
+ );
256
+ expect(getRadius()).toBeCloseTo(expectedBase);
257
+ }
258
+ );
259
+
260
+ it("keeps geolocation accuracy as the minimum automatic base radius", async () => {
261
+ vi.mocked(getUserLocation).mockResolvedValue({
262
+ coords: { latitude: 38.9, longitude: -77.1, accuracy: 30000 },
263
+ } as GeolocationPosition);
264
+ const { rerender } = renderLocator(undefined, {
265
+ defaultDistanceUnit: "mile",
266
+ });
267
+ await waitFor(() => expect(getRadius()).toBeCloseTo(40233.6));
268
+ await act(async () => mocks.filterModal.handleDistanceClick(5, "mile"));
269
+ await act(async () =>
270
+ rerender(createLocator(undefined, { defaultDistanceUnit: "kilometer" }))
271
+ );
272
+ await act(async () =>
273
+ mocks.filterModal.handleDistanceClick(5, "kilometer")
274
+ );
275
+ expect(getRadius()).toBeCloseTo(30000);
276
+ });
277
+
278
+ it.each<{
279
+ name: string;
280
+ radius?: LocatorProps["defaultSearchRadius"];
281
+ expectedRadius: number;
282
+ }>([
283
+ { name: "automatic radius", expectedRadius: 25000 },
284
+ {
285
+ name: "configured radius",
286
+ radius: { value: 50, unit: "mile" },
287
+ expectedRadius: 80467.2,
288
+ },
289
+ ])(
290
+ "uses the current unit after pending geolocation with $name",
291
+ async ({ radius, expectedRadius }) => {
292
+ let finishGeolocation!: (position: GeolocationPosition) => void;
293
+ vi.mocked(getUserLocation).mockImplementationOnce(
294
+ () =>
295
+ new Promise<GeolocationPosition>((resolve) => {
296
+ finishGeolocation = resolve;
297
+ })
298
+ );
299
+ renderLocator(radius, {
300
+ defaultDistanceUnit: "mile",
301
+ showDistanceUnitToggle: true,
302
+ });
303
+ await waitFor(() => expect(getUserLocation).toHaveBeenCalledTimes(1));
304
+ await act(async () => fireEvent.click(screen.getByText("km")));
305
+ await act(async () =>
306
+ finishGeolocation({
307
+ coords: { latitude: 38.9, longitude: -77.1, accuracy: 10 },
308
+ } as GeolocationPosition)
309
+ );
310
+ await waitFor(() => expect(getRadius()).toBeCloseTo(expectedRadius));
311
+ await act(async () =>
312
+ mocks.filterModal.handleDistanceClick(5, "kilometer")
313
+ );
314
+ await act(async () => mocks.filterModal.handleClearFiltersClick());
315
+ expect(getRadius()).toBeCloseTo(expectedRadius);
316
+ }
317
+ );
318
+
319
+ it("restarts a cancelled initialization after a unit change", async () => {
320
+ window.history.replaceState(null, "", "/?q=Arlington");
321
+ let finishFirstSearch!: (response: typeof searchResponse) => void;
322
+ mocks.actions.executeFilterSearch.mockImplementationOnce(
323
+ () =>
324
+ new Promise<typeof searchResponse>((resolve) => {
325
+ finishFirstSearch = resolve;
326
+ })
327
+ );
328
+ const { rerender } = renderLocator(undefined, {
329
+ defaultDistanceUnit: "mile",
330
+ });
331
+ await waitFor(() =>
332
+ expect(mocks.actions.executeFilterSearch).toHaveBeenCalledTimes(1)
333
+ );
334
+ await act(async () => mocks.filterModal.handleDistanceClick(5, "mile"));
335
+ await act(async () =>
336
+ rerender(createLocator(undefined, { defaultDistanceUnit: "kilometer" }))
337
+ );
338
+ await act(async () => finishFirstSearch(searchResponse));
339
+ await waitFor(() =>
340
+ expect(mocks.actions.executeFilterSearch).toHaveBeenCalledTimes(2)
341
+ );
342
+ expect(getRadius()).toBeCloseTo(5000);
343
+ });
344
+
345
+ it.each<{
346
+ name: string;
347
+ radius?: LocatorProps["defaultSearchRadius"];
348
+ expectedInitialRadius: number;
349
+ }>([
350
+ {
351
+ name: "with a configured search radius",
352
+ radius: { value: 50, unit: "mile" },
353
+ expectedInitialRadius: 80467.2,
354
+ },
355
+ {
356
+ name: "with an automatic search radius",
357
+ expectedInitialRadius: 40233.6,
358
+ },
359
+ ])(
360
+ "updates the applied distance filter when the configured unit changes $name",
361
+ async ({ radius, expectedInitialRadius }) => {
362
+ const { rerender } = renderLocator(radius, {
363
+ defaultDistanceUnit: "mile",
364
+ });
365
+ await waitFor(() =>
366
+ expect(getRadius()).toBeCloseTo(expectedInitialRadius)
367
+ );
368
+ await selectSuggestion();
369
+ await act(async () => mocks.filterModal.handleDistanceClick(5, "mile"));
370
+ expect(getRadius()).toBeCloseTo(8046.72);
371
+ const searchesBeforeChange =
372
+ mocks.actions.executeVerticalQuery.mock.calls.length;
373
+
374
+ await act(async () =>
375
+ rerender(createLocator(radius, { defaultDistanceUnit: "kilometer" }))
376
+ );
377
+ expect(mocks.filterModal.distanceUnit).toBe("kilometer");
378
+ expect(mocks.filterModal.selectedDistanceOption).toBe(5);
379
+ expect(mocks.actions.executeVerticalQuery.mock.calls.length).toBe(
380
+ searchesBeforeChange + 1
381
+ );
382
+ expect(getRadius()).toBeCloseTo(5000);
383
+ }
384
+ );
385
+
386
+ it("uses the configured unit and updates an active distance filter when switched", async () => {
387
+ renderLocator(undefined, {
388
+ defaultDistanceUnit: "kilometer",
389
+ showDistanceUnitToggle: true,
390
+ });
391
+ await waitFor(() => expect(getRadius()).toBeCloseTo(25000));
392
+ expect(mocks.filterModal.distanceUnit).toBe("kilometer");
393
+ await selectSuggestion();
394
+ await act(async () =>
395
+ mocks.filterModal.handleDistanceClick(5, "kilometer")
396
+ );
397
+ expect(getRadius()).toBeCloseTo(5000);
398
+ expect(mocks.filterModal.selectedDistanceOption).toBe(5);
399
+
400
+ for (const { label, unit, radius } of [
401
+ { label: "mi", unit: "mile", radius: 8046.72 },
402
+ { label: "km", unit: "kilometer", radius: 5000 },
403
+ ]) {
404
+ const queriesBeforeSwitch =
405
+ mocks.actions.executeVerticalQuery.mock.calls.length;
406
+ const lookupsBeforeSwitch =
407
+ mocks.actions.executeFilterSearch.mock.calls.length;
408
+ const button = screen.getByText(label);
409
+ await act(async (): Promise<void> => {
410
+ fireEvent.click(button);
411
+ });
412
+ expect(button.getAttribute("aria-pressed")).toBe("true");
413
+ expect(mocks.filterModal.distanceUnit).toBe(unit);
414
+ expect(getRadius()).toBeCloseTo(radius);
415
+ expect(mocks.actions.executeVerticalQuery).toHaveBeenCalledTimes(
416
+ queriesBeforeSwitch + 1
417
+ );
418
+ expect(mocks.actions.executeFilterSearch).toHaveBeenCalledTimes(
419
+ lookupsBeforeSwitch
420
+ );
421
+ }
422
+ });
423
+
424
+ it.each([
425
+ { entityTypes: ["ce_warehouse"] },
426
+ { entityTypes: ["ce_warehouse", "location"] },
427
+ { entityTypes: ["location", "ce_warehouse"] },
428
+ ])(
429
+ "uses a configured entity type for autocomplete and URL lookup: $entityTypes",
430
+ async ({ entityTypes }) => {
431
+ mocks.streamDocument = {
432
+ _pageset: JSON.stringify({
433
+ typeConfig: {
434
+ locatorConfig: {
435
+ entityTypeScope: entityTypes.map((entityType) => ({
436
+ entityType,
437
+ })),
438
+ },
439
+ },
440
+ }),
441
+ };
442
+ window.history.replaceState(null, "", "/?q=Arlington");
443
+ renderLocator();
444
+
445
+ expect(mocks.filterSearch.searchFields).toEqual([
446
+ { fieldApiName: "builtin.location", entityType: entityTypes[0] },
447
+ ]);
448
+ await waitFor(() => {
449
+ expect(mocks.actions.executeFilterSearch).toHaveBeenCalledWith(
450
+ "Arlington",
451
+ false,
452
+ [
453
+ {
454
+ fieldApiName: "builtin.location",
455
+ entityType: entityTypes[0],
456
+ fetchEntities: false,
457
+ },
458
+ ]
459
+ );
460
+ });
461
+ }
462
+ );
463
+
182
464
  it.each<{
183
465
  name: string;
184
466
  query: string;