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,177 +185,220 @@ export default {
}); });
} }
} }
},
addressModel: {
handler() {
if (this.isAddressWatchActive) {
this.displayNoMatchWarning = false;
this.isAddressWatchActive = false;
}
},
deep: true
} }
}, },
mounted() { mounted() {
this.setupAddressLookup(); // If we already have a full address, show it
this.showAllFields = !!this.addressModel.streetAddress; this.showAllFields =
(this.addressModel.streetAddress ?? '') !== ''
&& (this.addressModel.city ?? '') !== ''
&& (this.addressModel.state ?? '') !== ''
&& (this.addressModel.zipCode ?? '') !== '';
if (!this.showAllFields) {
this.setupAddressLookup();
}
}, },
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, {
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) // When the Street Address textbox receives focus,
.then(() => { // append the search results list container to the bottom of the textbox
// Script is loaded, initialize the autocomplete textbox // and disable browser autofill
const autocomplete = new window.google.maps.places.Autocomplete(addressField1, { this.addressField1.addEventListener('focus', () => {
componentRestrictions: { country: ['us'] }, // Make place results box stick to the input on scroll
fields: ['address_components'], const streetAddressField = document.getElementById('streetAddressField');
types: ['geocode'] const autocompleteResultsContainer =
}); document.getElementsByClassName('pac-container')[0];
if (autocompleteResultsContainer) {
streetAddressField.appendChild(autocompleteResultsContainer);
}
// Standard place_changed event handling // Unfortunately this is the only place we can set the autocomplete attribute without the
const autocompleteListener = window.google.maps.event.addListener( // Google Places object resetting it to "off" which does nothing to prevent browser autofill
autocomplete, this.addressField1.setAttribute('autocomplete', 'do-not-autofill');
'place_changed', });
fillInAddress
);
addressField1.addEventListener('focus', () => { this.addressField1.addEventListener('keydown', (e) => {
// Wrapping the addressField1 element in the Google Address Autocomplete object // If a match has been previously attempted then do nothing
// will cause "autocomplete='off'" which Chrome completely ignores. This event if (this.matchFound !== null) {
// handler will set the value to something arbitrary so autofill doesn't work. return;
// https://stackoverflow.com/a/30976223 }
addressField1.setAttribute('autocomplete', 'do-not-autofill');
// Make place results box stick to the input on scroll const event = new Event('place_changed');
const streetAddressField = document.getElementById('streetAddressField');
const autocompleteResultsContainer = document.getElementsByClassName('pac-container')[0];
if (autocompleteResultsContainer) {
streetAddressField.appendChild(autocompleteResultsContainer);
}
});
addressField1.addEventListener('keydown', (e) => { // 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;
}
// 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;
} }
case 'route': {
addressField1.blur(); self.addressModel.streetAddress += ` ${component.short_name}`;
} break;
});
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 '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:
} }
}); }
/** // After filling in the address fields, disable the address autocomplete
* this.unloadAutocomplete();
* @param place // Restore focus to the first address field
*/ this.addressField1.focus();
function fillInAddress(place) {
if (!place) {
place = autocomplete.getPlace();
}
if (place && place.address_components) { console.log(`displayVerificationWarningDynamic: ${self.matchingIndirectly}`);
self.matchFound = true; self.displayVerificationWarning = self.matchingIndirectly;
self.addressModel.streetAddress = ''; });
self.$nextTick(() => { } else {
// eslint-disable-next-line no-restricted-syntax console.log('displayVerificationWarning: true');
for (const component of place.address_components) { this.displayVerificationWarning = true;
const componentType = component.types[0]; }
},
fillInAddressUsingFirstItem() {
console.log('fillInWithFirstItem...');
const item = document.querySelector('.pac-container .pac-item');
if (item != null) {
this.matchingIndirectly = true;
switch (componentType) { const firstResult = item.textContent;
case 'street_number': { const self = this;
self.addressModel.streetAddress = component.long_name; const geocoder = new window.google.maps.Geocoder();
break; geocoder.geocode(
} {
case 'route': { address: firstResult
self.addressModel.streetAddress },
+= ` ${component.short_name}`; (results, status) => {
break; console.log('geoCoder geocode function...');
} if (status === window.google.maps.GeocoderStatus.OK) {
case 'locality': { self.fillInAddress(results[0]);
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 {
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();
}
}
} }
} }
}; };