initial check in

will remove console logs after figuring out last issue
This commit is contained in:
Bill Richardson 2023-12-29 09:41:27 -05:00
parent d0c6da9d63
commit 750cf89fd4

View file

@ -1,19 +1,5 @@
<template> <template>
<div role="application"> <div role="application">
<alert
v-if="displayVerificationWarning"
ref="alertVerificationWarning"
class="mb-4"
cmsWidgetName="AlertVerificationWarningWidget"
alertClass="alert-warning"
:isDismissible="false" />
<alert
v-if="displayNoMatchWarning"
ref="alertNoMatchWarning"
class="mb-4 mt-4"
cmsWidgetName="AlertNoMatchWarningWidget"
alertClass="alert-warning"
:isDismissible="false" />
<div class="row mt-2 mb-4"> <div class="row mt-2 mb-4">
<div class="col"> <div class="col">
<textboxQuestion <textboxQuestion
@ -85,6 +71,20 @@
</div> </div>
</div> </div>
</transition> </transition>
<alert
v-if="displayVerificationWarning"
ref="alertVerificationWarning"
class="mb-4"
cmsWidgetName="AlertVerificationWarningWidget"
alertClass="alert-warning"
:isDismissible="false" />
<alert
v-if="displayNoMatchWarning"
ref="alertNoMatchWarning"
class="mb-4 mt-4"
cmsWidgetName="AlertNoMatchWarningWidget"
alertClass="alert-warning"
:isDismissible="false" />
</div> </div>
</template> </template>
@ -112,7 +112,7 @@ export default {
textboxQuestion, textboxQuestion,
dropdownQuestion, dropdownQuestion,
alert alert
}, // The component emits an event },
props: { props: {
modelValue: { modelValue: {
type: Object, type: Object,
@ -125,29 +125,33 @@ export default {
}) })
}, },
validationRules: String, validationRules: String,
// TODO: fix this property definition (something like Boolean, default: false) - be sure to test it. includeStreetAddress2: {
includeStreetAddress2: false type: Boolean,
default: false
}
}, },
emits: ['update:modelValue'], emits: ['update:modelValue'],
data() { data() {
return { return {
displayVerificationWarning: false, autocomplete: null,
displayNoMatchWarning: false, autocompleteListener: null,
alertHeadlineVerificationWarning: '', alertCopyNoMatchWarning: '',
alertCopyVerificationWarning: '', alertCopyVerificationWarning: '',
alertHeadlineNoMatchWarning: '', alertHeadlineNoMatchWarning: '',
alertCopyNoMatchWarning: '', alertHeadlineVerificationWarning: '',
matchingIndirectly: false, displayVerificationWarning: false,
matchFound: null, // null = no attempted match, true = match was found, false = match was not found displayNoMatchWarning: false,
enterPressed: false, enterPressed: false,
isAddressWatchActive: false, // Only deep watch the address model when a match was not found 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 showAllFields: false
}; };
}, },
computed: { computed: {
stateOptions: { addressField1: {
get() { get() {
return states; return document.getElementById('autocomplete');
} }
}, },
addressModel: { addressModel: {
@ -157,6 +161,11 @@ export default {
set(newValue) { set(newValue) {
this.$emit('update:modelValue', newValue); this.$emit('update:modelValue', newValue);
} }
},
stateOptions: {
get() {
return states;
}
} }
}, },
watch: { watch: {
@ -176,127 +185,121 @@ export default {
}); });
} }
} }
},
addressModel: {
handler() {
if (this.isAddressWatchActive) {
this.displayNoMatchWarning = false;
this.isAddressWatchActive = false;
}
},
deep: true
} }
}, },
mounted() { mounted() {
// 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(); this.setupAddressLookup();
this.showAllFields = !!this.addressModel.streetAddress; }
}, },
methods: { methods: {
setupAddressLookup() { initializeAutocomplete() {
const addressField1 = document.getElementById('autocomplete'); // Initialize the Google Places Autocomplete
const self = this; this.autocomplete = new window.google.maps.places.Autocomplete(this.addressField1, {
const url = endpoints.GooglePlaces.url(applicationConfig.GOOGLE_PLACES_API_KEY);
this.$loadScript(url)
.then(() => {
// Script is loaded, initialize the autocomplete textbox
const autocomplete = new window.google.maps.places.Autocomplete(addressField1, {
componentRestrictions: { country: ['us'] }, componentRestrictions: { country: ['us'] },
fields: ['address_components'], fields: ['address_components'],
types: ['geocode'] types: ['geocode']
}); });
// Standard place_changed event handling // Set up the Autocomplete place_changed event to call our method to fill in the address
const autocompleteListener = window.google.maps.event.addListener( this.autocompleteListener = window.google.maps.event.addListener(
autocomplete, this.autocomplete,
'place_changed', 'place_changed',
fillInAddress this.fillInAddress
); );
addressField1.addEventListener('focus', () => { // When the Street Address textbox receives focus,
// Wrapping the addressField1 element in the Google Address Autocomplete object // append the search results list container to the bottom of the textbox
// will cause "autocomplete='off'" which Chrome completely ignores. This event // and disable browser autofill
// handler will set the value to something arbitrary so autofill doesn't work. this.addressField1.addEventListener('focus', () => {
// https://stackoverflow.com/a/30976223
addressField1.setAttribute('autocomplete', 'do-not-autofill');
// Make place results box stick to the input on scroll // Make place results box stick to the input on scroll
const streetAddressField = document.getElementById('streetAddressField'); const streetAddressField = document.getElementById('streetAddressField');
const autocompleteResultsContainer = document.getElementsByClassName('pac-container')[0]; const autocompleteResultsContainer =
document.getElementsByClassName('pac-container')[0];
if (autocompleteResultsContainer) { if (autocompleteResultsContainer) {
streetAddressField.appendChild(autocompleteResultsContainer); streetAddressField.appendChild(autocompleteResultsContainer);
} }
// 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('keydown', (e) => { this.addressField1.addEventListener('keydown', (e) => {
// If a match has been previously attempted then do nothing
if (this.matchFound !== null) {
return;
}
const event = new Event('place_changed');
// 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 === 'Enter' || e.code === 'NumpadEnter' || e.code === 'Tab') {
if (e.code === 'Tab') { if (e.code === 'Tab') {
self.matchingIndirectly = true; this.matchingIndirectly = true;
} else { } else {
self.enterPressed = true; this.enterPressed = true;
} }
addressField1.blur(); // 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();
}
} }
}); });
addressField1.addEventListener('change', () => { this.addressField1.addEventListener('change', () => {
// NOTE: The "place_changed" event of the autocomplete fires console.log('addr1 changed');
// after this and will use either the address the user had chosen // If a match has been previously attempted then do nothing
// using either the down / up arrows or the address the user was hovering over when they pressed "Enter." if (this.matchFound || this.enterPressed) {
// 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; return;
} }
// Get the address that the user clicked on (if any) // Get the address that the user clicked on (if any)
const clickedAddress = document.querySelector('.pac-container .pac-item:hover'); 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 the Street Address field changed without clicking (i.e. by pressing Tab, or clicking outside the field)
if (clickedAddress === null) { if (clickedAddress === null) {
// Fill-in the address using first item in the list. // Fill-in the address using first item in the list.
const item = document.querySelector('.pac-container .pac-item'); this.fillInAddressUsingFirstItem();
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;
}
} }
}); });
},
fillInAddress(place) {
console.log('fillInAddress...');
let fnPlace = place;
/** console.log(place);
* if (!fnPlace) {
* @param place fnPlace = this.autocomplete.getPlace();
*/
function fillInAddress(place) {
if (!place) {
place = autocomplete.getPlace();
} }
if (place && place.address_components) { if (place && place.address_components) {
self.matchFound = true; this.matchFound = true;
self.addressModel.streetAddress = '';
self.$nextTick(() => { const self = this;
this.$nextTick(() => {
this.showAllFields = true;
// eslint-disable-next-line no-restricted-syntax // eslint-disable-next-line no-restricted-syntax
for (const component of place.address_components) { for (const component of place.address_components) {
const componentType = component.types[0]; const componentType = component.types[0];
@ -307,8 +310,7 @@ export default {
break; break;
} }
case 'route': { case 'route': {
self.addressModel.streetAddress self.addressModel.streetAddress += ` ${component.short_name}`;
+= ` ${component.short_name}`;
break; break;
} }
case 'locality': { case 'locality': {
@ -327,26 +329,76 @@ export default {
} }
} }
self.displayVerificationWarning = self.matchingIndirectly; // After filling in the address fields, disable the address autocomplete
this.unloadAutocomplete();
// Restore focus to the first address field
this.addressField1.focus();
// after showing the address fields, disable the address autocomplete console.log(`displayVerificationWarningDynamic: ${self.matchingIndirectly}`);
window.google.maps.event.removeListener(autocompleteListener); self.displayVerificationWarning = self.matchingIndirectly;
window.google.maps.event.clearInstanceListeners(autocomplete);
addressField1.onchange = null;
const pacContainer = document.querySelector('.pac-container');
if (pacContainer) {
pacContainer.remove();
}
}); });
} else { } 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;
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; 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(() => { .catch(() => {
// Failed to fetch script // Failed to fetch script
window.console.warn('Unable to load Google Places API 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();
}
}
} }
} }
}; };