Commit 54833500 authored by Clément's avatar Clément

bugfix: observe bind-user attribute

parent 024021d1
Pipeline #3890 passed with stage
in 53 seconds
......@@ -29,7 +29,7 @@ class SIBAuth extends HTMLElement {
this.install();
this.processState();
if (this.getUser()) {
this.dispatchUserInfo(this.getUser());
this.dispatchUserInfo();
}
}
......@@ -52,6 +52,28 @@ class SIBAuth extends HTMLElement {
SIBBase.prototype.login = () => this.login();
SIBBase.prototype.logout = () => this.logout();
SIBBase.prototype.getUser = () => this.getUser();
this.bindUserObserver = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === 'attributes') {
if (!mutation.target.hasAttribute('bind-user')) return;
this.applyUser(mutation.target);
return;
}
mutation.addedNodes.forEach((node) => {
if (!(node instanceof Element)) return;
if (!node.hasAttribute('bind-user')) return;
this.applyUser(node);
});
});
});
this.bindUserObserver.observe(document.body, {
childList: true,
attributes: true,
characterData: false,
subtree: true,
attributeOldValue: false,
attributeFilter: ['bind-user'],
});
}
/** @function
......@@ -63,6 +85,7 @@ class SIBAuth extends HTMLElement {
SIBBase.prototype.login = null;
SIBBase.prototype.logout = null;
SIBBase.prototype.getUser = null;
this.bindUserObserver.disconnect();
}
/** @function
......@@ -176,17 +199,13 @@ class SIBAuth extends HTMLElement {
/** @function
* @name dispatchUserInfo
* @param {User} user - User
* Try to replace data-src by user iri on [bind-user] elements
*/
// eslint-disable-next-line class-methods-use-this
async dispatchUserInfo(user) {
async dispatchUserInfo() {
const processDOM = async () => {
const id = user.profile.website;
const elements = document.querySelectorAll(`[bind-user]:not([data-src="${id}"])`);
elements.forEach((element) => {
element.setAttribute('data-src', id);
});
const elements = document.querySelectorAll('[bind-user]');
elements.forEach(element => this.applyUser(element));
};
// check document state and add a hook on DOMContentLoaded if needed
if (document.readyState === 'loading') {
......@@ -196,6 +215,18 @@ class SIBAuth extends HTMLElement {
}
}
/** @function
* @name applyUser
* @param {Element} element
*/
applyUser(element) {
const user = this.getUser();
if (user == null) return;
const id = user.profile.website;
if (element.getAttribute(id === 'data-src')) return;
element.setAttribute('data-src', id);
}
/** @function
* @name getUser
* Return User or undefined
......@@ -224,7 +255,7 @@ class SIBAuth extends HTMLElement {
setUser(user) {
localStorage.setItem('oidc_user', JSON.stringify(user));
this.user = user;
this.dispatchUserInfo(user);
this.dispatchUserInfo();
}
/** @function
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment