-
Notifications
You must be signed in to change notification settings - Fork 57
/
sylius-address-book.js
74 lines (60 loc) · 2.43 KB
/
sylius-address-book.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* eslint-env browser */
const parseKey = function parseKey(key) {
return key.replace(/(_\w)/g, words => words[1].toUpperCase());
};
const SyliusAddressBook = function SyliusAddressBook(el) {
const element = el;
const select = element.querySelector('.dropdown');
const findByName = function findByName(name) {
return element.querySelector(`[name*=${parseKey(name)}]`);
};
const changeEvent = new Event('change');
select.querySelectorAll('.dropdown-item').forEach((item) => {
item.addEventListener('click', (e) => {
const choice = e.currentTarget;
const choiceData = {};
[...choice.attributes].forEach((attr) => {
if (attr.name.startsWith('data-')) {
const camelCased = attr.name.replace('data-', '').replace(/-([a-z])/g, g => g[1].toUpperCase());
choiceData[camelCased] = attr.value;
}
});
const { provinceCode, provinceName } = choiceData;
const provinceContainer = select.closest('[data-js-address-book]').querySelector('.province-container');
element.querySelectorAll('input, select').forEach((input) => {
input.value = '';
});
Object.entries(choiceData).forEach(([property, value]) => {
const field = findByName(property);
if (property.indexOf('countryCode') !== -1) {
field.value = value;
field.dispatchEvent(changeEvent);
const exists = setInterval(() => {
const provinceCodeField = findByName('provinceCode');
const provinceNameField = findByName('provinceName');
if (!provinceContainer.hasAttribute('data-loading')) {
if (provinceCodeField && provinceCodeField.length !== 0 && (provinceCode !== '' || provinceCode != undefined)) {
provinceCodeField.value = provinceCode;
clearInterval(exists);
} else if (provinceNameField && provinceNameField.length !== 0 && (provinceName !== '' || provinceName != undefined)) {
provinceNameField.value = provinceName;
clearInterval(exists);
}
}
}, 100);
} else if (field) {
field.value = value;
}
});
});
});
};
export default SyliusAddressBook;