<a class="c-login o-link-covert js-customizedUI" href="#" data-href="/assets/json/login.json">
<span class="o-css-icon o-css-icon--user"></span>
Anmelden
</a>
<a class="c-login o-link-covert js-customizedUI" href="#" data-href="{{ url }}">
<span class="o-css-icon o-css-icon--user"></span>
{{ label }}
</a>
{
"label": "Anmelden",
"url": "/assets/json/login.json"
}
/**
* @desc Renders the users name into the profile link when applicable
* @author Tibor Legat, HDNET GmbH & Co. KG
* @see HAZ-463
* @since 31.08.2020
*/
class CustomizedLogin {
constructor(loginItems) {
this.items = loginItems;
this.init(loginItems);
}
/**
* Replaces the current text node with the user name.
* @param {String} name
*/
updateTitle(name) {
if (!name) return;
this.items.forEach((item) => {
const nameNode = document.createTextNode(name);
if (item.lastChild.nodeType === Node.TEXT_NODE) {
item.removeChild(item.lastChild);
}
item.appendChild(nameNode);
});
}
updateHref(url) {
if (!url) return;
this.items.forEach((item) => {
item.setAttribute('href', url);
});
console.log('update href', url);
}
/**
* @desc Get JSON data, update profile link on success.
* Uses data-href for local development only.
*/
init() {
const activeText = 'Mein Konto';
const inactiveText = 'Anmelden';
const localStorageVar = 'login';
const activeLink = '/leser-service/mein-konto.html';
const inactiveLink = '/connect/xpresso';
// get data from localstorage to speed things up
if (localStorage[localStorageVar]) {
this.updateTitle(activeText);
}
// Initialize login state
function isLoggedIn(url) {
// Now, check if login is (still) valid and update text accordingly
return new Promise(((resolve) => {
window.fetch(url)
.then((data) => data.json())
.then((jsonData) => {
if (jsonData.loggedIn) {
window.dataLayer = window.dataLayer || [];
window.dataLayer.push(jsonData);
}
return jsonData;
})
.then((jsonData) => resolve(jsonData.loggedIn || false))
.catch((e) => {
console.error(e);
resolve(false);
// reject(new Error(e));
});
}));
}
// Now, check if login is (still) valid and update text accordingly
// Take for granted that we have the same href for all instances, so get first only.
const getLoginState = isLoggedIn(this.items[0].getAttribute('data-href') || '/user.json');
console.log('login: getLoginState', getLoginState);
getLoginState.then((loggedIn) => {
console.log('update title', loggedIn, activeText);
this.updateTitle(loggedIn ? activeText : inactiveText);
this.updateHref(loggedIn ? activeLink : inactiveLink);
});
}
}
export default CustomizedLogin;
.c-login {
display: block;
font-size: rem-calc(18);
font-weight: 500;
line-height: 2;
padding-left: 20px;
position: relative;
}
There are no notes for this item.