diff --git a/src/iss-components/address-questions/address-questions.vue b/src/iss-components/address-questions/address-questions.vue index 665a3772..14900e9b 100644 --- a/src/iss-components/address-questions/address-questions.vue +++ b/src/iss-components/address-questions/address-questions.vue @@ -1,19 +1,5 @@ @@ -112,7 +112,7 @@ export default { textboxQuestion, dropdownQuestion, alert - }, // The component emits an event + }, props: { modelValue: { type: Object, @@ -125,29 +125,33 @@ export default { }) }, validationRules: String, - // TODO: fix this property definition (something like Boolean, default: false) - be sure to test it. - includeStreetAddress2: false + includeStreetAddress2: { + type: Boolean, + default: false + } }, emits: ['update:modelValue'], data() { return { - displayVerificationWarning: false, - displayNoMatchWarning: false, - alertHeadlineVerificationWarning: '', + autocomplete: null, + autocompleteListener: null, + alertCopyNoMatchWarning: '', alertCopyVerificationWarning: '', alertHeadlineNoMatchWarning: '', - alertCopyNoMatchWarning: '', - matchingIndirectly: false, - matchFound: null, // null = no attempted match, true = match was found, false = match was not found + alertHeadlineVerificationWarning: '', + displayVerificationWarning: false, + displayNoMatchWarning: false, enterPressed: false, isAddressWatchActive: false, // Only deep watch the address model when a match was not found + matchingIndirectly: false, + matchFound: null, // null = no attempted match, true = match was found, false = match was not found showAllFields: false }; }, computed: { - stateOptions: { + addressField1: { get() { - return states; + return document.getElementById('autocomplete'); } }, addressModel: { @@ -157,6 +161,11 @@ export default { set(newValue) { this.$emit('update:modelValue', newValue); } + }, + stateOptions: { + get() { + return states; + } } }, watch: { @@ -176,177 +185,220 @@ export default { }); } } - }, - addressModel: { - handler() { - if (this.isAddressWatchActive) { - this.displayNoMatchWarning = false; - this.isAddressWatchActive = false; - } - }, - deep: true } }, mounted() { - this.setupAddressLookup(); - this.showAllFields = !!this.addressModel.streetAddress; + // If we already have a full address, show it + this.showAllFields = + (this.addressModel.streetAddress ?? '') !== '' + && (this.addressModel.city ?? '') !== '' + && (this.addressModel.state ?? '') !== '' + && (this.addressModel.zipCode ?? '') !== ''; + + if (!this.showAllFields) { + this.setupAddressLookup(); + } }, methods: { - setupAddressLookup() { - const addressField1 = document.getElementById('autocomplete'); - const self = this; + initializeAutocomplete() { + // Initialize the Google Places Autocomplete + this.autocomplete = new window.google.maps.places.Autocomplete(this.addressField1, { + componentRestrictions: { country: ['us'] }, + fields: ['address_components'], + types: ['geocode'] + }); - const url = endpoints.GooglePlaces.url(applicationConfig.GOOGLE_PLACES_API_KEY); + // Set up the Autocomplete place_changed event to call our method to fill in the address + this.autocompleteListener = window.google.maps.event.addListener( + this.autocomplete, + 'place_changed', + this.fillInAddress + ); - this.$loadScript(url) - .then(() => { - // Script is loaded, initialize the autocomplete textbox - const autocomplete = new window.google.maps.places.Autocomplete(addressField1, { - componentRestrictions: { country: ['us'] }, - fields: ['address_components'], - types: ['geocode'] - }); + // When the Street Address textbox receives focus, + // append the search results list container to the bottom of the textbox + // and disable browser autofill + this.addressField1.addEventListener('focus', () => { + // Make place results box stick to the input on scroll + const streetAddressField = document.getElementById('streetAddressField'); + const autocompleteResultsContainer = + document.getElementsByClassName('pac-container')[0]; + if (autocompleteResultsContainer) { + streetAddressField.appendChild(autocompleteResultsContainer); + } - // Standard place_changed event handling - const autocompleteListener = window.google.maps.event.addListener( - autocomplete, - 'place_changed', - fillInAddress - ); + // Unfortunately this is the only place we can set the autocomplete attribute without the + // Google Places object resetting it to "off" which does nothing to prevent browser autofill + this.addressField1.setAttribute('autocomplete', 'do-not-autofill'); + }); - addressField1.addEventListener('focus', () => { - // Wrapping the addressField1 element in the Google Address Autocomplete object - // will cause "autocomplete='off'" which Chrome completely ignores. This event - // handler will set the value to something arbitrary so autofill doesn't work. - // https://stackoverflow.com/a/30976223 - addressField1.setAttribute('autocomplete', 'do-not-autofill'); + this.addressField1.addEventListener('keydown', (e) => { + // If a match has been previously attempted then do nothing + if (this.matchFound !== null) { + return; + } - // Make place results box stick to the input on scroll - const streetAddressField = document.getElementById('streetAddressField'); - const autocompleteResultsContainer = document.getElementsByClassName('pac-container')[0]; - if (autocompleteResultsContainer) { - streetAddressField.appendChild(autocompleteResultsContainer); - } - }); + const event = new Event('place_changed'); - addressField1.addEventListener('keydown', (e) => { - if (e.code === 'Enter' || e.code === 'NumpadEnter' || e.code === 'Tab') { - if (e.code === 'Tab') { - self.matchingIndirectly = true; - } else { - self.enterPressed = true; + // When either of the two enter keys or the tab key are pressed + if (e.code === 'Enter' || e.code === 'NumpadEnter' || e.code === 'Tab') { + if (e.code === 'Tab') { + this.matchingIndirectly = true; + } else { + this.enterPressed = true; + } + + // Grab the selected item + const selectedItem = document.querySelector('.pac-container .pac-item-selected'); + + if (selectedItem !== null) { + // If an item was selected then fill in the address with the selected item + // by triggering the "place_changed" event of the Autocomplete object + console.log('keydown: found selected item...'); + console.log(selectedItem); + this.autocomplete.dispatchEvent(event); + } else { + // Otherwise fill-in the address using first item from the list. + console.log('keydown: did NOT find selected item...'); + console.log('keydown: use fillInAddressUsingFirstItem...'); + this.fillInAddressUsingFirstItem(); + } + } + }); + + this.addressField1.addEventListener('change', () => { + console.log('addr1 changed'); + // If a match has been previously attempted then do nothing + if (this.matchFound || this.enterPressed) { + return; + } + + // Get the address that the user clicked on (if any) + const clickedAddress = document.querySelector('.pac-container .pac-item:hover'); + console.log('clicked addr'); + console.log(clickedAddress); + + // If the Street Address field changed without clicking (i.e. by pressing Tab, or clicking outside the field) + if (clickedAddress === null) { + // Fill-in the address using first item in the list. + this.fillInAddressUsingFirstItem(); + } + }); + }, + fillInAddress(place) { + console.log('fillInAddress...'); + let fnPlace = place; + + console.log(place); + if (!fnPlace) { + fnPlace = this.autocomplete.getPlace(); + } + + if (place && place.address_components) { + this.matchFound = true; + + const self = this; + this.$nextTick(() => { + this.showAllFields = true; + // eslint-disable-next-line no-restricted-syntax + for (const component of place.address_components) { + const componentType = component.types[0]; + + switch (componentType) { + case 'street_number': { + self.addressModel.streetAddress = component.long_name; + break; } - - addressField1.blur(); - } - }); - - addressField1.addEventListener('change', () => { - // NOTE: The "place_changed" event of the autocomplete fires - // after this and will use either the address the user had chosen - // using either the down / up arrows or the address the user was hovering over when they pressed "Enter." - - // If a match has been previously found then do nothing - // OR - // If the user pressed "Enter" then do nothing - this.showAllFields = true; - - if (self.matchFound || self.enterPressed) { - return; - } - - // Get the address that the user clicked on (if any) - const clickedAddress = document.querySelector('.pac-container .pac-item:hover'); - - // If the Street Address field changed without clicking (i.e. by pressing Tab, or clicking outside the field) - if (clickedAddress === null) { - // Fill-in the address using first item in the list. - const item = document.querySelector('.pac-container .pac-item'); - if (item != null) { - self.matchingIndirectly = true; - - const firstResult = item.textContent; - const geocoder = new window.google.maps.Geocoder(); - geocoder.geocode( - { - address: firstResult - }, - (results, status) => { - if (status === window.google.maps.GeocoderStatus.OK) { - fillInAddress(results[0]); - } - } - ); - } else { - // No addresses found for the input - self.matchFound = false; + case 'route': { + self.addressModel.streetAddress += ` ${component.short_name}`; + break; } + case 'locality': { + self.addressModel.city = component.long_name; + break; + } + case 'administrative_area_level_1': { + self.addressModel.state = component.short_name; + break; + } + case 'postal_code': { + self.addressModel.zipCode = component.long_name; + break; + } + default: } - }); + } - /** - * - * @param place - */ - function fillInAddress(place) { - if (!place) { - place = autocomplete.getPlace(); - } + // After filling in the address fields, disable the address autocomplete + this.unloadAutocomplete(); + // Restore focus to the first address field + this.addressField1.focus(); - if (place && place.address_components) { - self.matchFound = true; - self.addressModel.streetAddress = ''; - self.$nextTick(() => { - // eslint-disable-next-line no-restricted-syntax - for (const component of place.address_components) { - const componentType = component.types[0]; + console.log(`displayVerificationWarningDynamic: ${self.matchingIndirectly}`); + self.displayVerificationWarning = self.matchingIndirectly; + }); + } else { + console.log('displayVerificationWarning: true'); + this.displayVerificationWarning = true; + } + }, + fillInAddressUsingFirstItem() { + console.log('fillInWithFirstItem...'); + const item = document.querySelector('.pac-container .pac-item'); + if (item != null) { + this.matchingIndirectly = true; - switch (componentType) { - case 'street_number': { - self.addressModel.streetAddress = component.long_name; - break; - } - case 'route': { - self.addressModel.streetAddress - += ` ${component.short_name}`; - break; - } - case 'locality': { - self.addressModel.city = component.long_name; - break; - } - case 'administrative_area_level_1': { - self.addressModel.state = component.short_name; - break; - } - case 'postal_code': { - self.addressModel.zipCode = component.long_name; - break; - } - default: - } - } - - self.displayVerificationWarning = self.matchingIndirectly; - - // after showing the address fields, disable the address autocomplete - window.google.maps.event.removeListener(autocompleteListener); - window.google.maps.event.clearInstanceListeners(autocomplete); - addressField1.onchange = null; - const pacContainer = document.querySelector('.pac-container'); - if (pacContainer) { - pacContainer.remove(); - } - }); - } else { + const firstResult = item.textContent; + const self = this; + const geocoder = new window.google.maps.Geocoder(); + geocoder.geocode( + { + address: firstResult + }, + (results, status) => { + console.log('geoCoder geocode function...'); + if (status === window.google.maps.GeocoderStatus.OK) { + self.fillInAddress(results[0]); self.displayVerificationWarning = true; } } + ); + } else { + // No addresses found for the input + this.matchFound = false; + } + }, + setupAddressLookup() { + const apiKey = applicationConfig.GOOGLE_PLACES_API_KEY; + + this.$loadScript(`https://maps.googleapis.com/maps/api/js?key=${apiKey}&libraries=places&callback=Function.prototype`) + .then(() => { + // Script is loaded, initialize the autocomplete textbox + this.initializeAutocomplete(); }) .catch(() => { // Failed to fetch script window.console.warn('Unable to load Google Places API script'); }); + }, + resetAlerts() { + this.displayVerificationWarning = false; + }, + unloadAutocomplete() { + if (this.autocompleteListener && this.autocomplete) { + window.google.maps.event.removeListener(this.autocompleteListener); + this.autocompleteListener = null; + + window.google.maps.event.clearInstanceListeners(this.autocomplete); + this.autocomplete = null; + + this.addressField1.onchange = null; + + const pacContainer = document.querySelector('.pac-container'); + if (pacContainer) { + pacContainer.remove(); + } + } } } };