@geogirafe/lib-geoportal
Version:
GeoGirafe is a flexible application to build online geoportals.
67 lines (66 loc) • 2.8 kB
JavaScript
// SPDX-License-Identifier: Apache-2.0
import GirafeSingleton from '../../base/GirafeSingleton.js';
const HTML_TEMPLATE = '<girafe-feedback-button question="${question}" component-name="${component-name}" margins="${margins}" placement="${placement}"></girafe-feedback-button>';
export var FeedbackResult;
(function (FeedbackResult) {
FeedbackResult["POSITIVE"] = "positive";
FeedbackResult["NEGATIVE"] = "negative";
FeedbackResult["NEUTRAL"] = "neutral";
})(FeedbackResult || (FeedbackResult = {}));
class FeedbackManager extends GirafeSingleton {
get config() {
return this.context.configManager.Config;
}
STORAGE_PATH = 'alreadyGaveFeedbackFor';
gaveFeedbackFor = {};
async initializeSingleton() {
await super.initializeSingleton();
this.gaveFeedbackFor =
(await this.context.userDataManager.getUserData(this.STORAGE_PATH)) || {};
this.initializeFeedbackOnComponents();
}
async giveFeedback(componentName, feedbackResult) {
const url = this.config.feedback?.url;
if (!url) {
console.error('Feedback URL is not defined in the configuration.');
return;
}
try {
const response = await fetch(url, {
method: this.config.feedback?.method || 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
componentName: componentName,
result: feedbackResult
})
});
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
const result = await response.json();
console.log('Success:', result);
this.gaveFeedbackFor[componentName] = true;
await this.context.userDataManager.saveUserData(this.STORAGE_PATH, this.gaveFeedbackFor);
}
catch (error) {
console.error('Error:', error);
}
}
initializeFeedbackOnComponents() {
this.config.feedback?.components?.forEach((component) => {
// Do nothing if a feedback was already given
if (this.gaveFeedbackFor[component.name]) {
return;
}
this.context.componentManager.registerComponentCallback(component.name, (girafeHTMLElement) => {
girafeHTMLElement.insertFeedbackTemplate(HTML_TEMPLATE.replace('${component-name}', component.name)
.replace('${question}', component.question)
.replace('${placement}', component.placement)
.replace('${margins}', component.margins ?? ''));
});
});
}
}
export default FeedbackManager;