@magicfeedback/native 2.1.2-beta.5 → 2.1.2-beta.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1 +1,256 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.magicfeedback=t():e.magicfeedback=t()}(self,(()=>{return e={945:function(e,t){var i="undefined"!=typeof self?self:this,n=function(){function e(){this.fetch=!1,this.DOMException=i.DOMException}return e.prototype=i,new e}();!function(e){!function(t){var i="URLSearchParams"in e,n="Symbol"in e&&"iterator"in Symbol,a="FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),s="FormData"in e,r="ArrayBuffer"in e;if(r)var o=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],l=ArrayBuffer.isView||function(e){return e&&o.indexOf(Object.prototype.toString.call(e))>-1};function d(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function c(e){return"string"!=typeof e&&(e=String(e)),e}function u(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return n&&(t[Symbol.iterator]=function(){return t}),t}function p(e){this.map={},e instanceof p?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function h(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function m(e){return new Promise((function(t,i){e.onload=function(){t(e.result)},e.onerror=function(){i(e.error)}}))}function f(e){var t=new FileReader,i=m(t);return t.readAsArrayBuffer(e),i}function g(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function v(){return this.bodyUsed=!1,this._initBody=function(e){var t;this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:a&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:s&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:i&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():r&&a&&(t=e)&&DataView.prototype.isPrototypeOf(t)?(this._bodyArrayBuffer=g(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):r&&(ArrayBuffer.prototype.isPrototypeOf(e)||l(e))?this._bodyArrayBuffer=g(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):i&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},a&&(this.blob=function(){var e=h(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?h(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(f)}),this.text=function(){var e,t,i,n=h(this);if(n)return n;if(this._bodyBlob)return e=this._bodyBlob,i=m(t=new FileReader),t.readAsText(e),i;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),i=new Array(t.length),n=0;n<t.length;n++)i[n]=String.fromCharCode(t[n]);return i.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},s&&(this.formData=function(){return this.text().then(b)}),this.json=function(){return this.text().then(JSON.parse)},this}p.prototype.append=function(e,t){e=d(e),t=c(t);var i=this.map[e];this.map[e]=i?i+", "+t:t},p.prototype.delete=function(e){delete this.map[d(e)]},p.prototype.get=function(e){return e=d(e),this.has(e)?this.map[e]:null},p.prototype.has=function(e){return this.map.hasOwnProperty(d(e))},p.prototype.set=function(e,t){this.map[d(e)]=c(t)},p.prototype.forEach=function(e,t){for(var i in this.map)this.map.hasOwnProperty(i)&&e.call(t,this.map[i],i,this)},p.prototype.keys=function(){var e=[];return this.forEach((function(t,i){e.push(i)})),u(e)},p.prototype.values=function(){var e=[];return this.forEach((function(t){e.push(t)})),u(e)},p.prototype.entries=function(){var e=[];return this.forEach((function(t,i){e.push([i,t])})),u(e)},n&&(p.prototype[Symbol.iterator]=p.prototype.entries);var y=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function E(e,t){var i,n,a=(t=t||{}).body;if(e instanceof E){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new p(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,a||null==e._bodyInit||(a=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"same-origin",!t.headers&&this.headers||(this.headers=new p(t.headers)),this.method=(n=(i=t.method||this.method||"GET").toUpperCase(),y.indexOf(n)>-1?n:i),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&a)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(a)}function b(e){var t=new FormData;return e.trim().split("&").forEach((function(e){if(e){var i=e.split("="),n=i.shift().replace(/\+/g," "),a=i.join("=").replace(/\+/g," ");t.append(decodeURIComponent(n),decodeURIComponent(a))}})),t}function A(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new p(t.headers),this.url=t.url||"",this._initBody(e)}E.prototype.clone=function(){return new E(this,{body:this._bodyInit})},v.call(E.prototype),v.call(A.prototype),A.prototype.clone=function(){return new A(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new p(this.headers),url:this.url})},A.error=function(){var e=new A(null,{status:0,statusText:""});return e.type="error",e};var k=[301,302,303,307,308];A.redirect=function(e,t){if(-1===k.indexOf(t))throw new RangeError("Invalid status code");return new A(null,{status:t,headers:{location:e}})},t.DOMException=e.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var i=Error(e);this.stack=i.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function C(e,i){return new Promise((function(n,s){var r=new E(e,i);if(r.signal&&r.signal.aborted)return s(new t.DOMException("Aborted","AbortError"));var o=new XMLHttpRequest;function l(){o.abort()}o.onload=function(){var e,t,i={status:o.status,statusText:o.statusText,headers:(e=o.getAllResponseHeaders()||"",t=new p,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(e){var i=e.split(":"),n=i.shift().trim();if(n){var a=i.join(":").trim();t.append(n,a)}})),t)};i.url="responseURL"in o?o.responseURL:i.headers.get("X-Request-URL");var a="response"in o?o.response:o.responseText;n(new A(a,i))},o.onerror=function(){s(new TypeError("Network request failed"))},o.ontimeout=function(){s(new TypeError("Network request failed"))},o.onabort=function(){s(new t.DOMException("Aborted","AbortError"))},o.open(r.method,r.url,!0),"include"===r.credentials?o.withCredentials=!0:"omit"===r.credentials&&(o.withCredentials=!1),"responseType"in o&&a&&(o.responseType="blob"),r.headers.forEach((function(e,t){o.setRequestHeader(t,e)})),r.signal&&(r.signal.addEventListener("abort",l),o.onreadystatechange=function(){4===o.readyState&&r.signal.removeEventListener("abort",l)}),o.send(void 0===r._bodyInit?null:r._bodyInit)}))}C.polyfill=!0,e.fetch||(e.fetch=C,e.Headers=p,e.Request=E,e.Response=A),t.Headers=p,t.Request=E,t.Response=A,t.fetch=C,Object.defineProperty(t,"__esModule",{value:!0})}({})}(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var a=n;(t=a.fetch).default=a.fetch,t.fetch=a.fetch,t.Headers=a.Headers,t.Request=a.Request,t.Response=a.Response,e.exports=t},317:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.HOST_API_URL_DEV=t.HOST_API_URL=void 0,t.HOST_API_URL="https://api.deepdots.com/",t.HOST_API_URL_DEV="https://api-dev.deepdots.com/"},156:function(e,t,i){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const a=n(i(927));let s=null;s||(s=(0,a.default)()),t.default=s},927:function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(a,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,o)}l((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0});const a=i(57),s=i(665),r=i(256),o=i(313),l=i(317);t.default=function(){const e=new s.Config;let t;return{init:function(i){(null==i?void 0:i.debug)&&e.set("debug",null==i?void 0:i.debug),e.set("url",(null==i?void 0:i.env)&&"dev"===(null==i?void 0:i.env)?l.HOST_API_URL_DEV:l.HOST_API_URL),e.set("env",null==i?void 0:i.env),t=new r.Log(e),t.log("Initialized Magicfeedback",e)},send:function(i,a,s,r=!0,l,d){return n(this,void 0,void 0,(function*(){i||t.err("No appID provided"),a||t.err("No publicKey provided"),s||t.err("No feedback provided"),s.answers||s.profile||s.metrics||s.metadata||t.err("No feedback data provided");const n=e.get("url"),c={integration:i,publicKey:a,privateKey:d,completed:r,id:l,feedback:s};try{const e=yield(0,o.sendFeedback)(n,c,t);return t.log("sent native feedback"),e}catch(e){return t.err("error native feedback",e),!1}}))},form:function(i,n){return i||t.err("No appID provided"),n||t.err("No publicKey provided"),new a.Form(e,i,n)},session:function(i){return i||t.err("No sessionId provided"),new a.Form(e,i)}}}},79:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.History=void 0,t.History=class{constructor(){this.items=[]}enqueue(e){this.items.push(e)}dequeue(){return this.items.shift()}rollback(){return this.items.pop()}front(){return this.items[0]}back(){return this.items[this.items.length-1]}isEmpty(){return 0===this.items.length}size(){return this.items.length}get(e){return this.items[e]}}},665:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Config=void 0,t.Config=class{constructor(){this.variables={},this.variables.env="prod",this.variables.debug=!1}get(e){return this.variables[e]}set(e,t){this.variables[e]=t}}},57:function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(a,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,o)}l((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.Form=void 0;const a=i(558),s=i(256),r=i(313),o=i(213),l=i(217),d=i(700),c=i(591),u=i(79),p=i(636);t.Form=class{constructor(e,t,i){this.config=e,this.log=new s.Log(e),this.formOptionsConfig={addButton:!0,sendButtonText:"Send",backButtonText:"Back",nextButtonText:"Next",addSuccessScreen:!0,getMetaData:!0,questionFormat:"standard"},this.selector="",this.appId=t,this.publicKey=i||"",this.url=e.get("url"),this.id="",this.formData=null,this.feedback={text:"",answers:[],profile:[],metrics:[],metadata:[]},this.history=new u.History,this.graph=new l.PageGraph([]),this.progress=0,this.total=0,this.completed=!1,this.timeToCompleted=0}generate(e,t){var i,a,s,o,l,d,c;return n(this,void 0,void 0,(function*(){try{this.formOptionsConfig=Object.assign(Object.assign({},this.formOptionsConfig),t),this.selector=e;let n=this.formData;if(void 0!==this.formData&&this.formData||(n=""!==this.publicKey?yield(0,r.getForm)(this.url,this.appId,this.publicKey,this.log):yield(0,r.getSessionForm)(this.url,this.appId,this.log)),void 0===n||!n)throw new Error(`No data for app ${this.appId}`);if(null===(i=n.error)||void 0===i?void 0:i.message)throw new Error(n.error.message);if(n.questions=(null===(a=n.questions)||void 0===a?void 0:a.filter((e=>"ACTIVE"===e.status)))||[],n.pages=(null===(s=n.pages)||void 0===s?void 0:s.filter((e=>"ACTIVE"===e.status)))||[],null===(o=n.pages)||void 0===o||o.forEach((e=>{var t;return e.integrationQuestions=null===(t=e.integrationQuestions)||void 0===t?void 0:t.filter((e=>"ACTIVE"===e.status))})),this.formData=n,this.formData.savedAt||(this.formData.savedAt=new Date,localStorage.setItem(`magicfeedback-${this.appId}`,JSON.stringify(this.formData))),void 0===this.formData.questions||!this.formData.questions)throw new Error(`No questions for app ${this.appId}`);this.formData.pages&&0!==(null===(l=this.formData.pages)||void 0===l?void 0:l.length)||this.formatPages(),null===(d=this.formData.questions)||void 0===d||d.sort(((e,t)=>e.position-t.position)),this.formData.pages=this.formData.pages.filter((e=>{var t;return(null===(t=e.integrationQuestions)||void 0===t?void 0:t.length)>0})),this.formOptionsConfig.getMetaData&&this.getMetaData(),(null===(c=this.formData.style)||void 0===c?void 0:c.startMessage)?yield this.generateWelcomeMessage(this.formData.style.startMessage):this.startForm()}catch(e){return this.log.err(e),void(this.formOptionsConfig.onLoadedEvent&&(yield this.formOptionsConfig.onLoadedEvent({loading:!1,error:e})))}}))}formatPages(){var e;if(this.formData)switch(this.formData.identity){case"MAGICSURVEY":this.formData.pages=[],null===(e=this.formData.questions)||void 0===e||e.forEach((e=>{var t,i;const n=new c.PageRoute(e.id,e.ref,c.OperatorType.NOEQUAL,[],c.TransitionType.PAGE,(e.position+1).toString(),e.position.toString()),a=new d.Page(e.position.toString(),e.position,this.appId,[e],[n]);null===(i=null===(t=this.formData)||void 0===t?void 0:t.pages)||void 0===i||i.push(a)}));break;case"MAGICFORM":const t=new d.Page("1",1,this.appId,this.formData.questions,[]);this.formData.pages=[t]}}generateContainer(){let e=document.getElementById(this.selector);if(!e&&(e=document.getElementById("magicfeedback-container-"+this.appId),!e))throw new Error(`Element with ID '${this.selector}' not found.`);return e.classList.add("magicfeedback-container"),e.id="magicfeedback-container-"+this.appId,e.innerHTML="",e}generateForm(){var e,t,i,a;return n(this,void 0,void 0,(function*(){try{if(console.log("Generating form for appId:",this.appId),!this.formData||!this.formData.pages||0===this.formData.pages.length)throw new Error("No form data");this.graph=new l.PageGraph(this.formData.pages.sort(((e,t)=>e.position-t.position)));let n=this.generateContainer();const s=document.createElement("form");s.classList.add("magicfeedback-form"),s.id="magicfeedback-"+this.appId,s.addEventListener("submit",(e=>e.preventDefault()));const r=document.createElement("div");r.classList.add("magicfeedback-questions"),r.id="magicfeedback-questions-"+this.appId;const d=this.graph.getFirstPage();if(!d)throw new Error("No page found");if(this.total=this.graph.findMaxDepth(),d.elements=(0,o.renderQuestions)(d.questions,this.formOptionsConfig.questionFormat,null===(e=this.formData)||void 0===e?void 0:e.lang[0],null===(t=this.formData)||void 0===t?void 0:t.product,(()=>this.send())),null===(i=d.elements)||void 0===i||i.forEach((e=>r.appendChild(e))),s.appendChild(r),this.history.enqueue(d),n.appendChild(s),this.progress=this.total-this.graph.findMaxDepth(d),this.formOptionsConfig.addButton){const e=(0,o.renderActions)(null===(a=this.formData)||void 0===a?void 0:a.identity,(()=>this.back()),this.formOptionsConfig.sendButtonText,this.formOptionsConfig.backButtonText,this.formOptionsConfig.nextButtonText);s.appendChild(e)}this.formOptionsConfig.addButton&&s.addEventListener("submit",(e=>{e.preventDefault(),this.send()})),this.timeToCompleted=(new Date).getTime()/1e3,this.formOptionsConfig.onLoadedEvent&&(yield this.formOptionsConfig.onLoadedEvent({loading:!1,progress:this.progress,total:this.total,formData:this.formData}))}catch(e){return this.log.err(e),void(this.formOptionsConfig.onLoadedEvent&&this.formOptionsConfig.onLoadedEvent({loading:!1,error:e}))}}))}startForm(){this.generateForm()}generateWelcomeMessage(e){return n(this,void 0,void 0,(function*(){try{const t=this.generateContainer(),i=(0,o.renderStartMessage)(e,this.formOptionsConfig.addButton,this.formOptionsConfig.startButtonText,(()=>this.startForm()));t.appendChild(i),this.formOptionsConfig.onLoadedEvent&&(yield this.formOptionsConfig.onLoadedEvent({loading:!1,formData:this.formData}))}catch(e){return this.log.err(e),void(this.formOptionsConfig.onLoadedEvent&&this.formOptionsConfig.onLoadedEvent({loading:!1,error:e}))}}))}getMetaData(){this.feedback.metadata.push({key:"navigator-url",value:[window.location.href]}),this.feedback.metadata.push({key:"navigator-origin",value:[window.location.origin]}),this.feedback.metadata.push({key:"navigator-pathname",value:[window.location.pathname]}),this.feedback.metadata.push({key:"navigator-search",value:[window.location.search]}),this.feedback.metadata.push({key:"navigator-user",value:[navigator.userAgent]}),this.feedback.metadata.push({key:"navigator-language",value:[navigator.language]}),this.feedback.metadata.push({key:"navigator-platform",value:[navigator.platform]}),this.feedback.metadata.push({key:"navigator-appVersion",value:[navigator.appVersion]}),this.feedback.metadata.push({key:"navigator-appName",value:[navigator.appName]}),this.feedback.metadata.push({key:"navigator-product",value:[navigator.product]}),this.feedback.metadata.push({key:"screen-width",value:[window.screen.width.toString()]}),this.feedback.metadata.push({key:"screen-height",value:[window.screen.height.toString()]}),this.appId&&""===this.publicKey&&this.feedback.metadata.push({key:"MAGICFEEDBACK_SESSION",value:[this.appId]})}send(e,t,i){return n(this,void 0,void 0,(function*(){const n=document.getElementById("magicfeedback-questions-"+this.appId);try{i&&(this.feedback.profile=[...this.feedback.profile,...i]),t&&(this.feedback.metrics=[...this.feedback.metrics,...t]),e&&(this.feedback.metadata=[...this.feedback.metadata,...e]),this.answer(),this.formOptionsConfig.beforeSubmitEvent&&(yield this.formOptionsConfig.beforeSubmitEvent({loading:!0,progress:this.progress,total:this.total}));const s=this.history.back();if(!s)throw new Error("No page found");for(const e of s.questions.filter((e=>e.require&&![a.FEEDBACKAPPANSWERTYPE.CONSENT,a.FEEDBACKAPPANSWERTYPE.INFO_PAGE].includes(e.type)))){const t=e.assets,i=this.feedback.answers.filter((t=>t.key.includes(e.ref)&&!t.key.includes("extra-option")));if(0===i.length||i.find((e=>0===e.value.length)))throw this.log.err(`The question ${e.ref} is required`),new Error("No response");if(null==t?void 0:t.minOptions){let n=[];if((null==t?void 0:t.exclusiveAnswers)&&(n=null==t?void 0:t.exclusiveAnswers),!i[0].value.find((e=>n.includes(e)))&&i[0].value.length<(null==t?void 0:t.minOptions))throw this.log.err(`The question ${e.ref} requires at least ${null==t?void 0:t.minOptions} options`),new Error("No response")}}const r=yield this.pushAnswers(!1);if(!r)throw new Error("No response");this.id=r,yield this.processNextQuestion(n)}catch(e){this.log.err(`An error occurred while submitting the form ${this.appId}:`,e),this.formOptionsConfig.afterSubmitEvent&&(yield this.formOptionsConfig.afterSubmitEvent({loading:!1,progress:this.progress,total:this.total,error:e}))}}))}answer(){const e=document.getElementById("magicfeedback-"+this.appId);if(!e)return this.log.err(`Form "${e}" not found.`),void(this.feedback.answers=[]);const t=this.history.back();if(!t)throw new Error("No page found");const i=[];let n=!1;if(e.querySelectorAll(".magicfeedback-input").forEach((e=>{const s=t.questions.find((t=>{var i;return null===(i=e.name)||void 0===i?void 0:i.includes(t.ref)})),o=e.type,l=e.classList[0],d={key:e.name,value:[]},c="magicfeedback-consent"===l?e.checked.toString():e.value;if(d.key&&""!==d.key){switch(null==s?void 0:s.type){case a.FEEDBACKAPPANSWERTYPE.EMAIL:case a.FEEDBACKAPPANSWERTYPE.TEXT:case a.FEEDBACKAPPANSWERTYPE.LONGTEXT:case a.FEEDBACKAPPANSWERTYPE.NUMBER:case a.FEEDBACKAPPANSWERTYPE.DATE:case a.FEEDBACKAPPANSWERTYPE.CONTACT:if(""!==c){if("email"===o){if(!(0,r.validateEmail)(c)){this.log.err("Invalid email"),n=!0;break}this.feedback.profile.push({key:"email",value:[c]})}d.value.push(c)}break;case a.FEEDBACKAPPANSWERTYPE.CONSENT:d.value.push(String(e.checked));break;case a.FEEDBACKAPPANSWERTYPE.POINT_SYSTEM:const t=e.id;d.value.push(`${t}:${c}%`);break;case a.FEEDBACKAPPANSWERTYPE.MULTIPLECHOICE:case a.FEEDBACKAPPANSWERTYPE.MULTIPLECHOISE_IMAGE:case a.FEEDBACKAPPANSWERTYPE.RATING_STAR:case a.FEEDBACKAPPANSWERTYPE.RADIO:case a.FEEDBACKAPPANSWERTYPE.RATING_EMOJI:case a.FEEDBACKAPPANSWERTYPE.RATING_NUMBER:(e.checked||e.id.includes("extra-option-"))&&d.value.push(c);break;case a.FEEDBACKAPPANSWERTYPE.SELECT:d.value.push(c);break;case a.FEEDBACKAPPANSWERTYPE.BOOLEAN:case a.FEEDBACKAPPANSWERTYPE.MULTI_QUESTION_MATRIX:e.checked&&d.value.push(c);break;case a.FEEDBACKAPPANSWERTYPE.PRIORITY_LIST:d.value.push(c)}if((null==i?void 0:i.length)>0&&(null==i?void 0:i.find((e=>e.key===d.key)))){const e=i.findIndex((e=>e.key===d.key));i[e].value=[...i[e].value,...d.value]}else i.push(d)}})),n)return this.feedback.answers=[],void t.setAnswer([]);try{t.questions.filter((e=>e.type===a.FEEDBACKAPPANSWERTYPE.MULTI_QUESTION_MATRIX)).forEach((e=>{const t=e.ref+"-",n=i.filter((e=>e.key.startsWith(t)));if(0===n.length)return;const a=n.map((e=>({key:e.key.substring(t.length),value:e.value}))),s={key:e.ref,value:[JSON.stringify(a)]};for(const e of n){const t=i.findIndex((t=>t.key===e.key));-1!==t&&i.splice(t,1)}const r=i.findIndex((t=>t.key===e.ref));-1!==r?i[r]=s:i.push(s)}))}catch(e){this.log.err("Error agrupando MULTI_QUESTION_MATRIX",e)}this.feedback.answers=i,t.setAnswer(i)}finish(){return n(this,void 0,void 0,(function*(){if(this.completed=!0,this.timeToCompleted=(new Date).getTime()-this.timeToCompleted,this.feedback.metadata.push({key:"time-to-complete",value:[this.timeToCompleted.toString()]}),this.formOptionsConfig.addSuccessScreen){const e=document.getElementById("magicfeedback-container-"+this.appId);e.childNodes.length>0&&e.removeChild(e.childNodes[0]);const t=(0,o.renderSuccess)(this.formOptionsConfig.successMessage||"Thank you for your feedback!");e.appendChild(t)}this.answer();try{const e=yield this.pushAnswers(!0);if(!e)throw this.formOptionsConfig.afterSubmitEvent&&(yield this.formOptionsConfig.afterSubmitEvent({loading:!1,progress:this.progress,total:this.total,completed:this.completed,error:`An error occurred while submitting the form ${this.appId}:`})),new Error("An error occurred while submitting the form ${this.appId}:");this.id=e,this.formOptionsConfig.afterSubmitEvent&&(yield this.formOptionsConfig.afterSubmitEvent({response:this.id,loading:!1,progress:this.progress,total:this.total,completed:this.completed,error:null}))}catch(e){this.log.err(`An error occurred while submitting the form ${this.appId}:`,e),this.formOptionsConfig.afterSubmitEvent&&(yield this.formOptionsConfig.afterSubmitEvent({loading:!1,progress:this.progress,total:this.total,completed:this.completed,error:e}))}}))}pushAnswers(e=!1){return n(this,void 0,void 0,(function*(){try{const t=this.config.get("url"),i={integration:this.appId,publicKey:this.publicKey,feedback:this.feedback,completed:e};return yield(0,r.sendFeedback)(t,this.id?Object.assign(Object.assign({},i),{sessionId:this.id}):i,this.log)}catch(e){return this.log.err(`An error occurred while submitting the form ${this.appId}:`,e),""}}))}callFollowUpQuestion(e){var t;return n(this,void 0,void 0,(function*(){if(!(null==e?void 0:e.followup))return null;try{if(0===this.feedback.answers.length)throw new Error("No answers provided");const i=this.config.get("url"),n=Object.assign(Object.assign(Object.assign({answer:null===(t=this.feedback.answers.find((t=>t.key===e.ref)))||void 0===t?void 0:t.value[0]},""!==this.publicKey&&{publicKey:this.publicKey}),""===this.publicKey&&{campaignSessionId:this.appId}),{sessionId:this.id,question:e});return yield(0,r.getFollowUpQuestion)(i,n,this.log)}catch(e){throw this.log.err(`An error occurred while submitting the form ${this.appId}:`,e),e}}))}processNextQuestion(e){var t,i,a;return n(this,void 0,void 0,(function*(){const n=this.history.back();if(!n)throw new Error("No page found");const s=n.getFollowupQuestions();if(0===(null==s?void 0:s.length))return void(yield this.renderNextQuestion(e,n));const r=[];for(const e of s){const t=n.questions.find((t=>t.ref===e));if(t){const e=yield this.callFollowUpQuestion(t);e&&r.push(e)}}if(0===r.length)return void(yield this.renderNextQuestion(e,n));const l=new d.Page(n.id,n.position,this.appId,r,n.edges),c=new p.PageNode(n.id,n.position,n.edges,l,r,!0);c.elements=(0,o.renderQuestions)(r,this.formOptionsConfig.questionFormat,null===(t=this.formData)||void 0===t?void 0:t.lang[0],null===(i=this.formData)||void 0===i?void 0:i.product,(()=>this.send())),this.history.enqueue(c),this.progress+=.5,e.innerHTML="",null===(a=c.elements)||void 0===a||a.forEach((t=>e.appendChild(t))),this.formOptionsConfig.afterSubmitEvent&&(yield this.formOptionsConfig.afterSubmitEvent({response:this.id,loading:!1,progress:this.progress,total:this.total,followup:c.isFollowup,completed:this.completed,error:null}))}))}renderNextQuestion(e,t){var i,s,r,l,d;return n(this,void 0,void 0,(function*(){let n=this.graph.getNextPage(t,this.feedback.answers);if(!n)return void this.finish();const u=n.edges.filter((e=>"PRECONDITIONAL"===e.typeCondition)).sort(((e,t)=>e.position<t.position?-1:e.position>t.position?1:0));if((null==u?void 0:u.length)>0){let t=null;const r=u.map((e=>e.questionRef));for(let e=this.history.size()-1;e>=0;e--){const n=this.history.get(e);if(n&&(t=null===(i=n.answers)||void 0===i?void 0:i.find((e=>r.includes(e.key))),t))break}let o=!u.some((e=>e.transition===c.TransitionType.ALLOW));if(t)for(const i of u){let r=!1;const l=null===(s=this.formData)||void 0===s?void 0:s.questions.find((e=>e.ref===i.questionRef)),d=Array.isArray(t.value)?t.value:[t.value],u=Array.isArray(i.value)?i.value:[i.value];if((null==l?void 0:l.type)===a.FEEDBACKAPPANSWERTYPE.MULTI_QUESTION_MATRIX)r=this.evaluateMatrixPreconditional(i,t);else switch(i.typeOperator){case"EQUAL":case"INQ":r=d.some((e=>u.includes(e)));break;case"NOEQUAL":case"NINQ":r=d.every((e=>!u.includes(e)));break;case"GREATER":r=d.some((e=>Number(e)>Number(u[0])));break;case"LESS":r=d.some((e=>Number(e)<Number(u[0])));break;case"GREATEREQUAL":r=d.some((e=>Number(e)>=Number(u[0])));break;case"LESSEQUAL":r=d.some((e=>Number(e)<=Number(u[0])))}if(r)switch(this.feedback.answers=[],i.transition){case c.TransitionType.NEXT:return void(n&&(yield this.renderNextQuestion(e,n)));case c.TransitionType.ALLOW:o=!0}}if(!o)return this.feedback.answers=[],void(n&&(yield this.renderNextQuestion(e,n)))}n.elements=(0,o.renderQuestions)(n.questions,this.formOptionsConfig.questionFormat,null===(r=this.formData)||void 0===r?void 0:r.lang[0],null===(l=this.formData)||void 0===l?void 0:l.product,(()=>this.send())),e.innerHTML="",null===(d=n.elements)||void 0===d||d.forEach((t=>e.appendChild(t))),this.history.enqueue(n),this.progress=this.total-this.graph.findMaxDepth(n),this.formOptionsConfig.afterSubmitEvent&&(yield this.formOptionsConfig.afterSubmitEvent({response:this.id,loading:!1,progress:this.progress,total:this.total,followup:n.isFollowup,completed:this.completed,error:null}))}))}back(){var e;return n(this,void 0,void 0,(function*(){if(0===this.history.size())return;const t=document.getElementById("magicfeedback-questions-"+this.appId);t&&t.childNodes.length>0&&(t.innerHTML=""),this.history.rollback();const i=this.history.back();i?(null===(e=i.elements)||void 0===e||e.forEach((e=>t.appendChild(e))),this.progress=this.total-this.graph.findMaxDepth(i)):this.progress=this.history.size(),this.formOptionsConfig.onBackEvent&&(yield this.formOptionsConfig.onBackEvent({loading:!1,progress:this.progress,followup:(null==i?void 0:i.isFollowup)||!1,error:i?null:"No page found"}))}))}previewQuestion(e,t,i){var n,a;const s=Array.isArray(t)?t:[t];if(!s||0===s.length)throw new Error("[MagicFeedback] No question provided for preview");const r=document.getElementById(e);if(!r)throw new Error(`[MagicFeedback] Element with ID '${e}' not found.`);const{format:l=this.formOptionsConfig.questionFormat||"standard",language:d=(null===(n=this.formData)||void 0===n?void 0:n.lang)&&this.formData.lang[0]||"en",product:c=(null===(a=this.formData)||void 0===a?void 0:a.product)||{customIcons:!1},clearContainer:u=!0,wrap:p=!0}=i||{};u&&(r.innerHTML="");let h=[];try{h=(0,o.renderQuestions)(s,l,d,c)}catch(e){throw this.log.err(e),e}let m=r;if(p){const e=document.createElement("div");e.classList.add("magicfeedback-preview-question"),m.appendChild(e),m=e}return h.forEach((e=>m.appendChild(e))),r}parseMatrixAnswerPre(e){if(!e||!e.value)return[];if(1===e.value.length&&"string"==typeof e.value[0]&&e.value[0].trim().startsWith("["))try{const t=JSON.parse(e.value[0]);if(Array.isArray(t))return t}catch(e){return[]}return Array.isArray(e.value)&&e.value.length>0&&"object"==typeof e.value[0]&&null!==e.value[0]&&"key"in e.value[0]?e.value:[]}evaluateMatrixPreconditional(e,t){const i=Array.isArray(e.value)?e.value:[e.value],n=new Set(e.option||[]),a=this.parseMatrixAnswerPre(t);if(!a.length)return!1;const s=n.size>0?a.filter((e=>n.has(e.key))):a;if(!s.length)return!1;switch(e.typeOperator){case"EQUAL":case"INQ":return s.some((e=>(Array.isArray(e.value)?e.value:[e.value]).some((e=>i.includes(e)))));case"NOEQUAL":case"NINQ":return s.every((e=>(Array.isArray(e.value)?e.value:[e.value]).every((e=>!i.includes(e)))));case"GREATER":return s.some((e=>(Array.isArray(e.value)?e.value:[e.value]).some((e=>i.some((t=>Number(e)>Number(t)))))));case"LESS":return s.some((e=>(Array.isArray(e.value)?e.value:[e.value]).some((e=>i.some((t=>Number(e)<Number(t)))))));case"GREATEREQUAL":return s.some((e=>(Array.isArray(e.value)?e.value:[e.value]).some((e=>i.some((t=>Number(e)>=Number(t)))))));case"LESSEQUAL":return s.some((e=>(Array.isArray(e.value)?e.value:[e.value]).some((e=>i.some((t=>Number(e)<=Number(t)))))));default:return!1}}}},700:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Page=void 0,t.Page=class{constructor(e,t,i,n,a){this.id=e,this.position=t,this.generatedAt=(new Date).toISOString(),this.updatedAt=(new Date).toISOString(),this.status="ACTIVE",this.integrationId=i,this.integrationQuestions=n,this.integrationPageRoutes=a}}},217:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PageGraph=void 0;const n=i(636),a=i(558),s=i(591);t.PageGraph=class{constructor(e){this.nodes=new Map,this.buildGraph(e)}buildGraph(e){e.forEach((e=>{var t;e.integrationPageRoutes&&(e.integrationPageRoutes=(null===(t=e.integrationPageRoutes)||void 0===t?void 0:t.sort(((e,t)=>new Date((null==e?void 0:e.generatedAt)||"").getTime()-new Date((null==t?void 0:t.generatedAt)||"").getTime()?"DIRECT"===e.typeCondition?1:-1:0)))||[]);const i=new n.PageNode(e.id,e.position,e.integrationPageRoutes||[],e,e.integrationQuestions);this.nodes.set(i.id,i)}))}getNodeById(e){return this.nodes.get(e)}getNextEdgeByDefault(e){if(!e)return;const t=e.edges.find((e=>e.typeCondition===s.ConditionType.DIRECT));if(!t||![s.TransitionType.FINISH,s.TransitionType.REDIRECT].includes(t.transition)){if(t&&t.transitionDestiny)return t.transitionDestiny;for(const t of this.nodes.values())if(t.position===e.position+1)return t.id}}getFirstPage(){let e,t=Number.MAX_VALUE;for(const i of this.nodes.values())i.position<t&&(t=i.position,e=i);return e}getNextPage(e,t){var i;if(!e)return;e.edges.sort(((e,t)=>"DIRECT"===e.typeCondition?1:"DIRECT"===t.typeCondition?-1:0));const n=e.edges.find((i=>{const n=e.questions.find((e=>e.ref===i.questionRef)),r=null==t?void 0:t.filter((e=>e.key===i.questionRef));if("DIRECT"===i.typeCondition)return!0;if(!r||0===r.length)return!1;if((null==n?void 0:n.type)===a.FEEDBACKAPPANSWERTYPE.MULTI_QUESTION_MATRIX)return this.evaluateMatrixCondition(i,r);const o=Array.isArray(i.value)?i.value:[i.value];switch(i.typeOperator){case s.OperatorType.EQUAL:return r.some((e=>(Array.isArray(e.value)?e.value:[e.value]).some((e=>o.includes(e)))));case s.OperatorType.NOEQUAL:return r.every((e=>(Array.isArray(e.value)?e.value:[e.value]).every((e=>!o.includes(e)))));case s.OperatorType.GREATER:return r.some((e=>(Array.isArray(e.value)?e.value:[e.value]).some((e=>o.some((t=>Number(e)>Number(t)))))));case s.OperatorType.LESS:return r.some((e=>(Array.isArray(e.value)?e.value:[e.value]).some((e=>o.some((t=>Number(e)<Number(t)))))));case s.OperatorType.GREATEREQUAL:return r.some((e=>(Array.isArray(e.value)?e.value:[e.value]).some((e=>o.some((t=>Number(e)>=Number(t)))))));case s.OperatorType.LESSEQUAL:return r.some((e=>(Array.isArray(e.value)?e.value:[e.value]).some((e=>o.some((t=>Number(e)<=Number(t)))))));case s.OperatorType.INQ:return r.some((e=>(Array.isArray(e.value)?e.value:[e.value]).some((e=>o.includes(e)))));case s.OperatorType.NINQ:return r.every((e=>(Array.isArray(e.value)?e.value:[e.value]).every((e=>!o.includes(e)))));default:return!1}}));if(!n){const t=this.getNextEdgeByDefault(e);if(!t)return;return this.getNodeById(t)}switch(n.transition){case s.TransitionType.PAGE:if(!n.transitionDestiny)return;return this.getNodeById(n.transitionDestiny);case s.TransitionType.FINISH:return;case s.TransitionType.REDIRECT:return void(window.location.href=(null===(i=n.transitionDestiny)||void 0===i?void 0:i.includes("?"))?`${n.transitionDestiny}&${window.location.search.slice(1)}`:`${n.transitionDestiny}${window.location.search}`);default:return}}findDepth(e){const t=this.getNodeById(e);if(!t)return 0;const i=new Set;return this.DFSUtil(t,i,0)}findMaxDepth(e){if(e||(e=this.getFirstPage()),!e)return 0;const t=new Set;let i=1;return i=Math.max(i,this.DFSUtil(e,t,i)),i}DFSUtil(e,t,i){t.add(e);let n=i;const a=[...e.edges.filter((e=>e.typeCondition!==s.ConditionType.PRECONDITIONAL))||[]],r=this.getNextEdgeByDefault(e);if(r){const i=this.getNodeById(r);i&&!t.has(i)&&a.push(new s.PageRoute(i.id,"",s.OperatorType.DEFAULT,[""],s.TransitionType.PAGE,i.id,e.id))}for(const e of a){if(!e.transitionDestiny)continue;const a=this.getNodeById(e.transitionDestiny);if(a&&!t.has(a)){const e=a.questions.find((e=>e.followup))?i+2:i+1,s=new Set(t),r=this.DFSUtil(a,s,e);n=Math.max(n,r)}}return n}parseMatrixAnswer(e){if(!e||!e.value)return[];if(1===e.value.length&&"string"==typeof e.value[0]&&e.value[0].trim().startsWith("["))try{const t=JSON.parse(e.value[0]);if(Array.isArray(t))return t}catch(e){return[]}return Array.isArray(e.value)&&e.value.length>0&&"object"==typeof e.value[0]&&null!==e.value[0]&&"key"in e.value[0]?e.value:[]}evaluateMatrixCondition(e,t){const i=Array.isArray(e.value)?e.value:[e.value],n=new Set(e.option||[]),a=t[0],r=this.parseMatrixAnswer(a);if(!r.length)return!1;const o=n.size>0?r.filter((e=>n.has(e.key))):r;if(!o.length)return!1;switch(e.typeOperator){case s.OperatorType.EQUAL:case s.OperatorType.INQ:return o.some((e=>(Array.isArray(e.value)?e.value:[e.value]).some((e=>i.includes(e)))));case s.OperatorType.NOEQUAL:case s.OperatorType.NINQ:return o.every((e=>(Array.isArray(e.value)?e.value:[e.value]).every((e=>!i.includes(e)))));case s.OperatorType.GREATER:return o.some((e=>(Array.isArray(e.value)?e.value:[e.value]).some((e=>i.some((t=>Number(e)>Number(t)))))));case s.OperatorType.LESS:return o.some((e=>(Array.isArray(e.value)?e.value:[e.value]).some((e=>i.some((t=>Number(e)<Number(t)))))));case s.OperatorType.GREATEREQUAL:return o.some((e=>(Array.isArray(e.value)?e.value:[e.value]).some((e=>i.some((t=>Number(e)>=Number(t)))))));case s.OperatorType.LESSEQUAL:return o.some((e=>(Array.isArray(e.value)?e.value:[e.value]).some((e=>i.some((t=>Number(e)<=Number(t)))))));default:return!1}}}},636:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.PageNode=void 0,t.PageNode=class{constructor(e,t,i,n,a,s=!1){this.answers=[],this.id=e,this.position=t,this.edges=i,this.data=n,this.questions=a.sort(((e,t)=>e.position-t.position)),this.elements=[],this.isFollowup=s}getFollowupQuestions(){return this.questions.filter((e=>e.followup)).map((e=>e.ref))}getRequiredQuestions(){return this.questions.filter((e=>e.require)).map((e=>e.ref))}setAnswer(e){this.answers=e}}},591:(e,t)=>{"use strict";var i,n,a,s;Object.defineProperty(t,"__esModule",{value:!0}),t.PageRoute=t.StatusType=t.OperatorType=t.ConditionType=t.TransitionType=void 0,(s=t.TransitionType||(t.TransitionType={})).PAGE="PAGE",s.FINISH="FINISH",s.REDIRECT="REDIRECT",s.NEXT="NEXT",s.ALLOW="ALLOW",function(e){e.LOGICAL="LOGICAL",e.DIRECT="DIRECT",e.PRECONDITIONAL="PRECONDITIONAL"}(i=t.ConditionType||(t.ConditionType={})),(a=t.OperatorType||(t.OperatorType={})).EQUAL="EQUAL",a.NOEQUAL="NOEQUAL",a.GREATER="GREATER",a.LESS="LESS",a.GREATEREQUAL="GREATEREQUAL",a.LESSEQUAL="LESSEQUAL",a.INQ="INQ",a.NINQ="NINQ",a.DEFAULT="DEFAULT",function(e){e.ACTIVE="ACTIVE",e.DEPRECATED="DEPRECATED",e.DELETE="DELETE"}(n=t.StatusType||(t.StatusType={})),t.PageRoute=class{constructor(e,t,a,s,r,o,l,d,c,u){this.id=e,this.questionRef=t,this.typeCondition=d||i.LOGICAL,this.typeOperator=a,this.value=s||[],this.transition=r,this.transitionDestiny=o,this.status=n.ACTIVE,this.generatedAt=new Date,this.updatedAt=new Date,this.integrationPageId=l,this.position=c||0,this.option=u||[]}}},558:(e,t)=>{"use strict";var i,n;Object.defineProperty(t,"__esModule",{value:!0}),t.QuestionType=t.FEEDBACKAPPANSWERTYPE=void 0,(n=t.FEEDBACKAPPANSWERTYPE||(t.FEEDBACKAPPANSWERTYPE={})).CONTACT="CONTACT",n.MULTIPLECHOISE_IMAGE="MULTIPLECHOISE_IMAGE",n.EMAIL="EMAIL",n.RATING_STAR="RATING_STAR",n.RADIO="RADIO",n.MULTIPLECHOICE="MULTIPLECHOICE",n.SELECT="SELECT",n.TEXT="TEXT",n.LONGTEXT="LONGTEXT",n.NUMBER="NUMBER",n.RATING_EMOJI="RATING_EMOJI",n.RATING_NUMBER="RATING_NUMBER",n.DATE="DATE",n.BOOLEAN="BOOLEAN",n.PASSWORD="PASSWORD",n.CONSENT="CONSENT",n.MULTI_QUESTION_MATRIX="MULTI_QUESTION_MATRIX",n.POINT_SYSTEM="POINT_SYSTEM",n.PRIORITY_LIST="PRIORITY_LIST",n.INFO_PAGE="INFO_PAGE",n.UPLOAD_FILE="UPLOAD_FILE",n.UPLOAD_IMAGE="UPLOAD_IMAGE",t.QuestionType=class{},function(e){e.FORM="form",e.DIV="div"}(i||(i={}))},857:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.endpoints=void 0,t.endpoints={sdk:{app:(e,t)=>`sdk/app/${e}/${t}`,app_info:(e,t)=>`sdk/app/${e}/${t}/info`,session:e=>`sdk/app/session/${e}/info`,feedback:"sdk/feedback",followUpQuestion:"sdk/followUpQuestion"}}},784:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.placeholder=void 0,t.placeholder={answer:e=>{switch(e){case"en":default:return"Write your answer here...";case"es":return"Escribe tu respuesta aquí...";case"da":return"Skriv dit svar her...";case"fi":return"Kirjoita vastauksesi tähän...";case"sv":return"Skriv ditt svar här...";case"no":return"Skriv svaret ditt her...";case"ar":return"اكتب إجابتك هنا...";case"bn":return"এখানে আপনার"}},number:e=>{switch(e){case"en":default:return"Write your number here...";case"es":return"Escribe tu número aquí...";case"da":return"Skriv dit nummer her...";case"fi":return"Kirjoita numerosi tähän...";case"sv":return"Skriv ditt nummer här...";case"no":return"Skriv nummeret ditt her...";case"ar":return"اكتب رقمك هنا...";case"bn":return"এখানে আপনার"}},email:e=>{switch(e){case"en":default:return"Write your email here...";case"es":return"Escribe tu correo electrónico aquí...";case"da":return"Skriv din e-mail her...";case"fi":return"Kirjoita sähköpostiosoitteesi tähän...";case"sv":return"Skriv din e-post här...";case"no":return"Skriv e-posten din her...";case"ar":return"اكتب بريدك الإلكتروني هنا...";case"bn":return"এখানে আপনার"}},date:e=>{switch(e){case"en":default:return"Write your date here...";case"es":return"Escribe tu fecha aquí...";case"da":return"Skriv din dato her...";case"fi":return"Kirjoita päivämääräsi tähän...";case"sv":return"Skriv ditt datum här...";case"no":return"Skriv datoen din her...";case"ar":return"اكتب تاريخك هنا...";case"bn":return"এখানে আপনার"}},password:e=>{switch(e){case"en":default:return"Write your password here...";case"es":return"Escribe tu contraseña aquí...";case"da":return"Skriv dit kodeord her...";case"fi":return"Kirjoita salasanasi tähän...";case"sv":return"Skriv ditt lösenord här...";case"no":return"Skriv passordet ditt her...";case"ar":return"اكتب كلمة المرور الخاصة بك هنا...";case"bn":return"এখানে আপনার"}},pointsystemerror:e=>{switch(e){case"en":default:return"The total points must be 100 %";case"es":return"El total de puntos debe ser 100 %";case"da":return"Samlet antal point skal være 100 %";case"fi":return"Kokonaispisteiden on oltava 100 %";case"sv":return"Totala poäng måste vara 100 %";case"no":return"Totalt antall poeng må være 100 %";case"ar":return"يجب أن تكون النقاط الإجمالية 100 %";case"bn":return"মোট পয়েন্ট 100 % হতে হবে"}}}},213:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.renderStartMessage=t.renderSuccess=t.renderError=t.renderActions=t.renderQuestions=void 0;const n=i(558),a=i(784),s="https://survey-dev.magicfeedback.io/assets/emojis";function r(e,t){return e?"object"==typeof e?e[t]||e.en:e:""}function o(e,t,i,n,a,s=!0,r="ltr",o="row"){const l=document.createElement("div");l.classList.add("magicfeedback-rating-placeholder"),l.style.display="flex",l.style.flexDirection=o,l.style.alignItems="center",l.style.justifyContent="space-between",l.style.width=a?`calc(100% - (100% / ${t+1}))`:"100%",l.style.marginRight="auto",s&&window.innerWidth<600&&(l.style.flexDirection="column");const d=document.createElement("span");d.textContent=i,d.classList.add("magicfeedback-rating-placeholder-value"),d.style.fontSize="15px",d.style.textAlign="ltr"===r?"left":"right",d.style.width="50%",(s&&window.innerWidth<600||"column"===o)&&(d.textContent=`${e} = ${i}`,d.style.width="100%",d.style.textAlign="left",d.style.marginBottom="5px");const c=document.createElement("span");return c.textContent=n,c.classList.add("magicfeedback-rating-placeholder-value"),c.style.fontSize="15px",c.style.textAlign="ltr"===r?"right":"left",c.style.width="50%",(s&&window.innerWidth<600||"column"===o)&&(c.textContent=`${t} = ${n}`,c.style.width="100%",c.style.textAlign="left",c.style.marginBottom="5px"),"ltr"===r?(i&&l.appendChild(d),n&&l.appendChild(c)):(n&&l.appendChild(c),i&&l.appendChild(d)),l}t.renderQuestions=function e(t,i="standard",l="en",d={customIcons:!1},c){if(!t)throw new Error("[MagicFeedback] No questions provided");const u=[],{customIcons:p,id:h}=d;return t.forEach((m=>{var f,g;if((null===(g=null===(f=null==m?void 0:m.questionType)||void 0===f?void 0:f.conf)||void 0===g?void 0:g.length)>0){let t=document.createElement("div");t.classList.add("magicfeedback-div");const n=document.createElement("label");n.setAttribute("for",`magicfeedback-${m.id}`),n.textContent=r(m.title,l),n.classList.add("magicfeedback-label"),t.appendChild(n),m.questionType.conf.forEach((e=>{e.ref=m.ref,m.assets[e.id]&&(e.assets={placeholder:m.assets[e.id]})})),e(m.questionType.conf,i,l,d,c).forEach((e=>{t.appendChild(e)})),u.push(t)}else{const e=function(e,t,i,l,d){var c,u,p;let h,m,{id:f,title:g,type:v,ref:y,require:E,value:b,defaultValue:A,assets:k}=e,C=document.createElement("div");C.classList.add("magicfeedback-div");const T=window.innerWidth<600,x="slim"===t?r(g,i):null==k?void 0:k.placeholder,w=(N=y,new URLSearchParams(window.location.search).get(N)),L=(null==k?void 0:k.maxCharacters)||0,P=void 0!==(null==k?void 0:k.randomPosition)&&(null==k?void 0:k.randomPosition),S=(null==k?void 0:k.direction)||"row",O=(null==k?void 0:k.order)||"ltr";var N;switch(v){case n.FEEDBACKAPPANSWERTYPE.TEXT:h=document.createElement("input"),h.type="text",h.placeholder=x||a.placeholder.answer(i||"en"),w&&(h.value=w),h.addEventListener("keyup",(e=>{e.preventDefault(),console.log(e.key,e),"Enter"===e.key&&d&&d()})),m="magicfeedback-text";break;case n.FEEDBACKAPPANSWERTYPE.LONGTEXT:h=document.createElement("textarea"),h.rows=3,L>0&&(h.maxLength=L),h.placeholder=x||a.placeholder.answer(i||"en"),w&&(h.value=w),m="magicfeedback-longtext";break;case n.FEEDBACKAPPANSWERTYPE.NUMBER:h=document.createElement("input"),h.type="number",h.placeholder="slim"===t?r(g,i):a.placeholder.number(i||"en"),m="magicfeedback-number",b.length&&(b.sort(((e,t)=>Number(e)-Number(t))),h.max=b[b.length-1],h.min=b[0],h.value=b[0]),w&&!isNaN(Number(w))&&(h.value=w);break;case n.FEEDBACKAPPANSWERTYPE.RADIO:case n.FEEDBACKAPPANSWERTYPE.MULTIPLECHOICE:h=document.createElement("div"),m="magicfeedback-"+("MULTIPLECHOICE"===v?"checkbox":"radio");let R=b||[];P&&(R=R.sort((()=>Math.random()-.5)));let $=(null==k?void 0:k.exclusiveAnswers)||[];(null==k?void 0:k.extraOption)&&($=$.filter((e=>e!==k.extraOptionText))),$.length>0&&(null==$||$.forEach((e=>{R.includes(e)||R.push(e)}))),(null==k?void 0:k.extraOption)&&!R.includes(null==k?void 0:k.extraOptionText)&&R.push(null==k?void 0:k.extraOptionText),R.forEach(((e,t)=>{const s=document.createElement("div");s.classList.add(`magicfeedback-${"MULTIPLECHOICE"===v?"checkbox":"radio"}-container`);const r=document.createElement("label"),o=document.createElement("input");if(o.id=`rating-${y}-${t}`,o.type="MULTIPLECHOICE"===v?"checkbox":"radio",o.name=y,o.value=e,o.classList.add(m),o.classList.add("magicfeedback-input"),v===n.FEEDBACKAPPANSWERTYPE.MULTIPLECHOICE&&(null==k?void 0:k.maxOptions)&&(null==k?void 0:k.maxOptions)>0&&o.addEventListener("change",(()=>{document.querySelectorAll(`input[name="${y}"]:checked`).length>(null==k?void 0:k.maxOptions)&&(o.checked=!1)})),v===n.FEEDBACKAPPANSWERTYPE.RADIO&&d&&(!(null==k?void 0:k.extraOptionText)||(null==k?void 0:k.extraOptionText)&&e!==(null==k?void 0:k.extraOptionText))&&o.addEventListener("change",(()=>{d()})),e!==A&&e!==w||(o.checked=!0),r.textContent=e,r.htmlFor=`rating-${y}-${t}`,o.addEventListener("change",(t=>{const i=document.getElementById(`extra-option-${y}`);t.target.checked&&$.includes(e)?(console.log("exclusiveAnswers",$,e),R.forEach((t=>{t!==e&&(document.querySelector(`input[value="${t}"]`).checked=!1)})),i&&(i.style.display="none")):$.forEach((t=>{t!==e&&(document.querySelector(`input[value="${t}"]`).checked=!1)})),(null==k?void 0:k.extraOption)&&e===(null==k?void 0:k.extraOptionText)&&i&&(i.style.display=t.target.checked?"block":"none")})),s.appendChild(o),s.appendChild(r),h.appendChild(s),(null==k?void 0:k.extraOption)&&e===(null==k?void 0:k.extraOptionText)){const e=document.createElement("input");e.type="text",e.placeholder=(null==k?void 0:k.extraOptionPlaceholder)||a.placeholder.answer(i||"en"),e.classList.add("magicfeedback-extra-option"),e.classList.add("magicfeedback-input"),e.id=`extra-option-${y}`,e.name=`extra-option-${y}`,e.style.display="none",h.appendChild(e)}}));break;case n.FEEDBACKAPPANSWERTYPE.BOOLEAN:h=document.createElement("div"),m="magicfeedback-radio";const _=document.createElement("div");_.classList.add("magicfeedback-boolean-container"),_.style.display="flex",_.style.flexDirection="row",_.style.justifyContent="space-between",_.style.width="70%",_.style.margin="auto",((null==k?void 0:k.addIcon)?["👍","👎"]:function(e){switch(e){case"es":return["Sí","No"];case"fr":return["Oui","Non"];case"de":return["Ja","Nein"];case"it":return["Sì","No"];case"pt":return["Sim","Não"];case"nl":return["Ja","Nee"];case"pl":return["Tak","Nie"];case"ru":return["Да","Нет"];case"ja":return["はい","いいえ"];case"zh":return["是","不"];case"ko":return["예","아니"];case"da":case"sv":return["Ja","Nej"];case"fi":return["Kyllä","Ei"];case"no":return["Ja","Nei"];case"ar":return["نعم","لا"];case"bn":return["হ্যাঁ","না"];default:return["Yes","No"]}}(i)).forEach(((e,t)=>{const i=document.createElement("label");i.classList.add("magicfeedback-boolean-option"),i.htmlFor=`rating-${y}-${t}`,i.style.cursor="pointer",i.style.border="1px solid #000",i.style.display="flex",i.style.justifyContent="center",i.style.alignItems="center",i.style.margin="auto",i.style.padding="0",i.style.width="45%",i.style.height="38px";const n=document.createElement("label");n.htmlFor=`rating-${y}-${t}`,n.textContent=e,n.style.margin="0",n.style.padding="0";const a=document.createElement("input");a.id=`rating-${y}-${t}`,a.type="radio",a.name=y,a.value=["Yes","No"][t],a.classList.add(m),a.classList.add("magicfeedback-input"),a.style.position="absolute",a.style.opacity="0",a.style.width="0",a.style.height="0",a.style.margin="0",a.addEventListener("change",(()=>{d&&d()})),w&&w.toLowerCase()===a.value.toLowerCase()&&(a.checked=!0),i.appendChild(a),i.appendChild(n),_.appendChild(i)})),h.appendChild(_);break;case n.FEEDBACKAPPANSWERTYPE.RATING_EMOJI:h=document.createElement("div"),m="magicfeedback-rating";const F=document.createElement("div");F.classList.add("magicfeedback-rating-container");const M=(null==k?void 0:k.max)?Number(null==k?void 0:k.max):5,B=(null==k?void 0:k.min)?Number(null==k?void 0:k.min):1,U=o(B,M,null==k?void 0:k.minPlaceholder,null==k?void 0:k.maxPlaceholder,null==k?void 0:k.extraOption);for(let ce=B;ce<=M;ce++){const ue=document.createElement("div");ue.classList.add("magicfeedback-rating-option");const pe=document.createElement("label");pe.htmlFor=`rating-${y}-${ce}`,pe.classList.add("magicfeedback-rating-option-label-container");const he=document.createElement("label");he.htmlFor=`rating-${y}-${ce}`,he.textContent=ce.toString();const me=document.createElement("img");if(me.alt=`face-${y}-${ce}`,me.className=`rating-image${ce}`,0===B&&10===M)me.src=`${l}/${ce}.svg`,me.onerror=()=>me.src=`${s}/${ce}.svg`;else if(1===B&&5===M)switch(ce){case 1:me.src=`${l}/1.svg`,me.onerror=()=>me.src=`${s}/1.svg`;break;case 2:me.src=`${l}/2.svg`,me.onerror=()=>me.src=`${s}/2.svg`;break;case 3:me.src=`${l}/6.svg`,me.onerror=()=>me.src=`${s}/6.svg`;break;case 4:me.src=`${l}/9.svg`,me.onerror=()=>me.src=`${s}/9.svg`;break;case 5:me.src=`${l}/10.svg`,me.onerror=()=>me.src=`${s}/10.svg`}else{const ge=Math.round(10/(M-B)*(ce-B));me.src=`${l}/${ge}.svg`,me.onerror=()=>me.src=`${s}/${ge}.svg`}const fe=document.createElement("input");fe.id=`rating-${y}-${ce}`,fe.type="radio",fe.name=y,fe.value=ce.toString(),fe.classList.add(m),fe.classList.add("magicfeedback-input"),d&&fe.addEventListener("change",(()=>{d()})),w&&w===fe.value&&(fe.checked=!0),pe.appendChild(fe),pe.appendChild(me),pe.appendChild(he),ue.appendChild(pe),F.appendChild(ue)}if((null==k?void 0:k.extraOption)&&(null==k?void 0:k.extraOptionText)){const ve=document.createElement("div");ve.classList.add("magicfeedback-rating-option");const ye=document.createElement("label");ye.htmlFor=`rating-${y}-extra`,ye.classList.add("magicfeedback-rating-option-label-container");const Ee=document.createElement("label");Ee.htmlFor=`rating-${y}-extra`,Ee.textContent=null==k?void 0:k.extraOptionText;const be=document.createElement("img");be.src="https://magicfeedback-c6458-dev.web.app/assets/question.svg",be.alt=`face-${y}-extra`,be.className="magicfeedback-rating-image-extra";const Ae=document.createElement("input");Ae.id=`rating-${y}-extra`,Ae.type="radio",Ae.name=y,Ae.value="-",Ae.classList.add(m),Ae.classList.add("magicfeedback-input"),d&&Ae.addEventListener("change",(()=>{d()})),ye.appendChild(Ae),ye.appendChild(be),ye.appendChild(Ee),ve.appendChild(ye),F.appendChild(ve)}h.appendChild(U),h.appendChild(F);break;case n.FEEDBACKAPPANSWERTYPE.RATING_NUMBER:m="magicfeedback-rating-number",h=function(e,t,i,n,a,s,r,o){const l=document.createElement("div");l.classList.add("magicfeedback-rating-number");const d="ltr"===i?n:`${n}-reverse`,c=document.createElement("div");c.classList.add("magicfeedback-rating-number-container"),c.classList.add(`magicfeedback-rating-number-container-${i}`),c.classList.add(`magicfeedback-rating-number-container-${n}`),c.style.display="flex",c.style.flexDirection=d,c.setAttribute("role","radiogroup"),c.setAttribute("aria-label",(null==t?void 0:t.ariaLabel)||"Rating");const u=(null==t?void 0:t.max)?Number(null==t?void 0:t.max):10,p=(null==t?void 0:t.min)?Number(null==t?void 0:t.min):0,h=!(a||"column"===n);for(let i=p;i<=u;i++){const a=document.createElement("div");a.classList.add("magicfeedback-rating-number-option"),a.classList.add(`magicfeedback-rating-number-option-${n}`);const l=document.createElement("label");if(l.htmlFor=`rating-${e}-${i}`,l.classList.add("magicfeedback-rating-number-option-label-container"),h&&(l.style.position="relative",l.style.overflow="visible"),h){const e=document.createElement("span");e.classList.add("magicfeedback-rating-number-cap"),e.classList.add("magicfeedback-rating-placeholder-value"),e.style.fontSize="14px",e.style.whiteSpace="nowrap",e.style.wordBreak="normal",i===p&&(null==t?void 0:t.minPlaceholder)?(e.textContent=t.minPlaceholder,e.dataset.capType="min"):i===u&&(null==t?void 0:t.maxPlaceholder)?(e.textContent=t.maxPlaceholder,e.dataset.capType="max"):e.dataset.capType="mid",l.appendChild(e)}let d=i.toString();h||(i===p&&(null==t?void 0:t.minPlaceholder)&&(d+=` = ${null==t?void 0:t.minPlaceholder}`),i===u&&(null==t?void 0:t.maxPlaceholder)&&(d+=` = ${null==t?void 0:t.maxPlaceholder}`));const m=document.createElement("input");m.id=`rating-${e}-${i}`,m.type="radio",m.name=e,m.value=i.toString(),m.classList.add(s),m.classList.add("magicfeedback-input"),m.setAttribute("aria-label",`${i}`),r&&m.addEventListener("change",(()=>r())),o&&o===m.value&&(m.checked=!0);const f=document.createElement("label");f.htmlFor=`rating-${e}-${i}`,f.textContent=d,f.classList.add("magicfeedback-rating-number-value"),l.appendChild(m),l.appendChild(f),a.appendChild(l),c.appendChild(a)}if((null==t?void 0:t.extraOption)&&(null==t?void 0:t.extraOptionText)){const n=document.createElement("div");n.classList.add("magicfeedback-rating-number-option");const a=document.createElement("label");if(a.htmlFor=`rating-${e}-extra`,a.classList.add("magicfeedback-rating-number-option-label-container"),h&&(a.style.position="relative",a.style.overflow="visible"),h){const e=document.createElement("span");e.classList.add("magicfeedback-rating-number-cap"),e.dataset.capType="extra",e.style.fontSize="12px",e.style.whiteSpace="nowrap",e.style.wordBreak="normal",a.appendChild(e)}const o=document.createElement("input");o.id=`rating-${e}-extra`,o.type="radio",o.name=e,o.value="-",o.classList.add(s),o.classList.add("magicfeedback-input"),o.setAttribute("aria-label",null==t?void 0:t.extraOptionText),r&&o.addEventListener("change",(()=>r()));const l=document.createElement("label");l.htmlFor=`rating-${e}-extra`,l.textContent=null==t?void 0:t.extraOptionText,l.classList.add("magicfeedback-rating-number-value"),a.appendChild(o),a.appendChild(l),n.appendChild(a),"ltr"===i?c.appendChild(n):c.insertBefore(n,c.firstChild)}return l.appendChild(c),h&&requestAnimationFrame((()=>{const e=Array.from(c.querySelectorAll(".magicfeedback-rating-number-cap"));if(0===e.length)return;let t=0;e.forEach((e=>{var i;if(null===(i=e.textContent)||void 0===i?void 0:i.trim()){const i=e.getBoundingClientRect().height||0;i>t&&(t=i)}})),c.style.position="relative",c.style.paddingTop=`${0===t?"42":t+6}px`,e.forEach((e=>{const n=e.getBoundingClientRect().height||0;console.log(t,n,6),e.style.position="absolute",e.style.top=`-${0===t?"42":t+n}px`,e.style.zIndex="1",e.style.pointerEvents="none",e.style.padding="0",e.style.boxSizing="border-box",e.style.whiteSpace="nowrap",e.style.wordBreak="normal",e.style.maxWidth="none",e.style.width="max-content";const a=e.dataset.capType;"min"===a?("ltr"===i?(e.style.left="10px",e.style.textAlign="left"):(e.style.right="10px",e.style.textAlign="right"),e.style.transform="none"):"max"===a?("ltr"===i?(e.style.right="10px",e.style.textAlign="right"):(e.style.left="10px",e.style.textAlign="left"),e.style.transform="none"):(e.style.left="50%",e.style.transform="translateX(-50%)",e.style.textAlign="center")})),c.style.overflow="visible"})),l}(y,k,O,S,T,m,d,w);break;case n.FEEDBACKAPPANSWERTYPE.RATING_STAR:h=document.createElement("div"),m="magicfeedback-rating-star";const q=function(e,t,i,n=()=>{},a){const s="magicfeedback-rating-star-selected",r=document.createElement("div");r.classList.add("magicfeedback-rating-star-container"),r.style.maxWidth="300px",r.style.margin="auto",r.dataset.originalSelection="0";for(let t=1;t<=5;t++){const i=document.createElement("label");i.classList.add("magicfeedback-rating-star-option");const o=document.createElement("input");o.id=`rating-${e}-${t}`,o.type="radio",o.name=e,o.value=t.toString(),o.style.position="absolute",o.style.opacity="0",o.style.width="0",o.style.height="0",o.classList.add("magicfeedback-input"),a&&a===o.value&&(o.checked=!0),o.addEventListener("change",(()=>{const e=r.querySelectorAll(".rating__star");for(let t=0;t<e.length;t++)t+1<=Number(o.value)?e[t].classList.contains(s)||e[t].classList.add(s):e[t].classList.contains(s)&&e[t].classList.remove(s);r.dataset.originalSelection=o.value,n&&n()})),i.appendChild(o);const l=document.createElement("label");l.htmlFor=`rating-${e}-${t}`,l.classList.add("rating__star"),l.textContent="★",l.style.fontSize="40px",l.style.color="#CCCCCC",l.style.cursor="pointer",l.addEventListener("mouseenter",(()=>{const e=r.querySelectorAll(".rating__star"),i=t-1;e.forEach(((e,t)=>{t<=i?e.classList.contains(s)||e.classList.add(s):e.classList.contains(s)&&e.classList.remove(s)}))})),l.addEventListener("mouseleave",(()=>{const e=Number(r.dataset.originalSelection||"0");r.querySelectorAll(".rating__star").forEach(((t,i)=>{i<e?t.classList.contains(s)||t.classList.add(s):t.classList.contains(s)&&t.classList.remove(s)}))})),i.appendChild(l),r.appendChild(i)}return r.appendChild(o(1,5,t,i,!1,!1)),r}(y,null==k?void 0:k.minPlaceholder,null==k?void 0:k.maxPlaceholder,d,w);h.appendChild(q);break;case n.FEEDBACKAPPANSWERTYPE.MULTIPLECHOISE_IMAGE:h=document.createElement("div"),m="magicfeedback-multiple-choice-image";const j=document.createElement("div");j.classList.add("magicfeedback-multiple-choice-image-container"),j.style.display="flex",j.style.flexDirection="row",j.style.flexWrap="wrap",j.style.justifyContent="center";const Q=b.length;let W=1,K=1;if(window.innerWidth<600)W=1,K=Q;else switch(Q){case 1:case 2:case 3:W=Q,K=1;break;case 4:case 5:case 6:K=2,W=Math.ceil(Q/K);break;case 7:case 8:case 9:K=3,W=Math.ceil(Q/K);break;default:K=4,W=Math.ceil(Q/K)}const G=void 0!==(null==k?void 0:k.addTitle)&&(null==k?void 0:k.addTitle),Y=void 0!==(null==k?void 0:k.multiOption)&&(null==k?void 0:k.multiOption),H=void 0!==(null==k?void 0:k.extraOption)&&(null==k?void 0:k.extraOption);function V(e){try{const{position:t,url:i,value:n}=e,a=document.createElement("label");a.classList.add("magicfeedback-multiple-choice-image-option"),a.style.width=`calc( ${100/W}% - 10px)`,a.style.height=`calc( ${100/K}% - 10px)`,a.style.margin="5px";const s=document.createElement("label");s.htmlFor=`rating-${y}-${t}`,s.classList.add("magicfeedback-image-option-label-container"),s.style.display="flex",s.style.flexDirection="column",s.addEventListener("mouseover",(()=>{s.style.border="2px solid #000"})),s.addEventListener("mouseout",(()=>{s.style.border="none"})),s.addEventListener("click",(()=>{s.style.border="2px solid #000"}));const r=document.createElement("label");r.textContent=n,r.classList.add("magicfeedback-multiple-choice-image-label");const o=document.createElement("input");o.id=`rating-${y}-${t}`,o.type=Y?"checkbox":"radio",o.name=y,o.value=n,o.style.position="absolute",o.style.opacity="0",o.style.width="0",o.style.height="0",o.classList.add("magicfeedback-input"),w&&w===o.value&&(o.checked=!0),!Y&&d&&o.addEventListener("change",(()=>{console.log("send"),d()}));const l=document.createElement("img");l.classList.add("magicfeedback-multiple-choice-image-image"),l.src=i,l.style.cursor="pointer",l.style.backgroundSize="cover",l.style.backgroundPosition="center",l.style.width="100%",l.style.height="100%",l.style.objectFit="cover",l.style.margin="auto",s.appendChild(o),s.appendChild(l),G&&s.appendChild(r),a.appendChild(s),j.appendChild(a)}catch(e){console.error(e)}}P&&(b=b.sort((()=>Math.random()-.5))),b.forEach((e=>V(JSON.parse(e)))),H&&(null==k?void 0:k.extraOptionValue)&&(null==k?void 0:k.extraOptionValue.length)>0&&V(null==k?void 0:k.extraOptionValue[0]),h.appendChild(j);break;case n.FEEDBACKAPPANSWERTYPE.SELECT:h=document.createElement("select"),m="magicfeedback-select";const X=document.createElement("option");X.value="",X.text="slim"===t?r(g,i):A||"Select an option",X.disabled=!0,X.selected=!0,h.appendChild(X),b.forEach((e=>{const t=document.createElement("option");t.value=e,t.text=e,h.appendChild(t)})),w&&b.includes(w)&&(h.value=w),d&&h.addEventListener("change",(()=>{d()}));break;case n.FEEDBACKAPPANSWERTYPE.DATE:h=document.createElement("input"),h.type="date",h.required=E,h.placeholder=x||a.placeholder.date(i||"en"),m="magicfeedback-date",w&&(h.value=w);break;case n.FEEDBACKAPPANSWERTYPE.CONSENT:h=document.createElement("input"),m="magicfeedback-consent",h.type="checkbox",h.id=`magicfeedback-${f}`,h.name=y,h.value="true",h.required=E,h.classList.add("magicfeedback-consent"),h.classList.add("magicfeedback-input"),w&&b.includes(w)&&(h.checked=!0),d&&h.addEventListener("change",(()=>{d()}));break;case n.FEEDBACKAPPANSWERTYPE.EMAIL:h=document.createElement("input"),h.type="email",h.required=E,h.placeholder=x||"you@example.com",m="magicfeedback-email",w&&(h.value=w);break;case n.FEEDBACKAPPANSWERTYPE.PASSWORD:h=document.createElement("input"),h.type="password",h.required=E,h.placeholder=x||a.placeholder.password(i||"en"),m="magicfeedback-password",w&&(h.value=w);break;case n.FEEDBACKAPPANSWERTYPE.MULTI_QUESTION_MATRIX:h=document.createElement("div"),m="magicfeedback-multi-question-matrix";const z=document.createElement("div");z.classList.add("magicfeedback-multi-question-matrix-container");let J=(null==k?void 0:k.options)||[],Z=[...b],ee=[];if(P&&(J=null==J?void 0:J.sort((()=>Math.random()-.5)),Z=[...Z].sort((()=>Math.random()-.5))),(null==k?void 0:k.exclusiveAnswers)&&(ee=null==k?void 0:k.exclusiveAnswers,null==ee||ee.forEach((e=>{Z.includes(e)||Z.push(e)}))),window.innerWidth<600){const ke=document.createElement("div");ke.classList.add("magicfeedback-multi-question-matrix-list"),null==J||J.forEach((e=>{const t=document.createElement("div");t.classList.add("magicfeedback-multi-question-matrix-list-item"),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="flex-start",t.style.marginBottom="10px";const i=document.createElement("label");i.classList.add("magicfeedback-multi-question-matrix-label"),i.style.paddingBottom="10px",i.textContent=e,t.appendChild(i),Z.forEach((i=>{const n=document.createElement("div");n.classList.add("magicfeedback-radio-container"),n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="flex-start",n.style.width="99%",n.style.margin="5px auto";const a=document.createElement("label"),s=document.createElement("input");s.id=`${y}-${e}-${i}`,s.type="radio",s.name=`${y}-${e}`,s.value=i,s.classList.add("magicfeedback-input"),a.textContent=i,a.htmlFor=`${y}-${e}-${i}`,n.appendChild(s),n.appendChild(a),t.appendChild(n)})),ke.appendChild(t)})),z.appendChild(ke)}else{const Ce=document.createElement("table");Ce.classList.add("magicfeedback-multi-question-matrix-table");const Te=document.createElement("thead");Te.classList.add("magicfeedback-multi-question-matrix-header"),Te.style.paddingBottom="15px";const xe=document.createElement("tr"),we=document.createElement("th");xe.appendChild(we),Z.forEach((e=>{const t=document.createElement("th");t.textContent=e,xe.appendChild(t)})),Te.appendChild(xe),Ce.appendChild(Te);const Le=document.createElement("tbody");null==J||J.forEach((e=>{const t=document.createElement("tr");t.classList.add("magicfeedback-multi-question-matrix-row-tr");const i=document.createElement("td");i.style.minWidth="200px",i.style.padding="15px 10px";const n=document.createElement("label");n.classList.add("magicfeedback-multi-question-matrix-label"),n.textContent=e,i.appendChild(n),t.appendChild(i),Z.forEach((i=>{const n=document.createElement("td"),a=document.createElement("input");a.type="radio",a.name=`${y}-${e}`,a.value=i,a.id=`${y}-${e}-${i}`,a.classList.add("magicfeedback-input"),n.appendChild(a),t.appendChild(n)})),Le.appendChild(t)})),Ce.appendChild(Le),z.appendChild(Ce)}h.appendChild(z);break;case n.FEEDBACKAPPANSWERTYPE.PRIORITY_LIST:h=document.createElement("div"),m="magicfeedback-priority-list";const te=document.createElement("div");te.classList.add("magicfeedback-priority-list-container");const ie=document.createElement("ul");ie.classList.add("magicfeedback-priority-list-list"),P&&(b=b.sort((()=>Math.random()-.5))),b.forEach(((e,t)=>{const i=document.createElement("li");i.classList.add("magicfeedback-priority-list-item"),i.style.display="flex",i.style.justifyContent="space-between",i.style.alignItems="center",i.style.margin="5px";const n=document.createElement("input");n.classList.add("magicfeedback-input-magicfeedback-priority-list"),n.classList.add("magicfeedback-input"),n.type="hidden",n.id=`priority-list-${y}`,n.name=y,n.value=`${t+1}. ${e}`,i.appendChild(n);const a=document.createElement("label");a.classList.add("magicfeedback-priority-list-item-label"),a.textContent=`${t+1}. ${e}`,i.appendChild(a);const s=document.createElement("div");s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="space-between";const r=document.createElement("img");r.classList.add("magicfeedback-priority-list-arrow-up"),r.src="https://magicfeedback-c6458-dev.web.app/assets/arrow.svg",r.style.width="20px",r.style.height="20px",r.style.cursor="pointer",r.style.margin="0 5px",r.style.color="#000",r.style.visibility=0===t?"hidden":"visible",r.addEventListener("click",(()=>{var t,s,l,d;const c=i.previousElementSibling;if(c){const u=Number(null===(t=n.value)||void 0===t?void 0:t.split(".")[0])-1;n.value=`${u}. ${e}`,a.textContent=`${u}. ${e}`,r.style.visibility=1===u?"hidden":"visible",o.style.visibility=u===b.length?"hidden":"visible";const p=c.querySelector(".magicfeedback-input-magicfeedback-priority-list"),h=c.querySelector(".magicfeedback-priority-list-item-label"),m=c.querySelector(".magicfeedback-priority-list-arrow-up"),f=c.querySelector(".magicfeedback-priority-list-arrow-down");if(p&&h&&m&&f){const e=Number(null===(s=p.value)||void 0===s?void 0:s.split(".")[0])+1;p.value=`${e}.${null===(l=h.textContent)||void 0===l?void 0:l.split(".")[1]}`,h.textContent=`${e}.${null===(d=h.textContent)||void 0===d?void 0:d.split(".")[1]}`,m.style.visibility=1===e?"hidden":"visible",f.style.visibility=e===b.length?"hidden":"visible"}ie.insertBefore(i,c)}})),s.appendChild(r);const o=document.createElement("img");o.classList.add("magicfeedback-priority-list-arrow-down"),o.src="https://magicfeedback-c6458-dev.web.app/assets/arrow.svg",o.style.width="20px",o.style.height="20px",o.style.cursor="pointer",o.style.margin="0 5px",o.style.color="#000",o.style.transform="rotate(180deg)",o.style.visibility=t===b.length-1?"hidden":"visible",o.addEventListener("click",(()=>{var t,s,l;const d=i.nextElementSibling;if(d){const c=Number(null===(t=n.value)||void 0===t?void 0:t.split(".")[0])+1;n.value=c.toString(),a.textContent=`${c.toString()}. ${e}`,r.style.visibility=1===c?"hidden":"visible",o.style.visibility=c===b.length?"hidden":"visible";const u=d.querySelector(".magicfeedback-input-magicfeedback-priority-list"),p=d.querySelector(".magicfeedback-priority-list-item-label"),h=d.querySelector(".magicfeedback-priority-list-arrow-up"),m=d.querySelector(".magicfeedback-priority-list-arrow-down");if(u&&p&&h&&m){const e=Number(u.value.split(".")[0])-1;u.value=`${e}.${null===(s=p.textContent)||void 0===s?void 0:s.split(".")[1]}`,p.textContent=`${e}.${null===(l=p.textContent)||void 0===l?void 0:l.split(".")[1]}`,h.style.visibility=1===e?"hidden":"visible",m.style.visibility=e===b.length?"hidden":"visible"}ie.insertBefore(d,i)}})),s.appendChild(o),i.appendChild(s),ie.appendChild(i)})),te.appendChild(ie),h.appendChild(te);break;case n.FEEDBACKAPPANSWERTYPE.POINT_SYSTEM:h=document.createElement("div"),m="magicfeedback-point-system";const ne=document.createElement("div");ne.classList.add("magicfeedback-point-system-container");const ae=document.createElement("ul");ae.classList.add("magicfeedback-point-system-list"),ae.style.padding="0";const se=100,re=se/b.length,oe=document.createElement("div");oe.classList.add("magicfeedback-error"),oe.textContent=a.placeholder.pointsystemerror(i||"en"),oe.style.color="#C70039",oe.style.fontSize="14px",oe.style.textAlign="right",oe.style.width="100%",oe.style.display="none";const le=document.createElement("div");le.classList.add("magicfeedback-point-system-total"),le.textContent="0 / 100 %",le.style.textAlign="right",le.style.fontSize="15px",le.style.marginTop="5px",b.forEach(((e,t)=>{const i=document.createElement("li");i.classList.add("magicfeedback-point-system-item"),i.style.display="flex",i.style.justifyContent="space-between",i.style.alignItems="center",i.style.margin="5px";const n=document.createElement("label");n.textContent=e,n.style.fontSize="15px",i.appendChild(n);const a=document.createElement("span");a.classList.add("magicfeedback-point-system-input-container");const s=document.createElement("input");s.name=y,s.id=`${e}`,s.type="number",s.min="0",s.max=`${se}`,s.value="0",s.classList.add("magicfeedback-input"),s.style.width="40px",s.style.border="0",s.style.textAlign="center",s.style.margin="0 5px",s.autofocus=0===t;const r=document.createElement("span");r.textContent="%",r.style.color="#000",s.addEventListener("input",(()=>{const e=ae.querySelectorAll("input");let t=0;e.forEach((e=>{t+=Number(e.value)})),t>se&&(s.value=`${re}%`,t-=Number(s.value));const i=document.getElementById("magicfeedback-submit");i&&(t<100?(le.style.color="orange",i.setAttribute("disabled","true")):(oe.style.display="none",le.style.color="green",i.removeAttribute("disabled"))),le.textContent=`${t} / 100 %`})),s.addEventListener("focus",(()=>{const e=document.getElementById("magicfeedback-submit");e&&(e.setAttribute("disabled","true"),e.addEventListener("pointerover",(()=>{const e=ae.querySelectorAll("input");let t=0;e.forEach((e=>{t+=Number(e.value)})),t<100&&(oe.style.display="block")})))})),a.appendChild(s),a.appendChild(r),i.appendChild(a),ae.appendChild(i)})),ne.appendChild(ae),ne.appendChild(le),ne.appendChild(oe),h.appendChild(ne);break;case n.FEEDBACKAPPANSWERTYPE.INFO_PAGE:h=document.createElement("div"),m="magicfeedback-info-page";const de=document.createElement("div");de.classList.add("magicfeedback-info-message"),de.innerHTML=x,h.appendChild(de);break;case n.FEEDBACKAPPANSWERTYPE.UPLOAD_IMAGE:h=document.createElement("input"),h.type="file",h.accept="image/*",h.required=E,h.multiple=(null==k?void 0:k.multiple)||!1,h.maxLength=(null==k?void 0:k.maxFiles)||1,m="magicfeedback-upload-image";break;case n.FEEDBACKAPPANSWERTYPE.UPLOAD_FILE:h=document.createElement("input"),h.type="file",h.required=E,h.multiple=(null==k?void 0:k.multiple)||!1,h.maxLength=(null==k?void 0:k.maxFiles)||1,m="magicfeedback-upload-file";break;default:return C}h.id=`magicfeedback-${f}`,h.setAttribute("name",y),h.classList.add(m),(void 0!==A||null!==w)&&(h.value=w||A),["RADIO","MULTIPLECHOICE"].includes(v)||(h.classList.add("magicfeedback-input"),h.required=E);const I=document.createElement("label");I.setAttribute("for",`magicfeedback-${f}`),I.textContent=r(g,i),I.classList.add("magicfeedback-label");const D=document.createElement("label");if(D.textContent=r(null==k?void 0:k.subtitle,i),D.classList.add("magicfeedback-sublabel"),(null===(c=null==k?void 0:k.subtitleStyle)||void 0===c?void 0:c.includes("italic"))&&(D.style.fontStyle="italic"),(null===(u=null==k?void 0:k.subtitleStyle)||void 0===u?void 0:u.includes("bold"))&&(D.style.fontWeight="bold"),(null===(p=null==k?void 0:k.subtitleStyle)||void 0===p?void 0:p.includes("underline"))&&(D.style.textDecoration="underline"),["CONSENT"].includes(v))C.classList.add("magicfeedback-consent-container"),C.appendChild(h),C.appendChild(I),C.appendChild(D);else{if("slim"!==t&&(C.appendChild(I),C.appendChild(D),void 0!==(null==k?void 0:k.general)&&""!==(null==k?void 0:k.general))){const Pe=document.createElement("img");Pe.src=null==k?void 0:k.general,Pe.classList.add("magicfeedback-image"),Pe.style.maxWidth="auto",Pe.style.height="400px",Pe.style.margin="10px 0",C.appendChild(Pe)}if("LONGTEXT"===v&&L>0){const Se=document.createElement("div");if(Se.classList.add("magicfeedback-counter"),Se.textContent=`${h.value.length}/${L}`,Se.style.textAlign="right",Se.style.fontSize="15px",Se.style.marginTop="5px",h.addEventListener("input",(()=>{Se.textContent=`${h.value.length}/${L}`})),C.appendChild(h),C.appendChild(Se),(null==k?void 0:k.extraOption)&&(null==k?void 0:k.extraOptionText)){const Oe=document.createElement("div");Oe.classList.add("magicfeedback-skip-container"),Oe.classList.add("magicfeedback-checkbox-container"),Oe.style.display="flex",Oe.style.justifyContent="flex-start";const Ne=document.createElement("input");Ne.classList.add("magicfeedback-skip"),Ne.type="checkbox",Ne.id=`skip-${y}`,Ne.name=y,Ne.value="-",Ne.style.cursor="pointer";const Ie=document.createElement("label");Ie.htmlFor=`skip-${y}`,Ie.textContent=null==k?void 0:k.extraOptionText,Ie.style.fontSize="15px",Ie.style.cursor="pointer",Ie.style.margin="0 5px",Ne.addEventListener("click",(()=>{h.value="-",d&&d()})),Oe.appendChild(Ne),Oe.appendChild(Ie),C.appendChild(Oe)}}else C.appendChild(h)}return C}(m,i,l,`${s}${p?`/${h}`:""}`,1===t.length?c:void 0);u.push(e)}})),u},t.renderActions=function(e="",t,i="Submit",n="Back",a="Next"){const s=document.createElement("div");s.classList.add("magicfeedback-action-container");const r=document.createElement("button");r.id="magicfeedback-submit",r.type="submit",r.classList.add("magicfeedback-submit"),r.textContent="MAGICSURVEY"===e?a||"Next":i||"Submit";const o=document.createElement("button");return o.id="magicfeedback-back",o.type="button",o.classList.add("magicfeedback-back"),o.textContent=n||"Back",o.addEventListener("click",t),o.addEventListener("click",(()=>{r.removeAttribute("disabled")})),"MAGICSURVEY"===e&&s.appendChild(o),s.appendChild(r),s},t.renderError=function(e){const t=document.createElement("div");return t.classList.add("magicfeedback-error"),t.textContent=e,t},t.renderSuccess=function(e){const t=document.createElement("div");return t.classList.add("magicfeedback-success"),t.textContent=e,t},t.renderStartMessage=function(e,t=!1,i="Go!",n=()=>{}){const a=document.createElement("div");a.classList.add("magicfeedback-start-message-container");const s=document.createElement("div");if(s.classList.add("magicfeedback-start-message"),s.innerHTML=e,a.appendChild(s),t){const e=document.createElement("button");e.id="magicfeedback-start-message-button",e.classList.add("magicfeedback-start-message-button"),e.textContent=i,e.addEventListener("click",(()=>n())),a.appendChild(e)}return a}},313:function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))((function(a,s){function r(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,o)}l((n=n.apply(e,t||[])).next())}))},a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getFollowUpQuestion=t.sendFeedback=t.getQuestions=t.getSessionForm=t.getForm=t.validateEmail=void 0;const s=a(i(945)),r=a(i(330)),o=i(857),l={Accept:"application/json","Magicfeedback-Sdk-Version":r.default.version,"x-magicfeedback-parameters":window.location.search||""};t.validateEmail=function(e){return/\S+@\S+\.\S+/.test(e)},t.getForm=function(e,t,i,a){return n(this,void 0,void 0,(function*(){try{const n=yield(0,s.default)(e+o.endpoints.sdk.app_info(t,i),{method:"GET",headers:l});return yield n.json()}catch(e){a.err(e)}}))},t.getSessionForm=function(e,t,i){return n(this,void 0,void 0,(function*(){try{const i=yield(0,s.default)(e+o.endpoints.sdk.session(t),{method:"GET",headers:l});return yield i.json()}catch(e){i.err(e)}}))},t.getQuestions=function(e,t,i,a){return n(this,void 0,void 0,(function*(){try{const n=yield(0,s.default)(e+o.endpoints.sdk.app(t,i),{method:"GET",headers:l});if(n.ok){const e=yield n.json();return a.log(`Received questions for app ${t}`,e),e}throw a.err(`Failed to get questions for app ${t}:`,n.status,n.statusText),new Error("[MagicFeedback] Bad response from server")}catch(e){return a.err(e),[]}}))},t.sendFeedback=function(e,t,i){return n(this,void 0,void 0,(function*(){try{const n=yield(0,s.default)(e+o.endpoints.sdk.feedback,{method:"POST",headers:Object.assign({"Content-Type":"application/json"},l),body:JSON.stringify(t)});if(n.ok)return i.log(`Form ${t.integration} submitted successfully!`),(yield n.json()).sessionId;throw i.err(`Failed to submit form ${t.integration}:`,n.status,n.statusText),new Error(n.statusText)}catch(e){return i.err(e),""}}))},t.getFollowUpQuestion=function(e,t,i){return n(this,void 0,void 0,(function*(){try{const n=yield(0,s.default)(e+o.endpoints.sdk.followUpQuestion,{method:"POST",headers:Object.assign({"Content-Type":"application/json"},l),body:JSON.stringify(t)});if(n.ok)return i.log(`Received follow up question for form ${t.integration}`),(yield n.json())||"";throw i.err(`Failed to get follow up question for form ${t.integration}:`,n.status,n.statusText),new Error(n.statusText)}catch(e){return i.err(e),""}}))}},256:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Log=void 0,t.Log=class{constructor(e){this.config=e}log(...e){this.config.get("debug")&&console.log("[MagicFeedback]:",...e)}err(...e){console.error("[MagicFeedback]:",...e)}}},330:e=>{"use strict";e.exports=JSON.parse('{"name":"@magicfeedback/native","version":"2.1.2-beta.5","main":"./dist/magicfeedback-sdk.node.js","browser":"./dist/magicfeedback-sdk.browser.js","types":"./dist/types/src/index.d.ts","repository":{"type":"git","url":"git+ssh://git@github.com/MagicFeedback/magicfeedback-sdk.git"},"author":"farias@magicfeedback.io","license":"MIT","private":false,"scripts":{"dev":"vite","build":"webpack","build:watch":"webpack --watch --mode development","publish":"npm publish --access public","publish:beta":"npm publish --access public --tag beta","publish:alpha":"npm publish --access public --tag alpha","test":"jest","test:watch":"jest --watchAll","coverage":"vitest run --coverage"},"files":["dist"],"devDependencies":{"@babel/preset-typescript":"^7.22.5","@types/node":"^17.0.21","@types/webpack":"^5.28.0","@types/webpack-node-externals":"^2.5.3","c8":"^7.11.0","copy-webpack-plugin":"^11.0.0","jest":"^29.5.0","jest-environment-jsdom":"^29.5.0","jest-fetch-mock":"^3.0.3","nock":"^13.2.4","ts-jest":"^29.1.0","ts-loader":"^9.2.7","ts-node":"^10.7.0","typescript":"^4.6.2","vite":"^2.8.0","vite-plugin-dts":"^0.9.9","vitest":"^0.5.9","webpack":"^5.70.0","webpack-cli":"^4.9.2","webpack-node-externals":"^3.0.0"},"dependencies":{"cross-fetch":"^3.1.5","is-bundling-for-browser-or-node":"^1.1.1"},"description":"MagicFeedbackAI JavaScript Library for [MagicFeedback.io](https://magicfeedback.io/)","bugs":{"url":"https://github.com/MagicFeedback/magicfeedback-sdk/issues"},"homepage":"https://github.com/MagicFeedback/magicfeedback-sdk#readme","directories":{"example":"examples","test":"test"},"style":"./dist/styles/magicfeedback-default.css"}')}},t={},function i(n){var a=t[n];if(void 0!==a)return a.exports;var s=t[n]={exports:{}};return e[n].call(s.exports,s,s.exports,i),s.exports}(156).default;var e,t}));
|
|
1
|
+
/*
|
|
2
|
+
* ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
|
|
3
|
+
* This devtool is neither made for production nor for readable output files.
|
|
4
|
+
* It uses "eval()" calls to create a separate source file in the browser devtools.
|
|
5
|
+
* If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
|
|
6
|
+
* or disable the default devtool with "devtool: false".
|
|
7
|
+
* If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
|
|
8
|
+
*/
|
|
9
|
+
(function webpackUniversalModuleDefinition(root, factory) {
|
|
10
|
+
if(typeof exports === 'object' && typeof module === 'object')
|
|
11
|
+
module.exports = factory();
|
|
12
|
+
else if(typeof define === 'function' && define.amd)
|
|
13
|
+
define([], factory);
|
|
14
|
+
else if(typeof exports === 'object')
|
|
15
|
+
exports["magicfeedback"] = factory();
|
|
16
|
+
else
|
|
17
|
+
root["magicfeedback"] = factory();
|
|
18
|
+
})(self, () => {
|
|
19
|
+
return /******/ (() => { // webpackBootstrap
|
|
20
|
+
/******/ var __webpack_modules__ = ({
|
|
21
|
+
|
|
22
|
+
/***/ "./node_modules/cross-fetch/dist/browser-ponyfill.js":
|
|
23
|
+
/*!***********************************************************!*\
|
|
24
|
+
!*** ./node_modules/cross-fetch/dist/browser-ponyfill.js ***!
|
|
25
|
+
\***********************************************************/
|
|
26
|
+
/***/ (function(module, exports) {
|
|
27
|
+
|
|
28
|
+
eval("var global = typeof self !== 'undefined' ? self : this;\nvar __self__ = (function () {\nfunction F() {\nthis.fetch = false;\nthis.DOMException = global.DOMException\n}\nF.prototype = global;\nreturn new F();\n})();\n(function(self) {\n\nvar irrelevant = (function (exports) {\n\n var support = {\n searchParams: 'URLSearchParams' in self,\n iterable: 'Symbol' in self && 'iterator' in Symbol,\n blob:\n 'FileReader' in self &&\n 'Blob' in self &&\n (function() {\n try {\n new Blob();\n return true\n } catch (e) {\n return false\n }\n })(),\n formData: 'FormData' in self,\n arrayBuffer: 'ArrayBuffer' in self\n };\n\n function isDataView(obj) {\n return obj && DataView.prototype.isPrototypeOf(obj)\n }\n\n if (support.arrayBuffer) {\n var viewClasses = [\n '[object Int8Array]',\n '[object Uint8Array]',\n '[object Uint8ClampedArray]',\n '[object Int16Array]',\n '[object Uint16Array]',\n '[object Int32Array]',\n '[object Uint32Array]',\n '[object Float32Array]',\n '[object Float64Array]'\n ];\n\n var isArrayBufferView =\n ArrayBuffer.isView ||\n function(obj) {\n return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1\n };\n }\n\n function normalizeName(name) {\n if (typeof name !== 'string') {\n name = String(name);\n }\n if (/[^a-z0-9\\-#$%&'*+.^_`|~]/i.test(name)) {\n throw new TypeError('Invalid character in header field name')\n }\n return name.toLowerCase()\n }\n\n function normalizeValue(value) {\n if (typeof value !== 'string') {\n value = String(value);\n }\n return value\n }\n\n // Build a destructive iterator for the value list\n function iteratorFor(items) {\n var iterator = {\n next: function() {\n var value = items.shift();\n return {done: value === undefined, value: value}\n }\n };\n\n if (support.iterable) {\n iterator[Symbol.iterator] = function() {\n return iterator\n };\n }\n\n return iterator\n }\n\n function Headers(headers) {\n this.map = {};\n\n if (headers instanceof Headers) {\n headers.forEach(function(value, name) {\n this.append(name, value);\n }, this);\n } else if (Array.isArray(headers)) {\n headers.forEach(function(header) {\n this.append(header[0], header[1]);\n }, this);\n } else if (headers) {\n Object.getOwnPropertyNames(headers).forEach(function(name) {\n this.append(name, headers[name]);\n }, this);\n }\n }\n\n Headers.prototype.append = function(name, value) {\n name = normalizeName(name);\n value = normalizeValue(value);\n var oldValue = this.map[name];\n this.map[name] = oldValue ? oldValue + ', ' + value : value;\n };\n\n Headers.prototype['delete'] = function(name) {\n delete this.map[normalizeName(name)];\n };\n\n Headers.prototype.get = function(name) {\n name = normalizeName(name);\n return this.has(name) ? this.map[name] : null\n };\n\n Headers.prototype.has = function(name) {\n return this.map.hasOwnProperty(normalizeName(name))\n };\n\n Headers.prototype.set = function(name, value) {\n this.map[normalizeName(name)] = normalizeValue(value);\n };\n\n Headers.prototype.forEach = function(callback, thisArg) {\n for (var name in this.map) {\n if (this.map.hasOwnProperty(name)) {\n callback.call(thisArg, this.map[name], name, this);\n }\n }\n };\n\n Headers.prototype.keys = function() {\n var items = [];\n this.forEach(function(value, name) {\n items.push(name);\n });\n return iteratorFor(items)\n };\n\n Headers.prototype.values = function() {\n var items = [];\n this.forEach(function(value) {\n items.push(value);\n });\n return iteratorFor(items)\n };\n\n Headers.prototype.entries = function() {\n var items = [];\n this.forEach(function(value, name) {\n items.push([name, value]);\n });\n return iteratorFor(items)\n };\n\n if (support.iterable) {\n Headers.prototype[Symbol.iterator] = Headers.prototype.entries;\n }\n\n function consumed(body) {\n if (body.bodyUsed) {\n return Promise.reject(new TypeError('Already read'))\n }\n body.bodyUsed = true;\n }\n\n function fileReaderReady(reader) {\n return new Promise(function(resolve, reject) {\n reader.onload = function() {\n resolve(reader.result);\n };\n reader.onerror = function() {\n reject(reader.error);\n };\n })\n }\n\n function readBlobAsArrayBuffer(blob) {\n var reader = new FileReader();\n var promise = fileReaderReady(reader);\n reader.readAsArrayBuffer(blob);\n return promise\n }\n\n function readBlobAsText(blob) {\n var reader = new FileReader();\n var promise = fileReaderReady(reader);\n reader.readAsText(blob);\n return promise\n }\n\n function readArrayBufferAsText(buf) {\n var view = new Uint8Array(buf);\n var chars = new Array(view.length);\n\n for (var i = 0; i < view.length; i++) {\n chars[i] = String.fromCharCode(view[i]);\n }\n return chars.join('')\n }\n\n function bufferClone(buf) {\n if (buf.slice) {\n return buf.slice(0)\n } else {\n var view = new Uint8Array(buf.byteLength);\n view.set(new Uint8Array(buf));\n return view.buffer\n }\n }\n\n function Body() {\n this.bodyUsed = false;\n\n this._initBody = function(body) {\n this._bodyInit = body;\n if (!body) {\n this._bodyText = '';\n } else if (typeof body === 'string') {\n this._bodyText = body;\n } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {\n this._bodyBlob = body;\n } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {\n this._bodyFormData = body;\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this._bodyText = body.toString();\n } else if (support.arrayBuffer && support.blob && isDataView(body)) {\n this._bodyArrayBuffer = bufferClone(body.buffer);\n // IE 10-11 can't handle a DataView body.\n this._bodyInit = new Blob([this._bodyArrayBuffer]);\n } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {\n this._bodyArrayBuffer = bufferClone(body);\n } else {\n this._bodyText = body = Object.prototype.toString.call(body);\n }\n\n if (!this.headers.get('content-type')) {\n if (typeof body === 'string') {\n this.headers.set('content-type', 'text/plain;charset=UTF-8');\n } else if (this._bodyBlob && this._bodyBlob.type) {\n this.headers.set('content-type', this._bodyBlob.type);\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');\n }\n }\n };\n\n if (support.blob) {\n this.blob = function() {\n var rejected = consumed(this);\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return Promise.resolve(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(new Blob([this._bodyArrayBuffer]))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as blob')\n } else {\n return Promise.resolve(new Blob([this._bodyText]))\n }\n };\n\n this.arrayBuffer = function() {\n if (this._bodyArrayBuffer) {\n return consumed(this) || Promise.resolve(this._bodyArrayBuffer)\n } else {\n return this.blob().then(readBlobAsArrayBuffer)\n }\n };\n }\n\n this.text = function() {\n var rejected = consumed(this);\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return readBlobAsText(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as text')\n } else {\n return Promise.resolve(this._bodyText)\n }\n };\n\n if (support.formData) {\n this.formData = function() {\n return this.text().then(decode)\n };\n }\n\n this.json = function() {\n return this.text().then(JSON.parse)\n };\n\n return this\n }\n\n // HTTP methods whose capitalization should be normalized\n var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];\n\n function normalizeMethod(method) {\n var upcased = method.toUpperCase();\n return methods.indexOf(upcased) > -1 ? upcased : method\n }\n\n function Request(input, options) {\n options = options || {};\n var body = options.body;\n\n if (input instanceof Request) {\n if (input.bodyUsed) {\n throw new TypeError('Already read')\n }\n this.url = input.url;\n this.credentials = input.credentials;\n if (!options.headers) {\n this.headers = new Headers(input.headers);\n }\n this.method = input.method;\n this.mode = input.mode;\n this.signal = input.signal;\n if (!body && input._bodyInit != null) {\n body = input._bodyInit;\n input.bodyUsed = true;\n }\n } else {\n this.url = String(input);\n }\n\n this.credentials = options.credentials || this.credentials || 'same-origin';\n if (options.headers || !this.headers) {\n this.headers = new Headers(options.headers);\n }\n this.method = normalizeMethod(options.method || this.method || 'GET');\n this.mode = options.mode || this.mode || null;\n this.signal = options.signal || this.signal;\n this.referrer = null;\n\n if ((this.method === 'GET' || this.method === 'HEAD') && body) {\n throw new TypeError('Body not allowed for GET or HEAD requests')\n }\n this._initBody(body);\n }\n\n Request.prototype.clone = function() {\n return new Request(this, {body: this._bodyInit})\n };\n\n function decode(body) {\n var form = new FormData();\n body\n .trim()\n .split('&')\n .forEach(function(bytes) {\n if (bytes) {\n var split = bytes.split('=');\n var name = split.shift().replace(/\\+/g, ' ');\n var value = split.join('=').replace(/\\+/g, ' ');\n form.append(decodeURIComponent(name), decodeURIComponent(value));\n }\n });\n return form\n }\n\n function parseHeaders(rawHeaders) {\n var headers = new Headers();\n // Replace instances of \\r\\n and \\n followed by at least one space or horizontal tab with a space\n // https://tools.ietf.org/html/rfc7230#section-3.2\n var preProcessedHeaders = rawHeaders.replace(/\\r?\\n[\\t ]+/g, ' ');\n preProcessedHeaders.split(/\\r?\\n/).forEach(function(line) {\n var parts = line.split(':');\n var key = parts.shift().trim();\n if (key) {\n var value = parts.join(':').trim();\n headers.append(key, value);\n }\n });\n return headers\n }\n\n Body.call(Request.prototype);\n\n function Response(bodyInit, options) {\n if (!options) {\n options = {};\n }\n\n this.type = 'default';\n this.status = options.status === undefined ? 200 : options.status;\n this.ok = this.status >= 200 && this.status < 300;\n this.statusText = 'statusText' in options ? options.statusText : 'OK';\n this.headers = new Headers(options.headers);\n this.url = options.url || '';\n this._initBody(bodyInit);\n }\n\n Body.call(Response.prototype);\n\n Response.prototype.clone = function() {\n return new Response(this._bodyInit, {\n status: this.status,\n statusText: this.statusText,\n headers: new Headers(this.headers),\n url: this.url\n })\n };\n\n Response.error = function() {\n var response = new Response(null, {status: 0, statusText: ''});\n response.type = 'error';\n return response\n };\n\n var redirectStatuses = [301, 302, 303, 307, 308];\n\n Response.redirect = function(url, status) {\n if (redirectStatuses.indexOf(status) === -1) {\n throw new RangeError('Invalid status code')\n }\n\n return new Response(null, {status: status, headers: {location: url}})\n };\n\n exports.DOMException = self.DOMException;\n try {\n new exports.DOMException();\n } catch (err) {\n exports.DOMException = function(message, name) {\n this.message = message;\n this.name = name;\n var error = Error(message);\n this.stack = error.stack;\n };\n exports.DOMException.prototype = Object.create(Error.prototype);\n exports.DOMException.prototype.constructor = exports.DOMException;\n }\n\n function fetch(input, init) {\n return new Promise(function(resolve, reject) {\n var request = new Request(input, init);\n\n if (request.signal && request.signal.aborted) {\n return reject(new exports.DOMException('Aborted', 'AbortError'))\n }\n\n var xhr = new XMLHttpRequest();\n\n function abortXhr() {\n xhr.abort();\n }\n\n xhr.onload = function() {\n var options = {\n status: xhr.status,\n statusText: xhr.statusText,\n headers: parseHeaders(xhr.getAllResponseHeaders() || '')\n };\n options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL');\n var body = 'response' in xhr ? xhr.response : xhr.responseText;\n resolve(new Response(body, options));\n };\n\n xhr.onerror = function() {\n reject(new TypeError('Network request failed'));\n };\n\n xhr.ontimeout = function() {\n reject(new TypeError('Network request failed'));\n };\n\n xhr.onabort = function() {\n reject(new exports.DOMException('Aborted', 'AbortError'));\n };\n\n xhr.open(request.method, request.url, true);\n\n if (request.credentials === 'include') {\n xhr.withCredentials = true;\n } else if (request.credentials === 'omit') {\n xhr.withCredentials = false;\n }\n\n if ('responseType' in xhr && support.blob) {\n xhr.responseType = 'blob';\n }\n\n request.headers.forEach(function(value, name) {\n xhr.setRequestHeader(name, value);\n });\n\n if (request.signal) {\n request.signal.addEventListener('abort', abortXhr);\n\n xhr.onreadystatechange = function() {\n // DONE (success or failure)\n if (xhr.readyState === 4) {\n request.signal.removeEventListener('abort', abortXhr);\n }\n };\n }\n\n xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit);\n })\n }\n\n fetch.polyfill = true;\n\n if (!self.fetch) {\n self.fetch = fetch;\n self.Headers = Headers;\n self.Request = Request;\n self.Response = Response;\n }\n\n exports.Headers = Headers;\n exports.Request = Request;\n exports.Response = Response;\n exports.fetch = fetch;\n\n Object.defineProperty(exports, '__esModule', { value: true });\n\n return exports;\n\n})({});\n})(__self__);\n__self__.fetch.ponyfill = true;\n// Remove \"polyfill\" property added by whatwg-fetch\ndelete __self__.fetch.polyfill;\n// Choose between native implementation (global) or custom implementation (__self__)\n// var ctx = global.fetch ? global : __self__;\nvar ctx = __self__; // this line disable service worker support temporarily\nexports = ctx.fetch // To enable: import fetch from 'cross-fetch'\nexports[\"default\"] = ctx.fetch // For TypeScript consumers without esModuleInterop.\nexports.fetch = ctx.fetch // To enable: import {fetch} from 'cross-fetch'\nexports.Headers = ctx.Headers\nexports.Request = ctx.Request\nexports.Response = ctx.Response\nmodule.exports = exports\n\n\n//# sourceURL=webpack://magicfeedback/./node_modules/cross-fetch/dist/browser-ponyfill.js?");
|
|
29
|
+
|
|
30
|
+
/***/ }),
|
|
31
|
+
|
|
32
|
+
/***/ "./src/config-globals.ts":
|
|
33
|
+
/*!*******************************!*\
|
|
34
|
+
!*** ./src/config-globals.ts ***!
|
|
35
|
+
\*******************************/
|
|
36
|
+
/***/ ((__unused_webpack_module, exports) => {
|
|
37
|
+
|
|
38
|
+
"use strict";
|
|
39
|
+
eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.HOST_API_URL_DEV = exports.HOST_API_URL = void 0;\nexports.HOST_API_URL = 'https://api.deepdots.com/';\nexports.HOST_API_URL_DEV = 'https://api-dev.deepdots.com/';\n\n\n//# sourceURL=webpack://magicfeedback/./src/config-globals.ts?");
|
|
40
|
+
|
|
41
|
+
/***/ }),
|
|
42
|
+
|
|
43
|
+
/***/ "./src/index.ts":
|
|
44
|
+
/*!**********************!*\
|
|
45
|
+
!*** ./src/index.ts ***!
|
|
46
|
+
\**********************/
|
|
47
|
+
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
|
|
48
|
+
|
|
49
|
+
"use strict";
|
|
50
|
+
eval("\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst main_1 = __importDefault(__webpack_require__(/*! ./main */ \"./src/main.ts\"));\nlet instance = null;\nif (!instance) {\n instance = (0, main_1.default)();\n}\nexports[\"default\"] = instance;\n\n\n//# sourceURL=webpack://magicfeedback/./src/index.ts?");
|
|
51
|
+
|
|
52
|
+
/***/ }),
|
|
53
|
+
|
|
54
|
+
/***/ "./src/main.ts":
|
|
55
|
+
/*!*********************!*\
|
|
56
|
+
!*** ./src/main.ts ***!
|
|
57
|
+
\*********************/
|
|
58
|
+
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
|
|
59
|
+
|
|
60
|
+
"use strict";
|
|
61
|
+
eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nconst form_1 = __webpack_require__(/*! ./models/form */ \"./src/models/form.ts\");\nconst config_1 = __webpack_require__(/*! ./models/config */ \"./src/models/config.ts\");\nconst log_1 = __webpack_require__(/*! ./utils/log */ \"./src/utils/log.ts\");\nconst request_service_1 = __webpack_require__(/*! ./services/request.service */ \"./src/services/request.service.ts\");\nconst config_globals_1 = __webpack_require__(/*! ./config-globals */ \"./src/config-globals.ts\");\n/**\n *\n * @returns\n */\nfunction main() {\n //===============================================\n // Attributes\n //===============================================\n const config = new config_1.Config();\n let log;\n /**\n *\n * @param options\n */\n function init(options) {\n if (options === null || options === void 0 ? void 0 : options.debug)\n config.set(\"debug\", options === null || options === void 0 ? void 0 : options.debug);\n config.set(\"url\", (options === null || options === void 0 ? void 0 : options.env) && (options === null || options === void 0 ? void 0 : options.env) === \"dev\" ? config_globals_1.HOST_API_URL_DEV : config_globals_1.HOST_API_URL);\n config.set(\"env\", options === null || options === void 0 ? void 0 : options.env);\n log = new log_1.Log(config);\n log.log(\"Initialized Magicfeedback\", config);\n }\n /**\n *\n * @param appId\n * @param publicKey\n * @param feedback\n * @param id\n * @param completed\n * @param privateKey\n * @returns\n */\n function send(appId, publicKey, feedback, completed = true, id, privateKey) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!appId)\n log.err(\"No appID provided\");\n if (!publicKey)\n log.err(\"No publicKey provided\");\n if (!feedback)\n log.err(\"No feedback provided\");\n if (!feedback.answers &&\n !feedback.profile &&\n !feedback.metrics &&\n !feedback.metadata)\n log.err(\"No feedback data provided\");\n const url = config.get(\"url\");\n const body = {\n integration: appId,\n publicKey: publicKey,\n privateKey: privateKey,\n completed: completed,\n id: id,\n feedback: feedback,\n };\n try {\n const res = yield (0, request_service_1.sendFeedback)(url, body, log);\n log.log(`sent native feedback`);\n return res;\n }\n catch (e) {\n log.err(`error native feedback`, e);\n return false;\n }\n });\n }\n /**\n *\n * @param appId\n * @param publicKey\n * @returns\n */\n function form(appId, publicKey) {\n if (!appId)\n log.err(\"No appID provided\");\n if (!publicKey)\n log.err(\"No publicKey provided\");\n return new form_1.Form(config, appId, publicKey);\n }\n /**\n *\n * @param sessionId\n * @returns\n */\n function session(sessionId) {\n if (!sessionId)\n log.err(\"No sessionId provided\");\n return new form_1.Form(config, sessionId);\n }\n //===============================================\n // Return\n //===============================================\n return {\n // lifecycle\n init,\n // requests\n send,\n form,\n session,\n };\n}\nexports[\"default\"] = main;\n\n\n//# sourceURL=webpack://magicfeedback/./src/main.ts?");
|
|
62
|
+
|
|
63
|
+
/***/ }),
|
|
64
|
+
|
|
65
|
+
/***/ "./src/models/History.ts":
|
|
66
|
+
/*!*******************************!*\
|
|
67
|
+
!*** ./src/models/History.ts ***!
|
|
68
|
+
\*******************************/
|
|
69
|
+
/***/ ((__unused_webpack_module, exports) => {
|
|
70
|
+
|
|
71
|
+
"use strict";
|
|
72
|
+
eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.History = void 0;\nclass History {\n constructor() {\n this.items = [];\n }\n // Adds an element to the back of the queue\n enqueue(element) {\n this.items.push(element);\n }\n // Removes the element from the front of the queue\n dequeue() {\n return this.items.shift();\n }\n // Removes the element from the back of the queue\n rollback() {\n return this.items.pop();\n }\n // Returns the element at the front of the queue without removing it\n front() {\n return this.items[0];\n }\n // Returns the element at the back of the queue without removing it\n back() {\n return this.items[this.items.length - 1];\n }\n // Checks if the queue is empty\n isEmpty() {\n return this.items.length === 0;\n }\n // Returns the number of elements in the queue\n size() {\n return this.items.length;\n }\n // Return the element by index\n get(index) {\n return this.items[index];\n }\n}\nexports.History = History;\n\n\n//# sourceURL=webpack://magicfeedback/./src/models/History.ts?");
|
|
73
|
+
|
|
74
|
+
/***/ }),
|
|
75
|
+
|
|
76
|
+
/***/ "./src/models/config.ts":
|
|
77
|
+
/*!******************************!*\
|
|
78
|
+
!*** ./src/models/config.ts ***!
|
|
79
|
+
\******************************/
|
|
80
|
+
/***/ ((__unused_webpack_module, exports) => {
|
|
81
|
+
|
|
82
|
+
"use strict";
|
|
83
|
+
eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.Config = void 0;\nclass Config {\n constructor() {\n this.variables = {};\n this.variables[\"env\"] = 'prod';\n this.variables[\"debug\"] = false;\n }\n get(key) {\n return this.variables[key];\n }\n set(key, value) {\n this.variables[key] = value;\n }\n}\nexports.Config = Config;\n\n\n//# sourceURL=webpack://magicfeedback/./src/models/config.ts?");
|
|
84
|
+
|
|
85
|
+
/***/ }),
|
|
86
|
+
|
|
87
|
+
/***/ "./src/models/form.ts":
|
|
88
|
+
/*!****************************!*\
|
|
89
|
+
!*** ./src/models/form.ts ***!
|
|
90
|
+
\****************************/
|
|
91
|
+
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
|
|
92
|
+
|
|
93
|
+
"use strict";
|
|
94
|
+
eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.Form = void 0;\nconst types_1 = __webpack_require__(/*! ./types */ \"./src/models/types.ts\");\nconst log_1 = __webpack_require__(/*! ../utils/log */ \"./src/utils/log.ts\");\nconst request_service_1 = __webpack_require__(/*! ../services/request.service */ \"./src/services/request.service.ts\");\nconst questions_service_1 = __webpack_require__(/*! ../services/questions.service */ \"./src/services/questions.service.ts\");\nconst pageGrafs_1 = __webpack_require__(/*! ./pageGrafs */ \"./src/models/pageGrafs.ts\");\nconst page_1 = __webpack_require__(/*! ./page */ \"./src/models/page.ts\");\nconst pageRoute_1 = __webpack_require__(/*! ./pageRoute */ \"./src/models/pageRoute.ts\");\nconst History_1 = __webpack_require__(/*! ./History */ \"./src/models/History.ts\");\nconst pageNode_1 = __webpack_require__(/*! ./pageNode */ \"./src/models/pageNode.ts\");\nclass Form {\n /**\n *\n * @param config\n * @param appId\n * @param publicKey\n */\n constructor(config, appId, publicKey) {\n // SDK Config\n this.config = config;\n this.log = new log_1.Log(config);\n // Form options\n this.formOptionsConfig = {\n addButton: true,\n sendButtonText: \"Send\",\n backButtonText: \"Back\",\n nextButtonText: \"Next\",\n addSuccessScreen: true,\n getMetaData: true,\n questionFormat: \"standard\",\n };\n this.selector = \"\";\n // Attributes\n this.appId = appId;\n this.publicKey = publicKey || '';\n this.url = config.get(\"url\");\n // Form completed data\n this.id = \"\";\n this.formData = null;\n // if (this.publicKey !== '') this.getDataFromStorage();\n this.feedback = {\n text: \"\",\n answers: [],\n profile: [],\n metrics: [],\n metadata: [],\n };\n this.history = new History_1.History();\n this.graph = new pageGrafs_1.PageGraph([]);\n // Count variables\n this.progress = 0;\n this.total = 0;\n this.completed = false;\n this.timeToCompleted = 0;\n }\n /**\n * Get data from the local storage, if the data is older than 24 hours, get the data from the server\n * @private\n\n private getDataFromStorage() {\n const localForm = localStorage.getItem(`magicfeedback-${this.appId}`);\n\n if (localForm && new Date(JSON.parse(localForm).savedAt) < new Date(new Date().getTime() + 60 * 60 * 24 * 1000)) {\n this.formData = JSON.parse(localForm);\n getForm(this.url, this.appId, this.publicKey, this.log).then((form: FormData | null) => {\n if (form?.updatedAt && this.formData?.savedAt && form?.updatedAt > this.formData?.savedAt) {\n // console.log(\"Form updated\");\n this.formData = form;\n this.formData.savedAt = new Date();\n\n localStorage.setItem(`magicfeedback-${this.appId}`, JSON.stringify(this.formData));\n\n if (this.formData.questions === undefined || !this.formData.questions) throw new Error(`No questions for app ${this.appId}`);\n\n if (!this.formData.pages || this.formData.pages?.length === 0) this.formatPages();\n this.formData.questions?.sort((a, b) => a.position - b.position);\n // Clear pages without questions\n this.formData.pages = this.formData.pages.filter((page) => page.integrationQuestions?.length > 0);\n\n // Create the form from the JSON\n this.formData.style?.startMessage ?\n this.generateWelcomeMessage(this.formData.style.startMessage) :\n this.startForm();\n }\n });\n }\n }\n **/\n /**\n * Generate\n * @param selector\n * @param options\n */\n generate(selector, options) {\n var _a, _b, _c, _d, _e, _f, _g;\n return __awaiter(this, void 0, void 0, function* () {\n // Check options, and set default values if this is not defined\n try {\n // Set the options\n this.formOptionsConfig = Object.assign(Object.assign({}, this.formOptionsConfig), options);\n this.selector = selector;\n let resData = this.formData;\n if (this.formData === undefined || !this.formData)\n resData = this.publicKey !== '' ?\n yield (0, request_service_1.getForm)(this.url, this.appId, this.publicKey, this.log) :\n yield (0, request_service_1.getSessionForm)(this.url, this.appId, this.log);\n if (resData === undefined || !resData)\n throw new Error(`No data for app ${this.appId}`);\n if ((_a = resData.error) === null || _a === void 0 ? void 0 : _a.message)\n throw new Error(resData.error.message);\n // Clear questions without status ACTIVE\n resData.questions = ((_b = resData.questions) === null || _b === void 0 ? void 0 : _b.filter((q) => q.status === 'ACTIVE')) || [];\n resData.pages = ((_c = resData.pages) === null || _c === void 0 ? void 0 : _c.filter((p) => p.status === 'ACTIVE')) || [];\n ((_d = resData.pages) === null || _d === void 0 ? void 0 : _d.forEach((p) => { var _a; return p.integrationQuestions = (_a = p.integrationQuestions) === null || _a === void 0 ? void 0 : _a.filter((q) => q.status === 'ACTIVE'); })) || [];\n this.formData = resData;\n if (!this.formData.savedAt) {\n // Save formData in the localstorage to use it in the future\n this.formData.savedAt = new Date();\n localStorage.setItem(`magicfeedback-${this.appId}`, JSON.stringify(this.formData));\n }\n if (this.formData.questions === undefined || !this.formData.questions)\n throw new Error(`No questions for app ${this.appId}`);\n if (!this.formData.pages || ((_e = this.formData.pages) === null || _e === void 0 ? void 0 : _e.length) === 0)\n this.formatPages();\n (_f = this.formData.questions) === null || _f === void 0 ? void 0 : _f.sort((a, b) => a.position - b.position);\n // Clear pages without questions\n this.formData.pages = this.formData.pages.filter((page) => { var _a; return ((_a = page.integrationQuestions) === null || _a === void 0 ? void 0 : _a.length) > 0; });\n if (this.formOptionsConfig.getMetaData)\n this.getMetaData();\n // If this.formData.product.originAllowed exists, check if the current domain is in the list\n // EJ originAllowed :[\"*\", \"survey.99thstudio.com\"]\n // \"*\" means that: all domains from deepdots.com are allowed\n // if is development, dont check the origin\n /* if (this.config.get('env') !== 'dev' && this.formData.product.originAllowed && this.formData.product.originAllowed.length > 0) {\n const domain = window.location.hostname;\n const allowed = this.formData.product.originAllowed.find((d: string) => d === domain || (d === '*' && domain.endsWith('.deepdots.com') || d === '*' && domain.endsWith('.magicfeedback.io')));\n if (!allowed) throw new Error(`Domain not allowed`);\n } */\n ((_g = this.formData.style) === null || _g === void 0 ? void 0 : _g.startMessage) ?\n yield this.generateWelcomeMessage(this.formData.style.startMessage) :\n this.startForm();\n }\n catch (e) {\n this.log.err(e);\n if (this.formOptionsConfig.onLoadedEvent) {\n yield this.formOptionsConfig.onLoadedEvent({\n loading: false,\n error: e,\n });\n }\n return;\n }\n });\n }\n /**\n * Format pages in case of the survey don't have pages\n * @private\n */\n formatPages() {\n var _a;\n if (!this.formData)\n return;\n switch (this.formData.identity) {\n case 'MAGICSURVEY':\n // In this case we will create a page for each question\n this.formData.pages = [];\n (_a = this.formData.questions) === null || _a === void 0 ? void 0 : _a.forEach((question) => {\n var _a, _b;\n const route = new pageRoute_1.PageRoute(question.id, question.ref, pageRoute_1.OperatorType.NOEQUAL, [], pageRoute_1.TransitionType.PAGE, (question.position + 1).toString(), question.position.toString());\n const page = new page_1.Page(question.position.toString(), question.position, this.appId, [question], [route]);\n (_b = (_a = this.formData) === null || _a === void 0 ? void 0 : _a.pages) === null || _b === void 0 ? void 0 : _b.push(page);\n });\n break;\n case 'MAGICFORM':\n // In this case we will create a page with all the questions\n const page = new page_1.Page('1', 1, this.appId, this.formData.questions, []);\n this.formData.pages = [page];\n break;\n }\n }\n /**\n * Generate container\n * @returns\n */\n generateContainer() {\n // Select and prepare the container\n let container = document.getElementById(this.selector);\n if (!container) {\n container = document.getElementById(\"magicfeedback-container-\" + this.appId);\n if (!container)\n throw new Error(`Element with ID '${this.selector}' not found.`);\n }\n container.classList.add(\"magicfeedback-container\");\n container.id = \"magicfeedback-container-\" + this.appId;\n container.innerHTML = \"\";\n return container;\n }\n /**\n * Generate form\n * @private\n * @returns void\n */\n generateForm() {\n var _a, _b, _c, _d;\n return __awaiter(this, void 0, void 0, function* () {\n try {\n console.log('Generating form for appId:', this.appId);\n if (!this.formData || !this.formData.pages || this.formData.pages.length === 0) {\n throw new Error(\"No form data\");\n }\n this.graph = new pageGrafs_1.PageGraph(this.formData.pages.sort((a, b) => a.position - b.position));\n // Select and prepare the container\n let container = this.generateContainer();\n // Create the form\n const form = document.createElement(\"form\");\n form.classList.add(\"magicfeedback-form\");\n form.id = \"magicfeedback-\" + this.appId;\n // Prevent reload on submit\n form.addEventListener(\"submit\", (event) => event.preventDefault());\n // Create the questions container\n const questionContainer = document.createElement(\"div\");\n questionContainer.classList.add(\"magicfeedback-questions\");\n questionContainer.id = \"magicfeedback-questions-\" + this.appId;\n const page = this.graph.getFirstPage();\n if (!page)\n throw new Error(\"No page found\");\n this.total = this.graph.findMaxDepth();\n // Process questions and create in the form\n page.elements = (0, questions_service_1.renderQuestions)(page.questions, this.formOptionsConfig.questionFormat, (_a = this.formData) === null || _a === void 0 ? void 0 : _a.lang[0], (_b = this.formData) === null || _b === void 0 ? void 0 : _b.product, () => this.send());\n (_c = page.elements) === null || _c === void 0 ? void 0 : _c.forEach((element) => questionContainer.appendChild(element));\n form.appendChild(questionContainer);\n // Add the new page to the history\n this.history.enqueue(page);\n // Add the form to the specified container\n container.appendChild(form);\n // Update the progress\n this.progress = this.total - this.graph.findMaxDepth(page);\n // Submit button\n if (this.formOptionsConfig.addButton) {\n // Create a container for the buttons\n const actionContainer = (0, questions_service_1.renderActions)((_d = this.formData) === null || _d === void 0 ? void 0 : _d.identity, () => this.back(), this.formOptionsConfig.sendButtonText, this.formOptionsConfig.backButtonText, this.formOptionsConfig.nextButtonText);\n form.appendChild(actionContainer);\n }\n if (this.formOptionsConfig.addButton) {\n // Submit event\n form.addEventListener(\"submit\", (event) => {\n event.preventDefault();\n this.send();\n });\n }\n // init time to complete in seconds\n this.timeToCompleted = new Date().getTime() / 1000;\n // Send the data to manage loadings and progress\n if (this.formOptionsConfig.onLoadedEvent) {\n yield this.formOptionsConfig.onLoadedEvent({\n loading: false,\n progress: this.progress,\n total: this.total,\n formData: this.formData,\n });\n }\n }\n catch (e) {\n this.log.err(e);\n if (this.formOptionsConfig.onLoadedEvent) {\n this.formOptionsConfig.onLoadedEvent({\n loading: false,\n error: e,\n });\n }\n return;\n }\n });\n }\n /**\n * Start form after the welcome message, mainly used in the start message\n * @public\n **/\n startForm() {\n this.generateForm();\n }\n /**\n * Generate welcome message page if the form has a start message,with a button to start the form\n * @private\n */\n generateWelcomeMessage(startMessage) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n // Select and prepare the container\n const container = this.generateContainer();\n const initialMessage = (0, questions_service_1.renderStartMessage)(startMessage, this.formOptionsConfig.addButton, this.formOptionsConfig.startButtonText, () => this.startForm());\n container.appendChild(initialMessage);\n // Send the data to manage loadings and progress\n if (this.formOptionsConfig.onLoadedEvent) {\n yield this.formOptionsConfig.onLoadedEvent({\n loading: false,\n formData: this.formData,\n });\n }\n }\n catch (e) {\n this.log.err(e);\n if (this.formOptionsConfig.onLoadedEvent) {\n this.formOptionsConfig.onLoadedEvent({\n loading: false,\n error: e,\n });\n }\n return;\n }\n });\n }\n /**\n * Get the metadata from the URL, navigators and others\n * @private\n */\n getMetaData() {\n // Add the navigator url and params from the URL to the metadata\n this.feedback.metadata.push({ key: \"navigator-url\", value: [window.location.href] });\n this.feedback.metadata.push({ key: \"navigator-origin\", value: [window.location.origin] });\n this.feedback.metadata.push({ key: \"navigator-pathname\", value: [window.location.pathname] });\n this.feedback.metadata.push({ key: \"navigator-search\", value: [window.location.search] });\n // Add the navigator metadata\n this.feedback.metadata.push({ key: \"navigator-user\", value: [navigator.userAgent] });\n this.feedback.metadata.push({ key: \"navigator-language\", value: [navigator.language] });\n this.feedback.metadata.push({ key: \"navigator-platform\", value: [navigator.platform] });\n this.feedback.metadata.push({ key: \"navigator-appVersion\", value: [navigator.appVersion] });\n this.feedback.metadata.push({ key: \"navigator-appName\", value: [navigator.appName] });\n this.feedback.metadata.push({ key: \"navigator-product\", value: [navigator.product] });\n // Add the size of the screen\n this.feedback.metadata.push({ key: \"screen-width\", value: [window.screen.width.toString()] });\n this.feedback.metadata.push({ key: \"screen-height\", value: [window.screen.height.toString()] });\n if (this.appId && this.publicKey === '') {\n // Add the session id to the metadata\n this.feedback.metadata.push({ key: \"MAGICFEEDBACK_SESSION\", value: [this.appId] });\n }\n }\n /**\n * Send current answer and verify if its necessary continue with a new question\n * @pubilc\n * @param profile\n * @param metrics\n * @param metadata\n */\n send(metadata, metrics, profile) {\n return __awaiter(this, void 0, void 0, function* () {\n const questionContainer = document.getElementById(\"magicfeedback-questions-\" + this.appId);\n try {\n if (profile)\n this.feedback.profile = [...this.feedback.profile, ...profile];\n if (metrics)\n this.feedback.metrics = [...this.feedback.metrics, ...metrics];\n if (metadata)\n this.feedback.metadata = [...this.feedback.metadata, ...metadata];\n // Get the survey answers from the answer() function\n this.answer();\n // BEFORE\n if (this.formOptionsConfig.beforeSubmitEvent) {\n yield this.formOptionsConfig.beforeSubmitEvent({\n loading: true,\n // answer: this.feedback.answers,\n progress: this.progress,\n total: this.total\n });\n }\n // Check if the required questions are answered\n const page = this.history.back();\n if (!page)\n throw new Error(\"No page found\");\n for (const question of page.questions.filter(question => question.require &&\n ![types_1.FEEDBACKAPPANSWERTYPE.CONSENT, types_1.FEEDBACKAPPANSWERTYPE.INFO_PAGE].includes(question.type))) {\n const assets = question.assets;\n const ans = this.feedback.answers.filter((a) => a.key.includes(question.ref) && !a.key.includes('extra-option'));\n if (ans.length === 0 ||\n ans.find((a) => a.value.length === 0)) {\n this.log.err(`The question ${question.ref} is required`);\n throw new Error(`No response`);\n }\n if (assets === null || assets === void 0 ? void 0 : assets.minOptions) {\n let exclusiveAnswers = [];\n if (assets === null || assets === void 0 ? void 0 : assets.exclusiveAnswers) {\n exclusiveAnswers = assets === null || assets === void 0 ? void 0 : assets.exclusiveAnswers;\n }\n // Check if the question has the minimum number of options selected and the exclusiveAnswers if it exists\n if (!ans[0].value.find((a) => exclusiveAnswers.includes(a)) &&\n ans[0].value.length < (assets === null || assets === void 0 ? void 0 : assets.minOptions)) {\n this.log.err(`The question ${question.ref} requires at least ${assets === null || assets === void 0 ? void 0 : assets.minOptions} options`);\n throw new Error(`No response`);\n }\n }\n }\n // SEND\n const response = yield this.pushAnswers(false);\n if (!response)\n throw new Error(\"No response\");\n this.id = response;\n yield this.processNextQuestion(questionContainer);\n }\n catch (error) {\n // Handle error in beforeSubmitEvent, send(), or afterSubmitEvent\n this.log.err(`An error occurred while submitting the form ${this.appId}:`, error);\n if (this.formOptionsConfig.afterSubmitEvent) {\n yield this.formOptionsConfig.afterSubmitEvent({\n loading: false,\n progress: this.progress,\n total: this.total,\n error\n });\n }\n }\n });\n }\n /**\n * Update feedback -> answers with the answers of the form in a JSON format\n * @returns\n * @public\n */\n answer() {\n const form = document.getElementById(\"magicfeedback-\" + this.appId);\n if (!form) {\n this.log.err(`Form \"${form}\" not found.`);\n this.feedback.answers = [];\n return;\n }\n // Check if the required questions are answered\n const page = this.history.back();\n if (!page)\n throw new Error(\"No page found\");\n const surveyAnswers = [];\n let hasError = false; // Flag to track if an error has occurred\n const inputs = form.querySelectorAll(\".magicfeedback-input\");\n inputs.forEach((input) => {\n const question = page.questions.find(q => { var _a; return (_a = input.name) === null || _a === void 0 ? void 0 : _a.includes(q.ref); });\n const inputType = input.type;\n const elementTypeClass = input.classList[0];\n const ans = {\n key: input.name,\n value: [],\n };\n const value = elementTypeClass === 'magicfeedback-consent' ?\n input.checked.toString() :\n input.value;\n if (!ans.key || ans.key === \"\")\n return;\n switch (question === null || question === void 0 ? void 0 : question.type) {\n case types_1.FEEDBACKAPPANSWERTYPE.EMAIL:\n case types_1.FEEDBACKAPPANSWERTYPE.TEXT:\n case types_1.FEEDBACKAPPANSWERTYPE.LONGTEXT:\n case types_1.FEEDBACKAPPANSWERTYPE.NUMBER:\n case types_1.FEEDBACKAPPANSWERTYPE.DATE:\n case types_1.FEEDBACKAPPANSWERTYPE.CONTACT:\n if (value !== \"\") {\n if (inputType === \"email\") {\n if (!(0, request_service_1.validateEmail)(value)) {\n this.log.err(\"Invalid email\");\n hasError = true;\n break;\n }\n else {\n this.feedback.profile.push({\n key: \"email\",\n value: [value],\n });\n }\n }\n ans.value.push(value);\n }\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.CONSENT:\n ans.value.push(String(input.checked));\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.POINT_SYSTEM:\n const key = input.id;\n ans.value.push(`${key}:${value}%`);\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.MULTIPLECHOICE:\n case types_1.FEEDBACKAPPANSWERTYPE.MULTIPLECHOISE_IMAGE:\n case types_1.FEEDBACKAPPANSWERTYPE.RATING_STAR:\n case types_1.FEEDBACKAPPANSWERTYPE.RADIO:\n case types_1.FEEDBACKAPPANSWERTYPE.RATING_EMOJI:\n case types_1.FEEDBACKAPPANSWERTYPE.RATING_NUMBER:\n if (input.checked || input.id.includes(\"extra-option-\")) {\n ans.value.push(value);\n }\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.SELECT:\n ans.value.push(value);\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.BOOLEAN:\n if (input.checked) {\n ans.value.push(value);\n }\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.MULTI_QUESTION_MATRIX:\n if (input.checked) {\n ans.value.push(value);\n }\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.PRIORITY_LIST:\n ans.value.push(value);\n break;\n default:\n break;\n }\n if ((surveyAnswers === null || surveyAnswers === void 0 ? void 0 : surveyAnswers.length) > 0 && (surveyAnswers === null || surveyAnswers === void 0 ? void 0 : surveyAnswers.find(a => a.key === ans.key))) {\n const index = surveyAnswers.findIndex(a => a.key === ans.key);\n surveyAnswers[index].value = [...surveyAnswers[index].value, ...ans.value];\n }\n else {\n surveyAnswers.push(ans);\n }\n });\n if (hasError) {\n this.feedback.answers = []; // Stop the process if there's an error\n page.setAnswer([]);\n return;\n }\n // --- Agrupación especial para MULTI_QUESTION_MATRIX ---\n try {\n const matrixQuestions = page.questions.filter(q => q.type === types_1.FEEDBACKAPPANSWERTYPE.MULTI_QUESTION_MATRIX);\n matrixQuestions.forEach(mq => {\n // Respuestas individuales capturadas como ref-rowName\n const rowPrefix = mq.ref + '-';\n const rowAnswers = surveyAnswers.filter(a => a.key.startsWith(rowPrefix));\n if (rowAnswers.length === 0)\n return; // nada que agrupar\n // Crear estructura: [{ key: rowName, value: [selected] }, ...]\n const groupedRows = rowAnswers.map(r => ({\n key: r.key.substring(rowPrefix.length),\n value: r.value\n }));\n // El formato requerido: valor debe ser un array que contiene (una sola posición) un array de objetos fila\n const matrixAnswer = {\n key: mq.ref,\n value: [JSON.stringify(groupedRows)]\n };\n // Eliminar las respuestas individuales\n for (const ra of rowAnswers) {\n const idx = surveyAnswers.findIndex(s => s.key === ra.key);\n if (idx !== -1)\n surveyAnswers.splice(idx, 1);\n }\n // Añadir (o reemplazar si ya existiera) la respuesta agrupada\n const existingIndex = surveyAnswers.findIndex(a => a.key === mq.ref);\n if (existingIndex !== -1) {\n surveyAnswers[existingIndex] = matrixAnswer;\n }\n else {\n surveyAnswers.push(matrixAnswer);\n }\n });\n }\n catch (e) {\n this.log.err('Error agrupando MULTI_QUESTION_MATRIX', e);\n }\n this.feedback.answers = surveyAnswers;\n page.setAnswer(surveyAnswers);\n }\n /**\n * Finish the form\n * @public\n */\n finish() {\n return __awaiter(this, void 0, void 0, function* () {\n this.completed = true;\n this.timeToCompleted = new Date().getTime() - this.timeToCompleted;\n this.feedback.metadata.push({ key: \"time-to-complete\", value: [this.timeToCompleted.toString()] });\n if (this.formOptionsConfig.addSuccessScreen) {\n const container = document.getElementById(\"magicfeedback-container-\" + this.appId);\n // Remove the form\n if (container.childNodes.length > 0)\n container.removeChild(container.childNodes[0]);\n // Show the success message\n const successMessage = (0, questions_service_1.renderSuccess)(this.formOptionsConfig.successMessage ||\n \"Thank you for your feedback!\");\n container.appendChild(successMessage);\n }\n this.answer();\n try {\n const response = yield this.pushAnswers(true);\n if (!response) {\n if (this.formOptionsConfig.afterSubmitEvent) {\n yield this.formOptionsConfig.afterSubmitEvent({\n loading: false,\n progress: this.progress,\n total: this.total,\n completed: this.completed,\n error: `An error occurred while submitting the form ${this.appId}:`\n });\n }\n throw new Error(\"An error occurred while submitting the form ${this.appId}:\");\n }\n this.id = response;\n // AFTER\n if (this.formOptionsConfig.afterSubmitEvent) {\n yield this.formOptionsConfig.afterSubmitEvent({\n response: this.id,\n loading: false,\n progress: this.progress,\n total: this.total,\n completed: this.completed,\n error: null\n });\n }\n }\n catch (error) {\n // Handle error in beforeSubmitEvent, send(), or afterSubmitEvent\n this.log.err(`An error occurred while submitting the form ${this.appId}:`, error);\n if (this.formOptionsConfig.afterSubmitEvent) {\n yield this.formOptionsConfig.afterSubmitEvent({\n loading: false,\n progress: this.progress,\n total: this.total,\n completed: this.completed,\n error\n });\n }\n }\n });\n }\n /**\n * Send\n * @param completed\n * @returns\n */\n pushAnswers(completed = false) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n // Define the URL and request payload\n const url = this.config.get(\"url\");\n const body = {\n integration: this.appId,\n publicKey: this.publicKey,\n feedback: this.feedback,\n completed,\n };\n // Make the AJAX POST request\n return yield (0, request_service_1.sendFeedback)(url, this.id ? Object.assign(Object.assign({}, body), { sessionId: this.id }) : body, this.log);\n }\n catch (error) {\n // Handle network or request error\n this.log.err(`An error occurred while submitting the form ${this.appId}:`, error);\n // You can perform error handling logic here if needed\n return '';\n }\n });\n }\n /**\n * Call follow up question\n * @param question\n * @private\n */\n callFollowUpQuestion(question) {\n var _a;\n return __awaiter(this, void 0, void 0, function* () {\n if (!(question === null || question === void 0 ? void 0 : question.followup))\n return null;\n try {\n if (this.feedback.answers.length === 0)\n throw new Error(\"No answers provided\");\n // Define the URL and request payload\n const url = this.config.get(\"url\");\n const body = Object.assign(Object.assign(Object.assign({ answer: (_a = this.feedback.answers.find((a) => a.key === question.ref)) === null || _a === void 0 ? void 0 : _a.value[0] }, (this.publicKey !== '' && { publicKey: this.publicKey })), (this.publicKey === '' && { campaignSessionId: this.appId })), { sessionId: this.id, question });\n return yield (0, request_service_1.getFollowUpQuestion)(url, body, this.log);\n }\n catch (error) {\n // Handle network or request error\n this.log.err(`An error occurred while submitting the form ${this.appId}:`, error);\n // You can perform error handling logic here if needed\n throw error;\n }\n });\n }\n /**\n * Process next question\n * @param form\n * @private\n */\n processNextQuestion(form) {\n var _a, _b, _c;\n return __awaiter(this, void 0, void 0, function* () {\n const page = this.history.back();\n if (!page)\n throw new Error(\"No page found\");\n const followUpList = page.getFollowupQuestions();\n if ((followUpList === null || followUpList === void 0 ? void 0 : followUpList.length) === 0) {\n yield this.renderNextQuestion(form, page);\n return;\n }\n const followUpQuestions = [];\n for (const followUp of followUpList) {\n const question = page.questions.find((q) => q.ref === followUp);\n if (question) {\n const followUpQuestion = yield this.callFollowUpQuestion(question);\n if (followUpQuestion)\n followUpQuestions.push(followUpQuestion);\n }\n }\n if (followUpQuestions.length === 0) {\n yield this.renderNextQuestion(form, page);\n return;\n }\n // Create a new page with the follow up questions\n const newPage = new page_1.Page(page.id, page.position, this.appId, followUpQuestions, page.edges);\n const n = new pageNode_1.PageNode(page.id, page.position, page.edges, newPage, followUpQuestions, true);\n n.elements = (0, questions_service_1.renderQuestions)(followUpQuestions, this.formOptionsConfig.questionFormat, (_a = this.formData) === null || _a === void 0 ? void 0 : _a.lang[0], (_b = this.formData) === null || _b === void 0 ? void 0 : _b.product, () => this.send());\n // Update the progress +0.5, because the follow up questions are\n // not included in the graph and one page with follow up questions is considered as 2\n this.history.enqueue(n);\n this.progress += 0.5;\n form.innerHTML = \"\";\n (_c = n.elements) === null || _c === void 0 ? void 0 : _c.forEach((element) => form.appendChild(element));\n // AFTER\n if (this.formOptionsConfig.afterSubmitEvent) {\n yield this.formOptionsConfig.afterSubmitEvent({\n response: this.id,\n loading: false,\n progress: this.progress,\n total: this.total,\n followup: n.isFollowup,\n completed: this.completed,\n error: null\n });\n }\n });\n }\n /**\n * Render next question\n * @param form\n * @param page\n * @private\n */\n renderNextQuestion(form, page) {\n var _a, _b, _c, _d, _e;\n return __awaiter(this, void 0, void 0, function* () {\n // Get next page from the graph\n //console.log(page, this.feedback.answers);\n let nextPage = this.graph.getNextPage(page, this.feedback.answers);\n //console.log(nextPage);\n if (!nextPage) {\n this.finish();\n return;\n }\n // --- NEW: Check preconditional routes ---\n const preconditionalRoute = nextPage.edges.filter(edge => edge.typeCondition === 'PRECONDITIONAL').sort((a, b) => {\n // Sort by position\n if (a.position < b.position)\n return -1;\n if (a.position > b.position)\n return 1;\n return 0;\n });\n if ((preconditionalRoute === null || preconditionalRoute === void 0 ? void 0 : preconditionalRoute.length) > 0) {\n // Look for the answer in previous PageNodes\n let foundAnswer = null;\n const allRefs = preconditionalRoute.map(route => route.questionRef);\n // Search in the history from the most recent backwards\n for (let i = this.history.size() - 1; i >= 0; i--) {\n const node = this.history.get(i);\n if (!node)\n continue;\n foundAnswer = (_a = node.answers) === null || _a === void 0 ? void 0 : _a.find((ans) => allRefs.includes(ans.key));\n if (foundAnswer)\n break;\n }\n // If there is an answer, evaluate the condition\n let allowToContinue = !preconditionalRoute.some(route => route.transition === pageRoute_1.TransitionType.ALLOW);\n if (foundAnswer) {\n for (const route of preconditionalRoute) {\n let conditionMet = false;\n const question = (_b = this.formData) === null || _b === void 0 ? void 0 : _b.questions.find(q => q.ref === route.questionRef);\n const answerVals = Array.isArray(foundAnswer.value) ? foundAnswer.value : [foundAnswer.value];\n const routeVals = Array.isArray(route.value) ? route.value : [route.value];\n // Lógica especial para matrices\n if ((question === null || question === void 0 ? void 0 : question.type) === types_1.FEEDBACKAPPANSWERTYPE.MULTI_QUESTION_MATRIX) {\n conditionMet = this.evaluateMatrixPreconditional(route, foundAnswer);\n }\n else {\n switch (route.typeOperator) {\n case 'EQUAL':\n // At least one answer value equals one expected value\n conditionMet = answerVals.some((v) => routeVals.includes(v));\n break;\n case 'NOEQUAL':\n // None of the answer values equals any expected value\n conditionMet = answerVals.every((v) => !routeVals.includes(v));\n break;\n case 'GREATER':\n conditionMet = answerVals.some((v) => Number(v) > Number(routeVals[0]));\n break;\n case 'LESS':\n conditionMet = answerVals.some((v) => Number(v) < Number(routeVals[0]));\n break;\n case 'GREATEREQUAL':\n conditionMet = answerVals.some((v) => Number(v) >= Number(routeVals[0]));\n break;\n case 'LESSEQUAL':\n conditionMet = answerVals.some((v) => Number(v) <= Number(routeVals[0]));\n break;\n case 'INQ':\n // Some answer value is included in route.value (array)\n conditionMet = answerVals.some((v) => routeVals.includes(v));\n break;\n case 'NINQ':\n // No answer value is included in route.value (array)\n conditionMet = answerVals.every((v) => !routeVals.includes(v));\n break;\n default:\n break;\n }\n }\n // If condition is met, apply the transition\n if (conditionMet) {\n this.feedback.answers = [];\n switch (route.transition) {\n case pageRoute_1.TransitionType.NEXT:\n if (nextPage)\n yield this.renderNextQuestion(form, nextPage);\n return;\n case pageRoute_1.TransitionType.ALLOW:\n allowToContinue = true;\n break;\n }\n }\n }\n }\n if (!allowToContinue) {\n this.feedback.answers = [];\n if (nextPage)\n yield this.renderNextQuestion(form, nextPage);\n return;\n }\n }\n // --- END NEW ---\n nextPage.elements = (0, questions_service_1.renderQuestions)(nextPage.questions, this.formOptionsConfig.questionFormat, (_c = this.formData) === null || _c === void 0 ? void 0 : _c.lang[0], (_d = this.formData) === null || _d === void 0 ? void 0 : _d.product, () => this.send());\n form.innerHTML = \"\";\n (_e = nextPage.elements) === null || _e === void 0 ? void 0 : _e.forEach((element) => form.appendChild(element));\n this.history.enqueue(nextPage);\n this.progress = this.total - this.graph.findMaxDepth(nextPage);\n // AFTER\n if (this.formOptionsConfig.afterSubmitEvent) {\n yield this.formOptionsConfig.afterSubmitEvent({\n response: this.id,\n loading: false,\n progress: this.progress,\n total: this.total,\n followup: nextPage.isFollowup,\n completed: this.completed,\n error: null\n });\n }\n });\n }\n /**\n * Render back question\n * @private\n */\n back() {\n var _a;\n return __awaiter(this, void 0, void 0, function* () {\n if (this.history.size() === 0)\n return;\n const form = document.getElementById(\"magicfeedback-questions-\" + this.appId);\n if (form && form.childNodes.length > 0)\n form.innerHTML = \"\";\n this.history.rollback();\n const page = this.history.back();\n if (page) {\n (_a = page.elements) === null || _a === void 0 ? void 0 : _a.forEach((element) => form.appendChild(element));\n this.progress = this.total - this.graph.findMaxDepth(page);\n }\n else {\n this.progress = this.history.size();\n }\n // AFTER\n if (this.formOptionsConfig.onBackEvent) {\n yield this.formOptionsConfig.onBackEvent({\n loading: false,\n progress: this.progress,\n followup: (page === null || page === void 0 ? void 0 : page.isFollowup) || false,\n error: !page ? \"No page found\" : null\n });\n }\n });\n }\n /**\n * Render a single question as a preview/test.\n * It does not modify the internal state (history, graph, progress) of the form.\n * @param selector ID of the container where the question will be injected.\n * @param question Full question object (NativeQuestion[] expected here).\n * @param options Optional configuration to customize format/language/product.\n * @returns HTMLElement container used.\n */\n previewQuestion(selector, question, options) {\n var _a, _b;\n const questionsArray = Array.isArray(question) ? question : [question];\n if (!questionsArray || questionsArray.length === 0)\n throw new Error(\"[MagicFeedback] No question provided for preview\");\n const container = document.getElementById(selector);\n if (!container)\n throw new Error(`[MagicFeedback] Element with ID '${selector}' not found.`);\n const { format = this.formOptionsConfig.questionFormat || \"standard\", language = (((_a = this.formData) === null || _a === void 0 ? void 0 : _a.lang) && this.formData.lang[0]) || \"en\", product = ((_b = this.formData) === null || _b === void 0 ? void 0 : _b.product) || { customIcons: false }, clearContainer = true, wrap = true, } = options || {};\n if (clearContainer)\n container.innerHTML = \"\";\n // Reuse existing renderQuestions logic passing the question array\n let elements = [];\n try {\n elements = (0, questions_service_1.renderQuestions)(questionsArray, format, language, product);\n }\n catch (e) {\n this.log.err(e);\n throw e;\n }\n // If wrap is true, create a wrapper container to isolate preview styles\n let target = container;\n if (wrap) {\n const wrapper = document.createElement(\"div\");\n wrapper.classList.add(\"magicfeedback-preview-question\");\n target.appendChild(wrapper);\n target = wrapper;\n }\n elements.forEach(el => target.appendChild(el));\n return container;\n }\n parseMatrixAnswerPre(ans) {\n if (!ans || !ans.value)\n return [];\n if (ans.value.length === 1 && typeof ans.value[0] === 'string' && ans.value[0].trim().startsWith('[')) {\n try {\n const parsed = JSON.parse(ans.value[0]);\n if (Array.isArray(parsed))\n return parsed;\n }\n catch (_) {\n return [];\n }\n }\n if (Array.isArray(ans.value) && ans.value.length > 0 && typeof ans.value[0] === 'object' && ans.value[0] !== null && 'key' in ans.value[0]) {\n return ans.value;\n }\n return [];\n }\n evaluateMatrixPreconditional(route, answer) {\n const edgeVals = Array.isArray(route.value) ? route.value : [route.value];\n const optionFilter = new Set(route.option || []);\n const rows = this.parseMatrixAnswerPre(answer);\n if (!rows.length)\n return false;\n const relevantRows = optionFilter.size > 0 ? rows.filter(r => optionFilter.has(r.key)) : rows;\n if (!relevantRows.length)\n return false;\n const intersects = (rowValues) => rowValues.some(v => edgeVals.includes(v));\n const notIntersects = (rowValues) => rowValues.every(v => !edgeVals.includes(v));\n switch (route.typeOperator) {\n case 'EQUAL':\n case 'INQ':\n return relevantRows.some(r => intersects(Array.isArray(r.value) ? r.value : [r.value]));\n case 'NOEQUAL':\n case 'NINQ':\n return relevantRows.every(r => notIntersects(Array.isArray(r.value) ? r.value : [r.value]));\n case 'GREATER':\n return relevantRows.some(r => {\n const vals = Array.isArray(r.value) ? r.value : [r.value];\n return vals.some(val => edgeVals.some(edgeVal => Number(val) > Number(edgeVal)));\n });\n case 'LESS':\n return relevantRows.some(r => {\n const vals = Array.isArray(r.value) ? r.value : [r.value];\n return vals.some(val => edgeVals.some(edgeVal => Number(val) < Number(edgeVal)));\n });\n case 'GREATEREQUAL':\n return relevantRows.some(r => {\n const vals = Array.isArray(r.value) ? r.value : [r.value];\n return vals.some(val => edgeVals.some(edgeVal => Number(val) >= Number(edgeVal)));\n });\n case 'LESSEQUAL':\n return relevantRows.some(r => {\n const vals = Array.isArray(r.value) ? r.value : [r.value];\n return vals.some(val => edgeVals.some(edgeVal => Number(val) <= Number(edgeVal)));\n });\n default:\n return false;\n }\n }\n}\nexports.Form = Form;\n\n\n//# sourceURL=webpack://magicfeedback/./src/models/form.ts?");
|
|
95
|
+
|
|
96
|
+
/***/ }),
|
|
97
|
+
|
|
98
|
+
/***/ "./src/models/page.ts":
|
|
99
|
+
/*!****************************!*\
|
|
100
|
+
!*** ./src/models/page.ts ***!
|
|
101
|
+
\****************************/
|
|
102
|
+
/***/ ((__unused_webpack_module, exports) => {
|
|
103
|
+
|
|
104
|
+
"use strict";
|
|
105
|
+
eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.Page = void 0;\nclass Page {\n constructor(id, position, integrationId, integrationQuestions, integrationPageRoutes) {\n this.id = id;\n this.position = position;\n this.generatedAt = new Date().toISOString();\n this.updatedAt = new Date().toISOString();\n this.status = 'ACTIVE';\n this.integrationId = integrationId;\n this.integrationQuestions = integrationQuestions;\n this.integrationPageRoutes = integrationPageRoutes;\n }\n}\nexports.Page = Page;\n\n\n//# sourceURL=webpack://magicfeedback/./src/models/page.ts?");
|
|
106
|
+
|
|
107
|
+
/***/ }),
|
|
108
|
+
|
|
109
|
+
/***/ "./src/models/pageGrafs.ts":
|
|
110
|
+
/*!*********************************!*\
|
|
111
|
+
!*** ./src/models/pageGrafs.ts ***!
|
|
112
|
+
\*********************************/
|
|
113
|
+
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
|
|
114
|
+
|
|
115
|
+
"use strict";
|
|
116
|
+
eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.PageGraph = void 0;\nconst pageNode_1 = __webpack_require__(/*! ./pageNode */ \"./src/models/pageNode.ts\");\nconst types_1 = __webpack_require__(/*! ./types */ \"./src/models/types.ts\");\nconst pageRoute_1 = __webpack_require__(/*! ./pageRoute */ \"./src/models/pageRoute.ts\");\nclass PageGraph {\n constructor(pages) {\n this.nodes = new Map();\n this.buildGraph(pages);\n }\n /**\n * Build the graph from the list of pages\n * @param pages\n * @private\n * */\n buildGraph(pages) {\n pages.forEach((page) => {\n var _a;\n // Sort by created date and then by type of transition (logical first)\n if (page.integrationPageRoutes)\n page.integrationPageRoutes = ((_a = page.integrationPageRoutes) === null || _a === void 0 ? void 0 : _a.sort((a, b) => (new Date((a === null || a === void 0 ? void 0 : a.generatedAt) || '').getTime() - new Date((b === null || b === void 0 ? void 0 : b.generatedAt) || '').getTime() || 0) &&\n (a.typeCondition === 'DIRECT' ? 1 : -1))) || [];\n const node = new pageNode_1.PageNode(page.id, page.position, page.integrationPageRoutes || [], page, page.integrationQuestions);\n this.nodes.set(node.id, node);\n });\n }\n getNodeById(id) {\n return this.nodes.get(id);\n }\n /**\n * Get the next page position of the graph given the current page and the answer\n * @param node\n */\n getNextEdgeByDefault(node) {\n if (!node)\n return undefined;\n const direct = node.edges.find((e) => e.typeCondition === pageRoute_1.ConditionType.DIRECT);\n if (direct && [pageRoute_1.TransitionType.FINISH, pageRoute_1.TransitionType.REDIRECT].includes(direct.transition))\n return undefined;\n if (direct && direct.transitionDestiny)\n return direct.transitionDestiny;\n for (const n of this.nodes.values()) {\n if (n.position === (node.position + 1))\n return n.id;\n }\n return undefined;\n }\n /**\n * Get the first page of the graph\n * @returns first page\n **/\n getFirstPage() {\n // Find the page with the smallest position\n // TODO: Chek if the graph is completed and don't have break loops\n let firstPage;\n let smallestPosition = Number.MAX_VALUE;\n for (const node of this.nodes.values()) {\n if (node.position < smallestPosition) {\n smallestPosition = node.position;\n firstPage = node;\n }\n }\n return firstPage;\n }\n /**\n * Get the next page of the graph given the current page and the answer\n * @param currentNode\n * @param answer - answer to the question in the current page\n * @returns page\n **/\n getNextPage(currentNode, answer) {\n var _a;\n if (!currentNode) {\n return undefined;\n }\n // Ordenar edges: primero lógicos, luego directos\n currentNode.edges.sort((a, b) => {\n if (a.typeCondition === 'DIRECT')\n return 1;\n if (b.typeCondition === 'DIRECT')\n return -1;\n return 0;\n });\n // console.log(currentNode)\n // Buscar la primera ruta que cumpla la condición\n const route = currentNode.edges.find(edge => {\n // Chequear condición\n const question = currentNode.questions.find(q => q.ref === edge.questionRef);\n const answerValue = answer === null || answer === void 0 ? void 0 : answer.filter(ans => ans.key === edge.questionRef);\n if (edge.typeCondition === 'DIRECT')\n return true;\n if (!answerValue || answerValue.length === 0)\n return false;\n // Lógica especial para matrices\n if ((question === null || question === void 0 ? void 0 : question.type) === types_1.FEEDBACKAPPANSWERTYPE.MULTI_QUESTION_MATRIX) {\n return this.evaluateMatrixCondition(edge, answerValue);\n }\n // Normalizar edge.value a array\n const edgeVals = Array.isArray(edge.value) ? edge.value : [edge.value];\n switch (edge.typeOperator) {\n case pageRoute_1.OperatorType.EQUAL:\n return answerValue.some(ans => {\n const ansVals = Array.isArray(ans.value) ? ans.value : [ans.value];\n return ansVals.some(val => edgeVals.includes(val));\n });\n case pageRoute_1.OperatorType.NOEQUAL:\n return answerValue.every(ans => {\n const ansVals = Array.isArray(ans.value) ? ans.value : [ans.value];\n return ansVals.every(val => !edgeVals.includes(val));\n });\n case pageRoute_1.OperatorType.GREATER:\n return answerValue.some(ans => {\n const ansVals = Array.isArray(ans.value) ? ans.value : [ans.value];\n return ansVals.some(val => edgeVals.some(edgeVal => Number(val) > Number(edgeVal)));\n });\n case pageRoute_1.OperatorType.LESS:\n return answerValue.some(ans => {\n const ansVals = Array.isArray(ans.value) ? ans.value : [ans.value];\n return ansVals.some(val => edgeVals.some(edgeVal => Number(val) < Number(edgeVal)));\n });\n case pageRoute_1.OperatorType.GREATEREQUAL:\n return answerValue.some(ans => {\n const ansVals = Array.isArray(ans.value) ? ans.value : [ans.value];\n return ansVals.some(val => edgeVals.some(edgeVal => Number(val) >= Number(edgeVal)));\n });\n case pageRoute_1.OperatorType.LESSEQUAL:\n return answerValue.some(ans => {\n const ansVals = Array.isArray(ans.value) ? ans.value : [ans.value];\n return ansVals.some(val => edgeVals.some(edgeVal => Number(val) <= Number(edgeVal)));\n });\n case pageRoute_1.OperatorType.INQ:\n return answerValue.some(ans => {\n const ansVals = Array.isArray(ans.value) ? ans.value : [ans.value];\n return ansVals.some(val => edgeVals.includes(val));\n });\n case pageRoute_1.OperatorType.NINQ:\n return answerValue.every(ans => {\n const ansVals = Array.isArray(ans.value) ? ans.value : [ans.value];\n return ansVals.every(val => !edgeVals.includes(val));\n });\n default:\n return false;\n }\n });\n // Si no hay ninguna ruta que cumpla, ir a la siguiente página por posición\n if (!route) {\n const nextPage = this.getNextEdgeByDefault(currentNode);\n if (!nextPage)\n return undefined;\n return this.getNodeById(nextPage);\n }\n switch (route.transition) {\n case pageRoute_1.TransitionType.PAGE:\n if (!route.transitionDestiny)\n return undefined;\n return this.getNodeById(route.transitionDestiny);\n case pageRoute_1.TransitionType.FINISH:\n return undefined;\n case pageRoute_1.TransitionType.REDIRECT:\n window.location.href = ((_a = route.transitionDestiny) === null || _a === void 0 ? void 0 : _a.includes('?')) ? `${route.transitionDestiny}&${window.location.search.slice(1)}`\n : `${route.transitionDestiny}${window.location.search}`;\n return undefined;\n default:\n return undefined;\n }\n }\n /**\n * Get the number deep (DFS) of this node\n * @param id - node id\n * @returns DFS number\n */\n findDepth(id) {\n const node = this.getNodeById(id);\n if (!node) {\n return 0;\n }\n const visited = new Set();\n return this.DFSUtil(node, visited, 0);\n }\n /**\n * Get the max depth of the graph\n * @param n - node\n * @returns max depth\n */\n findMaxDepth(n) {\n // Find first node\n if (!n)\n n = this.getFirstPage();\n if (!n)\n return 0;\n // Start DFS from the first node\n const visited = new Set();\n // const haveFollowup = !!n.questions.find(q => q.followup);\n //console.log(this.nodes);\n // If the first node have followup questions, the depth is 2\n let max_depth = 1; // haveFollowup ? 2 : 1;\n max_depth = Math.max(max_depth, this.DFSUtil(n, visited, max_depth));\n return max_depth;\n }\n /**\n * A function used by DFS\n * @param v - node\n * @param visited - set of visited nodes\n * @param depth - current depth\n */\n DFSUtil(v, visited, depth) {\n visited.add(v);\n let max_depth = depth;\n // Haz una copia local de los vecinos para evitar modificar el grafo original\n const neighbours = [...(v.edges.filter((e) => e.typeCondition !== pageRoute_1.ConditionType.PRECONDITIONAL) || [])];\n // Si no hay edges, ir a la siguiente página por posición\n const defaultEdge = this.getNextEdgeByDefault(v);\n if (defaultEdge) {\n const defaultNode = this.getNodeById(defaultEdge);\n if (defaultNode && !visited.has(defaultNode)) {\n neighbours.push(new pageRoute_1.PageRoute(defaultNode.id, '', pageRoute_1.OperatorType.DEFAULT, [''], pageRoute_1.TransitionType.PAGE, defaultNode.id, v.id));\n }\n }\n for (const neighbour of neighbours) {\n if (!neighbour.transitionDestiny)\n continue;\n const node = this.getNodeById(neighbour.transitionDestiny);\n if (node && !visited.has(node)) {\n // const haveFollowup = !!node.questions.find(q => q.followup);\n const new_depth = depth + 1; // haveFollowup ? depth + 2 : depth + 1;\n // Make a copy of the visited set to only for this branch\n const visitedBranch = new Set(visited);\n const dfs = this.DFSUtil(node, visitedBranch, new_depth);\n max_depth = Math.max(max_depth, dfs);\n }\n }\n return max_depth;\n }\n parseMatrixAnswer(ans) {\n // ans.value puede ser:\n // 1. Un array con un string JSON que representa la matriz\n // 2. Un array de objetos ya parseados\n // 3. Un array vacío\n if (!ans || !ans.value)\n return [];\n // Caso 1: primer elemento es string con JSON de la matriz\n if (ans.value.length === 1 && typeof ans.value[0] === 'string' && ans.value[0].trim().startsWith('[')) {\n try {\n const parsed = JSON.parse(ans.value[0]);\n if (Array.isArray(parsed))\n return parsed;\n }\n catch (e) {\n // Ignorar errores de parseo\n return [];\n }\n }\n // Caso 2: el array ya contiene objetos { key, value }\n if (Array.isArray(ans.value) && ans.value.length > 0 && typeof ans.value[0] === 'object' && ans.value[0] !== null && 'key' in ans.value[0]) {\n return ans.value;\n }\n return [];\n }\n evaluateMatrixCondition(edge, answerValue) {\n const edgeVals = Array.isArray(edge.value) ? edge.value : [edge.value];\n const optionFilter = new Set(edge.option || []); // eje X a filtrar\n const ans = answerValue[0]; // Se asume una respuesta por pregunta\n const rows = this.parseMatrixAnswer(ans);\n if (!rows.length)\n return false;\n const relevantRows = optionFilter.size > 0 ? rows.filter(r => optionFilter.has(r.key)) : rows;\n if (!relevantRows.length)\n return false;\n const intersects = (rowValues) => rowValues.some(v => edgeVals.includes(v));\n const notIntersects = (rowValues) => rowValues.every(v => !edgeVals.includes(v));\n switch (edge.typeOperator) {\n case pageRoute_1.OperatorType.EQUAL:\n // Todas las filas relevantes deben contener al menos un valor de edgeVals\n // return relevantRows.every(r => intersects(Array.isArray(r.value) ? r.value : [r.value]));\n case pageRoute_1.OperatorType.INQ:\n // Alguna fila relevante contiene al menos un valor de edgeVals (se mantiene comportamiento original para INQ)\n return relevantRows.some(r => intersects(Array.isArray(r.value) ? r.value : [r.value]));\n case pageRoute_1.OperatorType.NOEQUAL:\n case pageRoute_1.OperatorType.NINQ:\n // Todas las filas relevantes NO contienen valores de edgeVals\n return relevantRows.every(r => notIntersects(Array.isArray(r.value) ? r.value : [r.value]));\n case pageRoute_1.OperatorType.GREATER:\n return relevantRows.some(r => {\n const vals = Array.isArray(r.value) ? r.value : [r.value];\n return vals.some(val => edgeVals.some(edgeVal => Number(val) > Number(edgeVal)));\n });\n case pageRoute_1.OperatorType.LESS:\n return relevantRows.some(r => {\n const vals = Array.isArray(r.value) ? r.value : [r.value];\n return vals.some(val => edgeVals.some(edgeVal => Number(val) < Number(edgeVal)));\n });\n case pageRoute_1.OperatorType.GREATEREQUAL:\n return relevantRows.some(r => {\n const vals = Array.isArray(r.value) ? r.value : [r.value];\n return vals.some(val => edgeVals.some(edgeVal => Number(val) >= Number(edgeVal)));\n });\n case pageRoute_1.OperatorType.LESSEQUAL:\n return relevantRows.some(r => {\n const vals = Array.isArray(r.value) ? r.value : [r.value];\n return vals.some(val => edgeVals.some(edgeVal => Number(val) <= Number(edgeVal)));\n });\n default:\n return false;\n }\n }\n}\nexports.PageGraph = PageGraph;\n\n\n//# sourceURL=webpack://magicfeedback/./src/models/pageGrafs.ts?");
|
|
117
|
+
|
|
118
|
+
/***/ }),
|
|
119
|
+
|
|
120
|
+
/***/ "./src/models/pageNode.ts":
|
|
121
|
+
/*!********************************!*\
|
|
122
|
+
!*** ./src/models/pageNode.ts ***!
|
|
123
|
+
\********************************/
|
|
124
|
+
/***/ ((__unused_webpack_module, exports) => {
|
|
125
|
+
|
|
126
|
+
"use strict";
|
|
127
|
+
eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.PageNode = void 0;\nclass PageNode {\n constructor(id, position, edges, data, questions, isFollowup = false) {\n this.answers = [];\n this.id = id;\n this.position = position;\n this.edges = edges;\n this.data = data;\n this.questions = questions.sort((a, b) => a.position - b.position);\n this.elements = [];\n this.isFollowup = isFollowup;\n }\n /**\n * Get a list of followup questions ref\n * @returns list of followup questions ref\n **/\n getFollowupQuestions() {\n return this.questions.filter(question => question.followup).map(question => question.ref);\n }\n /**\n * Get a list of ref of the questions that are required in the page\n * @returns ref of the required questions ref\n **/\n getRequiredQuestions() {\n return this.questions.filter(question => question.require).map(question => question.ref);\n }\n /**\n * Set the answer for a question\n * @param questionRef\n * @param answer\n */\n setAnswer(answer) {\n this.answers = answer;\n }\n}\nexports.PageNode = PageNode;\n\n\n//# sourceURL=webpack://magicfeedback/./src/models/pageNode.ts?");
|
|
128
|
+
|
|
129
|
+
/***/ }),
|
|
130
|
+
|
|
131
|
+
/***/ "./src/models/pageRoute.ts":
|
|
132
|
+
/*!*********************************!*\
|
|
133
|
+
!*** ./src/models/pageRoute.ts ***!
|
|
134
|
+
\*********************************/
|
|
135
|
+
/***/ ((__unused_webpack_module, exports) => {
|
|
136
|
+
|
|
137
|
+
"use strict";
|
|
138
|
+
eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.PageRoute = exports.StatusType = exports.OperatorType = exports.ConditionType = exports.TransitionType = void 0;\nvar TransitionType;\n(function (TransitionType) {\n TransitionType[\"PAGE\"] = \"PAGE\";\n TransitionType[\"FINISH\"] = \"FINISH\";\n TransitionType[\"REDIRECT\"] = \"REDIRECT\";\n TransitionType[\"NEXT\"] = \"NEXT\";\n TransitionType[\"ALLOW\"] = \"ALLOW\";\n})(TransitionType = exports.TransitionType || (exports.TransitionType = {}));\nvar ConditionType;\n(function (ConditionType) {\n ConditionType[\"LOGICAL\"] = \"LOGICAL\";\n ConditionType[\"DIRECT\"] = \"DIRECT\";\n ConditionType[\"PRECONDITIONAL\"] = \"PRECONDITIONAL\";\n})(ConditionType = exports.ConditionType || (exports.ConditionType = {}));\nvar OperatorType;\n(function (OperatorType) {\n OperatorType[\"EQUAL\"] = \"EQUAL\";\n OperatorType[\"NOEQUAL\"] = \"NOEQUAL\";\n OperatorType[\"GREATER\"] = \"GREATER\";\n OperatorType[\"LESS\"] = \"LESS\";\n OperatorType[\"GREATEREQUAL\"] = \"GREATEREQUAL\";\n OperatorType[\"LESSEQUAL\"] = \"LESSEQUAL\";\n OperatorType[\"INQ\"] = \"INQ\";\n OperatorType[\"NINQ\"] = \"NINQ\";\n OperatorType[\"DEFAULT\"] = \"DEFAULT\";\n})(OperatorType = exports.OperatorType || (exports.OperatorType = {}));\nvar StatusType;\n(function (StatusType) {\n StatusType[\"ACTIVE\"] = \"ACTIVE\";\n StatusType[\"DEPRECATED\"] = \"DEPRECATED\";\n StatusType[\"DELETE\"] = \"DELETE\";\n})(StatusType = exports.StatusType || (exports.StatusType = {}));\nclass PageRoute {\n constructor(id, questionRef, typeOperator, value, transition, transitionDestiny, integrationPageId, typeCondition, position, option) {\n this.id = id;\n this.questionRef = questionRef;\n this.typeCondition = typeCondition || ConditionType.LOGICAL;\n this.typeOperator = typeOperator;\n this.value = value || [];\n this.transition = transition;\n this.transitionDestiny = transitionDestiny;\n this.status = StatusType.ACTIVE;\n this.generatedAt = new Date();\n this.updatedAt = new Date();\n this.integrationPageId = integrationPageId;\n this.position = position || 0;\n this.option = option || [];\n }\n}\nexports.PageRoute = PageRoute;\n\n\n//# sourceURL=webpack://magicfeedback/./src/models/pageRoute.ts?");
|
|
139
|
+
|
|
140
|
+
/***/ }),
|
|
141
|
+
|
|
142
|
+
/***/ "./src/models/types.ts":
|
|
143
|
+
/*!*****************************!*\
|
|
144
|
+
!*** ./src/models/types.ts ***!
|
|
145
|
+
\*****************************/
|
|
146
|
+
/***/ ((__unused_webpack_module, exports) => {
|
|
147
|
+
|
|
148
|
+
"use strict";
|
|
149
|
+
eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.QuestionType = exports.FEEDBACKAPPANSWERTYPE = void 0;\nvar FEEDBACKAPPANSWERTYPE;\n(function (FEEDBACKAPPANSWERTYPE) {\n FEEDBACKAPPANSWERTYPE[\"CONTACT\"] = \"CONTACT\";\n FEEDBACKAPPANSWERTYPE[\"MULTIPLECHOISE_IMAGE\"] = \"MULTIPLECHOISE_IMAGE\";\n FEEDBACKAPPANSWERTYPE[\"EMAIL\"] = \"EMAIL\";\n FEEDBACKAPPANSWERTYPE[\"RATING_STAR\"] = \"RATING_STAR\";\n FEEDBACKAPPANSWERTYPE[\"RADIO\"] = \"RADIO\";\n FEEDBACKAPPANSWERTYPE[\"MULTIPLECHOICE\"] = \"MULTIPLECHOICE\";\n FEEDBACKAPPANSWERTYPE[\"SELECT\"] = \"SELECT\";\n FEEDBACKAPPANSWERTYPE[\"TEXT\"] = \"TEXT\";\n FEEDBACKAPPANSWERTYPE[\"LONGTEXT\"] = \"LONGTEXT\";\n FEEDBACKAPPANSWERTYPE[\"NUMBER\"] = \"NUMBER\";\n FEEDBACKAPPANSWERTYPE[\"RATING_EMOJI\"] = \"RATING_EMOJI\";\n FEEDBACKAPPANSWERTYPE[\"RATING_NUMBER\"] = \"RATING_NUMBER\";\n FEEDBACKAPPANSWERTYPE[\"DATE\"] = \"DATE\";\n FEEDBACKAPPANSWERTYPE[\"BOOLEAN\"] = \"BOOLEAN\";\n FEEDBACKAPPANSWERTYPE[\"PASSWORD\"] = \"PASSWORD\";\n FEEDBACKAPPANSWERTYPE[\"CONSENT\"] = \"CONSENT\";\n FEEDBACKAPPANSWERTYPE[\"MULTI_QUESTION_MATRIX\"] = \"MULTI_QUESTION_MATRIX\";\n FEEDBACKAPPANSWERTYPE[\"POINT_SYSTEM\"] = \"POINT_SYSTEM\";\n FEEDBACKAPPANSWERTYPE[\"PRIORITY_LIST\"] = \"PRIORITY_LIST\";\n FEEDBACKAPPANSWERTYPE[\"INFO_PAGE\"] = \"INFO_PAGE\";\n FEEDBACKAPPANSWERTYPE[\"UPLOAD_FILE\"] = \"UPLOAD_FILE\";\n FEEDBACKAPPANSWERTYPE[\"UPLOAD_IMAGE\"] = \"UPLOAD_IMAGE\";\n})(FEEDBACKAPPANSWERTYPE = exports.FEEDBACKAPPANSWERTYPE || (exports.FEEDBACKAPPANSWERTYPE = {}));\nclass QuestionType {\n}\nexports.QuestionType = QuestionType;\nvar generateFormOptionsTag;\n(function (generateFormOptionsTag) {\n generateFormOptionsTag[\"FORM\"] = \"form\";\n generateFormOptionsTag[\"DIV\"] = \"div\";\n})(generateFormOptionsTag || (generateFormOptionsTag = {}));\n\n\n//# sourceURL=webpack://magicfeedback/./src/models/types.ts?");
|
|
150
|
+
|
|
151
|
+
/***/ }),
|
|
152
|
+
|
|
153
|
+
/***/ "./src/services/paths.ts":
|
|
154
|
+
/*!*******************************!*\
|
|
155
|
+
!*** ./src/services/paths.ts ***!
|
|
156
|
+
\*******************************/
|
|
157
|
+
/***/ ((__unused_webpack_module, exports) => {
|
|
158
|
+
|
|
159
|
+
"use strict";
|
|
160
|
+
eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.endpoints = void 0;\nexports.endpoints = {\n sdk: {\n app: (appId, publicKey) => `sdk/app/${appId}/${publicKey}`,\n app_info: (appId, publicKey) => `sdk/app/${appId}/${publicKey}/info`,\n session: (sessionId) => `sdk/app/session/${sessionId}/info`,\n feedback: 'sdk/feedback',\n followUpQuestion: 'sdk/followUpQuestion',\n }\n};\n\n\n//# sourceURL=webpack://magicfeedback/./src/services/paths.ts?");
|
|
161
|
+
|
|
162
|
+
/***/ }),
|
|
163
|
+
|
|
164
|
+
/***/ "./src/services/placeholder.ts":
|
|
165
|
+
/*!*************************************!*\
|
|
166
|
+
!*** ./src/services/placeholder.ts ***!
|
|
167
|
+
\*************************************/
|
|
168
|
+
/***/ ((__unused_webpack_module, exports) => {
|
|
169
|
+
|
|
170
|
+
"use strict";
|
|
171
|
+
eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.placeholder = void 0;\nexports.placeholder = {\n answer: (language) => {\n switch (language) {\n case \"en\":\n return \"Write your answer here...\";\n case \"es\":\n return \"Escribe tu respuesta aquí...\";\n case 'da':\n return 'Skriv dit svar her...';\n case 'fi':\n return 'Kirjoita vastauksesi tähän...';\n case 'sv':\n return 'Skriv ditt svar här...';\n case 'no':\n return 'Skriv svaret ditt her...';\n case 'ar':\n return 'اكتب إجابتك هنا...';\n case 'bn':\n return 'এখানে আপনার';\n default:\n return \"Write your answer here...\";\n }\n },\n number: (language) => {\n switch (language) {\n case \"en\":\n return \"Write your number here...\";\n case \"es\":\n return \"Escribe tu número aquí...\";\n case 'da':\n return 'Skriv dit nummer her...';\n case 'fi':\n return 'Kirjoita numerosi tähän...';\n case 'sv':\n return 'Skriv ditt nummer här...';\n case 'no':\n return 'Skriv nummeret ditt her...';\n case 'ar':\n return 'اكتب رقمك هنا...';\n case 'bn':\n return 'এখানে আপনার';\n default:\n return \"Write your number here...\";\n }\n },\n email: (language) => {\n switch (language) {\n case \"en\":\n return \"Write your email here...\";\n case \"es\":\n return \"Escribe tu correo electrónico aquí...\";\n case 'da':\n return 'Skriv din e-mail her...';\n case 'fi':\n return 'Kirjoita sähköpostiosoitteesi tähän...';\n case 'sv':\n return 'Skriv din e-post här...';\n case 'no':\n return 'Skriv e-posten din her...';\n case 'ar':\n return 'اكتب بريدك الإلكتروني هنا...';\n case 'bn':\n return 'এখানে আপনার';\n default:\n return \"Write your email here...\";\n }\n },\n date: (language) => {\n switch (language) {\n case \"en\":\n return \"Write your date here...\";\n case \"es\":\n return \"Escribe tu fecha aquí...\";\n case 'da':\n return 'Skriv din dato her...';\n case 'fi':\n return 'Kirjoita päivämääräsi tähän...';\n case 'sv':\n return 'Skriv ditt datum här...';\n case 'no':\n return 'Skriv datoen din her...';\n case 'ar':\n return 'اكتب تاريخك هنا...';\n case 'bn':\n return 'এখানে আপনার';\n default:\n return \"Write your date here...\";\n }\n },\n password: (language) => {\n switch (language) {\n case \"en\":\n return \"Write your password here...\";\n case \"es\":\n return \"Escribe tu contraseña aquí...\";\n case 'da':\n return 'Skriv dit kodeord her...';\n case 'fi':\n return 'Kirjoita salasanasi tähän...';\n case 'sv':\n return 'Skriv ditt lösenord här...';\n case 'no':\n return 'Skriv passordet ditt her...';\n case 'ar':\n return 'اكتب كلمة المرور الخاصة بك هنا...';\n case 'bn':\n return 'এখানে আপনার';\n default:\n return \"Write your password here...\";\n }\n },\n pointsystemerror: (language) => {\n switch (language) {\n case \"en\":\n return \"The total points must be 100 %\";\n case \"es\":\n return \"El total de puntos debe ser 100 %\";\n case 'da':\n return 'Samlet antal point skal være 100 %';\n case 'fi':\n return 'Kokonaispisteiden on oltava 100 %';\n case 'sv':\n return 'Totala poäng måste vara 100 %';\n case 'no':\n return 'Totalt antall poeng må være 100 %';\n case 'ar':\n return 'يجب أن تكون النقاط الإجمالية 100 %';\n case 'bn':\n return 'মোট পয়েন্ট 100 % হতে হবে';\n default:\n return \"The total points must be 100 %\";\n }\n }\n};\n\n\n//# sourceURL=webpack://magicfeedback/./src/services/placeholder.ts?");
|
|
172
|
+
|
|
173
|
+
/***/ }),
|
|
174
|
+
|
|
175
|
+
/***/ "./src/services/questions.service.ts":
|
|
176
|
+
/*!*******************************************!*\
|
|
177
|
+
!*** ./src/services/questions.service.ts ***!
|
|
178
|
+
\*******************************************/
|
|
179
|
+
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
|
|
180
|
+
|
|
181
|
+
"use strict";
|
|
182
|
+
eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.renderStartMessage = exports.renderSuccess = exports.renderError = exports.renderActions = exports.renderQuestions = void 0;\nconst types_1 = __webpack_require__(/*! ../models/types */ \"./src/models/types.ts\");\nconst placeholder_1 = __webpack_require__(/*! ./placeholder */ \"./src/services/placeholder.ts\");\n// Function to get the query params\nconst params = (a) => {\n const searchParams = new URLSearchParams(window.location.search);\n return searchParams.get(a);\n};\nconst defaultUrl = `https://survey-dev.magicfeedback.io/assets/emojis`;\nfunction renderQuestions(appQuestions, format = \"standard\", language = \"en\", product = { customIcons: false }, send) {\n if (!appQuestions)\n throw new Error(\"[MagicFeedback] No questions provided\");\n const questions = [];\n const { customIcons, id } = product;\n appQuestions.forEach((question) => {\n var _a, _b;\n if (((_b = (_a = question === null || question === void 0 ? void 0 : question.questionType) === null || _a === void 0 ? void 0 : _a.conf) === null || _b === void 0 ? void 0 : _b.length) > 0) {\n let elementContainer = document.createElement(\"div\");\n elementContainer.classList.add(\"magicfeedback-div\");\n const label = document.createElement(\"label\");\n label.setAttribute(\"for\", `magicfeedback-${question.id}`);\n label.textContent = parseTitle(question.title, language);\n label.classList.add(\"magicfeedback-label\");\n elementContainer.appendChild(label);\n question.questionType.conf.forEach((conf) => {\n conf.ref = question.ref;\n if (question.assets[conf.id]) {\n conf.assets = {\n placeholder: question.assets[conf.id],\n };\n }\n });\n const elements = renderQuestions(question.questionType.conf, format, language, product, send);\n elements.forEach((element) => {\n elementContainer.appendChild(element);\n });\n questions.push(elementContainer);\n }\n else {\n // Create a container for each question\n const url = `${defaultUrl}${customIcons ? `/${id}` : ''}`;\n const elementContainer = renderContainer(question, format, language, url, appQuestions.length === 1 ? send : undefined);\n questions.push(elementContainer);\n }\n });\n return questions;\n}\nexports.renderQuestions = renderQuestions;\nfunction parseTitle(title, lang) {\n if (!title)\n return '';\n return typeof title === \"object\" ? (title[lang] || title['en']) : title;\n}\n// Make a function to return a array with yes and no in every language\nfunction getBooleanOptions(lang) {\n switch (lang) {\n case \"es\":\n return ['Sí', 'No'];\n case \"fr\":\n return ['Oui', 'Non'];\n case \"de\":\n return ['Ja', 'Nein'];\n case \"it\":\n return ['Sì', 'No'];\n case \"pt\":\n return ['Sim', 'Não'];\n case \"nl\":\n return ['Ja', 'Nee'];\n case \"pl\":\n return ['Tak', 'Nie'];\n case \"ru\":\n return ['Да', 'Нет'];\n case \"ja\":\n return ['はい', 'いいえ'];\n case \"zh\":\n return ['是', '不'];\n case \"ko\":\n return ['예', '아니'];\n case 'da':\n return ['Ja', 'Nej'];\n case 'fi':\n return ['Kyllä', 'Ei'];\n case 'sv':\n return ['Ja', 'Nej'];\n case 'no':\n return ['Ja', 'Nei'];\n case 'ar':\n return ['نعم', 'لا'];\n case 'bn':\n return ['হ্যাঁ', 'না'];\n default:\n return ['Yes', 'No'];\n }\n}\nfunction renderContainer(question, format, language, url, send) {\n var _a, _b, _c;\n let { id, title, type, ref, require, \n //external_id,\n value, defaultValue, \n // questionType,\n assets } = question;\n let element;\n let elementTypeClass;\n let elementContainer = document.createElement(\"div\");\n elementContainer.classList.add(\"magicfeedback-div\");\n const isPhone = window.innerWidth < 600;\n const placeholderText = format === 'slim' ? parseTitle(title, language) : assets === null || assets === void 0 ? void 0 : assets.placeholder;\n // Look if exist the value in a query param with the ref like a key\n const urlParamValue = params(ref);\n const maxCharacters = (assets === null || assets === void 0 ? void 0 : assets.maxCharacters) || 0;\n const randomPosition = (assets === null || assets === void 0 ? void 0 : assets.randomPosition) === undefined ? false : assets === null || assets === void 0 ? void 0 : assets.randomPosition;\n const direction = (assets === null || assets === void 0 ? void 0 : assets.direction) || \"row\";\n const order = (assets === null || assets === void 0 ? void 0 : assets.order) || \"ltr\";\n switch (type) {\n case types_1.FEEDBACKAPPANSWERTYPE.TEXT:\n // Create a text input field\n element = document.createElement(\"input\");\n element.type = \"text\";\n element.placeholder = placeholderText || placeholder_1.placeholder.answer(language || 'en');\n if (urlParamValue) {\n element.value = urlParamValue;\n }\n // Control on press enter\n element.addEventListener(\"keyup\", (event) => {\n event.preventDefault();\n console.log(event.key, event);\n if (event.key === \"Enter\") {\n if (send)\n send();\n }\n });\n elementTypeClass = \"magicfeedback-text\";\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.LONGTEXT:\n // Create a textarea element for TEXT and LONGTEXT types\n element = document.createElement(\"textarea\");\n element.rows = 3; // Set the number of rows based on the type\n if (maxCharacters > 0)\n element.maxLength = maxCharacters; // Set the max length of the text area\n element.placeholder = placeholderText || placeholder_1.placeholder.answer(language || 'en');\n if (urlParamValue) {\n element.value = urlParamValue;\n }\n elementTypeClass = \"magicfeedback-longtext\";\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.NUMBER:\n // Create an input element with type \"number\" for NUMBER type\n element = document.createElement(\"input\");\n element.type = \"number\";\n element.placeholder = format === 'slim' ? parseTitle(title, language) : placeholder_1.placeholder.number(language || 'en');\n elementTypeClass = \"magicfeedback-number\";\n if (value.length) {\n value.sort((a, b) => Number(a) - Number(b));\n element.max = value[value.length - 1];\n element.min = value[0];\n element.value = value[0];\n }\n if (urlParamValue && !isNaN(Number(urlParamValue))) {\n element.value = urlParamValue;\n }\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.RADIO:\n case types_1.FEEDBACKAPPANSWERTYPE.MULTIPLECHOICE:\n element = document.createElement(\"div\");\n elementTypeClass =\n `magicfeedback-${(type === \"MULTIPLECHOICE\" ? \"checkbox\" : \"radio\")}`;\n let opt = value || [];\n // reorder the options if randomPosition is true\n if (randomPosition) {\n opt = opt.sort(() => Math.random() - 0.5);\n }\n let exclusiveAnswers = (assets === null || assets === void 0 ? void 0 : assets.exclusiveAnswers) || [];\n // Fix: excluir la opción extraOptionText de la lista de exclusivas si por error viene incluida desde backend/state\n if (assets === null || assets === void 0 ? void 0 : assets.extraOption) {\n exclusiveAnswers = exclusiveAnswers.filter(a => a !== assets.extraOptionText);\n }\n if (exclusiveAnswers.length > 0) {\n exclusiveAnswers === null || exclusiveAnswers === void 0 ? void 0 : exclusiveAnswers.forEach((answer) => {\n if (!opt.includes(answer))\n opt.push(answer);\n });\n }\n if ((assets === null || assets === void 0 ? void 0 : assets.extraOption) && !opt.includes(assets === null || assets === void 0 ? void 0 : assets.extraOptionText)) {\n opt.push(assets === null || assets === void 0 ? void 0 : assets.extraOptionText);\n }\n opt.forEach((option, index) => {\n const container = document.createElement(\"div\");\n container.classList.add(`magicfeedback-${type === \"MULTIPLECHOICE\" ? \"checkbox\" : \"radio\"}-container`);\n const label = document.createElement(\"label\");\n const input = document.createElement(\"input\");\n input.id = `rating-${ref}-${index}`;\n input.type = type === \"MULTIPLECHOICE\" ? \"checkbox\" : \"radio\";\n input.name = ref;\n input.value = option;\n input.classList.add(elementTypeClass);\n input.classList.add(\"magicfeedback-input\");\n if (type === types_1.FEEDBACKAPPANSWERTYPE.MULTIPLECHOICE && (assets === null || assets === void 0 ? void 0 : assets.maxOptions) && (assets === null || assets === void 0 ? void 0 : assets.maxOptions) > 0) {\n input.addEventListener(\"change\", () => {\n const checkboxes = document.querySelectorAll(`input[name=\"${ref}\"]:checked`);\n if (checkboxes.length > (assets === null || assets === void 0 ? void 0 : assets.maxOptions)) {\n input.checked = false;\n }\n //TODO: Enable in the future with a setting variable to send the answer when reach the max options selected\n /**\n if (send && checkboxes.length === assets?.maxOptions && !(assets?.extraOptionText && option === assets?.extraOptionText)) {\n send()\n }\n **/\n });\n }\n if (type === types_1.FEEDBACKAPPANSWERTYPE.RADIO && send) {\n if (!(assets === null || assets === void 0 ? void 0 : assets.extraOptionText) || (assets === null || assets === void 0 ? void 0 : assets.extraOptionText) && option !== (assets === null || assets === void 0 ? void 0 : assets.extraOptionText))\n input.addEventListener(\"change\", () => {\n send();\n });\n }\n if (option === defaultValue || option === urlParamValue) {\n input.checked = true;\n }\n label.textContent = option;\n label.htmlFor = `rating-${ref}-${index}`;\n input.addEventListener(\"change\", (event) => {\n const extraOption = document.getElementById(`extra-option-${ref}`);\n if (event.target.checked && exclusiveAnswers.includes(option)) {\n console.log('exclusiveAnswers', exclusiveAnswers, option);\n opt.forEach((answer) => {\n if (answer !== option) {\n const input = document.querySelector(`input[value=\"${answer}\"]`);\n input.checked = false;\n }\n });\n if (extraOption)\n extraOption.style.display = \"none\";\n }\n else {\n // Remove the checke of the exclusiveAnswers\n exclusiveAnswers.forEach((answer) => {\n if (answer !== option) {\n const input = document.querySelector(`input[value=\"${answer}\"]`);\n input.checked = false;\n }\n });\n // if (extraOption) extraOption.style.display = assets?.extraOption && option === assets?.extraOptionText ? \"block\" : \"none\";\n }\n if ((assets === null || assets === void 0 ? void 0 : assets.extraOption) && option === (assets === null || assets === void 0 ? void 0 : assets.extraOptionText) && extraOption)\n // SI al opcion con value assets?.extraOptionText esta seleccionada mostrar el input text si no ocultarlo\n extraOption.style.display = event.target.checked ? \"block\" : \"none\";\n });\n container.appendChild(input);\n container.appendChild(label);\n element.appendChild(container);\n // If is assets.extraOptionText add a input text after the label to add a custom value available only if is selected\n if ((assets === null || assets === void 0 ? void 0 : assets.extraOption) && option === (assets === null || assets === void 0 ? void 0 : assets.extraOptionText)) {\n const inputText = document.createElement(\"input\");\n inputText.type = \"text\";\n inputText.placeholder = (assets === null || assets === void 0 ? void 0 : assets.extraOptionPlaceholder) || placeholder_1.placeholder.answer(language || 'en');\n inputText.classList.add(\"magicfeedback-extra-option\");\n inputText.classList.add(\"magicfeedback-input\");\n inputText.id = `extra-option-${ref}`;\n inputText.name = `extra-option-${ref}`;\n inputText.style.display = \"none\";\n element.appendChild(inputText);\n }\n });\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.BOOLEAN:\n // Create an input element with type \"checkbox\" for BOOLEAN type with option yes or no\n element = document.createElement(\"div\");\n elementTypeClass = 'magicfeedback-radio';\n const booleanContainer = document.createElement('div');\n booleanContainer.classList.add('magicfeedback-boolean-container');\n booleanContainer.style.display = \"flex\";\n booleanContainer.style.flexDirection = \"row\";\n booleanContainer.style.justifyContent = \"space-between\";\n booleanContainer.style.width = \"70%\";\n booleanContainer.style.margin = \"auto\";\n const booleanOptions = (assets === null || assets === void 0 ? void 0 : assets.addIcon) ? ['👍', '👎'] : getBooleanOptions(language);\n // Create a input button element for each value in the question's value array\n booleanOptions.forEach((option, index) => {\n const container = document.createElement(\"label\");\n container.classList.add(\"magicfeedback-boolean-option\");\n container.htmlFor = `rating-${ref}-${index}`;\n container.style.cursor = \"pointer\";\n container.style.border = \"1px solid #000\";\n container.style.display = \"flex\";\n container.style.justifyContent = \"center\";\n container.style.alignItems = \"center\";\n container.style.margin = \"auto\";\n container.style.padding = \"0\";\n container.style.width = \"45%\";\n container.style.height = \"38px\";\n const label = document.createElement(\"label\");\n label.htmlFor = `rating-${ref}-${index}`;\n label.textContent = option;\n label.style.margin = \"0\";\n label.style.padding = \"0\";\n const input = document.createElement(\"input\");\n input.id = `rating-${ref}-${index}`;\n input.type = \"radio\";\n input.name = ref;\n input.value = ['Yes', 'No'][index];\n input.classList.add(elementTypeClass);\n input.classList.add(\"magicfeedback-input\");\n input.style.position = \"absolute\";\n input.style.opacity = \"0\";\n input.style.width = \"0\";\n input.style.height = \"0\";\n input.style.margin = \"0\";\n input.addEventListener(\"change\", () => {\n if (send)\n send();\n });\n if (urlParamValue && urlParamValue.toLowerCase() === input.value.toLowerCase()) {\n input.checked = true;\n }\n container.appendChild(input);\n container.appendChild(label);\n booleanContainer.appendChild(container);\n });\n element.appendChild(booleanContainer);\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.RATING_EMOJI:\n element = document.createElement(\"div\");\n elementTypeClass = 'magicfeedback-rating';\n const ratingContainer = document.createElement('div');\n ratingContainer.classList.add('magicfeedback-rating-container');\n const maxRating = (assets === null || assets === void 0 ? void 0 : assets.max) ? Number(assets === null || assets === void 0 ? void 0 : assets.max) : 5;\n const minRating = (assets === null || assets === void 0 ? void 0 : assets.min) ? Number(assets === null || assets === void 0 ? void 0 : assets.min) : 1;\n const ratingPlaceholder = createRatingPlaceholder(minRating, maxRating, assets === null || assets === void 0 ? void 0 : assets.minPlaceholder, assets === null || assets === void 0 ? void 0 : assets.maxPlaceholder, assets === null || assets === void 0 ? void 0 : assets.extraOption);\n for (let i = minRating; i <= maxRating; i++) {\n const ratingOption = document.createElement('div');\n ratingOption.classList.add('magicfeedback-rating-option');\n const containerLabel = document.createElement('label');\n containerLabel.htmlFor = `rating-${ref}-${i}`;\n containerLabel.classList.add('magicfeedback-rating-option-label-container');\n const ratingLabel = document.createElement('label');\n ratingLabel.htmlFor = `rating-${ref}-${i}`;\n ratingLabel.textContent = i.toString();\n const ratingImage = document.createElement('img');\n ratingImage.alt = `face-${ref}-${i}`;\n ratingImage.className = `rating-image${i}`;\n if (minRating === 0 && maxRating === 10) {\n ratingImage.src = `${url}/${i}.svg`;\n ratingImage.onerror = () => ratingImage.src = `${defaultUrl}/${i}.svg`;\n }\n else if (minRating === 1 && maxRating === 5) {\n switch (i) {\n case 1:\n ratingImage.src = `${url}/1.svg`;\n ratingImage.onerror = () => ratingImage.src = `${defaultUrl}/1.svg`;\n break;\n case 2:\n ratingImage.src = `${url}/2.svg`;\n ratingImage.onerror = () => ratingImage.src = `${defaultUrl}/2.svg`;\n break;\n case 3:\n ratingImage.src = `${url}/6.svg`;\n ratingImage.onerror = () => ratingImage.src = `${defaultUrl}/6.svg`;\n break;\n case 4:\n ratingImage.src = `${url}/9.svg`;\n ratingImage.onerror = () => ratingImage.src = `${defaultUrl}/9.svg`;\n break;\n case 5:\n ratingImage.src = `${url}/10.svg`;\n ratingImage.onerror = () => ratingImage.src = `${defaultUrl}/10.svg`;\n break;\n }\n }\n else {\n const ratingNum = Math.round((i - minRating) * (10 / (maxRating - minRating)));\n ratingImage.src = `${url}/${ratingNum}.svg`;\n ratingImage.onerror = () => ratingImage.src = `${defaultUrl}/${ratingNum}.svg`;\n }\n const input = document.createElement(\"input\");\n input.id = `rating-${ref}-${i}`;\n input.type = \"radio\";\n input.name = ref;\n input.value = i.toString();\n input.classList.add(elementTypeClass);\n input.classList.add(\"magicfeedback-input\");\n if (send) {\n input.addEventListener(\"change\", () => {\n send();\n });\n }\n if (urlParamValue && urlParamValue === input.value) {\n input.checked = true;\n }\n containerLabel.appendChild(input);\n containerLabel.appendChild(ratingImage);\n containerLabel.appendChild(ratingLabel);\n ratingOption.appendChild(containerLabel);\n ratingContainer.appendChild(ratingOption);\n }\n if ((assets === null || assets === void 0 ? void 0 : assets.extraOption) && (assets === null || assets === void 0 ? void 0 : assets.extraOptionText)) {\n const extraOption = document.createElement('div');\n extraOption.classList.add('magicfeedback-rating-option');\n const containerLabel = document.createElement('label');\n containerLabel.htmlFor = `rating-${ref}-extra`;\n containerLabel.classList.add('magicfeedback-rating-option-label-container');\n const ratingLabel = document.createElement('label');\n ratingLabel.htmlFor = `rating-${ref}-extra`;\n ratingLabel.textContent = assets === null || assets === void 0 ? void 0 : assets.extraOptionText;\n // Add a question mark icon to the extra option\n const ratingImage = document.createElement('img');\n ratingImage.src = \"https://magicfeedback-c6458-dev.web.app/assets/question.svg\";\n ratingImage.alt = `face-${ref}-extra`;\n ratingImage.className = `magicfeedback-rating-image-extra`;\n const input = document.createElement(\"input\");\n input.id = `rating-${ref}-extra`;\n input.type = \"radio\";\n input.name = ref;\n input.value = '-';\n input.classList.add(elementTypeClass);\n input.classList.add(\"magicfeedback-input\");\n if (send) {\n input.addEventListener(\"change\", () => {\n send();\n });\n }\n containerLabel.appendChild(input);\n containerLabel.appendChild(ratingImage);\n containerLabel.appendChild(ratingLabel);\n extraOption.appendChild(containerLabel);\n ratingContainer.appendChild(extraOption);\n }\n element.appendChild(ratingPlaceholder);\n element.appendChild(ratingContainer);\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.RATING_NUMBER:\n elementTypeClass = 'magicfeedback-rating-number';\n element = createRatingNumberElement(ref, assets, order, direction, isPhone, elementTypeClass, send, urlParamValue);\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.RATING_STAR:\n element = document.createElement(\"div\");\n elementTypeClass = 'magicfeedback-rating-star';\n const ratingStarContainer = createStarRating(ref, assets === null || assets === void 0 ? void 0 : assets.minPlaceholder, assets === null || assets === void 0 ? void 0 : assets.maxPlaceholder, send, urlParamValue);\n element.appendChild(ratingStarContainer);\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.MULTIPLECHOISE_IMAGE:\n element = document.createElement(\"div\");\n elementTypeClass = 'magicfeedback-multiple-choice-image';\n // Display de items inside a flex container if only have one item display it as a single image in the center, if have 2 items display them as a row, if have more than 2 items display them as a grid, if have 4 items display them as a 2x2 grid and if have 6 items display them as a 3x2 grid\n const multipleChoiceImageContainer = document.createElement(\"div\");\n multipleChoiceImageContainer.classList.add(\"magicfeedback-multiple-choice-image-container\");\n multipleChoiceImageContainer.style.display = \"flex\";\n multipleChoiceImageContainer.style.flexDirection = \"row\";\n multipleChoiceImageContainer.style.flexWrap = \"wrap\";\n multipleChoiceImageContainer.style.justifyContent = \"center\";\n const maxItems = value.length;\n let itemsPerRow = 1;\n let itemsPerColumn = 1;\n if (window.innerWidth < 600) {\n itemsPerRow = 1;\n itemsPerColumn = maxItems;\n }\n else {\n switch (maxItems) {\n case 1:\n case 2:\n case 3:\n itemsPerRow = maxItems;\n itemsPerColumn = 1;\n break;\n case 4:\n case 5:\n case 6:\n itemsPerColumn = 2;\n itemsPerRow = Math.ceil(maxItems / itemsPerColumn);\n break;\n case 7:\n case 8:\n case 9:\n itemsPerColumn = 3;\n itemsPerRow = Math.ceil(maxItems / itemsPerColumn);\n break;\n default:\n itemsPerColumn = 4;\n itemsPerRow = Math.ceil(maxItems / itemsPerColumn);\n break;\n }\n }\n const useLabel = (assets === null || assets === void 0 ? void 0 : assets.addTitle) === undefined ? false : assets === null || assets === void 0 ? void 0 : assets.addTitle;\n const multiOptions = (assets === null || assets === void 0 ? void 0 : assets.multiOption) === undefined ? false : assets === null || assets === void 0 ? void 0 : assets.multiOption;\n const extraOption = (assets === null || assets === void 0 ? void 0 : assets.extraOption) === undefined ? false : assets === null || assets === void 0 ? void 0 : assets.extraOption;\n // reorder the options if randomPosition is true\n if (randomPosition) {\n value = value.sort(() => Math.random() - 0.5);\n }\n function generateOption(option) {\n try {\n const { position, url, value } = option;\n const container = document.createElement(\"label\");\n container.classList.add(\"magicfeedback-multiple-choice-image-option\");\n container.style.width = `calc( ${100 / itemsPerRow}% - 10px)`;\n container.style.height = `calc( ${100 / itemsPerColumn}% - 10px)`;\n container.style.margin = \"5px\";\n const containerLabel = document.createElement('label');\n containerLabel.htmlFor = `rating-${ref}-${position}`;\n containerLabel.classList.add('magicfeedback-image-option-label-container');\n containerLabel.style.display = \"flex\";\n containerLabel.style.flexDirection = \"column\";\n // Add a effect on hover and on select\n containerLabel.addEventListener(\"mouseover\", () => {\n containerLabel.style.border = \"2px solid #000\";\n });\n containerLabel.addEventListener(\"mouseout\", () => {\n containerLabel.style.border = \"none\";\n });\n containerLabel.addEventListener(\"click\", () => {\n containerLabel.style.border = \"2px solid #000\";\n });\n const label = document.createElement(\"label\");\n label.textContent = value;\n label.classList.add(\"magicfeedback-multiple-choice-image-label\");\n const input = document.createElement(\"input\");\n input.id = `rating-${ref}-${position}`;\n input.type = multiOptions ? \"checkbox\" : \"radio\";\n input.name = ref;\n input.value = value;\n input.style.position = \"absolute\";\n input.style.opacity = \"0\";\n input.style.width = \"0\";\n input.style.height = \"0\";\n input.classList.add(\"magicfeedback-input\");\n if (urlParamValue && urlParamValue === input.value) {\n input.checked = true;\n }\n if (!multiOptions && send) {\n input.addEventListener(\"change\", () => {\n console.log('send');\n send();\n });\n }\n // Add max size to the image\n const image = document.createElement(\"img\");\n image.classList.add(\"magicfeedback-multiple-choice-image-image\");\n image.src = url;\n image.style.cursor = \"pointer\";\n image.style.backgroundSize = \"cover\";\n image.style.backgroundPosition = \"center\";\n image.style.width = \"100%\";\n image.style.height = \"100%\";\n image.style.objectFit = \"cover\";\n image.style.margin = \"auto\";\n containerLabel.appendChild(input);\n containerLabel.appendChild(image);\n if (useLabel)\n containerLabel.appendChild(label);\n container.appendChild(containerLabel);\n multipleChoiceImageContainer.appendChild(container);\n }\n catch (e) {\n console.error(e);\n }\n }\n // The image is the only input but can have a title\n value.forEach((option) => generateOption(JSON.parse(option)));\n if (extraOption && (assets === null || assets === void 0 ? void 0 : assets.extraOptionValue) && (assets === null || assets === void 0 ? void 0 : assets.extraOptionValue.length) > 0) {\n generateOption(assets === null || assets === void 0 ? void 0 : assets.extraOptionValue[0]);\n }\n element.appendChild(multipleChoiceImageContainer);\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.SELECT:\n // Create a select element for RADIO and MULTIPLECHOICE types\n element = document.createElement(\"select\");\n elementTypeClass = \"magicfeedback-select\";\n // Create an option <option value=\"\" disabled selected hidden>Please Choose...</option>\n const option = document.createElement(\"option\");\n option.value = \"\";\n option.text = format === 'slim' ? parseTitle(title, language) : (defaultValue || \"Select an option\");\n option.disabled = true;\n option.selected = true;\n element.appendChild(option);\n value.forEach((optionValue) => {\n // Create an option element for each value in the question's value array\n const option = document.createElement(\"option\");\n option.value = optionValue;\n option.text = optionValue;\n element.appendChild(option);\n });\n if (urlParamValue && value.includes(urlParamValue)) {\n element.value = urlParamValue;\n }\n if (send) {\n element.addEventListener(\"change\", () => {\n send();\n });\n }\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.DATE:\n // Create an input element with type \"date\" for DATE type\n element = document.createElement(\"input\");\n element.type = \"date\";\n element.required = require;\n element.placeholder = placeholderText || placeholder_1.placeholder.date(language || 'en');\n elementTypeClass = \"magicfeedback-date\";\n if (urlParamValue) {\n element.value = urlParamValue;\n }\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.CONSENT:\n // Create an input element with type \"checkbox\" for BOOLEAN type\n element = document.createElement(\"input\");\n elementTypeClass = \"magicfeedback-consent\";\n element.type = \"checkbox\";\n element.id = `magicfeedback-${id}`;\n element.name = ref;\n element.value = \"true\";\n element.required = require;\n element.classList.add(\"magicfeedback-consent\");\n element.classList.add(\"magicfeedback-input\");\n if (urlParamValue && value.includes(urlParamValue)) {\n element.checked = true;\n }\n if (send) {\n element.addEventListener(\"change\", () => {\n send();\n });\n }\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.EMAIL:\n // Create an input element with type \"email\" for EMAIL type\n element = document.createElement(\"input\");\n element.type = \"email\";\n element.required = require;\n element.placeholder = placeholderText || \"you@example.com\";\n elementTypeClass = \"magicfeedback-email\";\n if (urlParamValue) {\n element.value = urlParamValue;\n }\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.PASSWORD:\n // Create an input element with type \"password\" for PASSWORD type\n element = document.createElement(\"input\");\n element.type = \"password\";\n element.required = require;\n element.placeholder = placeholderText || placeholder_1.placeholder.password(language || 'en');\n elementTypeClass = \"magicfeedback-password\";\n if (urlParamValue) {\n element.value = urlParamValue;\n }\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.MULTI_QUESTION_MATRIX:\n element = document.createElement(\"div\");\n elementTypeClass = \"magicfeedback-multi-question-matrix\";\n const matrixContainer = document.createElement(\"div\");\n matrixContainer.classList.add(\"magicfeedback-multi-question-matrix-container\");\n let options = (assets === null || assets === void 0 ? void 0 : assets.options) || [];\n let values = [...value];\n let exclusiveValues = [];\n if (randomPosition) {\n options = options === null || options === void 0 ? void 0 : options.sort(() => Math.random() - 0.5);\n values = [...values].sort(() => Math.random() - 0.5);\n }\n if (assets === null || assets === void 0 ? void 0 : assets.exclusiveAnswers) {\n exclusiveValues = assets === null || assets === void 0 ? void 0 : assets.exclusiveAnswers;\n exclusiveValues === null || exclusiveValues === void 0 ? void 0 : exclusiveValues.forEach((answer) => {\n if (!values.includes(answer))\n values.push(answer);\n });\n }\n if (window.innerWidth < 600) {\n const list = document.createElement(\"div\");\n list.classList.add(\"magicfeedback-multi-question-matrix-list\");\n // Add the questions as rows\n options === null || options === void 0 ? void 0 : options.forEach((question) => {\n const row = document.createElement(\"div\");\n row.classList.add(\"magicfeedback-multi-question-matrix-list-item\");\n row.style.display = \"flex\";\n row.style.flexDirection = \"column\";\n row.style.alignItems = \"flex-start\";\n row.style.marginBottom = \"10px\";\n // Add the question label as the first cell\n const label = document.createElement(\"label\");\n label.classList.add(\"magicfeedback-multi-question-matrix-label\");\n label.style.paddingBottom = \"10px\";\n label.textContent = question;\n row.appendChild(label);\n // Add the options as radio buttons, one by line\n values.forEach((option) => {\n const container = document.createElement(\"div\");\n container.classList.add(`magicfeedback-radio-container`);\n container.style.display = \"flex\";\n container.style.alignItems = \"center\";\n container.style.justifyContent = \"flex-start\";\n container.style.width = \"99%\";\n container.style.margin = \"5px auto\";\n const label = document.createElement(\"label\");\n const input = document.createElement(\"input\");\n input.id = `${ref}-${question}-${option}`;\n input.type = \"radio\";\n input.name = `${ref}-${question}`;\n input.value = option;\n input.classList.add(\"magicfeedback-input\");\n label.textContent = option;\n label.htmlFor = `${ref}-${question}-${option}`;\n container.appendChild(input);\n container.appendChild(label);\n row.appendChild(container);\n });\n list.appendChild(row);\n });\n matrixContainer.appendChild(list);\n }\n else {\n //The matrix have a table format with the questions in the rows and the options in the columns, all the options have a title in the header of the column and is posssioble select moere than one option per question\n const table = document.createElement(\"table\");\n table.classList.add(\"magicfeedback-multi-question-matrix-table\");\n // Create the header of the table\n const header = document.createElement(\"thead\");\n header.classList.add(\"magicfeedback-multi-question-matrix-header\");\n header.style.paddingBottom = \"15px\";\n const headerRow = document.createElement(\"tr\");\n // Add an empty cell for the question column\n const emptyHeaderCell = document.createElement(\"th\");\n headerRow.appendChild(emptyHeaderCell);\n // Add the options as column headers\n values.forEach((option) => {\n const headerCell = document.createElement(\"th\");\n headerCell.textContent = option;\n headerRow.appendChild(headerCell);\n });\n header.appendChild(headerRow);\n table.appendChild(header);\n // Create the body of the table\n const body = document.createElement(\"tbody\");\n // Add the questions as rows\n options === null || options === void 0 ? void 0 : options.forEach((question) => {\n const row = document.createElement(\"tr\");\n row.classList.add(\"magicfeedback-multi-question-matrix-row-tr\");\n // Add the question label as the first cell\n const questionCell = document.createElement(\"td\");\n questionCell.style.minWidth = \"200px\";\n questionCell.style.padding = \"10px\";\n const label = document.createElement(\"label\");\n label.classList.add(\"magicfeedback-multi-question-matrix-label\");\n label.textContent = question;\n questionCell.appendChild(label);\n row.appendChild(questionCell);\n // Add the options as radio buttons or checkboxes\n values.forEach((option) => {\n const optionCell = document.createElement(\"td\");\n const input = document.createElement(\"input\");\n input.type = \"radio\";\n input.name = `${ref}-${question}`;\n input.value = option;\n input.id = `${ref}-${question}-${option}`;\n input.classList.add(\"magicfeedback-input\");\n optionCell.appendChild(input);\n row.appendChild(optionCell);\n });\n body.appendChild(row);\n });\n table.appendChild(body);\n matrixContainer.appendChild(table);\n }\n element.appendChild(matrixContainer);\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.PRIORITY_LIST:\n element = document.createElement(\"div\");\n elementTypeClass = \"magicfeedback-priority-list\";\n const priorityListContainer = document.createElement(\"div\");\n priorityListContainer.classList.add(\"magicfeedback-priority-list-container\");\n // The priority list have a list of items that the user can order by priority,\n // the item is a card with the number of the position and title in the left and a\n // arrow up and down to change the position of the item\n const list = document.createElement(\"ul\");\n list.classList.add(\"magicfeedback-priority-list-list\");\n if (randomPosition) {\n value = value.sort(() => Math.random() - 0.5);\n }\n value.forEach((option, index) => {\n const item = document.createElement(\"li\");\n item.classList.add(\"magicfeedback-priority-list-item\");\n item.style.display = \"flex\";\n item.style.justifyContent = \"space-between\";\n item.style.alignItems = \"center\";\n item.style.margin = \"5px\";\n // Add input position\n const input = document.createElement(\"input\");\n input.classList.add(\"magicfeedback-input-magicfeedback-priority-list\");\n input.classList.add(\"magicfeedback-input\");\n input.type = \"hidden\";\n input.id = `priority-list-${ref}`;\n input.name = ref;\n input.value = `${index + 1}. ${option}`;\n item.appendChild(input);\n const itemLabel = document.createElement(\"label\");\n itemLabel.classList.add(\"magicfeedback-priority-list-item-label\");\n itemLabel.textContent = `${index + 1}. ${option}`;\n item.appendChild(itemLabel);\n const arrowContainer = document.createElement(\"div\");\n arrowContainer.style.display = \"flex\";\n arrowContainer.style.alignItems = \"center\";\n arrowContainer.style.justifyContent = \"space-between\";\n const upArrow = document.createElement(\"img\");\n upArrow.classList.add(\"magicfeedback-priority-list-arrow-up\");\n // Add a up arrow svg icon\n upArrow.src = \"https://magicfeedback-c6458-dev.web.app/assets/arrow.svg\";\n upArrow.style.width = \"20px\";\n upArrow.style.height = \"20px\";\n upArrow.style.cursor = \"pointer\";\n upArrow.style.margin = \"0 5px\";\n upArrow.style.color = \"#000\";\n upArrow.style.visibility = index === 0 ? \"hidden\" : \"visible\";\n upArrow.addEventListener(\"click\", () => {\n var _a, _b, _c, _d;\n const previous = item.previousElementSibling;\n if (previous) {\n const position = Number((_a = input.value) === null || _a === void 0 ? void 0 : _a.split(\".\")[0]) - 1;\n input.value = `${position}. ${option}`;\n itemLabel.textContent = `${position}. ${option}`;\n upArrow.style.visibility = position === 1 ? \"hidden\" : \"visible\";\n downArrow.style.visibility = position === value.length ? \"hidden\" : \"visible\";\n // Update the value of the item that had the new value to update the order\n const previousInput = previous.querySelector(\".magicfeedback-input-magicfeedback-priority-list\");\n const previousLabel = previous.querySelector(\".magicfeedback-priority-list-item-label\");\n const previousArrowUp = previous.querySelector(\".magicfeedback-priority-list-arrow-up\");\n const previousArrowDown = previous.querySelector(\".magicfeedback-priority-list-arrow-down\");\n if (previousInput && previousLabel && previousArrowUp && previousArrowDown) {\n const newPosition = Number((_b = previousInput.value) === null || _b === void 0 ? void 0 : _b.split(\".\")[0]) + 1;\n previousInput.value = `${newPosition}.${(_c = previousLabel.textContent) === null || _c === void 0 ? void 0 : _c.split(\".\")[1]}`;\n previousLabel.textContent = `${newPosition}.${(_d = previousLabel.textContent) === null || _d === void 0 ? void 0 : _d.split(\".\")[1]}`;\n previousArrowUp.style.visibility = newPosition === 1 ? \"hidden\" : \"visible\";\n previousArrowDown.style.visibility = newPosition === value.length ? \"hidden\" : \"visible\";\n }\n list.insertBefore(item, previous);\n }\n });\n arrowContainer.appendChild(upArrow);\n const downArrow = document.createElement(\"img\");\n downArrow.classList.add(\"magicfeedback-priority-list-arrow-down\");\n // Add a down arrow svg icon\n downArrow.src = \"https://magicfeedback-c6458-dev.web.app/assets/arrow.svg\";\n downArrow.style.width = \"20px\";\n downArrow.style.height = \"20px\";\n downArrow.style.cursor = \"pointer\";\n downArrow.style.margin = \"0 5px\";\n downArrow.style.color = \"#000\";\n downArrow.style.transform = \"rotate(180deg)\";\n // Hidden if is the bottom\n downArrow.style.visibility = index === value.length - 1 ? \"hidden\" : \"visible\";\n downArrow.addEventListener(\"click\", () => {\n var _a, _b, _c;\n const next = item.nextElementSibling;\n if (next) {\n const position = Number((_a = input.value) === null || _a === void 0 ? void 0 : _a.split(\".\")[0]) + 1;\n input.value = position.toString();\n itemLabel.textContent = `${position.toString()}. ${option}`;\n upArrow.style.visibility = position === 1 ? \"hidden\" : \"visible\";\n downArrow.style.visibility = position === value.length ? \"hidden\" : \"visible\";\n // Update the value of the item that had the new value to update the order\n const nextInput = next.querySelector(\".magicfeedback-input-magicfeedback-priority-list\");\n const nextLabel = next.querySelector(\".magicfeedback-priority-list-item-label\");\n const nextArrowUp = next.querySelector(\".magicfeedback-priority-list-arrow-up\");\n const nextArrowDown = next.querySelector(\".magicfeedback-priority-list-arrow-down\");\n if (nextInput && nextLabel && nextArrowUp && nextArrowDown) {\n const newPosition = Number(nextInput.value.split(\".\")[0]) - 1;\n nextInput.value = `${newPosition}.${(_b = nextLabel.textContent) === null || _b === void 0 ? void 0 : _b.split(\".\")[1]}`;\n nextLabel.textContent = `${newPosition}.${(_c = nextLabel.textContent) === null || _c === void 0 ? void 0 : _c.split(\".\")[1]}`;\n nextArrowUp.style.visibility = newPosition === 1 ? \"hidden\" : \"visible\";\n nextArrowDown.style.visibility = newPosition === value.length ? \"hidden\" : \"visible\";\n }\n list.insertBefore(next, item);\n }\n });\n arrowContainer.appendChild(downArrow);\n item.appendChild(arrowContainer);\n list.appendChild(item);\n });\n priorityListContainer.appendChild(list);\n element.appendChild(priorityListContainer);\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.POINT_SYSTEM:\n element = document.createElement(\"div\");\n elementTypeClass = \"magicfeedback-point-system\";\n const pointSystemContainer = document.createElement(\"div\");\n pointSystemContainer.classList.add(\"magicfeedback-point-system-container\");\n // The point system have a list of items that the user can assign a value, the user can assign a value to each item in % of the total points but the total points can't be more than 100\n const pointSystemList = document.createElement(\"ul\");\n pointSystemList.classList.add(\"magicfeedback-point-system-list\");\n pointSystemList.style.padding = \"0\";\n const totalPoints = 100;\n const pointsPerItem = totalPoints / value.length;\n // Add error message to say that the 100 % is mandatory\n const errorMessage = document.createElement(\"div\");\n errorMessage.classList.add(\"magicfeedback-error\");\n errorMessage.textContent = placeholder_1.placeholder.pointsystemerror(language || 'en');\n errorMessage.style.color = \"#C70039\";\n errorMessage.style.fontSize = \"14px\";\n errorMessage.style.textAlign = \"right\";\n errorMessage.style.width = \"100%\";\n errorMessage.style.display = \"none\";\n //Add a total points counter\n const totalPointsContainer = document.createElement(\"div\");\n totalPointsContainer.classList.add(\"magicfeedback-point-system-total\");\n totalPointsContainer.textContent = `0 / 100 %`;\n totalPointsContainer.style.textAlign = \"right\";\n totalPointsContainer.style.fontSize = \"15px\";\n totalPointsContainer.style.marginTop = \"5px\";\n value.forEach((option, index) => {\n const item = document.createElement(\"li\");\n item.classList.add(\"magicfeedback-point-system-item\");\n item.style.display = \"flex\";\n item.style.justifyContent = \"space-between\";\n item.style.alignItems = \"center\";\n item.style.margin = \"5px\";\n const itemLabel = document.createElement(\"label\");\n itemLabel.textContent = option;\n itemLabel.style.fontSize = \"15px\";\n item.appendChild(itemLabel);\n const inputContainer = document.createElement(\"span\");\n inputContainer.classList.add(\"magicfeedback-point-system-input-container\");\n const itemInput = document.createElement(\"input\");\n itemInput.name = ref;\n itemInput.id = `${option}`;\n itemInput.type = \"number\";\n itemInput.min = \"0\";\n itemInput.max = `${totalPoints}`;\n itemInput.value = `0`;\n itemInput.classList.add(\"magicfeedback-input\");\n itemInput.style.width = \"40px\";\n itemInput.style.border = \"0\";\n itemInput.style.textAlign = \"center\";\n itemInput.style.margin = \"0 5px\";\n itemInput.autofocus = index === 0;\n // Add the % symbol to the input\n const percentSymbol = document.createElement(\"span\");\n percentSymbol.textContent = \"%\";\n percentSymbol.style.color = \"#000\";\n // Control the total points assigned to the items\n itemInput.addEventListener(\"input\", () => {\n const allInputs = pointSystemList.querySelectorAll(\"input\");\n let total = 0;\n allInputs.forEach((input) => {\n total += Number(input.value);\n });\n if (total > totalPoints) {\n itemInput.value = `${pointsPerItem}%`;\n total = total - Number(itemInput.value);\n }\n const submitButton = document.getElementById(\"magicfeedback-submit\");\n if (submitButton) {\n if (total < 100) {\n // Disable the submit button if the total points are less than 100\n totalPointsContainer.style.color = \"orange\";\n submitButton.setAttribute(\"disabled\", \"true\");\n }\n else {\n errorMessage.style.display = \"none\";\n totalPointsContainer.style.color = \"green\";\n submitButton.removeAttribute(\"disabled\");\n }\n }\n totalPointsContainer.textContent = `${total} / 100 %`;\n });\n itemInput.addEventListener(\"focus\", () => {\n const submitButton = document.getElementById(\"magicfeedback-submit\");\n if (submitButton) {\n submitButton.setAttribute(\"disabled\", \"true\");\n submitButton.addEventListener(\"pointerover\", () => {\n const allInputs = pointSystemList.querySelectorAll(\"input\");\n let total = 0;\n allInputs.forEach((input) => {\n total += Number(input.value);\n });\n if (total < 100)\n errorMessage.style.display = \"block\";\n });\n }\n });\n inputContainer.appendChild(itemInput);\n inputContainer.appendChild(percentSymbol);\n item.appendChild(inputContainer);\n pointSystemList.appendChild(item);\n });\n pointSystemContainer.appendChild(pointSystemList);\n pointSystemContainer.appendChild(totalPointsContainer);\n pointSystemContainer.appendChild(errorMessage);\n element.appendChild(pointSystemContainer);\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.INFO_PAGE:\n element = document.createElement(\"div\");\n elementTypeClass = \"magicfeedback-info-page\";\n const infoMessageElement = document.createElement(\"div\");\n infoMessageElement.classList.add(\"magicfeedback-info-message\");\n infoMessageElement.innerHTML = placeholderText;\n element.appendChild(infoMessageElement);\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.UPLOAD_IMAGE:\n element = document.createElement(\"input\");\n element.type = \"file\";\n element.accept = \"image/*\";\n element.required = require;\n element.multiple = (assets === null || assets === void 0 ? void 0 : assets.multiple) || false;\n element.maxLength = (assets === null || assets === void 0 ? void 0 : assets.maxFiles) || 1;\n elementTypeClass = \"magicfeedback-upload-image\";\n break;\n case types_1.FEEDBACKAPPANSWERTYPE.UPLOAD_FILE:\n element = document.createElement(\"input\");\n element.type = \"file\";\n element.required = require;\n element.multiple = (assets === null || assets === void 0 ? void 0 : assets.multiple) || false;\n element.maxLength = (assets === null || assets === void 0 ? void 0 : assets.maxFiles) || 1;\n elementTypeClass = \"magicfeedback-upload-file\";\n break;\n default:\n return elementContainer;\n }\n element.id = `magicfeedback-${id}`;\n element.setAttribute(\"name\", ref);\n element.classList.add(elementTypeClass);\n if (defaultValue !== undefined || urlParamValue !== null) {\n element.value = urlParamValue || defaultValue;\n }\n if (![\"RADIO\", \"MULTIPLECHOICE\"].includes(type)) {\n element.classList.add(\"magicfeedback-input\");\n element.required = require;\n }\n // Add the label and input element to the form\n const label = document.createElement(\"label\");\n label.setAttribute(\"for\", `magicfeedback-${id}`);\n label.textContent = parseTitle(title, language);\n label.classList.add(\"magicfeedback-label\");\n const subLabel = document.createElement(\"label\");\n subLabel.textContent = parseTitle(assets === null || assets === void 0 ? void 0 : assets.subtitle, language);\n subLabel.classList.add(\"magicfeedback-sublabel\");\n if ((_a = assets === null || assets === void 0 ? void 0 : assets.subtitleStyle) === null || _a === void 0 ? void 0 : _a.includes('italic')) {\n subLabel.style.fontStyle = \"italic\";\n }\n if ((_b = assets === null || assets === void 0 ? void 0 : assets.subtitleStyle) === null || _b === void 0 ? void 0 : _b.includes('bold')) {\n subLabel.style.fontWeight = \"bold\";\n }\n if ((_c = assets === null || assets === void 0 ? void 0 : assets.subtitleStyle) === null || _c === void 0 ? void 0 : _c.includes('underline')) {\n subLabel.style.textDecoration = \"underline\";\n }\n if ([\"CONSENT\"].includes(type)) {\n elementContainer.classList.add(\"magicfeedback-consent-container\");\n elementContainer.appendChild(element);\n elementContainer.appendChild(label);\n elementContainer.appendChild(subLabel);\n }\n else {\n if (format !== 'slim') {\n elementContainer.appendChild(label);\n elementContainer.appendChild(subLabel);\n if ((assets === null || assets === void 0 ? void 0 : assets.general) !== undefined && (assets === null || assets === void 0 ? void 0 : assets.general) !== \"\") {\n // Add a image to the form\n const image = document.createElement(\"img\");\n image.src = assets === null || assets === void 0 ? void 0 : assets.general;\n image.classList.add(\"magicfeedback-image\");\n // Add a max default width to the image\n image.style.maxWidth = \"auto\";\n image.style.height = \"400px\";\n image.style.margin = \"10px 0\";\n elementContainer.appendChild(image);\n }\n }\n if (type === \"LONGTEXT\" && maxCharacters > 0) {\n const counter = document.createElement(\"div\");\n counter.classList.add(\"magicfeedback-counter\");\n counter.textContent = `${element.value.length}/${maxCharacters}`;\n counter.style.textAlign = \"right\";\n counter.style.fontSize = \"15px\";\n counter.style.marginTop = \"5px\";\n element.addEventListener(\"input\", () => {\n counter.textContent = `${element.value.length}/${maxCharacters}`;\n });\n elementContainer.appendChild(element);\n elementContainer.appendChild(counter);\n if ((assets === null || assets === void 0 ? void 0 : assets.extraOption) && (assets === null || assets === void 0 ? void 0 : assets.extraOptionText)) {\n const skipContainer = document.createElement(\"div\");\n skipContainer.classList.add(\"magicfeedback-skip-container\");\n skipContainer.classList.add(`magicfeedback-checkbox-container`);\n skipContainer.style.display = \"flex\";\n skipContainer.style.justifyContent = \"flex-start\";\n // Option to skip the question checkbox\n const skipButton = document.createElement(\"input\");\n skipButton.classList.add(\"magicfeedback-skip\");\n skipButton.type = \"checkbox\";\n skipButton.id = `skip-${ref}`;\n skipButton.name = ref;\n skipButton.value = '-';\n skipButton.style.cursor = \"pointer\";\n const skipLabel = document.createElement(\"label\");\n skipLabel.htmlFor = `skip-${ref}`;\n skipLabel.textContent = assets === null || assets === void 0 ? void 0 : assets.extraOptionText;\n skipLabel.style.fontSize = \"15px\";\n skipLabel.style.cursor = \"pointer\";\n skipLabel.style.margin = \"0 5px\";\n skipButton.addEventListener(\"click\", () => {\n element.value = '-';\n if (send)\n send();\n });\n skipContainer.appendChild(skipButton);\n skipContainer.appendChild(skipLabel);\n elementContainer.appendChild(skipContainer);\n }\n }\n else {\n elementContainer.appendChild(element);\n }\n }\n return elementContainer;\n}\nfunction renderActions(identity = '', backAction, sendButtonText = \"Submit\", backButtonText = \"Back\", nextButtonText = \"Next\") {\n const actionContainer = document.createElement(\"div\");\n actionContainer.classList.add(\"magicfeedback-action-container\");\n // Create a submit button if specified in options\n const submitButton = document.createElement(\"button\");\n submitButton.id = \"magicfeedback-submit\";\n submitButton.type = \"submit\";\n submitButton.classList.add(\"magicfeedback-submit\");\n submitButton.textContent = identity === 'MAGICSURVEY' ? (nextButtonText || \"Next\") : (sendButtonText || \"Submit\");\n // Create a back button\n const backButton = document.createElement(\"button\");\n backButton.id = \"magicfeedback-back\";\n backButton.type = \"button\";\n backButton.classList.add(\"magicfeedback-back\");\n backButton.textContent = backButtonText || \"Back\";\n backButton.addEventListener(\"click\", backAction);\n backButton.addEventListener(\"click\", () => {\n submitButton.removeAttribute(\"disabled\");\n });\n if (identity === 'MAGICSURVEY') {\n actionContainer.appendChild(backButton);\n }\n actionContainer.appendChild(submitButton);\n return actionContainer;\n}\nexports.renderActions = renderActions;\nfunction createStarRating(ref, minPlaceholder, maxPlaceholder, send = () => {\n}, urlParamValue) {\n const size = 40;\n const selectedClass = \"magicfeedback-rating-star-selected\";\n const starFilled = \"★\";\n const ratingContainer = document.createElement(\"div\");\n ratingContainer.classList.add(\"magicfeedback-rating-star-container\");\n ratingContainer.style.maxWidth = \"300px\";\n ratingContainer.style.margin = \"auto\";\n // Mantiene el valor seleccionado original para restaurar tras hover\n ratingContainer.dataset.originalSelection = '0';\n for (let i = 1; i <= 5; i++) {\n const ratingOption = document.createElement(\"label\");\n ratingOption.classList.add(\"magicfeedback-rating-star-option\");\n // Create hidden radio input\n const ratingInput = document.createElement(\"input\");\n ratingInput.id = `rating-${ref}-${i}`;\n ratingInput.type = \"radio\";\n ratingInput.name = ref;\n ratingInput.value = i.toString();\n ratingInput.style.position = \"absolute\";\n ratingInput.style.opacity = \"0\";\n ratingInput.style.width = \"0\";\n ratingInput.style.height = \"0\";\n ratingInput.classList.add(\"magicfeedback-input\");\n if (urlParamValue && urlParamValue === ratingInput.value) {\n ratingInput.checked = true;\n }\n // Update filled stars on radio input change\n ratingInput.addEventListener(\"change\", () => {\n const allStars = ratingContainer.querySelectorAll(\".rating__star\");\n for (let j = 0; j < allStars.length; j++) {\n if (j + 1 <= Number(ratingInput.value)) {\n if (!allStars[j].classList.contains(selectedClass))\n allStars[j].classList.add(selectedClass);\n }\n else {\n if (allStars[j].classList.contains(selectedClass))\n allStars[j].classList.remove(selectedClass);\n }\n }\n // Actualizamos el valor original para futuros hover\n ratingContainer.dataset.originalSelection = ratingInput.value;\n if (send)\n send();\n });\n ratingOption.appendChild(ratingInput);\n // Create star element (after for better positioning)\n const starElement = document.createElement(\"label\");\n starElement.htmlFor = `rating-${ref}-${i}`;\n starElement.classList.add(\"rating__star\");\n starElement.textContent = starFilled;\n starElement.style.fontSize = `${size}px`; // Set star size\n starElement.style.color = \"#CCCCCC\"; // Set star color\n starElement.style.cursor = \"pointer\";\n // Hover para previsualizar selección (amarillear todas las anteriores)\n starElement.addEventListener(\"mouseenter\", () => {\n const allStars = ratingContainer.querySelectorAll(\".rating__star\");\n const idx = i - 1; // índice de la estrella sobre la que se hace hover\n allStars.forEach((star, starIdx) => {\n if (starIdx <= idx) {\n if (!star.classList.contains(selectedClass))\n star.classList.add(selectedClass);\n }\n else {\n if (star.classList.contains(selectedClass))\n star.classList.remove(selectedClass);\n }\n });\n });\n // Al salir se restaura la selección original\n starElement.addEventListener(\"mouseleave\", () => {\n const original = Number(ratingContainer.dataset.originalSelection || '0');\n const allStars = ratingContainer.querySelectorAll(\".rating__star\");\n allStars.forEach((star, starIdx) => {\n if (starIdx < original) {\n if (!star.classList.contains(selectedClass))\n star.classList.add(selectedClass);\n }\n else {\n if (star.classList.contains(selectedClass))\n star.classList.remove(selectedClass);\n }\n });\n });\n ratingOption.appendChild(starElement);\n ratingContainer.appendChild(ratingOption);\n }\n ratingContainer.appendChild(createRatingPlaceholder(1, 5, minPlaceholder, maxPlaceholder, false, false));\n return ratingContainer;\n}\nfunction createRatingPlaceholder(min, max, minPlaceholder, maxPlaceholder, extraOption, mobile = true, order = 'ltr', direction = 'row') {\n const ratingPlaceholder = document.createElement('div');\n ratingPlaceholder.classList.add('magicfeedback-rating-placeholder');\n ratingPlaceholder.style.display = \"flex\";\n ratingPlaceholder.style.flexDirection = direction;\n ratingPlaceholder.style.alignItems = \"center\";\n ratingPlaceholder.style.justifyContent = \"space-between\";\n ratingPlaceholder.style.width = extraOption ? `calc(100% - (100% / ${max + 1}))` : \"100%\";\n ratingPlaceholder.style.marginRight = \"auto\";\n if (mobile && window.innerWidth < 600)\n ratingPlaceholder.style.flexDirection = \"column\";\n const ratingPlaceholderMin = document.createElement('span');\n ratingPlaceholderMin.textContent = minPlaceholder;\n ratingPlaceholderMin.classList.add('magicfeedback-rating-placeholder-value');\n ratingPlaceholderMin.style.fontSize = \"15px\";\n ratingPlaceholderMin.style.textAlign = order === 'ltr' ? \"left\" : \"right\";\n ratingPlaceholderMin.style.width = `50%`;\n if (mobile && window.innerWidth < 600 || direction === 'column') {\n ratingPlaceholderMin.textContent = `${min} = ${minPlaceholder}`;\n ratingPlaceholderMin.style.width = '100%';\n ratingPlaceholderMin.style.textAlign = \"left\";\n ratingPlaceholderMin.style.marginBottom = \"5px\";\n }\n const ratingPlaceholderMax = document.createElement('span');\n ratingPlaceholderMax.textContent = maxPlaceholder;\n ratingPlaceholderMax.classList.add('magicfeedback-rating-placeholder-value');\n ratingPlaceholderMax.style.fontSize = \"15px\";\n ratingPlaceholderMax.style.textAlign = order === 'ltr' ? \"right\" : \"left\";\n ratingPlaceholderMax.style.width = `50%`;\n if (mobile && window.innerWidth < 600 || direction === 'column') {\n ratingPlaceholderMax.textContent = `${max} = ${maxPlaceholder}`;\n ratingPlaceholderMax.style.width = '100%';\n ratingPlaceholderMax.style.textAlign = \"left\";\n ratingPlaceholderMax.style.marginBottom = \"5px\";\n }\n if (order === 'ltr') {\n if (minPlaceholder)\n ratingPlaceholder.appendChild(ratingPlaceholderMin);\n if (maxPlaceholder)\n ratingPlaceholder.appendChild(ratingPlaceholderMax);\n }\n else {\n if (maxPlaceholder)\n ratingPlaceholder.appendChild(ratingPlaceholderMax);\n if (minPlaceholder)\n ratingPlaceholder.appendChild(ratingPlaceholderMin);\n }\n return ratingPlaceholder;\n}\nfunction renderError(error) {\n const errorElement = document.createElement(\"div\");\n errorElement.classList.add(\"magicfeedback-error\");\n errorElement.textContent = error;\n return errorElement;\n}\nexports.renderError = renderError;\nfunction renderSuccess(success) {\n const successElement = document.createElement(\"div\");\n successElement.classList.add(\"magicfeedback-success\");\n successElement.textContent = success;\n return successElement;\n}\nexports.renderSuccess = renderSuccess;\nfunction renderStartMessage(startMessage, addButton = false, startButtonText = \"Go!\", startEvent = () => {\n}) {\n const startMessageContainer = document.createElement(\"div\");\n startMessageContainer.classList.add(\"magicfeedback-start-message-container\");\n const startMessageElement = document.createElement(\"div\");\n startMessageElement.classList.add(\"magicfeedback-start-message\");\n startMessageElement.innerHTML = startMessage;\n startMessageContainer.appendChild(startMessageElement);\n if (addButton) {\n const startMessageButton = document.createElement(\"button\");\n startMessageButton.id = \"magicfeedback-start-message-button\";\n startMessageButton.classList.add(\"magicfeedback-start-message-button\");\n startMessageButton.textContent = startButtonText;\n startMessageButton.addEventListener(\"click\", () => startEvent());\n startMessageContainer.appendChild(startMessageButton);\n }\n return startMessageContainer;\n}\nexports.renderStartMessage = renderStartMessage;\nfunction createRatingNumberElement(ref, assets, order, direction, isPhone, elementTypeClass, send, urlParamValue) {\n const element = document.createElement(\"div\");\n element.classList.add('magicfeedback-rating-number');\n const numberContainerDirection = order === 'ltr' ? direction : `${direction}-reverse`;\n const ratingNumberContainer = document.createElement('div');\n ratingNumberContainer.classList.add('magicfeedback-rating-number-container');\n ratingNumberContainer.classList.add(`magicfeedback-rating-number-container-${order}`);\n ratingNumberContainer.classList.add(`magicfeedback-rating-number-container-${direction}`);\n ratingNumberContainer.style.display = \"flex\";\n ratingNumberContainer.style.flexDirection = numberContainerDirection;\n ratingNumberContainer.setAttribute('role', 'radiogroup');\n ratingNumberContainer.setAttribute('aria-label', (assets === null || assets === void 0 ? void 0 : assets.ariaLabel) || 'Rating');\n const maxRatingNumber = (assets === null || assets === void 0 ? void 0 : assets.max) ? Number(assets === null || assets === void 0 ? void 0 : assets.max) : 10;\n const minRatingNumber = (assets === null || assets === void 0 ? void 0 : assets.min) ? Number(assets === null || assets === void 0 ? void 0 : assets.min) : 0;\n const integratePlaceholders = !(isPhone || direction === 'column');\n for (let i = minRatingNumber; i <= maxRatingNumber; i++) {\n const ratingOption = document.createElement('div');\n ratingOption.classList.add('magicfeedback-rating-number-option');\n ratingOption.classList.add(`magicfeedback-rating-number-option-${direction}`);\n const containerLabel = document.createElement('label');\n containerLabel.htmlFor = `rating-${ref}-${i}`;\n containerLabel.classList.add('magicfeedback-rating-number-option-label-container');\n if (integratePlaceholders) {\n containerLabel.style.position = 'relative';\n containerLabel.style.overflow = 'visible';\n }\n // Cap span (placeholder visual) para todas las opciones para mantener altura uniforme\n if (integratePlaceholders) {\n const cap = document.createElement('span');\n cap.classList.add('magicfeedback-rating-number-cap');\n cap.classList.add('magicfeedback-rating-placeholder-value');\n cap.style.fontSize = \"14px\";\n cap.style.whiteSpace = 'nowrap';\n cap.style.wordBreak = 'normal';\n if (i === minRatingNumber && (assets === null || assets === void 0 ? void 0 : assets.minPlaceholder)) {\n cap.textContent = assets.minPlaceholder;\n cap.dataset.capType = 'min';\n }\n else if (i === maxRatingNumber && (assets === null || assets === void 0 ? void 0 : assets.maxPlaceholder)) {\n cap.textContent = assets.maxPlaceholder;\n cap.dataset.capType = 'max';\n }\n else\n cap.dataset.capType = 'mid';\n containerLabel.appendChild(cap);\n }\n let inputText = i.toString();\n if (!integratePlaceholders) {\n if (i === minRatingNumber && (assets === null || assets === void 0 ? void 0 : assets.minPlaceholder))\n inputText += ` = ${assets === null || assets === void 0 ? void 0 : assets.minPlaceholder}`;\n if (i === maxRatingNumber && (assets === null || assets === void 0 ? void 0 : assets.maxPlaceholder))\n inputText += ` = ${assets === null || assets === void 0 ? void 0 : assets.maxPlaceholder}`;\n }\n const input = document.createElement(\"input\");\n input.id = `rating-${ref}-${i}`;\n input.type = \"radio\";\n input.name = ref;\n input.value = i.toString();\n input.classList.add(elementTypeClass);\n input.classList.add(\"magicfeedback-input\");\n input.setAttribute('aria-label', `${i}`);\n if (send)\n input.addEventListener(\"change\", () => send());\n if (urlParamValue && urlParamValue === input.value) {\n input.checked = true;\n }\n const ratingLabel = document.createElement('label');\n ratingLabel.htmlFor = `rating-${ref}-${i}`;\n ratingLabel.textContent = inputText;\n ratingLabel.classList.add('magicfeedback-rating-number-value');\n containerLabel.appendChild(input);\n containerLabel.appendChild(ratingLabel);\n ratingOption.appendChild(containerLabel);\n ratingNumberContainer.appendChild(ratingOption);\n }\n if ((assets === null || assets === void 0 ? void 0 : assets.extraOption) && (assets === null || assets === void 0 ? void 0 : assets.extraOptionText)) {\n const extraOption = document.createElement('div');\n extraOption.classList.add('magicfeedback-rating-number-option');\n const containerLabel = document.createElement('label');\n containerLabel.htmlFor = `rating-${ref}-extra`;\n containerLabel.classList.add('magicfeedback-rating-number-option-label-container');\n if (integratePlaceholders) {\n containerLabel.style.position = 'relative';\n containerLabel.style.overflow = 'visible';\n }\n if (integratePlaceholders) {\n const cap = document.createElement('span');\n cap.classList.add('magicfeedback-rating-number-cap');\n cap.dataset.capType = 'extra';\n cap.style.fontSize = '12px';\n cap.style.whiteSpace = 'nowrap';\n cap.style.wordBreak = 'normal';\n containerLabel.appendChild(cap);\n }\n const input = document.createElement(\"input\");\n input.id = `rating-${ref}-extra`;\n input.type = \"radio\";\n input.name = ref;\n input.value = '-';\n input.classList.add(elementTypeClass);\n input.classList.add(\"magicfeedback-input\");\n input.setAttribute('aria-label', assets === null || assets === void 0 ? void 0 : assets.extraOptionText);\n if (send)\n input.addEventListener(\"change\", () => send());\n const ratingLabel = document.createElement('label');\n ratingLabel.htmlFor = `rating-${ref}-extra`;\n ratingLabel.textContent = assets === null || assets === void 0 ? void 0 : assets.extraOptionText;\n ratingLabel.classList.add('magicfeedback-rating-number-value');\n containerLabel.appendChild(input);\n containerLabel.appendChild(ratingLabel);\n extraOption.appendChild(containerLabel);\n if (order === 'ltr')\n ratingNumberContainer.appendChild(extraOption);\n else\n ratingNumberContainer.insertBefore(extraOption, ratingNumberContainer.firstChild);\n }\n element.appendChild(ratingNumberContainer);\n // Normalizar alturas de los caps sólo en desktop/row\n if (integratePlaceholders) {\n requestAnimationFrame(() => {\n const caps = Array.from(ratingNumberContainer.querySelectorAll('.magicfeedback-rating-number-cap'));\n if (caps.length === 0)\n return;\n const gap = 6;\n let maxH = 0;\n caps.forEach(c => {\n var _a;\n if ((_a = c.textContent) === null || _a === void 0 ? void 0 : _a.trim()) {\n const h = c.getBoundingClientRect().height || 0;\n if (h > maxH)\n maxH = h;\n }\n });\n ratingNumberContainer.style.position = 'relative';\n ratingNumberContainer.style.paddingTop = `${maxH === 0 ? '42' : (maxH + gap)}px`;\n caps.forEach(c => {\n const h = c.getBoundingClientRect().height || 0;\n console.log(maxH, h, gap);\n c.style.position = 'absolute';\n c.style.top = `-${maxH === 0 ? '42' : (maxH + h)}px`;\n c.style.zIndex = '1';\n c.style.pointerEvents = 'none';\n c.style.padding = '0';\n c.style.boxSizing = 'border-box';\n c.style.whiteSpace = 'nowrap';\n c.style.wordBreak = 'normal';\n c.style.maxWidth = 'none';\n c.style.width = 'max-content';\n // Posicionamiento según tipo\n const type = c.dataset.capType;\n if (type === 'min') {\n if (order === 'ltr') {\n c.style.left = '10px';\n c.style.textAlign = 'left';\n }\n else {\n c.style.right = '10px';\n c.style.textAlign = 'right';\n }\n c.style.transform = 'none';\n }\n else if (type === 'max') {\n if (order === 'ltr') {\n c.style.right = '10px';\n c.style.textAlign = 'right';\n }\n else {\n c.style.left = '10px';\n c.style.textAlign = 'left';\n }\n c.style.transform = 'none';\n }\n else {\n // mid / extra (vacíos) centrados sobre su botón pero invisibles en práctica\n c.style.left = '50%';\n c.style.transform = 'translateX(-50%)';\n c.style.textAlign = 'center';\n }\n });\n ratingNumberContainer.style.overflow = 'visible';\n });\n }\n return element;\n}\n\n\n//# sourceURL=webpack://magicfeedback/./src/services/questions.service.ts?");
|
|
183
|
+
|
|
184
|
+
/***/ }),
|
|
185
|
+
|
|
186
|
+
/***/ "./src/services/request.service.ts":
|
|
187
|
+
/*!*****************************************!*\
|
|
188
|
+
!*** ./src/services/request.service.ts ***!
|
|
189
|
+
\*****************************************/
|
|
190
|
+
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
|
|
191
|
+
|
|
192
|
+
"use strict";
|
|
193
|
+
eval("\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.getFollowUpQuestion = exports.sendFeedback = exports.getQuestions = exports.getSessionForm = exports.getForm = exports.validateEmail = void 0;\nconst cross_fetch_1 = __importDefault(__webpack_require__(/*! cross-fetch */ \"./node_modules/cross-fetch/dist/browser-ponyfill.js\"));\nconst package_json_1 = __importDefault(__webpack_require__(/*! ../../package.json */ \"./package.json\"));\nconst paths_1 = __webpack_require__(/*! ./paths */ \"./src/services/paths.ts\");\nconst header = {\n Accept: \"application/json\",\n \"Magicfeedback-Sdk-Version\": package_json_1.default.version,\n \"x-magicfeedback-parameters\": window.location.search || \"\",\n};\n// @ts-ignore\nconst serializedParams = (params) => Object.entries(params).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`).join(\"&\");\nfunction validateEmail(email) {\n const re = /\\S+@\\S+\\.\\S+/;\n return re.test(email);\n}\nexports.validateEmail = validateEmail;\nfunction getForm(url, appId, publicKey, log) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const response = yield (0, cross_fetch_1.default)(url + paths_1.endpoints.sdk.app_info(appId, publicKey), {\n method: \"GET\",\n headers: header\n });\n // Handle success response\n return yield response.json();\n }\n catch (e) {\n log.err(e);\n }\n });\n}\nexports.getForm = getForm;\nfunction getSessionForm(url, sessionId, log) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const response = yield (0, cross_fetch_1.default)(url + paths_1.endpoints.sdk.session(sessionId), {\n method: \"GET\",\n headers: header\n });\n // Handle success response\n return yield response.json();\n }\n catch (e) {\n log.err(e);\n }\n });\n}\nexports.getSessionForm = getSessionForm;\nfunction getQuestions(url, appId, publicKey, log) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const response = yield (0, cross_fetch_1.default)(url + paths_1.endpoints.sdk.app(appId, publicKey), {\n method: \"GET\",\n headers: header\n });\n if (response.ok) {\n // Handle success response\n const json = yield response.json();\n log.log(`Received questions for app ${appId}`, json);\n return json;\n }\n else {\n // Handle error response\n log.err(`Failed to get questions for app ${appId}:`, response.status, response.statusText);\n throw new Error(\"[MagicFeedback] Bad response from server\");\n }\n }\n catch (e) {\n log.err(e);\n return [];\n }\n });\n}\nexports.getQuestions = getQuestions;\nfunction sendFeedback(url, body, log) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const response = yield (0, cross_fetch_1.default)(url + paths_1.endpoints.sdk.feedback, {\n method: \"POST\",\n headers: Object.assign({ \"Content-Type\": \"application/json\" }, header),\n body: JSON.stringify(body),\n });\n if (response.ok) {\n // Handle success response\n log.log(`Form ${body.integration} submitted successfully!`);\n // You can perform additional actions here if needed\n const responseJson = yield response.json();\n return responseJson.sessionId;\n }\n else {\n // Handle error response\n log.err(`Failed to submit form ${body.integration}:`, response.status, response.statusText);\n throw new Error(response.statusText);\n }\n }\n catch (e) {\n log.err(e);\n return '';\n }\n });\n}\nexports.sendFeedback = sendFeedback;\nfunction getFollowUpQuestion(url, body, log) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const response = yield (0, cross_fetch_1.default)(url + paths_1.endpoints.sdk.followUpQuestion, {\n method: \"POST\",\n headers: Object.assign({ \"Content-Type\": \"application/json\" }, header),\n body: JSON.stringify(body),\n });\n if (response.ok) {\n // Handle success response\n log.log(`Received follow up question for form ${body.integration}`);\n // You can perform additional actions here if needed\n const responseJson = yield response.json();\n return responseJson || '';\n }\n else {\n // Handle error response\n log.err(`Failed to get follow up question for form ${body.integration}:`, response.status, response.statusText);\n throw new Error(response.statusText);\n }\n }\n catch (e) {\n log.err(e);\n return '';\n }\n });\n}\nexports.getFollowUpQuestion = getFollowUpQuestion;\n\n\n//# sourceURL=webpack://magicfeedback/./src/services/request.service.ts?");
|
|
194
|
+
|
|
195
|
+
/***/ }),
|
|
196
|
+
|
|
197
|
+
/***/ "./src/utils/log.ts":
|
|
198
|
+
/*!**************************!*\
|
|
199
|
+
!*** ./src/utils/log.ts ***!
|
|
200
|
+
\**************************/
|
|
201
|
+
/***/ ((__unused_webpack_module, exports) => {
|
|
202
|
+
|
|
203
|
+
"use strict";
|
|
204
|
+
eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.Log = void 0;\nclass Log {\n /**\n *\n * @param config\n */\n constructor(config) {\n // Config\n this.config = config;\n }\n /**\n *\n * @param args\n */\n log(...args) {\n if (this.config.get(\"debug\")) {\n console.log(\"[MagicFeedback]:\", ...args);\n }\n }\n /**\n *\n * @param args\n */\n err(...args) {\n console.error(\"[MagicFeedback]:\", ...args);\n }\n}\nexports.Log = Log;\n\n\n//# sourceURL=webpack://magicfeedback/./src/utils/log.ts?");
|
|
205
|
+
|
|
206
|
+
/***/ }),
|
|
207
|
+
|
|
208
|
+
/***/ "./package.json":
|
|
209
|
+
/*!**********************!*\
|
|
210
|
+
!*** ./package.json ***!
|
|
211
|
+
\**********************/
|
|
212
|
+
/***/ ((module) => {
|
|
213
|
+
|
|
214
|
+
"use strict";
|
|
215
|
+
eval("module.exports = /*#__PURE__*/JSON.parse('{\"name\":\"@magicfeedback/native\",\"version\":\"2.1.2-beta.7\",\"main\":\"./dist/magicfeedback-sdk.node.js\",\"browser\":\"./dist/magicfeedback-sdk.browser.js\",\"types\":\"./dist/types/src/index.d.ts\",\"repository\":{\"type\":\"git\",\"url\":\"git+ssh://git@github.com/MagicFeedback/magicfeedback-sdk.git\"},\"author\":\"farias@magicfeedback.io\",\"license\":\"MIT\",\"private\":false,\"scripts\":{\"dev\":\"vite\",\"build\":\"webpack\",\"build:watch\":\"webpack --watch --mode development\",\"publish\":\"npm publish --access public\",\"publish:beta\":\"npm publish --access public --tag beta\",\"publish:alpha\":\"npm publish --access public --tag alpha\",\"test\":\"jest\",\"test:watch\":\"jest --watchAll\",\"coverage\":\"vitest run --coverage\"},\"files\":[\"dist\"],\"devDependencies\":{\"@babel/preset-typescript\":\"^7.22.5\",\"@types/node\":\"^17.0.21\",\"@types/webpack\":\"^5.28.0\",\"@types/webpack-node-externals\":\"^2.5.3\",\"c8\":\"^7.11.0\",\"copy-webpack-plugin\":\"^11.0.0\",\"jest\":\"^29.5.0\",\"jest-environment-jsdom\":\"^29.5.0\",\"jest-fetch-mock\":\"^3.0.3\",\"nock\":\"^13.2.4\",\"ts-jest\":\"^29.1.0\",\"ts-loader\":\"^9.2.7\",\"ts-node\":\"^10.7.0\",\"typescript\":\"^4.6.2\",\"vite\":\"^2.8.0\",\"vite-plugin-dts\":\"^0.9.9\",\"vitest\":\"^0.5.9\",\"webpack\":\"^5.70.0\",\"webpack-cli\":\"^4.9.2\",\"webpack-node-externals\":\"^3.0.0\"},\"dependencies\":{\"cross-fetch\":\"^3.1.5\",\"is-bundling-for-browser-or-node\":\"^1.1.1\"},\"description\":\"MagicFeedbackAI JavaScript Library for [MagicFeedback.io](https://magicfeedback.io/)\",\"bugs\":{\"url\":\"https://github.com/MagicFeedback/magicfeedback-sdk/issues\"},\"homepage\":\"https://github.com/MagicFeedback/magicfeedback-sdk#readme\",\"directories\":{\"example\":\"examples\",\"test\":\"test\"},\"style\":\"./dist/styles/magicfeedback-default.css\"}');\n\n//# sourceURL=webpack://magicfeedback/./package.json?");
|
|
216
|
+
|
|
217
|
+
/***/ })
|
|
218
|
+
|
|
219
|
+
/******/ });
|
|
220
|
+
/************************************************************************/
|
|
221
|
+
/******/ // The module cache
|
|
222
|
+
/******/ var __webpack_module_cache__ = {};
|
|
223
|
+
/******/
|
|
224
|
+
/******/ // The require function
|
|
225
|
+
/******/ function __webpack_require__(moduleId) {
|
|
226
|
+
/******/ // Check if module is in cache
|
|
227
|
+
/******/ var cachedModule = __webpack_module_cache__[moduleId];
|
|
228
|
+
/******/ if (cachedModule !== undefined) {
|
|
229
|
+
/******/ return cachedModule.exports;
|
|
230
|
+
/******/ }
|
|
231
|
+
/******/ // Create a new module (and put it into the cache)
|
|
232
|
+
/******/ var module = __webpack_module_cache__[moduleId] = {
|
|
233
|
+
/******/ // no module.id needed
|
|
234
|
+
/******/ // no module.loaded needed
|
|
235
|
+
/******/ exports: {}
|
|
236
|
+
/******/ };
|
|
237
|
+
/******/
|
|
238
|
+
/******/ // Execute the module function
|
|
239
|
+
/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
|
|
240
|
+
/******/
|
|
241
|
+
/******/ // Return the exports of the module
|
|
242
|
+
/******/ return module.exports;
|
|
243
|
+
/******/ }
|
|
244
|
+
/******/
|
|
245
|
+
/************************************************************************/
|
|
246
|
+
/******/
|
|
247
|
+
/******/ // startup
|
|
248
|
+
/******/ // Load entry module and return exports
|
|
249
|
+
/******/ // This entry module is referenced by other modules so it can't be inlined
|
|
250
|
+
/******/ var __webpack_exports__ = __webpack_require__("./src/index.ts");
|
|
251
|
+
/******/ __webpack_exports__ = __webpack_exports__["default"];
|
|
252
|
+
/******/
|
|
253
|
+
/******/ return __webpack_exports__;
|
|
254
|
+
/******/ })()
|
|
255
|
+
;
|
|
256
|
+
});
|