@nuskin/shipping-address-form 1.5.1 → 1.7.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.
Files changed (96) hide show
  1. package/README.md +54 -12
  2. package/dist/addressLookup/AddressLookup.js +74 -0
  3. package/dist/addressLookup/AddressLookup.js.map +1 -0
  4. package/dist/addressLookup/components/LocationPinIcon.js +33 -0
  5. package/dist/addressLookup/components/LocationPinIcon.js.map +1 -0
  6. package/dist/addressLookup/components/SmartyIntlResults.js +1020 -0
  7. package/dist/addressLookup/components/SmartyIntlResults.js.map +1 -0
  8. package/dist/addressLookup/components/SmartyUSResults.js +1001 -0
  9. package/dist/addressLookup/components/SmartyUSResults.js.map +1 -0
  10. package/dist/addressLookup/config/address/countries.js +61 -0
  11. package/dist/addressLookup/config/address/countries.js.map +1 -0
  12. package/dist/addressLookup/config/address/index.js +19 -0
  13. package/dist/addressLookup/config/address/index.js.map +1 -0
  14. package/dist/addressLookup/config/googleMaps.js +12 -0
  15. package/dist/addressLookup/config/googleMaps.js.map +1 -0
  16. package/dist/addressLookup/countries.js +19 -0
  17. package/dist/addressLookup/countries.js.map +1 -0
  18. package/dist/addressLookup/hooks/useAddressFieldLabels.js +41 -0
  19. package/dist/addressLookup/hooks/useAddressFieldLabels.js.map +1 -0
  20. package/dist/addressLookup/hooks/useAddressForm.js +36 -0
  21. package/dist/addressLookup/hooks/useAddressForm.js.map +1 -0
  22. package/dist/addressLookup/hooks/useAddressMapModal.js +136 -0
  23. package/dist/addressLookup/hooks/useAddressMapModal.js.map +1 -0
  24. package/dist/addressLookup/hooks/useAddressValidationBase.js +143 -0
  25. package/dist/addressLookup/hooks/useAddressValidationBase.js.map +1 -0
  26. package/dist/addressLookup/hooks/useInitialAddressVerification.js +57 -0
  27. package/dist/addressLookup/hooks/useInitialAddressVerification.js.map +1 -0
  28. package/dist/addressLookup/hooks/useIntlAddressValidation.js +122 -0
  29. package/dist/addressLookup/hooks/useIntlAddressValidation.js.map +1 -0
  30. package/dist/addressLookup/hooks/useSmartyInternationalLookup.js +74 -0
  31. package/dist/addressLookup/hooks/useSmartyInternationalLookup.js.map +1 -0
  32. package/dist/addressLookup/hooks/useSmartyLookupBase.js +152 -0
  33. package/dist/addressLookup/hooks/useSmartyLookupBase.js.map +1 -0
  34. package/dist/addressLookup/hooks/useSmartyUSLookup.js +79 -0
  35. package/dist/addressLookup/hooks/useSmartyUSLookup.js.map +1 -0
  36. package/dist/addressLookup/hooks/useUSAddressValidation.js +166 -0
  37. package/dist/addressLookup/hooks/useUSAddressValidation.js.map +1 -0
  38. package/dist/addressLookup/index.js +41 -0
  39. package/dist/addressLookup/index.js.map +1 -0
  40. package/dist/addressLookup/styles/addressLookup.css +383 -0
  41. package/dist/addressLookup/utils/addressForm.js +150 -0
  42. package/dist/addressLookup/utils/addressForm.js.map +1 -0
  43. package/dist/addressLookup/utils/addressMapping.js +190 -0
  44. package/dist/addressLookup/utils/addressMapping.js.map +1 -0
  45. package/dist/addressLookup/utils/addressStatus.js +173 -0
  46. package/dist/addressLookup/utils/addressStatus.js.map +1 -0
  47. package/dist/addressLookup/utils/addressStrings.js +159 -0
  48. package/dist/addressLookup/utils/addressStrings.js.map +1 -0
  49. package/dist/addressLookup/utils/addressVerification.js +66 -0
  50. package/dist/addressLookup/utils/addressVerification.js.map +1 -0
  51. package/dist/addressLookup/utils/addressWrapper.js +40 -0
  52. package/dist/addressLookup/utils/addressWrapper.js.map +1 -0
  53. package/dist/addressLookup/utils/componentPropTypes.js +118 -0
  54. package/dist/addressLookup/utils/componentPropTypes.js.map +1 -0
  55. package/dist/addressLookup/utils/googleMapsLoader.js +68 -0
  56. package/dist/addressLookup/utils/googleMapsLoader.js.map +1 -0
  57. package/dist/addressLookup/utils/inFlightRequests.js +50 -0
  58. package/dist/addressLookup/utils/inFlightRequests.js.map +1 -0
  59. package/dist/addressLookup/utils/intlAutocompleteBusinessRules.js +62 -0
  60. package/dist/addressLookup/utils/intlAutocompleteBusinessRules.js.map +1 -0
  61. package/dist/addressLookup/utils/requestCache.js +44 -0
  62. package/dist/addressLookup/utils/requestCache.js.map +1 -0
  63. package/dist/addressLookup/utils/requestRateLimiter.js +53 -0
  64. package/dist/addressLookup/utils/requestRateLimiter.js.map +1 -0
  65. package/dist/addressLookup/utils/smartyConfig.js +11 -0
  66. package/dist/addressLookup/utils/smartyConfig.js.map +1 -0
  67. package/dist/addressLookup/utils/validators.js +45 -0
  68. package/dist/addressLookup/utils/validators.js.map +1 -0
  69. package/dist/index.js +28 -1
  70. package/dist/index.js.map +1 -1
  71. package/dist/{ShippingAddressForm.js → shippingAddressForm/ShippingAddressForm.js} +10 -2
  72. package/dist/shippingAddressForm/ShippingAddressForm.js.map +1 -0
  73. package/dist/{components → shippingAddressForm/components}/ShippingField.js +32 -22
  74. package/dist/shippingAddressForm/components/ShippingField.js.map +1 -0
  75. package/dist/shippingAddressForm/hooks/useAddressFieldLabels.js.map +1 -0
  76. package/dist/shippingAddressForm/hooks/useShippingAddressForm.js.map +1 -0
  77. package/dist/shippingAddressForm/hooks/useShippingFormState.js.map +1 -0
  78. package/dist/shippingAddressForm/utils/emailVerify.js.map +1 -0
  79. package/dist/{utils → shippingAddressForm/utils}/shippingAddressForm.js +3 -3
  80. package/dist/shippingAddressForm/utils/shippingAddressForm.js.map +1 -0
  81. package/dist/shippingAddressForm/utils/shippingStrings.js.map +1 -0
  82. package/package.json +2 -3
  83. package/dist/ShippingAddressForm.js.map +0 -1
  84. package/dist/components/ShippingField.js.map +0 -1
  85. package/dist/hooks/useAddressFieldLabels.js.map +0 -1
  86. package/dist/hooks/useShippingAddressForm.js.map +0 -1
  87. package/dist/hooks/useShippingFormState.js.map +0 -1
  88. package/dist/utils/emailVerify.js.map +0 -1
  89. package/dist/utils/shippingAddressForm.js.map +0 -1
  90. package/dist/utils/shippingStrings.js.map +0 -1
  91. /package/dist/{hooks → shippingAddressForm/hooks}/useAddressFieldLabels.js +0 -0
  92. /package/dist/{hooks → shippingAddressForm/hooks}/useShippingAddressForm.js +0 -0
  93. /package/dist/{hooks → shippingAddressForm/hooks}/useShippingFormState.js +0 -0
  94. /package/dist/{styles → shippingAddressForm/styles}/shippingAddressForm.css +0 -0
  95. /package/dist/{utils → shippingAddressForm/utils}/emailVerify.js +0 -0
  96. /package/dist/{utils → shippingAddressForm/utils}/shippingStrings.js +0 -0
@@ -0,0 +1,1001 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _propTypes = _interopRequireDefault(require("prop-types"));
8
+ var _react = require("react");
9
+ var _useSmartyUSLookup = _interopRequireDefault(require("../hooks/useSmartyUSLookup"));
10
+ var _useUSAddressValidation = _interopRequireDefault(require("../hooks/useUSAddressValidation"));
11
+ var _useAddressFieldLabels = _interopRequireDefault(require("../hooks/useAddressFieldLabels"));
12
+ var _useAddressForm = _interopRequireDefault(require("../hooks/useAddressForm"));
13
+ var _useInitialAddressVerification = _interopRequireDefault(require("../hooks/useInitialAddressVerification"));
14
+ var _useAddressMapModal = _interopRequireDefault(require("../hooks/useAddressMapModal"));
15
+ var _addressMapping = require("../utils/addressMapping");
16
+ var _addressWrapper = require("../utils/addressWrapper");
17
+ var _addressStatus = require("../utils/addressStatus");
18
+ var _addressVerification = require("../utils/addressVerification");
19
+ var _validators = require("../utils/validators");
20
+ var _componentPropTypes = require("../utils/componentPropTypes");
21
+ var _LocationPinIcon = _interopRequireDefault(require("./LocationPinIcon"));
22
+ var _foundationUiComponents = require("@nuskin/foundation-ui-components");
23
+ var _jsxRuntime = require("react/jsx-runtime");
24
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
25
+ const stripGeocode = (address = {}) => {
26
+ const nextAddress = {
27
+ ...address
28
+ };
29
+ delete nextAddress.latitude;
30
+ delete nextAddress.longitude;
31
+ return nextAddress;
32
+ };
33
+ const FIELD_TEST_IDS = {
34
+ address1: 'qa-address-1',
35
+ address2: 'qa-address-2',
36
+ district: 'qa-address-district',
37
+ region: 'qa-address-region',
38
+ city: 'qa-address-city',
39
+ postalCode: 'qa-address-postal-code'
40
+ };
41
+ const FIELD_IDS = {
42
+ address1: 'address-line-1',
43
+ address2: 'address-line-2',
44
+ district: 'address-district',
45
+ region: 'address-region',
46
+ city: 'address-city',
47
+ postalCode: 'address-postal-code'
48
+ };
49
+ const getFieldTestId = field => FIELD_TEST_IDS[field] || `qa-address-${field}`;
50
+ const getFieldId = field => FIELD_IDS[field] || `address-${field}`;
51
+ const LOOKUP_LIST_BUTTON_SELECTOR = '.ns-address-lookup__list-button';
52
+ const SmartyUSResults = ({
53
+ onSelect,
54
+ initialAddress = null,
55
+ entryMode = 'both',
56
+ requireValidation = true,
57
+ readOnlyView = false,
58
+ showManualValidateButton = false,
59
+ validationRequestId = 0,
60
+ language = 'en',
61
+ strings = null,
62
+ formDefinition = null,
63
+ deferFormLookup = false
64
+ }) => {
65
+ var _formDefinition$addre;
66
+ const [mode, setMode] = (0, _react.useState)(entryMode === 'manual' ? 'manual' : 'autocomplete');
67
+ const [query, setQuery] = (0, _react.useState)('');
68
+ const [selectedAddress, setSelectedAddress] = (0, _react.useState)(null);
69
+ const [selectedUSAddress, setSelectedUSAddress] = (0, _react.useState)(null);
70
+ const [formData, setFormData] = (0, _react.useState)(initialAddress || {});
71
+ const [verificationStatus, setVerificationStatus] = (0, _react.useState)((0, _addressVerification.getIncomingVerificationStatus)(initialAddress));
72
+ const [validationTrigger, setValidationTrigger] = (0, _react.useState)(0);
73
+ const [validationTriggerSource, setValidationTriggerSource] = (0, _react.useState)(null);
74
+ const [showValidationSuggestions, setShowValidationSuggestions] = (0, _react.useState)(false);
75
+ const [mapAddressLines, setMapAddressLines] = (0, _react.useState)([]);
76
+ const [hasPendingLookupDraft, setHasPendingLookupDraft] = (0, _react.useState)(false);
77
+ const [touchedFields, setTouchedFields] = (0, _react.useState)({});
78
+ const [showAllRequiredErrors, setShowAllRequiredErrors] = (0, _react.useState)(false);
79
+ const [lookupServiceError, setLookupServiceError] = (0, _react.useState)(null);
80
+ const [validationServiceError, setValidationServiceError] = (0, _react.useState)(null);
81
+ const shouldSearchRef = (0, _react.useRef)(true);
82
+ const fieldTimerRef = (0, _react.useRef)(null);
83
+ const componentRef = (0, _react.useRef)(null);
84
+ const suggestionsListRef = (0, _react.useRef)(null);
85
+ const lastCommittedAddressRef = (0, _react.useRef)(initialAddress || {});
86
+ const lookupDraftOriginalRef = (0, _react.useRef)(initialAddress || {});
87
+ const appliedSelectionKeyRef = (0, _react.useRef)(null);
88
+ const mapValidationStartedRef = (0, _react.useRef)(false);
89
+ const autoApplyValidationStartedRef = (0, _react.useRef)(false);
90
+ const hasInitializedAddressRef = (0, _react.useRef)(false);
91
+ (0, _react.useEffect)(() => {
92
+ if (!initialAddress || hasInitializedAddressRef.current) {
93
+ return;
94
+ }
95
+ hasInitializedAddressRef.current = true;
96
+ setFormData(initialAddress);
97
+ setVerificationStatus((0, _addressVerification.getIncomingVerificationStatus)(initialAddress));
98
+ shouldSearchRef.current = false;
99
+ lastCommittedAddressRef.current = initialAddress;
100
+ lookupDraftOriginalRef.current = initialAddress;
101
+ setTouchedFields({});
102
+ setShowAllRequiredErrors(false);
103
+ setLookupServiceError(null);
104
+ setValidationServiceError(null);
105
+ setMapAddressLines([]);
106
+ }, [initialAddress]);
107
+ (0, _react.useEffect)(() => {
108
+ return () => {
109
+ if (fieldTimerRef.current) {
110
+ clearTimeout(fieldTimerRef.current);
111
+ }
112
+ };
113
+ }, []);
114
+ const isAutocompleteMode = mode === 'autocomplete';
115
+ const {
116
+ labels: fieldLabels,
117
+ isLoading: areLabelsLoading
118
+ } = (0, _useAddressFieldLabels.default)('US', language, strings);
119
+ const shouldLoadAddressForm = !formDefinition && !deferFormLookup;
120
+ const {
121
+ addressForm: loadedAddressForm,
122
+ isLoading: isFormLoading
123
+ } = (0, _useAddressForm.default)('US', shouldLoadAddressForm);
124
+ const providedAddressForm = formDefinition !== null && formDefinition !== void 0 && (_formDefinition$addre = formDefinition.addressElements) !== null && _formDefinition$addre !== void 0 && _formDefinition$addre.length ? formDefinition : null;
125
+ const resolvedAddressForm = providedAddressForm || loadedAddressForm;
126
+ const allowValidation = requireValidation && !readOnlyView;
127
+ const lookupField = (resolvedAddressForm === null || resolvedAddressForm === void 0 ? void 0 : resolvedAddressForm.lookupField) || 'address1';
128
+ const requiredFields = (0, _addressStatus.getRequiredFieldsFromAddressForm)(resolvedAddressForm);
129
+ const hasEmailField = ((resolvedAddressForm === null || resolvedAddressForm === void 0 ? void 0 : resolvedAddressForm.addressElements) || []).some(field => field.field === 'email');
130
+ const hasMapCoordinates = (formData === null || formData === void 0 ? void 0 : formData.latitude) !== undefined && (formData === null || formData === void 0 ? void 0 : formData.longitude) !== undefined;
131
+ const hasLookupValue = Boolean(String((formData === null || formData === void 0 ? void 0 : formData[lookupField]) || '').trim());
132
+ const canAttemptMap = Boolean(!isAutocompleteMode && hasLookupValue || isAutocompleteMode && ['autocomplete', 'verified'].includes(verificationStatus) && hasLookupValue);
133
+ const showMapAction = !readOnlyView && (hasMapCoordinates || canAttemptMap);
134
+ const mapInfoLines = (mapAddressLines.length ? mapAddressLines : [formData.address1, formData.address2, [formData.city, formData.region, formData.postalCode].filter(Boolean).join(' ')]).filter(Boolean);
135
+ const {
136
+ mapContainerRef,
137
+ pendingMapOpen,
138
+ setPendingMapOpen,
139
+ setShowMapModal,
140
+ showMapModal
141
+ } = (0, _useAddressMapModal.default)({
142
+ formData,
143
+ infoLines: mapInfoLines,
144
+ hasMapCoordinates,
145
+ openInMapsLabel: fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.openInMaps,
146
+ shouldPrepareMap: showMapAction
147
+ });
148
+ const {
149
+ suggestions,
150
+ loading,
151
+ error,
152
+ rateLimited
153
+ } = (0, _useSmartyUSLookup.default)(!readOnlyView && shouldSearchRef.current && isAutocompleteMode ? query : '', selectedUSAddress, 500);
154
+ const {
155
+ suggestions: validationSuggestions,
156
+ loading: validationLoading,
157
+ error: validationError,
158
+ rateLimited: validationRateLimited
159
+ } = (0, _useUSAddressValidation.default)(formData, allowValidation ? validationTrigger : 0);
160
+ const lookupValue = formData[lookupField];
161
+ const lookupErrorMessage = lookupServiceError !== null && lookupServiceError !== void 0 && lookupServiceError.rateLimited ? (fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.rateLimited) || 'Too many requests. Please wait a moment and try again.' : (fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.lookupError) || 'We could not look up that address right now.';
162
+ const validationErrorMessage = validationServiceError !== null && validationServiceError !== void 0 && validationServiceError.rateLimited ? (fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.rateLimited) || 'Too many requests. Please wait a moment and try again.' : (fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.validationError) || 'We could not validate that address right now.';
163
+ (0, _react.useEffect)(() => {
164
+ if (!validationRequestId) {
165
+ return;
166
+ }
167
+ setShowAllRequiredErrors(true);
168
+ onSelect === null || onSelect === void 0 || onSelect({
169
+ type: 'validation-request',
170
+ address: formData,
171
+ status: (0, _addressStatus.buildAddressStatus)({
172
+ countryCode: 'US',
173
+ addressForm: resolvedAddressForm,
174
+ formData,
175
+ verificationStatus,
176
+ mode,
177
+ requireValidation: allowValidation
178
+ })
179
+ });
180
+ }, [allowValidation, validationRequestId]);
181
+ (0, _react.useEffect)(() => {
182
+ if (!error) {
183
+ setLookupServiceError(null);
184
+ return;
185
+ }
186
+ setLookupServiceError({
187
+ rateLimited,
188
+ rawMessage: error
189
+ });
190
+ }, [error, rateLimited]);
191
+ (0, _react.useEffect)(() => {
192
+ if (!validationError) {
193
+ setValidationServiceError(null);
194
+ return;
195
+ }
196
+ setValidationServiceError({
197
+ rateLimited: validationRateLimited,
198
+ rawMessage: validationError
199
+ });
200
+ setPendingMapOpen(false);
201
+ mapValidationStartedRef.current = false;
202
+ }, [validationError, validationRateLimited]);
203
+ (0, _react.useEffect)(() => {
204
+ if (!lookupServiceError) {
205
+ return;
206
+ }
207
+ onSelect === null || onSelect === void 0 || onSelect({
208
+ type: 'lookup-error',
209
+ address: formData,
210
+ status: (0, _addressStatus.buildAddressStatus)({
211
+ countryCode: 'US',
212
+ addressForm: resolvedAddressForm,
213
+ formData,
214
+ verificationStatus,
215
+ mode,
216
+ requireValidation: allowValidation
217
+ }),
218
+ error: {
219
+ kind: lookupServiceError.rateLimited ? 'rate-limited' : 'api',
220
+ source: 'autocomplete',
221
+ message: lookupErrorMessage
222
+ }
223
+ });
224
+ }, [lookupServiceError]);
225
+ (0, _react.useEffect)(() => {
226
+ if (!validationServiceError) {
227
+ return;
228
+ }
229
+ onSelect === null || onSelect === void 0 || onSelect({
230
+ type: 'validation-error',
231
+ address: formData,
232
+ status: (0, _addressStatus.buildAddressStatus)({
233
+ countryCode: 'US',
234
+ addressForm: resolvedAddressForm,
235
+ formData,
236
+ verificationStatus,
237
+ mode,
238
+ requireValidation: allowValidation
239
+ }),
240
+ error: {
241
+ kind: validationServiceError.rateLimited ? 'rate-limited' : 'api',
242
+ source: 'validation',
243
+ message: validationErrorMessage
244
+ }
245
+ });
246
+ }, [validationServiceError]);
247
+ const clearServiceErrors = ({
248
+ lookup = true,
249
+ validation = true
250
+ } = {}) => {
251
+ if (lookup) {
252
+ setLookupServiceError(null);
253
+ }
254
+ if (validation) {
255
+ setValidationServiceError(null);
256
+ }
257
+ };
258
+ const stripUnusedEmail = (address = {}) => {
259
+ if (hasEmailField) {
260
+ return address;
261
+ }
262
+ const nextAddress = {
263
+ ...address
264
+ };
265
+ delete nextAddress.email;
266
+ return nextAddress;
267
+ };
268
+ const buildTrackedAddress = (address = {}, status = 'unverified', source = null) => stripUnusedEmail((0, _addressVerification.withAddressVerification)(address, status, source));
269
+ const isAcceptableInitialValidationResult = validatedAddress => Boolean(validatedAddress === null || validatedAddress === void 0 ? void 0 : validatedAddress.isDeliverable);
270
+ const getBestInitialValidationResult = (suggestions = []) => suggestions.find(isAcceptableInitialValidationResult) || null;
271
+ (0, _useInitialAddressVerification.default)({
272
+ initialAddress,
273
+ countryCode: 'US',
274
+ lookupField,
275
+ requireValidation: allowValidation,
276
+ resolvedAddressForm,
277
+ setValidationServiceError,
278
+ setShowValidationSuggestions,
279
+ setValidationTriggerSource,
280
+ setValidationTrigger
281
+ });
282
+ (0, _react.useEffect)(() => {
283
+ if (validationTrigger > 0 && ['autocomplete', 'map', 'initial'].includes(validationTriggerSource)) {
284
+ autoApplyValidationStartedRef.current = false;
285
+ }
286
+ }, [validationTrigger, validationTriggerSource]);
287
+ (0, _react.useEffect)(() => {
288
+ if (validationLoading && validationTriggerSource === 'map') {
289
+ mapValidationStartedRef.current = true;
290
+ }
291
+ if (validationLoading && ['autocomplete', 'map', 'initial'].includes(validationTriggerSource)) {
292
+ autoApplyValidationStartedRef.current = true;
293
+ }
294
+ }, [validationLoading, validationTriggerSource]);
295
+ (0, _react.useEffect)(() => {
296
+ if (validationTriggerSource === 'map' && showValidationSuggestions && !validationLoading && validationSuggestions.length === 0 && !validationServiceError && mapValidationStartedRef.current) {
297
+ setPendingMapOpen(false);
298
+ mapValidationStartedRef.current = false;
299
+ }
300
+ }, [validationLoading, validationSuggestions, validationTriggerSource, showValidationSuggestions, validationServiceError]);
301
+ (0, _react.useEffect)(() => {
302
+ if (lookupValue !== undefined && shouldSearchRef.current && !selectedAddress) {
303
+ setQuery(lookupValue);
304
+ }
305
+ }, [lookupValue, selectedAddress]);
306
+ (0, _react.useEffect)(() => {
307
+ var _suggestionButtons$;
308
+ const shouldShowValidationResults = allowValidation && showValidationSuggestions && validationSuggestions.length > 0 && !validationLoading && (!isAutocompleteMode || validationTriggerSource === 'map');
309
+ if (!shouldShowValidationResults) {
310
+ return;
311
+ }
312
+ const suggestionButtons = getVisibleSuggestionButtons();
313
+ if (suggestionButtons.length === 0 || suggestionButtons.includes(document.activeElement)) {
314
+ return;
315
+ }
316
+ (_suggestionButtons$ = suggestionButtons[0]) === null || _suggestionButtons$ === void 0 || _suggestionButtons$.focus();
317
+ }, [isAutocompleteMode, allowValidation, showValidationSuggestions, validationLoading, validationSuggestions, validationTriggerSource]);
318
+ (0, _react.useEffect)(() => {
319
+ var _getLookupInputElemen;
320
+ const shouldRefocusLookupField = isAutocompleteMode && selectedUSAddress && suggestions.length > 0 && !selectedAddress && !loading;
321
+ if (!shouldRefocusLookupField) {
322
+ return;
323
+ }
324
+ (_getLookupInputElemen = getLookupInputElement()) === null || _getLookupInputElemen === void 0 || _getLookupInputElemen.focus();
325
+ }, [isAutocompleteMode, selectedUSAddress, suggestions, selectedAddress, loading]);
326
+ (0, _react.useEffect)(() => {
327
+ if (!hasPendingLookupDraft || suggestions.length === 0) {
328
+ return undefined;
329
+ }
330
+ const handleDocumentMouseDown = event => {
331
+ const component = componentRef.current;
332
+ if (component !== null && component !== void 0 && component.contains(event.target)) {
333
+ return;
334
+ }
335
+ const suggestionsList = suggestionsListRef.current;
336
+ if ((suggestionsList === null || suggestionsList === void 0 ? void 0 : suggestionsList.contains(event.target)) === false) {
337
+ shouldSearchRef.current = false;
338
+ setQuery('');
339
+ setSelectedAddress(null);
340
+ setSelectedUSAddress(null);
341
+ setShowValidationSuggestions(false);
342
+ setShowMapModal(false);
343
+ setPendingMapOpen(false);
344
+ mapValidationStartedRef.current = false;
345
+ clearServiceErrors();
346
+ setFormData(lookupDraftOriginalRef.current);
347
+ setMapAddressLines([]);
348
+ setHasPendingLookupDraft(false);
349
+ }
350
+ };
351
+ document.addEventListener('pointerdown', handleDocumentMouseDown);
352
+ return () => {
353
+ document.removeEventListener('pointerdown', handleDocumentMouseDown);
354
+ };
355
+ }, [hasPendingLookupDraft, suggestions]);
356
+ (0, _react.useEffect)(() => {
357
+ if (isAutocompleteMode || !showValidationSuggestions || validationLoading || validationSuggestions.length === 0) {
358
+ return undefined;
359
+ }
360
+ const handleDocumentPointerDown = event => {
361
+ var _componentRef$current;
362
+ if ((_componentRef$current = componentRef.current) !== null && _componentRef$current !== void 0 && _componentRef$current.contains(event.target)) {
363
+ return;
364
+ }
365
+ setShowValidationSuggestions(false);
366
+ };
367
+ document.addEventListener('pointerdown', handleDocumentPointerDown);
368
+ return () => {
369
+ document.removeEventListener('pointerdown', handleDocumentPointerDown);
370
+ };
371
+ }, [isAutocompleteMode, showValidationSuggestions, validationLoading, validationSuggestions]);
372
+ (0, _react.useEffect)(() => {
373
+ if (selectedAddress) {
374
+ const selectionKey = selectedAddress.street_line ? `${selectedAddress.street_line}|${selectedAddress.secondary || ''}|${selectedAddress.zipcode || ''}` : JSON.stringify(selectedAddress);
375
+ if (appliedSelectionKeyRef.current === selectionKey) {
376
+ return;
377
+ }
378
+ appliedSelectionKeyRef.current = selectionKey;
379
+ const config = resolvedAddressForm.addressElements || [];
380
+ let mapped = {
381
+ address1: selectedAddress.street_line,
382
+ address2: selectedAddress.secondary || '',
383
+ city: selectedAddress.city,
384
+ region: selectedAddress.state,
385
+ postalCode: selectedAddress.zipcode
386
+ };
387
+
388
+ // Apply address wrapping if enabled
389
+ if (resolvedAddressForm.wrapAddress1ToAddress2) {
390
+ const address1Field = config.find(f => f.field === 'address1');
391
+ if (address1Field !== null && address1Field !== void 0 && address1Field.maxLength) {
392
+ const wrapped = (0, _addressWrapper.wrapAddress1ToAddress2)(mapped.address1, mapped.address2, address1Field.maxLength);
393
+ mapped.address1 = wrapped.address1;
394
+ mapped.address2 = wrapped.address2;
395
+ }
396
+ }
397
+ const updatedFormData = {
398
+ ...stripGeocode(formData),
399
+ ...mapped,
400
+ email: formData.email
401
+ };
402
+ const normalizedFormData = buildTrackedAddress(updatedFormData, 'autocomplete', 'smarty-us');
403
+ setFormData(normalizedFormData);
404
+ setMapAddressLines([]);
405
+ lastCommittedAddressRef.current = normalizedFormData;
406
+ lookupDraftOriginalRef.current = normalizedFormData;
407
+ setHasPendingLookupDraft(false);
408
+ clearServiceErrors();
409
+ const currentVerificationStatus = 'autocomplete';
410
+ setVerificationStatus(currentVerificationStatus);
411
+ onSelect === null || onSelect === void 0 || onSelect({
412
+ type: 'autocomplete',
413
+ address: normalizedFormData,
414
+ status: (0, _addressStatus.buildAddressStatus)({
415
+ countryCode: 'US',
416
+ addressForm: resolvedAddressForm,
417
+ formData: normalizedFormData,
418
+ verificationStatus: currentVerificationStatus,
419
+ mode,
420
+ requireValidation: allowValidation
421
+ })
422
+ });
423
+ }
424
+ }, [selectedAddress]);
425
+ const handleInputChange = e => {
426
+ const value = (0, _validators.normalizeAddressFieldValue)(lookupField, e.target.value);
427
+ shouldSearchRef.current = true;
428
+ appliedSelectionKeyRef.current = null;
429
+ setSelectedAddress(null);
430
+ setSelectedUSAddress(null);
431
+ setShowValidationSuggestions(false);
432
+ setShowMapModal(false);
433
+ setPendingMapOpen(false);
434
+ mapValidationStartedRef.current = false;
435
+ setMapAddressLines([]);
436
+ setValidationTriggerSource(null);
437
+ clearServiceErrors();
438
+ if (!hasPendingLookupDraft) {
439
+ lookupDraftOriginalRef.current = formData;
440
+ setHasPendingLookupDraft(true);
441
+ }
442
+ const updatedLookupData = stripUnusedEmail({
443
+ ...stripGeocode(formData),
444
+ [lookupField]: value
445
+ });
446
+ setFormData(buildTrackedAddress(updatedLookupData, 'unverified'));
447
+ setVerificationStatus('unverified');
448
+ };
449
+ const isFieldRequired = field => requiredFields.includes(field);
450
+ const isFieldBlank = field => String(formData[field] || '').trim() === '';
451
+ const hasInvalidPostalCodeFormat = field => {
452
+ if (field !== 'postalCode') {
453
+ return false;
454
+ }
455
+ const value = String(formData.postalCode || '').trim();
456
+ if (!value || !resolvedAddressForm.postalCodeRegex) {
457
+ return false;
458
+ }
459
+ return !resolvedAddressForm.postalCodeRegex.test((0, _validators.normalizePostalCodeValue)(value));
460
+ };
461
+ const hasInvalidEmailFormat = field => {
462
+ if (field !== 'email') {
463
+ return false;
464
+ }
465
+ const value = String(formData.email || '').trim();
466
+ if (!value) {
467
+ return false;
468
+ }
469
+ return !(0, _validators.isValidEmail)(value);
470
+ };
471
+ const shouldShowFieldError = field => {
472
+ const shouldShowValidation = Boolean(showAllRequiredErrors || touchedFields[field]);
473
+ if (!shouldShowValidation) {
474
+ return false;
475
+ }
476
+ const requiredError = isFieldRequired(field) && isFieldBlank(field);
477
+ return requiredError || hasInvalidPostalCodeFormat(field) || hasInvalidEmailFormat(field);
478
+ };
479
+ const handleFieldBlur = field => {
480
+ if (!isFieldRequired(field) && field !== 'email' && field !== 'postalCode') {
481
+ return;
482
+ }
483
+ setTouchedFields(prev => ({
484
+ ...prev,
485
+ [field]: true
486
+ }));
487
+ };
488
+ const getFieldErrorMessage = field => {
489
+ if (!shouldShowFieldError(field)) {
490
+ return '';
491
+ }
492
+ if (isFieldRequired(field) && isFieldBlank(field)) {
493
+ return areLabelsLoading ? '' : fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.fieldRequired;
494
+ }
495
+ if (hasInvalidPostalCodeFormat(field)) {
496
+ return areLabelsLoading ? '' : fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.invalidPostalCode;
497
+ }
498
+ if (hasInvalidEmailFormat(field)) {
499
+ return areLabelsLoading ? '' : fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.invalidEmail;
500
+ }
501
+ return '';
502
+ };
503
+ const hasVisibleFieldError = field => shouldShowFieldError(field);
504
+ const handleEditableFieldChange = (field, value) => {
505
+ const normalizedValue = (0, _validators.normalizeAddressFieldValue)(field, value);
506
+ if (field === lookupField) {
507
+ setShowValidationSuggestions(false);
508
+ }
509
+ clearServiceErrors();
510
+ setShowMapModal(false);
511
+ setPendingMapOpen(false);
512
+ mapValidationStartedRef.current = false;
513
+ setMapAddressLines([]);
514
+ const requiredFieldsForVerification = (resolvedAddressForm === null || resolvedAddressForm === void 0 ? void 0 : resolvedAddressForm.requiredFields) || requiredFields;
515
+ const nextVerificationStatus = (0, _addressVerification.getManualEditVerificationStatus)(verificationStatus, field, lookupField, requiredFieldsForVerification);
516
+ const updatedFormData = (0, _addressVerification.withManualAddressVerificationEdit)(stripUnusedEmail({
517
+ ...stripGeocode(formData),
518
+ [field]: normalizedValue
519
+ }), field, nextVerificationStatus);
520
+ setFormData(updatedFormData);
521
+ setVerificationStatus(nextVerificationStatus);
522
+ if (fieldTimerRef.current) {
523
+ clearTimeout(fieldTimerRef.current);
524
+ }
525
+ fieldTimerRef.current = setTimeout(() => {
526
+ const payload = {
527
+ type: 'field-change',
528
+ field,
529
+ value: normalizedValue,
530
+ address: updatedFormData,
531
+ status: (0, _addressStatus.buildAddressStatus)({
532
+ countryCode: 'US',
533
+ addressForm: resolvedAddressForm,
534
+ formData: updatedFormData,
535
+ verificationStatus: nextVerificationStatus,
536
+ mode,
537
+ requireValidation: allowValidation
538
+ })
539
+ };
540
+ if (hasEmailField && field === 'email' && value) {
541
+ payload.isValidEmail = (0, _validators.isValidEmail)(normalizedValue);
542
+ }
543
+ onSelect === null || onSelect === void 0 || onSelect(payload);
544
+ }, 500);
545
+ };
546
+ const handleSelect = address => {
547
+ clearServiceErrors({
548
+ lookup: true,
549
+ validation: false
550
+ });
551
+ if (address.entries > 1) {
552
+ shouldSearchRef.current = true;
553
+ appliedSelectionKeyRef.current = null;
554
+ setSelectedUSAddress(address);
555
+ const baseAddress = `${address.street_line} ${address.secondary}`.trim();
556
+ setQuery(baseAddress);
557
+ } else {
558
+ shouldSearchRef.current = false;
559
+ appliedSelectionKeyRef.current = null;
560
+ setSelectedUSAddress(null);
561
+ setSelectedAddress(address);
562
+ setQuery('');
563
+ }
564
+ };
565
+ const handleValidationSelect = validatedAddress => {
566
+ var _validatedAddress$met, _validatedAddress$met2;
567
+ clearServiceErrors({
568
+ lookup: false,
569
+ validation: true
570
+ });
571
+ const config = resolvedAddressForm.addressElements || [];
572
+ const {
573
+ mapped: verifiedMapped,
574
+ mapAddressLines: nextMapAddressLines
575
+ } = (0, _addressMapping.buildUSVerifiedAddressMapping)(validatedAddress);
576
+ let mapped = {
577
+ ...verifiedMapped
578
+ };
579
+ if (resolvedAddressForm.wrapAddress1ToAddress2) {
580
+ const address1Field = config.find(f => f.field === 'address1');
581
+ if (address1Field !== null && address1Field !== void 0 && address1Field.maxLength) {
582
+ const wrapped = (0, _addressWrapper.wrapAddress1ToAddress2)(mapped.address1, mapped.address2, address1Field.maxLength);
583
+ mapped.address1 = wrapped.address1;
584
+ mapped.address2 = wrapped.address2;
585
+ }
586
+ }
587
+ const updatedFormData = {
588
+ ...stripGeocode(formData),
589
+ ...mapped,
590
+ email: formData.email,
591
+ latitude: (_validatedAddress$met = validatedAddress.metadata) === null || _validatedAddress$met === void 0 ? void 0 : _validatedAddress$met.latitude,
592
+ longitude: (_validatedAddress$met2 = validatedAddress.metadata) === null || _validatedAddress$met2 === void 0 ? void 0 : _validatedAddress$met2.longitude
593
+ };
594
+ const normalizedFormData = buildTrackedAddress(updatedFormData, 'verified', 'smarty-us');
595
+ setShowValidationSuggestions(false);
596
+ setValidationTriggerSource(null);
597
+ setMapAddressLines(nextMapAddressLines);
598
+ setFormData(normalizedFormData);
599
+ lastCommittedAddressRef.current = normalizedFormData;
600
+ lookupDraftOriginalRef.current = normalizedFormData;
601
+ setHasPendingLookupDraft(false);
602
+ const currentVerificationStatus = 'verified';
603
+ setVerificationStatus(currentVerificationStatus);
604
+ autoApplyValidationStartedRef.current = false;
605
+ if (pendingMapOpen) {
606
+ setPendingMapOpen(false);
607
+ mapValidationStartedRef.current = false;
608
+ setShowMapModal(true);
609
+ }
610
+ onSelect === null || onSelect === void 0 || onSelect({
611
+ type: 'validation',
612
+ address: normalizedFormData,
613
+ verification: validatedAddress.analysis,
614
+ isDeliverable: validatedAddress.isDeliverable,
615
+ status: (0, _addressStatus.buildAddressStatus)({
616
+ countryCode: 'US',
617
+ addressForm: resolvedAddressForm,
618
+ formData: normalizedFormData,
619
+ verificationStatus: currentVerificationStatus,
620
+ mode,
621
+ requireValidation: allowValidation
622
+ })
623
+ });
624
+ };
625
+ const handleValidate = () => {
626
+ if (!allowValidation) {
627
+ return;
628
+ }
629
+ clearServiceErrors({
630
+ lookup: false,
631
+ validation: true
632
+ });
633
+ setShowValidationSuggestions(true);
634
+ setValidationTriggerSource('manual');
635
+ setValidationTrigger(prev => prev + 1);
636
+ };
637
+ const handleOpenMap = () => {
638
+ if (hasMapCoordinates) {
639
+ setShowMapModal(true);
640
+ return;
641
+ }
642
+ if (!canAttemptMap || validationLoading) {
643
+ return;
644
+ }
645
+ clearServiceErrors({
646
+ lookup: false,
647
+ validation: true
648
+ });
649
+ mapValidationStartedRef.current = false;
650
+ setPendingMapOpen(true);
651
+ setShowValidationSuggestions(true);
652
+ setValidationTriggerSource('map');
653
+ setValidationTrigger(prev => prev + 1);
654
+ };
655
+ const getFieldKey = fieldConfig => fieldConfig.field;
656
+ const getSuggestionKey = suggestion => [suggestion.street_line, suggestion.secondary, suggestion.city, suggestion.state, suggestion.zipcode, suggestion.entries].filter(value => value !== undefined && value !== null).join('|');
657
+ const getValidationSuggestionKey = suggestion => [suggestion.delivery_line_1, suggestion.delivery_line_2, suggestion.last_line, suggestion.dpvMatchCode].filter(value => value !== undefined && value !== null).join('|');
658
+ const getValidationSummaryTitle = suggestion => {
659
+ var _suggestion$validatio, _suggestion$validatio2, _suggestion$validatio3, _suggestion$validatio4, _suggestion$validatio5, _suggestion$validatio6, _suggestion$validatio7, _suggestion$validatio8, _suggestion$validatio9;
660
+ const code = (_suggestion$validatio = suggestion.validationSummary) === null || _suggestion$validatio === void 0 ? void 0 : _suggestion$validatio.code;
661
+ switch (code) {
662
+ case 'verified':
663
+ return (fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.usVerified) || ((_suggestion$validatio2 = suggestion.validationSummary) === null || _suggestion$validatio2 === void 0 ? void 0 : _suggestion$validatio2.title) || 'Verified';
664
+ case 'missing-secondary':
665
+ return (fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.usMissingSecondaryTitle) || ((_suggestion$validatio3 = suggestion.validationSummary) === null || _suggestion$validatio3 === void 0 ? void 0 : _suggestion$validatio3.title) || 'Apartment or suite needed';
666
+ case 'invalid-secondary-required':
667
+ return (fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.usInvalidSecondaryRequiredTitle) || ((_suggestion$validatio4 = suggestion.validationSummary) === null || _suggestion$validatio4 === void 0 ? void 0 : _suggestion$validatio4.title) || 'Apartment or suite not recognized';
668
+ case 'invalid-secondary-optional':
669
+ return (fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.usInvalidSecondaryOptionalTitle) || ((_suggestion$validatio5 = suggestion.validationSummary) === null || _suggestion$validatio5 === void 0 ? void 0 : _suggestion$validatio5.title) || 'Unit not recognized';
670
+ case 'vacant':
671
+ return (fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.usVacantTitle) || ((_suggestion$validatio6 = suggestion.validationSummary) === null || _suggestion$validatio6 === void 0 ? void 0 : _suggestion$validatio6.title) || 'Verified, but marked vacant';
672
+ case 'no-stat':
673
+ return (fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.usNoStatTitle) || ((_suggestion$validatio7 = suggestion.validationSummary) === null || _suggestion$validatio7 === void 0 ? void 0 : _suggestion$validatio7.title) || 'Verified with caution';
674
+ case 'not-confirmed':
675
+ return (fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.usNotConfirmedTitle) || ((_suggestion$validatio8 = suggestion.validationSummary) === null || _suggestion$validatio8 === void 0 ? void 0 : _suggestion$validatio8.title) || 'Not verified';
676
+ default:
677
+ return ((_suggestion$validatio9 = suggestion.validationSummary) === null || _suggestion$validatio9 === void 0 ? void 0 : _suggestion$validatio9.title) || 'Candidate';
678
+ }
679
+ };
680
+ const getValidationSummaryMessage = suggestion => {
681
+ var _suggestion$validatio0, _suggestion$validatio1, _suggestion$validatio10, _suggestion$validatio11, _suggestion$validatio12, _suggestion$validatio13, _suggestion$validatio14, _suggestion$validatio15, _suggestion$validatio16;
682
+ const code = (_suggestion$validatio0 = suggestion.validationSummary) === null || _suggestion$validatio0 === void 0 ? void 0 : _suggestion$validatio0.code;
683
+ switch (code) {
684
+ case 'missing-secondary':
685
+ return (fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.usMissingSecondaryMessage) || ((_suggestion$validatio1 = suggestion.validationSummary) === null || _suggestion$validatio1 === void 0 ? void 0 : _suggestion$validatio1.message) || '';
686
+ case 'invalid-secondary-required':
687
+ return (fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.usInvalidSecondaryRequiredMessage) || ((_suggestion$validatio10 = suggestion.validationSummary) === null || _suggestion$validatio10 === void 0 ? void 0 : _suggestion$validatio10.message) || '';
688
+ case 'invalid-secondary-optional':
689
+ return (fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.usInvalidSecondaryOptionalMessage) || ((_suggestion$validatio11 = suggestion.validationSummary) === null || _suggestion$validatio11 === void 0 ? void 0 : _suggestion$validatio11.message) || '';
690
+ case 'vacant':
691
+ return (fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.usVacantMessage) || ((_suggestion$validatio12 = suggestion.validationSummary) === null || _suggestion$validatio12 === void 0 ? void 0 : _suggestion$validatio12.message) || '';
692
+ case 'no-stat':
693
+ return (fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.usNoStatMessage) || ((_suggestion$validatio13 = suggestion.validationSummary) === null || _suggestion$validatio13 === void 0 ? void 0 : _suggestion$validatio13.message) || '';
694
+ case 'not-confirmed':
695
+ return (fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.usNotConfirmedMessage) || ((_suggestion$validatio14 = suggestion.validationSummary) === null || _suggestion$validatio14 === void 0 ? void 0 : _suggestion$validatio14.message) || '';
696
+ case 'verified':
697
+ return (fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.usVerifiedMessage) || ((_suggestion$validatio15 = suggestion.validationSummary) === null || _suggestion$validatio15 === void 0 ? void 0 : _suggestion$validatio15.message) || '';
698
+ default:
699
+ return ((_suggestion$validatio16 = suggestion.validationSummary) === null || _suggestion$validatio16 === void 0 ? void 0 : _suggestion$validatio16.message) || '';
700
+ }
701
+ };
702
+ const renderLookupActions = () => /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
703
+ className: "ns-address-lookup__actions",
704
+ children: [showMapAction && /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
705
+ type: "button",
706
+ onClick: handleOpenMap,
707
+ className: "ns-address-lookup__toggle ns-address-lookup__toggle--icon",
708
+ title: fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.openInMaps,
709
+ "aria-label": fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.openInMaps,
710
+ children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_LocationPinIcon.default, {
711
+ className: "ns-address-lookup__icon"
712
+ })
713
+ }), !isAutocompleteMode && allowValidation && showManualValidateButton && /*#__PURE__*/(0, _jsxRuntime.jsx)(_foundationUiComponents.NsButton, {
714
+ type: "button",
715
+ onClick: handleValidate,
716
+ disabled: validationLoading || !String(formData[lookupField] || '').trim(),
717
+ variant: "contained",
718
+ color: "primary",
719
+ size: "small",
720
+ children: validationLoading ? 'Validating...' : 'Validate Address'
721
+ }), entryMode === 'both' && /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
722
+ type: "button",
723
+ onClick: () => {
724
+ setShowValidationSuggestions(false);
725
+ setShowMapModal(false);
726
+ setPendingMapOpen(false);
727
+ mapValidationStartedRef.current = false;
728
+ setValidationTriggerSource(null);
729
+ clearServiceErrors();
730
+ setMode(mode === 'autocomplete' ? 'manual' : 'autocomplete');
731
+ },
732
+ className: "ns-address-lookup__toggle",
733
+ children: mode === 'autocomplete' ? fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.switchToManualEntry : fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.switchToAutocomplete
734
+ })]
735
+ });
736
+ const getLookupInputElement = () => typeof document !== 'undefined' ? document.getElementById(getFieldId(lookupField)) : null;
737
+ const getVisibleSuggestionButtons = () => {
738
+ var _componentRef$current2;
739
+ return Array.from(((_componentRef$current2 = componentRef.current) === null || _componentRef$current2 === void 0 ? void 0 : _componentRef$current2.querySelectorAll(LOOKUP_LIST_BUTTON_SELECTOR)) || []);
740
+ };
741
+ const handleLookupInputKeyDown = event => {
742
+ if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') {
743
+ return;
744
+ }
745
+ const suggestionButtons = getVisibleSuggestionButtons();
746
+ if (suggestionButtons.length === 0) {
747
+ return;
748
+ }
749
+ event.preventDefault();
750
+ const targetButton = event.key === 'ArrowUp' ? suggestionButtons[suggestionButtons.length - 1] : suggestionButtons[0];
751
+ targetButton === null || targetButton === void 0 || targetButton.focus();
752
+ };
753
+ const handleSuggestionButtonKeyDown = (event, index) => {
754
+ const suggestionButtons = getVisibleSuggestionButtons();
755
+ if (suggestionButtons.length === 0) {
756
+ return;
757
+ }
758
+ if (event.key === 'ArrowDown') {
759
+ var _suggestionButtons;
760
+ event.preventDefault();
761
+ if (index === suggestionButtons.length - 1) {
762
+ var _getLookupInputElemen2;
763
+ (_getLookupInputElemen2 = getLookupInputElement()) === null || _getLookupInputElemen2 === void 0 || _getLookupInputElemen2.focus();
764
+ return;
765
+ }
766
+ (_suggestionButtons = suggestionButtons[index + 1]) === null || _suggestionButtons === void 0 || _suggestionButtons.focus();
767
+ return;
768
+ }
769
+ if (event.key === 'ArrowUp') {
770
+ var _suggestionButtons2;
771
+ event.preventDefault();
772
+ if (index === 0) {
773
+ var _getLookupInputElemen3;
774
+ (_getLookupInputElemen3 = getLookupInputElement()) === null || _getLookupInputElemen3 === void 0 || _getLookupInputElemen3.focus();
775
+ return;
776
+ }
777
+ (_suggestionButtons2 = suggestionButtons[index - 1]) === null || _suggestionButtons2 === void 0 || _suggestionButtons2.focus();
778
+ return;
779
+ }
780
+ if (event.key === 'Escape') {
781
+ var _getLookupInputElemen4;
782
+ event.preventDefault();
783
+ (_getLookupInputElemen4 = getLookupInputElement()) === null || _getLookupInputElemen4 === void 0 || _getLookupInputElemen4.focus();
784
+ }
785
+ };
786
+ const renderLookupLists = isLookupField => {
787
+ if (readOnlyView) {
788
+ return null;
789
+ }
790
+ const shouldShowValidationResults = allowValidation && showValidationSuggestions && (!isAutocompleteMode || validationTriggerSource === 'map');
791
+ const shouldShowNoResults = shouldShowValidationResults && !validationLoading && validationSuggestions.length === 0 && !validationServiceError && (validationTriggerSource !== 'map' || mapValidationStartedRef.current);
792
+ if (!isLookupField) {
793
+ return null;
794
+ }
795
+ if (loading && isAutocompleteMode) {
796
+ return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
797
+ className: "ns-address-lookup__spinner"
798
+ });
799
+ }
800
+ if (suggestions.length > 0 && !selectedAddress && isAutocompleteMode) {
801
+ return /*#__PURE__*/(0, _jsxRuntime.jsx)("ul", {
802
+ ref: suggestionsListRef,
803
+ className: "ns-address-lookup__list ns-address-lookup__list--suggestions",
804
+ children: suggestions.map((suggestion, index) => /*#__PURE__*/(0, _jsxRuntime.jsx)("li", {
805
+ className: ['ns-address-lookup__list-item', index < suggestions.length - 1 ? 'ns-address-lookup__list-item--divided' : ''].filter(Boolean).join(' '),
806
+ children: /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
807
+ type: "button",
808
+ onClick: () => handleSelect(suggestion),
809
+ onKeyDown: event => handleSuggestionButtonKeyDown(event, index),
810
+ className: "ns-address-lookup__list-button",
811
+ children: suggestion.displayText
812
+ })
813
+ }, getSuggestionKey(suggestion)))
814
+ });
815
+ }
816
+ if (shouldShowValidationResults && validationSuggestions.length > 0) {
817
+ return /*#__PURE__*/(0, _jsxRuntime.jsx)("ul", {
818
+ className: "ns-address-lookup__list ns-address-lookup__list--validation-inline",
819
+ children: validationSuggestions.map((suggestion, index) => {
820
+ var _suggestion$validatio17;
821
+ return /*#__PURE__*/(0, _jsxRuntime.jsx)("li", {
822
+ className: ['ns-address-lookup__list-item', ((_suggestion$validatio17 = suggestion.validationSummary) === null || _suggestion$validatio17 === void 0 ? void 0 : _suggestion$validatio17.code) === 'not-confirmed' ? 'ns-address-lookup__list-item--not-verified' : '', index < validationSuggestions.length - 1 ? 'ns-address-lookup__list-item--divided' : ''].filter(Boolean).join(' '),
823
+ children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("button", {
824
+ type: "button",
825
+ onClick: () => handleValidationSelect(suggestion),
826
+ onKeyDown: event => handleSuggestionButtonKeyDown(event, index),
827
+ className: "ns-address-lookup__list-button",
828
+ children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
829
+ className: "ns-address-lookup__list-title",
830
+ children: getValidationSummaryTitle(suggestion)
831
+ }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
832
+ className: "ns-address-lookup__list-subtitle",
833
+ children: suggestion.displayText
834
+ }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
835
+ className: "ns-address-lookup__list-subtitle",
836
+ children: getValidationSummaryMessage(suggestion)
837
+ })]
838
+ })
839
+ }, getValidationSuggestionKey(suggestion));
840
+ })
841
+ });
842
+ }
843
+ if (shouldShowNoResults) {
844
+ return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
845
+ className: "ns-address-lookup__message",
846
+ children: fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.usNoResults
847
+ });
848
+ }
849
+ return null;
850
+ };
851
+ (0, _react.useEffect)(() => {
852
+ if (['autocomplete', 'map'].includes(validationTriggerSource) && validationSuggestions.length === 1 && autoApplyValidationStartedRef.current) {
853
+ handleValidationSelect(validationSuggestions[0]);
854
+ }
855
+ if (validationTriggerSource === 'initial' && autoApplyValidationStartedRef.current && !validationLoading) {
856
+ const bestSuggestion = getBestInitialValidationResult(validationSuggestions);
857
+ if (bestSuggestion) {
858
+ handleValidationSelect(bestSuggestion);
859
+ return;
860
+ }
861
+ autoApplyValidationStartedRef.current = false;
862
+ setShowValidationSuggestions(false);
863
+ setValidationTriggerSource(null);
864
+ }
865
+ }, [validationLoading, validationSuggestions, validationTriggerSource]);
866
+ const renderField = fieldConfig => {
867
+ const isLookupField = fieldConfig.field === lookupField;
868
+ const fieldId = getFieldId(fieldConfig.field);
869
+ const fieldLabel = areLabelsLoading ? '' : (fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels[fieldConfig.field]) || fieldConfig.label;
870
+ const fieldError = getFieldErrorMessage(fieldConfig.field);
871
+ const isInvalid = hasVisibleFieldError(fieldConfig.field);
872
+ const isReadOnly = readOnlyView || !fieldConfig.editable && !isLookupField && isAutocompleteMode;
873
+ const fieldWidth = fieldConfig.width === 'full' ? '100%' : fieldConfig.width === 'third' ? '33.333333%' : '50%';
874
+ const inputClassName = ['ns-address-lookup__input', isReadOnly ? 'ns-address-lookup__input--readonly' : '', isLookupField && loading ? 'ns-address-lookup__input--loading' : ''].filter(Boolean).join(' ');
875
+ const labelRowClassName = ['ns-address-lookup__label-row', isLookupField ? '' : 'ns-address-lookup__label-row--field'].filter(Boolean).join(' ');
876
+ return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
877
+ className: "ns-address-lookup__field",
878
+ style: {
879
+ width: fieldWidth
880
+ },
881
+ children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
882
+ className: labelRowClassName,
883
+ children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("label", {
884
+ htmlFor: fieldId,
885
+ className: "MuiFormLabel-root MuiFormLabel-colorPrimary css-1ef1ceb-MuiFormLabel-root",
886
+ children: [fieldLabel, fieldConfig.required && !areLabelsLoading && /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
887
+ "aria-hidden": "true",
888
+ className: "MuiFormLabel-asterisk",
889
+ children: ' *'
890
+ })]
891
+ }), isLookupField && !readOnlyView && renderLookupActions()]
892
+ }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_foundationUiComponents.NsInputField, {
893
+ id: fieldId,
894
+ type: "text",
895
+ value: formData[fieldConfig.field] || '',
896
+ "aria-invalid": shouldShowFieldError(fieldConfig.field) ? 'true' : undefined,
897
+ fieldState: isInvalid ? 'error' : undefined,
898
+ helperText: fieldError || undefined,
899
+ required: fieldConfig.required,
900
+ onBlur: () => handleFieldBlur(fieldConfig.field),
901
+ onKeyDown: isLookupField && !readOnlyView ? handleLookupInputKeyDown : undefined,
902
+ onChange: e => {
903
+ const filtered = (0, _validators.filterAllowedCharacters)(e.target.value, fieldConfig.allowedCharacters);
904
+ if (readOnlyView) {
905
+ return;
906
+ }
907
+ if (isLookupField && isAutocompleteMode) {
908
+ handleInputChange({
909
+ ...e,
910
+ target: {
911
+ ...e.target,
912
+ value: filtered
913
+ }
914
+ });
915
+ } else {
916
+ handleEditableFieldChange(fieldConfig.field, filtered);
917
+ }
918
+ },
919
+ InputProps: {
920
+ readOnly: isReadOnly
921
+ },
922
+ inputProps: {
923
+ maxLength: fieldConfig.maxLength,
924
+ 'data-testid': getFieldTestId(fieldConfig.field)
925
+ },
926
+ className: inputClassName
927
+ }), renderLookupLists(isLookupField)]
928
+ }, getFieldKey(fieldConfig));
929
+ };
930
+ const renderAddressForm = () => {
931
+ const config = resolvedAddressForm === null || resolvedAddressForm === void 0 ? void 0 : resolvedAddressForm.addressElements;
932
+ if (!(config !== null && config !== void 0 && config.length)) {
933
+ if (isFormLoading) {
934
+ return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
935
+ children: fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.loadingAddressForm
936
+ });
937
+ }
938
+ return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
939
+ children: "No form available for this country: US"
940
+ });
941
+ }
942
+ return /*#__PURE__*/(0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {
943
+ children: config.map(renderField)
944
+ });
945
+ };
946
+ return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
947
+ ref: componentRef,
948
+ className: "ns-address-lookup__panel",
949
+ children: [lookupServiceError && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
950
+ className: "ns-address-lookup__message",
951
+ children: lookupErrorMessage
952
+ }), allowValidation && validationServiceError && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
953
+ className: "ns-address-lookup__message",
954
+ children: validationErrorMessage
955
+ }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
956
+ className: "ns-address-lookup__form",
957
+ children: renderAddressForm()
958
+ }), showMapModal && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
959
+ className: "ns-address-lookup__modal-backdrop",
960
+ onClick: () => setShowMapModal(false),
961
+ children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
962
+ className: "ns-address-lookup__modal",
963
+ role: "dialog",
964
+ "aria-modal": "true",
965
+ "aria-label": fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.addressLocation,
966
+ onClick: event => event.stopPropagation(),
967
+ children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
968
+ className: "ns-address-lookup__modal-header",
969
+ children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
970
+ className: "ns-address-lookup__modal-title",
971
+ children: fieldLabels === null || fieldLabels === void 0 ? void 0 : fieldLabels.addressLocation
972
+ }), /*#__PURE__*/(0, _jsxRuntime.jsx)("button", {
973
+ type: "button",
974
+ className: "ns-address-lookup__toggle",
975
+ "aria-label": "Close",
976
+ onClick: () => setShowMapModal(false),
977
+ children: "X"
978
+ })]
979
+ }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
980
+ ref: mapContainerRef,
981
+ className: "ns-address-lookup__map"
982
+ })]
983
+ })
984
+ })]
985
+ });
986
+ };
987
+ SmartyUSResults.propTypes = {
988
+ onSelect: _propTypes.default.func,
989
+ initialAddress: _componentPropTypes.addressPropType,
990
+ entryMode: _propTypes.default.oneOf(['both', 'autocomplete', 'manual']),
991
+ requireValidation: _propTypes.default.bool,
992
+ readOnlyView: _propTypes.default.bool,
993
+ showManualValidateButton: _propTypes.default.bool,
994
+ validationRequestId: _propTypes.default.number,
995
+ language: _propTypes.default.string,
996
+ strings: _componentPropTypes.labelStringsPropType,
997
+ formDefinition: _componentPropTypes.formDefinitionPropType,
998
+ deferFormLookup: _propTypes.default.bool
999
+ };
1000
+ var _default = exports.default = SmartyUSResults;
1001
+ //# sourceMappingURL=SmartyUSResults.js.map