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