Merge pull request #532 from Safelite/feature/richardson/SSR-1052
Fix modal validation
This commit is contained in:
commit
c9eba2613d
4 changed files with 171 additions and 574 deletions
|
|
@ -41,16 +41,6 @@ function setupMocks({
|
|||
},
|
||||
places: {
|
||||
Autocomplete: jest.fn().mockImplementation((el) => el)
|
||||
},
|
||||
Geocoder: class Geocoder {
|
||||
// constructor();
|
||||
|
||||
geocode(request, callback) {
|
||||
callback([geocoderResult], true);
|
||||
}
|
||||
},
|
||||
GeocoderStatus: {
|
||||
OK: true
|
||||
}
|
||||
}
|
||||
};
|
||||
|
|
@ -60,6 +50,7 @@ function setupMocks({
|
|||
const wrapper = isShallowMount
|
||||
? shallowMount(addressQuestions, resultingMountOptions)
|
||||
: mount(addressQuestions, resultingMountOptions);
|
||||
|
||||
document.querySelector = jest.fn().mockImplementation((query) => {
|
||||
let result = null;
|
||||
if (query === '.pac-container') result = document.createElement('div');
|
||||
|
|
@ -153,375 +144,4 @@ describe('address-questions.vue', () => {
|
|||
expect(streetAddress2.exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('happy paths', () => {
|
||||
test('street address is entered, user chooses good result from autocomplete results => other fields are filled in', async () => {
|
||||
// Arrange
|
||||
const { wrapper } = setupMocks({});
|
||||
await wrapper.setData({
|
||||
addressModel: {
|
||||
streetAddress: '123 Test Street'
|
||||
}
|
||||
});
|
||||
|
||||
const selectedPlace = {
|
||||
address_components: [
|
||||
{
|
||||
long_name: '1234',
|
||||
short_name: '1234',
|
||||
types: ['street_number']
|
||||
},
|
||||
{
|
||||
long_name: 'Test Road',
|
||||
short_name: 'Test Road',
|
||||
types: ['route']
|
||||
},
|
||||
{
|
||||
long_name: 'East Columbus',
|
||||
short_name: 'Columbus',
|
||||
types: ['neighborhood', 'political']
|
||||
},
|
||||
{
|
||||
long_name: 'Columbus',
|
||||
short_name: 'Columbus',
|
||||
types: ['locality', 'political']
|
||||
},
|
||||
{
|
||||
long_name: 'Franklin County',
|
||||
short_name: 'Franklin County',
|
||||
types: ['administrative_area_level_2', 'political']
|
||||
},
|
||||
{
|
||||
long_name: 'Ohio',
|
||||
short_name: 'OH',
|
||||
types: ['administrative_area_level_1', 'political']
|
||||
},
|
||||
{
|
||||
long_name: 'United States',
|
||||
short_name: 'US',
|
||||
types: ['country', 'political']
|
||||
},
|
||||
{
|
||||
long_name: '43215',
|
||||
short_name: '43215',
|
||||
types: ['postal_code']
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
// Act
|
||||
autocompleteElement.dispatchEvent(new CustomEvent('place_changed', { detail: selectedPlace }));
|
||||
|
||||
// Assert
|
||||
wrapper.vm.$nextTick(() => {
|
||||
const { addressModel } = wrapper.vm;
|
||||
expect(addressModel.streetAddress).toEqual('1234 Test Road');
|
||||
expect(addressModel.city).toEqual('Columbus');
|
||||
expect(addressModel.state).toEqual('OH');
|
||||
expect(addressModel.zipCode).toEqual('43215');
|
||||
});
|
||||
});
|
||||
|
||||
test('street address is entered, but user clicks away => first result is selected and other fields are filled in', async () => {
|
||||
// Arrange
|
||||
let changeEventCallbackFunction;
|
||||
autocompleteElement.addEventListener = jest
|
||||
.fn()
|
||||
.mockImplementation((eventName, callbackFunction) => {
|
||||
if (eventName === 'change') {
|
||||
changeEventCallbackFunction = callbackFunction;
|
||||
}
|
||||
});
|
||||
|
||||
const { wrapper } = setupMocks({
|
||||
querySelectorFunction(query) {
|
||||
if (query === '.pac-container .pac-item') {
|
||||
const element = document.createElement('div');
|
||||
element.textContent = '123 Test Street';
|
||||
return element;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
geocoderResult: {
|
||||
address_components: [
|
||||
{
|
||||
long_name: '1234',
|
||||
short_name: '1234',
|
||||
types: ['street_number']
|
||||
},
|
||||
{
|
||||
long_name: 'Test Road',
|
||||
short_name: 'Test Road',
|
||||
types: ['route']
|
||||
},
|
||||
{
|
||||
long_name: 'East Columbus',
|
||||
short_name: 'Columbus',
|
||||
types: ['neighborhood', 'political']
|
||||
},
|
||||
{
|
||||
long_name: 'Columbus',
|
||||
short_name: 'Columbus',
|
||||
types: ['locality', 'political']
|
||||
},
|
||||
{
|
||||
long_name: 'Franklin County',
|
||||
short_name: 'Franklin County',
|
||||
types: ['administrative_area_level_2', 'political']
|
||||
},
|
||||
{
|
||||
long_name: 'Ohio',
|
||||
short_name: 'OH',
|
||||
types: ['administrative_area_level_1', 'political']
|
||||
},
|
||||
{
|
||||
long_name: 'United States',
|
||||
short_name: 'US',
|
||||
types: ['country', 'political']
|
||||
},
|
||||
{
|
||||
long_name: '43215',
|
||||
short_name: '43215',
|
||||
types: ['postal_code']
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
const noMatchAlert = wrapper.findComponent({ ref: 'alertNoMatchWarning' });
|
||||
const verificationAlert = wrapper.findComponent({ ref: 'alertVerificationWarning' });
|
||||
expect(noMatchAlert.exists()).toBeFalsy();
|
||||
expect(verificationAlert.exists()).toBeFalsy();
|
||||
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
// Act
|
||||
changeEventCallbackFunction();
|
||||
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
// Assert
|
||||
const { addressModel } = wrapper.vm;
|
||||
expect(addressModel.streetAddress).toEqual('1234 Test Road');
|
||||
expect(addressModel.city).toEqual('Columbus');
|
||||
expect(addressModel.state).toEqual('OH');
|
||||
expect(addressModel.zipCode).toEqual('43215');
|
||||
});
|
||||
});
|
||||
|
||||
describe('alerts', () => {
|
||||
const places = [null, { address_components: null }, undefined, {}];
|
||||
test.each(places)(
|
||||
'selected place/place properties is null => display verification alert',
|
||||
async (place) => {
|
||||
// Arrange
|
||||
const { wrapper } = setupMocks({});
|
||||
await wrapper.setData({
|
||||
addressModel: {
|
||||
streetAddress: '123 Test Street'
|
||||
}
|
||||
});
|
||||
|
||||
const selectedPlace = place;
|
||||
|
||||
// Act
|
||||
autocompleteElement.dispatchEvent(new CustomEvent('place_changed', { detail: selectedPlace }));
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
// Assert
|
||||
const verificationAlert = wrapper.findComponent({
|
||||
ref: 'alertVerificationWarning'
|
||||
});
|
||||
expect(verificationAlert.exists()).toBe(true);
|
||||
expect(verificationAlert.isVisible()).toBe(true);
|
||||
|
||||
const noMatchAlert = wrapper.findComponent({ ref: 'alertNoMatchWarning' });
|
||||
expect(noMatchAlert.exists()).toBe(false);
|
||||
}
|
||||
);
|
||||
|
||||
test('user enters address that yields no autocomplete results => show noMatch alert', async () => {
|
||||
// Arrange
|
||||
let changeEventCallbackFunction;
|
||||
autocompleteElement.addEventListener = jest
|
||||
.fn()
|
||||
.mockImplementation((eventName, callbackFunction) => {
|
||||
if (eventName === 'change') {
|
||||
changeEventCallbackFunction = callbackFunction;
|
||||
}
|
||||
});
|
||||
|
||||
const { wrapper } = setupMocks({});
|
||||
|
||||
let noMatchAlert = wrapper.findComponent({ ref: 'alertNoMatchWarning' });
|
||||
expect(noMatchAlert.exists()).toBeFalsy();
|
||||
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
// Act
|
||||
changeEventCallbackFunction();
|
||||
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
// Assert
|
||||
expect(wrapper.vm.displayNoMatchWarning).toBeTruthy();
|
||||
noMatchAlert = wrapper.findComponent({ ref: 'alertNoMatchWarning' });
|
||||
expect(noMatchAlert.exists()).toBeTruthy();
|
||||
expect(noMatchAlert.isVisible()).toBeTruthy();
|
||||
});
|
||||
|
||||
test("user enters address that yields autocomplete results, but doesn't select => show verification alert", async () => {
|
||||
// Arrange
|
||||
let changeEventCallbackFunction;
|
||||
autocompleteElement.addEventListener = jest
|
||||
.fn()
|
||||
.mockImplementation((eventName, callbackFunction) => {
|
||||
if (eventName === 'change') {
|
||||
changeEventCallbackFunction = callbackFunction;
|
||||
}
|
||||
});
|
||||
|
||||
const { wrapper } = setupMocks({
|
||||
querySelectorFunction(query) {
|
||||
if (query === '.pac-container .pac-item') {
|
||||
const element = document.createElement('div');
|
||||
element.textContent = '123 Test Street';
|
||||
return element;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
let noMatchAlert = wrapper.findComponent({ ref: 'alertNoMatchWarning' });
|
||||
let verificationAlert = wrapper.findComponent({ ref: 'alertVerificationWarning' });
|
||||
expect(noMatchAlert.exists()).toBeFalsy();
|
||||
expect(verificationAlert.exists()).toBeFalsy();
|
||||
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
// Act
|
||||
changeEventCallbackFunction();
|
||||
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
// Assert
|
||||
verificationAlert = wrapper.findComponent({ ref: 'alertVerificationWarning' });
|
||||
expect(wrapper.vm.displayVerificationWarning).toBeTruthy();
|
||||
expect(verificationAlert.exists()).toBeTruthy();
|
||||
expect(verificationAlert.isVisible()).toBeTruthy();
|
||||
noMatchAlert = wrapper.findComponent({ ref: 'alertNoMatchWarning' });
|
||||
expect(wrapper.vm.displayNoMatchWarning).toBeFalsy();
|
||||
expect(noMatchAlert.exists()).toBeFalsy();
|
||||
});
|
||||
|
||||
describe('noMatch alert is cleared on address change', () => {
|
||||
test('user sees noMatch warning and modifies street address => noMatch warning is removed', async () => {
|
||||
// Arrange
|
||||
const { wrapper } = setupMocks({});
|
||||
|
||||
await wrapper.setData({
|
||||
matchFound: false
|
||||
});
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
let noMatchAlert = wrapper.findComponent({ ref: 'alertNoMatchWarning' });
|
||||
expect(noMatchAlert.exists()).toBeTruthy();
|
||||
expect(noMatchAlert.isVisible()).toBeTruthy();
|
||||
|
||||
// // Act
|
||||
wrapper.vm.$options.watch.addressModel.handler.call(wrapper.vm, {
|
||||
streetAddress: 'LS'
|
||||
});
|
||||
|
||||
// Assert
|
||||
wrapper.vm.$nextTick(() => {
|
||||
expect(wrapper.vm.displayNoMatchWarning).toBeFalsy();
|
||||
|
||||
noMatchAlert = wrapper.findComponent({ ref: 'alertNoMatchWarning' });
|
||||
expect(noMatchAlert.exists()).toBeFalsy();
|
||||
});
|
||||
});
|
||||
|
||||
test('user sees noMatch warning and enters city => noMatch warning is removed', async () => {
|
||||
// Arrange
|
||||
const { wrapper } = setupMocks({});
|
||||
|
||||
await wrapper.setData({
|
||||
matchFound: false
|
||||
});
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
let noMatchAlert = wrapper.findComponent({ ref: 'alertNoMatchWarning' });
|
||||
expect(noMatchAlert.exists()).toBeTruthy();
|
||||
expect(noMatchAlert.isVisible()).toBeTruthy();
|
||||
|
||||
// // Act
|
||||
wrapper.vm.$options.watch.addressModel.handler.call(wrapper.vm, {
|
||||
city: 'LS'
|
||||
});
|
||||
|
||||
// Assert
|
||||
wrapper.vm.$nextTick(() => {
|
||||
expect(wrapper.vm.displayNoMatchWarning).toBeFalsy();
|
||||
|
||||
noMatchAlert = wrapper.findComponent({ ref: 'alertNoMatchWarning' });
|
||||
expect(noMatchAlert.exists()).toBeFalsy();
|
||||
});
|
||||
});
|
||||
|
||||
test('user sees noMatch warning and enters state => noMatch warning is removed', async () => {
|
||||
// Arrange
|
||||
const { wrapper } = setupMocks({});
|
||||
|
||||
await wrapper.setData({
|
||||
matchFound: false
|
||||
});
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
let noMatchAlert = wrapper.findComponent({ ref: 'alertNoMatchWarning' });
|
||||
expect(noMatchAlert.exists()).toBeTruthy();
|
||||
expect(noMatchAlert.isVisible()).toBeTruthy();
|
||||
|
||||
// // Act
|
||||
wrapper.vm.$options.watch.addressModel.handler.call(wrapper.vm, {
|
||||
state: 'KO'
|
||||
});
|
||||
|
||||
// Assert
|
||||
wrapper.vm.$nextTick(() => {
|
||||
expect(wrapper.vm.displayNoMatchWarning).toBeFalsy();
|
||||
|
||||
noMatchAlert = wrapper.findComponent({ ref: 'alertNoMatchWarning' });
|
||||
expect(noMatchAlert.exists()).toBeFalsy();
|
||||
});
|
||||
});
|
||||
|
||||
test('user sees noMatch warning and enters zip code => noMatch warning is removed', async () => {
|
||||
// Arrange
|
||||
const { wrapper } = setupMocks({});
|
||||
|
||||
await wrapper.setData({
|
||||
matchFound: false
|
||||
});
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
let noMatchAlert = wrapper.findComponent({ ref: 'alertNoMatchWarning' });
|
||||
expect(noMatchAlert.exists()).toBeTruthy();
|
||||
expect(noMatchAlert.isVisible()).toBeTruthy();
|
||||
|
||||
// // Act
|
||||
wrapper.vm.$options.watch.addressModel.handler.call(wrapper.vm, {
|
||||
zipCode: '12345'
|
||||
});
|
||||
|
||||
// Assert
|
||||
wrapper.vm.$nextTick(() => {
|
||||
expect(wrapper.vm.displayNoMatchWarning).toBeFalsy();
|
||||
|
||||
noMatchAlert = wrapper.findComponent({ ref: 'alertNoMatchWarning' });
|
||||
expect(noMatchAlert.exists()).toBeFalsy();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,19 +1,5 @@
|
|||
<template>
|
||||
<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="col">
|
||||
<textboxQuestion
|
||||
|
|
@ -85,6 +71,20 @@
|
|||
</div>
|
||||
</div>
|
||||
</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>
|
||||
</template>
|
||||
|
||||
|
|
@ -97,7 +97,6 @@ import { defineRule } from 'vee-validate';
|
|||
import { required, regex } from '@/helpers/validation-rules';
|
||||
import errorMessages from '@/constants/error-messages';
|
||||
import states from '@/constants/states';
|
||||
import { endpoints } from '@/constants/endpoints';
|
||||
|
||||
// DEFINE VALIDATION RULES
|
||||
defineRule('street-address-required', required(errorMessages.STREET_ADDRESS_REQUIRED));
|
||||
|
|
@ -112,7 +111,7 @@ export default {
|
|||
textboxQuestion,
|
||||
dropdownQuestion,
|
||||
alert
|
||||
}, // The component emits an event
|
||||
},
|
||||
props: {
|
||||
modelValue: {
|
||||
type: Object,
|
||||
|
|
@ -125,29 +124,31 @@ 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,
|
||||
alertCopyNoMatchWarning: '',
|
||||
alertCopyVerificationWarning: '',
|
||||
alertHeadlineNoMatchWarning: '',
|
||||
alertCopyNoMatchWarning: '',
|
||||
alertHeadlineVerificationWarning: '',
|
||||
displayVerificationWarning: false,
|
||||
displayNoMatchWarning: false,
|
||||
enterPressed: false,
|
||||
matchingIndirectly: false,
|
||||
matchFound: null, // null = no attempted match, true = match was found, false = match was not found
|
||||
enterPressed: false,
|
||||
isAddressWatchActive: false, // Only deep watch the address model when a match was not found
|
||||
showAllFields: false
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
stateOptions: {
|
||||
addressField1: {
|
||||
get() {
|
||||
return states;
|
||||
return document.getElementById('autocomplete');
|
||||
}
|
||||
},
|
||||
addressModel: {
|
||||
|
|
@ -157,208 +158,180 @@ export default {
|
|||
set(newValue) {
|
||||
this.$emit('update:modelValue', newValue);
|
||||
}
|
||||
},
|
||||
stateOptions: {
|
||||
get() {
|
||||
return states;
|
||||
}
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
matchFound: {
|
||||
handler(newValue) {
|
||||
this.displayNoMatchWarning = !newValue;
|
||||
if (!newValue) {
|
||||
this.displayNoMatchWarning = true;
|
||||
|
||||
this.addressModel.city = '';
|
||||
this.addressModel.state = '';
|
||||
this.addressModel.zipCode = '';
|
||||
this.displayVerificationWarning = false;
|
||||
|
||||
this.$nextTick(() => {
|
||||
// Only deep watch the Address Model after a failed match
|
||||
this.isAddressWatchActive = true;
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
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');
|
||||
initializeAutocomplete() {
|
||||
// Initialize the Google Places Autocomplete
|
||||
this.autocomplete = new window.google.maps.places.Autocomplete(document.getElementById('autocomplete'), {
|
||||
componentRestrictions: { country: ['us'] },
|
||||
fields: ['address_components'],
|
||||
types: ['geocode']
|
||||
});
|
||||
|
||||
// Set up the Autocomplete place_changed event to call our method to fill in the address
|
||||
this.autocomplete.addListener('place_changed', this.onPlaceChanged);
|
||||
|
||||
// Set up the pressing tab inside address1 field (enter's are caught by Google Autocomplete)
|
||||
this.addressField1.addEventListener('keydown', (e) => {
|
||||
if (this.addressField1.value?.length > 0 && e.code === 'Tab') {
|
||||
this.fillInAddressUsingFirstItem();
|
||||
}
|
||||
});
|
||||
},
|
||||
onPlaceChanged() {
|
||||
const place = this.autocomplete.getPlace();
|
||||
if (place && place.address_components) {
|
||||
this.matchingIndirectly = false;
|
||||
this.fillInAddress(place);
|
||||
} else {
|
||||
this.fillInAddressUsingFirstItem();
|
||||
}
|
||||
},
|
||||
fillInAddress(googlePlace) {
|
||||
this.matchFound = true;
|
||||
|
||||
const self = this;
|
||||
this.$nextTick(() => {
|
||||
this.showAllFields = true;
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
for (const component of googlePlace.address_components) {
|
||||
const componentType = component.types[0];
|
||||
|
||||
const url = endpoints.GooglePlaces.url(applicationConfig.GOOGLE_PLACES_API_KEY);
|
||||
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:
|
||||
}
|
||||
}
|
||||
|
||||
this.$loadScript(url)
|
||||
.then(() => {
|
||||
// Script is loaded, initialize the autocomplete textbox
|
||||
const autocomplete = new window.google.maps.places.Autocomplete(addressField1, {
|
||||
// After filling in the address fields, disable the address autocomplete
|
||||
this.unloadAutocomplete();
|
||||
// Restore focus to the first address field
|
||||
this.addressField1.focus();
|
||||
|
||||
self.displayVerificationWarning = self.matchingIndirectly;
|
||||
});
|
||||
},
|
||||
fillInAddressUsingFirstItem() {
|
||||
const addressValue = this.addressField1.value;
|
||||
if (addressValue && addressValue.length > 0) {
|
||||
// Get Autocomplete Service
|
||||
const acService = new window.google.maps.places.AutocompleteService();
|
||||
// Get Places Service, needs psuedo element (or a map)
|
||||
const placeService = new window.google.maps.places.PlacesService(document.createElement('div'));
|
||||
// Create Autocomplete Session token, multiple requests one pricing hit
|
||||
const acSessionToken = new window.google.maps.places.AutocompleteSessionToken();
|
||||
|
||||
acService.getPlacePredictions(
|
||||
{
|
||||
input: addressValue,
|
||||
type: ['geocode'],
|
||||
componentRestrictions: { country: ['us'] },
|
||||
fields: ['address_components'],
|
||||
types: ['geocode']
|
||||
});
|
||||
|
||||
// Standard place_changed event handling
|
||||
const autocompleteListener = window.google.maps.event.addListener(
|
||||
autocomplete,
|
||||
'place_changed',
|
||||
fillInAddress
|
||||
);
|
||||
|
||||
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');
|
||||
|
||||
// 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);
|
||||
}
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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(
|
||||
sessionToken: acSessionToken
|
||||
},
|
||||
(predictions) => {
|
||||
if (predictions && predictions.length > 0) {
|
||||
const firstPrediction = predictions[0];
|
||||
if (firstPrediction.place_id) {
|
||||
placeService.getDetails(
|
||||
{
|
||||
address: firstResult
|
||||
placeId: firstPrediction.place_id,
|
||||
fields: ['address_components'],
|
||||
sessionToken: acSessionToken
|
||||
},
|
||||
(results, status) => {
|
||||
if (status === window.google.maps.GeocoderStatus.OK) {
|
||||
fillInAddress(results[0]);
|
||||
}
|
||||
(details) => {
|
||||
this.matchingIndirectly = true;
|
||||
this.fillInAddress(details);
|
||||
}
|
||||
);
|
||||
} else {
|
||||
// No addresses found for the input
|
||||
self.matchFound = false;
|
||||
// No place_id found for the prediction
|
||||
this.matchFound = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
*
|
||||
* @param place
|
||||
*/
|
||||
function fillInAddress(place) {
|
||||
if (!place) {
|
||||
place = autocomplete.getPlace();
|
||||
}
|
||||
|
||||
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];
|
||||
|
||||
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 {
|
||||
self.displayVerificationWarning = true;
|
||||
// No prediction 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.autocomplete) {
|
||||
window.google.maps.event.clearInstanceListeners(this.autocomplete);
|
||||
this.autocomplete = null;
|
||||
|
||||
const pacContainer = document.querySelector('.pac-container');
|
||||
if (pacContainer) {
|
||||
pacContainer.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
#streetAddressField {
|
||||
position: relative;
|
||||
|
||||
:deep(.pac-container) {
|
||||
top: 76px !important; // Height of #streetAddressField
|
||||
left: 0 !important;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
|
|
|||
|
|
@ -50,7 +50,7 @@
|
|||
v-model="internalModel.addressQuestions"
|
||||
captureApartmentNumberOrBusinessName="true"
|
||||
preserveCityAndStateOnReset="true"
|
||||
includeStreetAddress2="true" />
|
||||
:includeStreetAddress2="true" />
|
||||
<vehicleProtectedQuestion
|
||||
ref="vehicleProtectedQuestion"
|
||||
v-model="internalModel.isVehicleProtected"
|
||||
|
|
|
|||
|
|
@ -51,6 +51,10 @@ body {
|
|||
overflow: hidden;
|
||||
}
|
||||
|
||||
.pac-container {
|
||||
z-index: 10000 !important;
|
||||
}
|
||||
|
||||
.page-container-grouped-styles {
|
||||
@extend .container-fluid, .shadow, .p-0, .position-relative, .make-tall;
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue