@citolab/qti-components 6.9.1-beta.13 → 6.9.1-beta.14

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.
package/dist/index.js CHANGED
@@ -26,7 +26,7 @@ var Br=Object.defineProperty,Yi=Object.defineProperties,Wi=Object.getOwnProperty
26
26
  :host {
27
27
  display: block;
28
28
  }
29
- `;var _e=class extends u{render(){return h`<slot name="qti-rubric-block"></slot><slot></slot>`}};_e.styles=Ci,_e=l([m("qti-item-body")],_e);var Mt=class extends u{render(){return h`<slot></slot>`}connectedCallback(){this.parentElement.tagName.endsWith("INTERACTION")&&this.setAttribute("slot","prompt")}};Mt=l([m("qti-prompt")],Mt);var Lt=class extends u{firstUpdated(t){super.firstUpdated(t);let e=this,r=this.getAttribute("href");if(r!==null){let i=document.createElement("link");i.rel="stylesheet",i.type="text/css",i.media="screen",i.href=r,e.appendChild(i),this.styleLink=i}if(this.textContent!==null){let i=document.createElement("style");i.media="screen",i.textContent=this.textContent,e.appendChild(i),this.styleLink=i}}disconnectedCallback(){if(this.styleLink)try{this.styleLink.remove()}catch(t){console.log("could not remove stylesheet")}}};Lt=l([m("qti-stylesheet")],Lt);var oe=class extends u{render(){return h`<slot></slot>`}defaultValues(t){let e=Array.from(this.querySelectorAll("qti-default-value > qti-value"));if(e.length===0)return null;let r=e.map(i=>i.innerHTML);return r.length>1||t.cardinality==="multiple"||t.cardinality==="ordered"?r:r[0]}};oe=l([m("qti-variabledeclaration")],oe);var U=class extends oe{constructor(){super(...arguments);this.externalScored=null}render(){var r,i;let e=(i=(r=this.itemContext)==null?void 0:r.variables.find(o=>o.identifier===this.identifier))==null?void 0:i.value;return h`${JSON.stringify(e,null,2)}`}get interpolationTable(){let e=this.querySelector("qti-interpolation-table");if(e){let r=new Map;for(let i of e.querySelectorAll("qti-interpolation-table-entry")){!i.getAttribute("source-value")&&i.getAttribute("target-value")&&console.error("source-value or target-value is missing in qti-interpolation-table-entry");let o=parseInt(i.getAttribute("source-value")),n=parseInt(i.getAttribute("target-value"));(isNaN(o)||isNaN(n))&&console.error("source-value or target-value is not a number in qti-interpolation-table-entry"),r.set(o,n)}return r}return null}connectedCallback(){super.connectedCallback();let e={identifier:this.identifier,cardinality:this.cardinality,baseType:this.baseType,type:"outcome",value:null,interpolationTable:this.interpolationTable,externalScored:this.externalScored};e.value=this.defaultValues(e),this.dispatchEvent(new CustomEvent("qti-register-variable",{bubbles:!0,composed:!0,detail:{variable:e}}))}};U.styles=[b`
29
+ `;var _e=class extends u{render(){return h`<slot name="qti-rubric-block"></slot><slot></slot>`}};_e.styles=Ci,_e=l([m("qti-item-body")],_e);var Mt=class extends u{render(){return h`<slot></slot>`}connectedCallback(){this.parentElement.tagName.endsWith("INTERACTION")&&this.setAttribute("slot","prompt")}};Mt=l([m("qti-prompt")],Mt);var Lt=class extends u{firstUpdated(t){super.firstUpdated(t);let e=this,r=this.getAttribute("href");if(r!==null){let i=document.createElement("link");i.rel="stylesheet",i.type="text/css",i.media="screen",i.href=r,e.appendChild(i),this.styleLink=i}if(this.textContent!==null){let i=document.createElement("style");i.media="screen",i.textContent=this.textContent,e.appendChild(i),this.styleLink=i}}disconnectedCallback(){if(this.styleLink)try{this.styleLink.remove()}catch(t){console.log("could not remove stylesheet")}}};Lt=l([m("qti-stylesheet")],Lt);var oe=class extends u{render(){return h`<slot></slot>`}defaultValues(t){let e=Array.from(this.querySelectorAll("qti-default-value > qti-value"));if(e.length===0)return null;let r=e.map(i=>i.innerHTML.trim());return r.length>1||t.cardinality==="multiple"||t.cardinality==="ordered"?r:r[0]}};oe=l([m("qti-variabledeclaration")],oe);var U=class extends oe{constructor(){super(...arguments);this.externalScored=null}render(){var r,i;let e=(i=(r=this.itemContext)==null?void 0:r.variables.find(o=>o.identifier===this.identifier))==null?void 0:i.value;return h`${JSON.stringify(e,null,2)}`}get interpolationTable(){let e=this.querySelector("qti-interpolation-table");if(e){let r=new Map;for(let i of e.querySelectorAll("qti-interpolation-table-entry")){!i.getAttribute("source-value")&&i.getAttribute("target-value")&&console.error("source-value or target-value is missing in qti-interpolation-table-entry");let o=parseInt(i.getAttribute("source-value")),n=parseInt(i.getAttribute("target-value"));(isNaN(o)||isNaN(n))&&console.error("source-value or target-value is not a number in qti-interpolation-table-entry"),r.set(o,n)}return r}return null}connectedCallback(){super.connectedCallback();let e={identifier:this.identifier,cardinality:this.cardinality,baseType:this.baseType,type:"outcome",value:null,interpolationTable:this.interpolationTable,externalScored:this.externalScored};e.value=this.defaultValues(e),this.dispatchEvent(new CustomEvent("qti-register-variable",{bubbles:!0,composed:!0,detail:{variable:e}}))}};U.styles=[b`
30
30
  :host {
31
31
  display: none;
32
32
  }
@@ -239,15 +239,15 @@ var Br=Object.defineProperty,Yi=Object.defineProperties,Wi=Object.getOwnProperty
239
239
  :host {
240
240
  display: none;
241
241
  }
242
- `],xe=l([m("qti-response-processing")],xe);var X=class extends u{render(){return h`<slot></slot>`}process(){throw new Error("Not implemented")}};X=l([m("qti-rule")],X);var Ut=class extends X{get childExpression(){return this.firstElementChild}process(){let t=this.getAttribute("identifier"),e=this.closest("qti-assessment-item").getVariable(t),r;return e.interpolationTable&&(r=e.interpolationTable.get(parseInt(this.childExpression.calculate()))),r==null?(console.warn("lookupOutcomeValue: value is null or undefined"),0):(this.dispatchEvent(new CustomEvent("qti-set-outcome-value",{bubbles:!0,composed:!0,detail:{outcomeIdentifier:this.identifier,value:Je(r)}})),r)}};l([d({type:String})],Ut.prototype,"identifier",2);customElements.define("qti-lookup-outcome-value",Ut);var xr=class extends X{render(){return h`<slot></slot>`}process(){let t=[...this.children];for(let e=0;e<t.length;e++){let r=t[e];if(r.calculate()){r.process();return}}}};customElements.define("qti-response-condition",xr);var qr=class extends X{process(){let t=this.getAttribute("identifier"),e=this.firstElementChild,i=new wr(e).process();this.dispatchEvent(new CustomEvent("qti-set-outcome-value",{bubbles:!0,composed:!0,detail:{outcomeIdentifier:t,value:Array.isArray(i)?i.map(o=>Je(o)):Je(i)}}))}},wr=class{constructor(t){this.expression=t}process(){let t=this.expression?this.expression.calculate():null;if(t==null){console.warn("setOutcomeValue: value is null or undefined");return}return t}};customElements.define("qti-set-outcome-value",qr);var ot=class extends u{render(){return h`<slot></slot>`}calculate(){return!0}getSubRules(){return[...this.children]}process(){let t=this.getSubRules();for(let e=0;e<t.length;e++)t[e].process()}};customElements.define("qti-response-else",ot);var nt=class extends ot{calculate(){return this.firstElementChild.calculate()}getSubRules(){let t=[];for(let e=1;e<this.children.length;e++)t.push(this.children[e]);return t}};customElements.define("qti-response-if",nt);var Er=class extends nt{render(){return h`${super.render()}`}};customElements.define("qti-response-else-if",Er);var x=class extends u{constructor(){super(...arguments);this.getVariables=()=>Array.from(this.children).map(e=>{switch(e.tagName.toLowerCase()){case"qti-base-value":return{baseType:e.getAttribute("base-type"),value:e.textContent,cardinality:"single"};case"qti-variable":{let r=e.getAttribute("identifier")||"";return this.assessmentItem.getVariable(r)}case"qti-multiple":{let i=e.getResult();return i.length>0?{identifier:"",baseType:i[0].baseType,value:i.map(o=>o.value),cardinality:"multiple",type:"response"}:null}case"qti-correct":{let r=e.getAttribute("identifier")||"",i=this.assessmentItem.getResponse(r);return{baseType:i.baseType,value:i.correctResponse,cardinality:i.cardinality}}default:{try{return{baseType:"integer",value:e.getResult().toString(),cardinality:"single"}}catch(r){console.warn("default not sufficient")}return null}}}).filter(e=>e!==null)}render(){return h`<pre>${JSON.stringify(this.result,null,2)}</pre>
242
+ `],xe=l([m("qti-response-processing")],xe);var X=class extends u{render(){return h`<slot></slot>`}process(){throw new Error("Not implemented")}};X=l([m("qti-rule")],X);var Ut=class extends X{get childExpression(){return this.firstElementChild}process(){let t=this.getAttribute("identifier"),e=this.closest("qti-assessment-item").getVariable(t),r;return e.interpolationTable&&(r=e.interpolationTable.get(parseInt(this.childExpression.calculate()))),r==null?(console.warn("lookupOutcomeValue: value is null or undefined"),0):(this.dispatchEvent(new CustomEvent("qti-set-outcome-value",{bubbles:!0,composed:!0,detail:{outcomeIdentifier:this.identifier,value:Je(r)}})),r)}};l([d({type:String})],Ut.prototype,"identifier",2);customElements.define("qti-lookup-outcome-value",Ut);var xr=class extends X{render(){return h`<slot></slot>`}process(){let t=[...this.children];for(let e=0;e<t.length;e++){let r=t[e];if(r.calculate()){r.process();return}}}};customElements.define("qti-response-condition",xr);var qr=class extends X{process(){let t=this.getAttribute("identifier"),e=this.firstElementChild,i=new wr(e).process();this.dispatchEvent(new CustomEvent("qti-set-outcome-value",{bubbles:!0,composed:!0,detail:{outcomeIdentifier:t,value:Array.isArray(i)?i.map(o=>Je(o)):Je(i)}}))}},wr=class{constructor(t){this.expression=t}process(){let t=this.expression?this.expression.calculate():null;if(t==null){console.warn("setOutcomeValue: value is null or undefined");return}return t}};customElements.define("qti-set-outcome-value",qr);var ot=class extends u{render(){return h`<slot></slot>`}calculate(){return!0}getSubRules(){return[...this.children]}process(){let t=this.getSubRules();for(let e=0;e<t.length;e++)t[e].process()}};customElements.define("qti-response-else",ot);var nt=class extends ot{calculate(){return this.firstElementChild.calculate()}getSubRules(){let t=[];for(let e=1;e<this.children.length;e++)t.push(this.children[e]);return t}};customElements.define("qti-response-if",nt);var Er=class extends nt{render(){return h`${super.render()}`}};customElements.define("qti-response-else-if",Er);var x=class extends u{constructor(){super(...arguments);this.getVariables=()=>Array.from(this.children).map(e=>{switch(e.tagName.toLowerCase()){case"qti-base-value":return{baseType:e.getAttribute("base-type"),value:e.textContent.trim(),cardinality:"single"};case"qti-variable":{let r=e.getAttribute("identifier")||"";return this.assessmentItem.getVariable(r)}case"qti-multiple":{let i=e.getResult();return i.length>0?{identifier:"",baseType:i[0].baseType,value:i.map(o=>o.value),cardinality:"multiple",type:"response"}:null}case"qti-correct":{let r=e.getAttribute("identifier")||"",i=this.assessmentItem.getResponse(r);return{baseType:i.baseType,value:i.correctResponse,cardinality:i.cardinality}}default:{try{return{baseType:"integer",value:e.getResult().toString(),cardinality:"single"}}catch(r){console.warn("default not sufficient")}return null}}}).filter(e=>e!==null)}render(){return h`<pre>${JSON.stringify(this.result,null,2)}</pre>
243
243
  <slot></slot>`}calculate(){return this.result=this.getResult(),this.result}getResult(){throw new Error("Not implemented")}get assessmentItem(){return this.closest("qti-assessment-item")}};x.styles=b`
244
244
  slot {
245
245
  display: none;
246
246
  }
247
- `,l([q()],x.prototype,"result",2);var H=class extends x{calculate(){return this.result=this.getResult(),this.result}getResult(){throw new Error("Not implemented")}};var zt=class extends Ts(H){calculate(){return this.calculateChildren(Array.from(this.children))}};function Ts(s){return class extends s{calculateChildren(e){return e.map(i=>{let o=i;if(!o.calculate)return console.error("Element doesn't implement QtiConditionExpression"),null;let n=o.calculate();if(typeof n=="string")if(n==="true")n=!0;else if(n==="false")n=!1;else return console.error("unexpected value in qti-and, expected boolean"),null;return n}).every(i=>typeof i=="boolean"&&i)}}}customElements.define("qti-and",zt);var Ft=class extends x{constructor(){super(...arguments);this.baseType="string"}getResult(){return this.textContent}};l([d({type:String,attribute:"base-type"})],Ft.prototype,"baseType",2);customElements.define("qti-base-value",Ft);var Cr=class extends H{getResult(){let t=this.getVariables();if(this.children.length===2){let e=t[0],r=t[1];if(e.baseType==="directedPair"&&r.baseType==="directedPair"&&e.cardinality==="multiple"){let i=e.value,o=r.value;return i.filter(c=>o.includes(c)).length>0}else if(e.baseType==="directedPair"&&r.baseType==="directedPair"&&e.cardinality==="single"){let i=e.value;return r.value.includes(i)}else console.error("unsupported baseType or cardinality in qti contains, only baseType: directedPair and cardinality: multiple is supported")}else console.error("unexpected number of children in qti contains");return!1}};customElements.define("qti-contains",Cr);var kr=class extends x{get interpretation(){return this.getAttribute("interpretation")||""}getResult(){let t=this.getAttribute("identifier")||"",e=this.closest("qti-assessment-item").getResponse(t);return e.correctResponse,e.cardinality!=="single"?e.correctResponse.length>0?e.correctResponse[0]:"":e.correctResponse}};customElements.define("qti-correct",kr);var Bt=class extends x{constructor(){super(...arguments);this.roundingMode="significantFigures"}get figures(){if(!this.getAttribute("figures"))return console.error("figures attribute is missing"),null;let r=parseInt(this.getAttribute("figures")||"0");return isNaN(r)?(console.error("figures attribute is not a number"),null):r<0?(console.error("figures attribute is negative"),null):r<1&&this.roundingMode==="significantFigures"?(console.error("figures cannot be smaller than 1 for RoundingMode significantFigures"),null):r}getResult(){if(this.children.length===2){let e=this.getVariables(),r=e[0],i=e[1];if(this.roundingMode===null)return null;if(r.cardinality!=="single"||i.cardinality!=="single"||Array.isArray(r.value)||Array.isArray(i.value))return console.error("unexpected cardinality in qti equal"),!1;switch(e[0].baseType){case"integer":case"float":{let o=parseFloat(r.value),n=parseFloat(i.value);if(!isNaN(o)&&!isNaN(n))return this.roundingMode==="significantFigures"?o.toPrecision(this.figures)===n.toPrecision(this.figures):Math.round(o*Math.pow(10,this.figures))/Math.pow(10,this.figures)===Math.round(n*Math.pow(10,this.figures))/Math.pow(10,this.figures);console.error(`value cannot be casted to numeric value in equalRounded operator: ${o}, ${n}`);break}default:{console.error("values other than float and int cannot be used in equalRounded operator.");break}}return!1}return console.error("unexpected number of children in qti-equal-rounded"),null}};l([d({type:String})],Bt.prototype,"roundingMode",2);customElements.define("qti-equal-rounded",Bt);var P=class{static compareSingleValues(t,e,r){switch(r){case"identifier":case"string":return t===e;case"integer":{let i=parseInt(t,10),o=parseInt(e,10);if(!isNaN(i)&&!isNaN(o))return i===o;console.error(`Cannot convert ${t} and/or ${e} to int.`);break}case"float":{let i=parseFloat(t),o=parseFloat(e);if(!isNaN(i)&&!isNaN(o))return i===o;console.error(`couldn't convert ${t} and/or ${e} to float.`);break}case"pair":case"directedPair":{let i=t.split(" ").sort(),o=e.split(" ").sort();if(i.length===2&&o.length===2)return r==="pair"&&(i.sort(),o.sort()),i.join(" ")===o.join(" ");console.error(`compared two pair but one of the values does not have 2 values: 1: ${t} 2: ${e}`);break}}return!1}};var jt=class extends x{constructor(){super(...arguments);this.toleranceMode="exact"}getResult(){if(this.children.length===2){let e=this.getVariables(),r=e[0],i=e[1];return this.toleranceMode!=="exact"?(console.error("toleranceMode is not supported yet"),!1):r.cardinality!=="single"||i.cardinality!=="single"||Array.isArray(r.value)||Array.isArray(i.value)?(console.error("unexpected cardinality in qti equal"),!1):P.compareSingleValues(r.value,i.value,r.baseType)}return console.error("unexpected number of children in qti-equal"),null}};l([d({type:String})],jt.prototype,"toleranceMode",2);customElements.define("qti-equal",jt);var Tr=class extends x{getResult(){if(this.children.length===2){let t=this.getVariables(),e=t[0],r=t[1];if(e.baseType===r.baseType&&(e.baseType==="integer"||e.baseType==="float"))return+e.value>+r.value;console.error("unexpected baseType or cardinality in qti gt")}return console.error("unexpected number of children in qt"),null}};customElements.define("qti-gt",Tr);var Ar=class extends H{getResult(){if(this.children.length===2){let t=this.getVariables(),e=t[0],r=t[1];return e.baseType===r.baseType&&(e.baseType==="integer"||e.baseType==="float")?+e.value>=+r.value:(console.error("unexpected baseType or cardinality in qti gte"),null)}return console.log("unexpected number of children in qte"),null}};customElements.define("qti-gte",Ar);var _r=class extends x{getResult(){if(this.children.length===1){let t=this.getVariables();if(!t)return!0;let e=t[0].value;return e==null||e==null||e===""}return console.error("unexpected number of children in qti Null"),null}};customElements.define("qti-is-null",_r);var Sr=class extends x{getResult(){if(this.children.length===2){let t=this.getVariables(),e=t[0],r=t[1];if(e.baseType===r.baseType&&(e.baseType==="integer"||e.baseType==="float"))return+e.value<+r.value;console.error("unexpected baseType or cardinality in qti lt")}return console.error("unexpected number of children in lt"),null}};customElements.define("qti-lt",Sr);var Rr=class extends H{getResult(){if(this.children.length===2){let t=this.getVariables(),e=t[0],r=t[1];return e.baseType===r.baseType&&(e.baseType==="integer"||e.baseType==="float")?+e.value<=+r.value:(console.error("unexpected baseType or cardinality in qti lte"),null)}return console.log("unexpected number of children in lte"),null}};customElements.define("qti-lte",Rr);var Xt=class extends x{getResult(){let t=this.assessmentItem.getResponse(this.identifier);if(!t)return console.warn(`Response ${this.identifier} can not be found`),null;let e=t.mapping,r=Array.isArray(t.value)?t.value:[t.value],i=0;for(let o of r){let n=e.mapEntries.find(a=>P.compareSingleValues(a.mapKey,o,t.baseType));n==null||n.mappedValue==null?i+=e.defaultValue:i+=n.mappedValue}return e.lowerBound!=null&&(i=Math.max(e.lowerBound,i)),e.upperBound!=null&&(i=Math.min(e.upperBound,i)),i}};l([d({type:String})],Xt.prototype,"identifier",2);customElements.define("qti-map-response",Xt);var Me=class extends u{constructor(){super(...arguments);this.defaultValue=0}get mapEntries(){return Array.from(this.querySelectorAll("qti-map-entry")).map(e=>({mapKey:e.getAttribute("map-key"),mappedValue:+e.getAttribute("mapped-value")}))}};l([d({attribute:"default-value",type:Number})],Me.prototype,"defaultValue",2),l([d({attribute:"lower-bound",type:Number})],Me.prototype,"lowerBound",2),l([d({attribute:"upper-bound",type:Number})],Me.prototype,"upperBound",2);customElements.define("qti-mapping",Me);var Mr=class s extends x{getResult(){if(this.children.length===2){let t=this.getVariables(),e=t[0],r=t[1];return s.match(e,r)}return console.error("unexpected number of children in match"),null}static match(t,e){var r;switch(e.cardinality){case"single":return t.value===null?!1:Array.isArray(t.value)||Array.isArray(e.value)?(console.error("unexpected cardinality in qti match"),!1):P.compareSingleValues((r=t.value)==null?void 0:r.toString(),e.value.toString(),e.baseType);case"ordered":{if(!Array.isArray(t.value)||!Array.isArray(e.value))return console.error("unexpected cardinality in qti match"),!1;if(t.value.length!==e.value.length)return!1;for(let i=0;i<t.value.length;i++)if(!P.compareSingleValues(e.value[i],t.value[i],e.baseType))return!1;return!0}case"multiple":{if(!Array.isArray(t.value)||!Array.isArray(e.value))return console.error("unexpected cardinality in qti match"),!1;if(t.value.length!==e.value.length)return!1;let i=0;for(let o of e.value){let n=null,a=[...t.value];for(let c of a)if(P.compareSingleValues(o,c,e.baseType)){n=c;break}if(n!==null)a.splice(a.indexOf(n),1);else return!1;i++}return!0}default:return console.error("unexpected cardinality in qti match"),!1}}};customElements.define("qti-match",Mr);var Lr=class extends x{getResult(){let t=this.getVariables();this.children.length!==2&&console.warn("The member operator takes two sub-expressions");let[e,r]=t;if(e.baseType!==r.baseType&&console.warn("Which must both have the same base-type"),r.cardinality==="multiple"||r.cardinality==="ordered"||console.warn("and the second must be a multiple or ordered container"),(e.baseType==="float"||r.baseType==="float")&&console.warn("The member operator should not be used on sub-expressions with a base-type of float"),(e.baseType==="duration"||r.baseType==="duration")&&console.warn("It must not be used on sub-expressions with a base-type of duration"),e.value===null||r.value===null)return null;let i=e.value;return r.value.includes(i)}};customElements.define("qti-member",Lr);var $r=class extends x{getResult(){let t=this.getVariables();if(t.length===0)return console.error("unexpected number of children in qti multiple"),null;for(let e of t)if(e.cardinality!=="multiple"&&e.cardinality!=="single")return console.error("unexpected cardinality in qti multiple"),[];return t}};customElements.define("qti-multiple",$r);var Dr=class extends x{render(){return h`${super.render()}`}getResult(){return!this.firstElementChild.calculate()}};customElements.define("qti-not",Dr);var Hr=class extends H{getResult(){return Array.from(this.children).map(e=>{let r=e;if(!r.calculate)return console.error("Element doesn't implement QtiConditionExpression"),null;let i=r.calculate();if(typeof i=="string")if(i==="true")i=!0;else if(i==="false")i=!1;else return console.error("unexpected value in qti-or, expected boolean"),null;return i}).some(e=>typeof e=="boolean"&&e)}};customElements.define("qti-or",Hr);var Pr=class extends x{getResult(){let t=this.getVariables();if(t.length===0)return console.error("unexpected number of children in qti multiple"),null;for(let e of t)if(e.cardinality!=="ordered"&&e.cardinality!=="single")return console.error("unexpected cardinality in qti ordered"),[];return t}};customElements.define("qti-ordered",Pr);var at=class extends u{render(){var e,r;let t=(r=(e=this.itemContext)==null?void 0:e.variables.find(i=>i.identifier===this.identifier))==null?void 0:r.value;return h`${JSON.stringify(t,null,2)}`}calculate(){let t=this.closest("qti-assessment-item"),e=this.identifier;return t.getVariable(e).value}};l([d({type:String})],at.prototype,"identifier",2),l([J({context:I,subscribe:!0}),q()],at.prototype,"itemContext",2);customElements.define("qti-printed-variable",at);var Nr=class extends x{getResult(){return this.getVariables().reduce((r,i)=>{if(i.baseType=="float"||i.baseType=="integer")try{return r*parseInt(i.value.toString())}catch(o){console.warn("can not convert to number")}else console.warn(`has another baseType ${i.baseType}`);return r},1)}};customElements.define("qti-product",Nr);var Yt=class extends x{constructor(){super(...arguments);this.caseSensitive="true"}getResult(){if(this.children.length===2){let e=this.getVariables(),r=e[0],i=e[1];if(r.cardinality!=="single"||i.cardinality!=="single"||Array.isArray(r.value)||Array.isArray(i.value))return console.error("unexpected cardinality in qti string-match"),!1;let o=this.caseSensitive==="true"?r.value:r.value.toLowerCase(),n=this.caseSensitive==="true"?i.value:i.value.toLowerCase();return P.compareSingleValues(o,n,r.baseType)}return console.error("unexpected number of children in qti-string-match"),null}};l([d({type:String,attribute:"case-sensitive"})],Yt.prototype,"caseSensitive",2);customElements.define("qti-string-match",Yt);var Vr=class extends x{constructor(){super(),this._expression=new Ir(Array.from(this.children))}getResult(){return this._expression.calculate()}},Ir=class{constructor(t){this.expressions=t}calculate(){return this.expressions.map(e=>{if(!e.calculate)return console.error("Element doesn't implement QtiConditionExpression"),null;let r=e.calculate();return Number.isNaN(r)?(console.error("unexpected value in qti-sum, expected number"),null):Number(r)}).reduce((e,r)=>e+r,0)}};customElements.define("qti-sum",Vr);var Or=class extends x{getResult(){let t=this.getAttribute("identifier");return this.closest("qti-assessment-item").getVariable(t).value}};customElements.define("qti-variable",Or);var pe=class extends T{constructor(){super(...arguments);this._errorMessage=null;this.loadConfig=async(e,r)=>{e=this.removeDoubleSlashes(e);try{let i=await fetch(e);if(i.ok){let n=await i.json();for(let a in n.paths)r&&(n.paths[a]=this.getResolvablePath(n.paths[a],r));return n}}catch(i){}return null};this.getResolvablePathString=(e,r)=>(e=e.replace(/\.js$/,""),e!=null&&e.toLocaleLowerCase().startsWith("http")||!r?e:this.removeDoubleSlashes(`${r}/${e}`));this.getResolvablePath=(e,r)=>Array.isArray(e)?e.map(i=>this.getResolvablePathString(i,r)):this.getResolvablePathString(e,r)}convertQtiVariableJSON(e){for(let r in e)if(e.hasOwnProperty(r)){let i=e[r];if(i){for(let o in i)if(i.hasOwnProperty(o)){let n=i[o];if(Array.isArray(n))return n.map(String);if(n!=null)return String(n)}}}return null}startChecking(){this.intervalId=setInterval(()=>{let e=this.pci.getResponse(),r=this.pci.getResponse(),i=JSON.stringify(e);if(i!==this.rawResponse){this.rawResponse=i;let o=this.convertQtiVariableJSON(r);this.response=o,this.saveResponse(o)}},200)}stopChecking(){this.intervalId!==void 0&&clearInterval(this.intervalId)}validate(){return!0}set response(e){}getTAOConfig(e){let r=e.querySelectorAll("properties"),i={},o=a=>{let c={},p=a.getAttribute("key");if(p){let f=Array.from(a.children),g=f.map(v=>v.getAttribute("key"));g.length>0&&!g.find(v=>!Number.isInteger(+v))?c[p]=f.map(v=>n(v)):c[p]=a.textContent}return c},n=a=>{if(a){let c={};for(let p of a.children)c=C(C({},c),o(p));return c}};for(let a of r)return a.getAttribute("key")||(i=C(C({},i),n(a))),i;return console.log("Can not find qti-custom-interaction config"),null}register(e){this.pci=e;let r=this.parentElement.tagName==="QTI-CUSTOM-INTERACTION"?"TAO":"IMS",i=r=="IMS"?this.querySelector("qti-interaction-markup"):this.querySelector("markup");i.classList.add("qti-customInteraction"),r=="TAO"&&this.querySelector("properties")&&(this.querySelector("properties").style.display="none");let o=r=="IMS"?{properties:this.dataset,onready:()=>{console.log("onready")}}:this.getTAOConfig(this);r=="IMS"?e.getInstance(i,o,void 0):e.initialize(this.customInteractionTypeIdentifier,i.firstElementChild,o),r=="TAO"&&Array.from(this.querySelectorAll("link")).map(a=>a.getAttribute("href")).forEach(a=>{let c=document.createElement("link");c.rel="stylesheet",c.type="text/css",c.media="screen",c.href=a,i.appendChild(c)}),this.startChecking()}connectedCallback(){super.connectedCallback(),define("qtiCustomInteractionContext",()=>({register:i=>{this.register(i)},notifyReady:()=>{}}));let e=this.buildRequireConfig();requirejs.config(e)(["require"],i=>{i([this.module])})}disconnectedCallback(){super.disconnectedCallback(),requirejs.undef(this.customInteractionTypeIdentifier);let e=requirejs.s.contexts;delete e[this.customInteractionTypeIdentifier],this.stopChecking()}buildRequireConfig(){let e={context:this.customInteractionTypeIdentifier,catchError:!0,paths:window.requirePaths||{},shim:window.requireShim||{}};if(!globalThis.require)return this._errorMessage="RequireJS not found. Please load it via CDN: https://cdnjs.com/libraries/require.js",null;let r=this.getAttribute("data-base-url"),i=this.querySelector("qti-interaction-modules");if(i){let o=i.querySelectorAll("qti-interaction-module");for(let n of o){let a=n.getAttribute("id"),c=n.getAttribute("primary-path"),p=n.getAttribute("fallback-path");if(a&&c){let f=p?this.combineRequireResolvePaths(this.getResolvablePath(c,r),this.getResolvablePath(p,r)):this.getResolvablePath(c,r),g=e.paths[a]||[];e.paths[a]=this.combineRequireResolvePaths(g,f)}}}return e}combineRequireResolvePaths(e,r){let i=Array.isArray(e)?e:[e],o=Array.isArray(r)?r:[r];return i.concat(o)}removeDoubleSlashes(e){return e.replace(/([^:]\/)\/+/g,"$1").replace(/\/\//g,"/").replace("http:/","http://").replace("https:/","https://")}render(){return h`<slot></slot>${this._errorMessage&&h`<div style="color:red">
247
+ `,l([q()],x.prototype,"result",2);var H=class extends x{calculate(){return this.result=this.getResult(),this.result}getResult(){throw new Error("Not implemented")}};var zt=class extends Ts(H){calculate(){return this.calculateChildren(Array.from(this.children))}};function Ts(s){return class extends s{calculateChildren(e){return e.map(i=>{let o=i;if(!o.calculate)return console.error("Element doesn't implement QtiConditionExpression"),null;let n=o.calculate();if(typeof n=="string")if(n==="true")n=!0;else if(n==="false")n=!1;else return console.error("unexpected value in qti-and, expected boolean"),null;return n}).every(i=>typeof i=="boolean"&&i)}}}customElements.define("qti-and",zt);var Ft=class extends x{constructor(){super(...arguments);this.baseType="string"}getResult(){return this.textContent.trim()}};l([d({type:String,attribute:"base-type"})],Ft.prototype,"baseType",2);customElements.define("qti-base-value",Ft);var Cr=class extends H{getResult(){let t=this.getVariables();if(this.children.length===2){let e=t[0],r=t[1];if(e.baseType==="directedPair"&&r.baseType==="directedPair"&&e.cardinality==="multiple"){let i=e.value,o=r.value;return i.filter(c=>o.includes(c)).length>0}else if(e.baseType==="directedPair"&&r.baseType==="directedPair"&&e.cardinality==="single"){let i=e.value;return r.value.includes(i)}else console.error("unsupported baseType or cardinality in qti contains, only baseType: directedPair and cardinality: multiple is supported")}else console.error("unexpected number of children in qti contains");return!1}};customElements.define("qti-contains",Cr);var kr=class extends x{get interpretation(){return this.getAttribute("interpretation")||""}getResult(){let t=this.getAttribute("identifier")||"",e=this.closest("qti-assessment-item").getResponse(t);return e.correctResponse,e.cardinality!=="single"?e.correctResponse.length>0?e.correctResponse[0]:"":e.correctResponse}};customElements.define("qti-correct",kr);var Bt=class extends x{constructor(){super(...arguments);this.roundingMode="significantFigures"}get figures(){if(!this.getAttribute("figures"))return console.error("figures attribute is missing"),null;let r=parseInt(this.getAttribute("figures")||"0");return isNaN(r)?(console.error("figures attribute is not a number"),null):r<0?(console.error("figures attribute is negative"),null):r<1&&this.roundingMode==="significantFigures"?(console.error("figures cannot be smaller than 1 for RoundingMode significantFigures"),null):r}getResult(){if(this.children.length===2){let e=this.getVariables(),r=e[0],i=e[1];if(this.roundingMode===null)return null;if(r.cardinality!=="single"||i.cardinality!=="single"||Array.isArray(r.value)||Array.isArray(i.value))return console.error("unexpected cardinality in qti equal"),!1;switch(e[0].baseType){case"integer":case"float":{let o=parseFloat(r.value),n=parseFloat(i.value);if(!isNaN(o)&&!isNaN(n))return this.roundingMode==="significantFigures"?o.toPrecision(this.figures)===n.toPrecision(this.figures):Math.round(o*Math.pow(10,this.figures))/Math.pow(10,this.figures)===Math.round(n*Math.pow(10,this.figures))/Math.pow(10,this.figures);console.error(`value cannot be casted to numeric value in equalRounded operator: ${o}, ${n}`);break}default:{console.error("values other than float and int cannot be used in equalRounded operator.");break}}return!1}return console.error("unexpected number of children in qti-equal-rounded"),null}};l([d({type:String})],Bt.prototype,"roundingMode",2);customElements.define("qti-equal-rounded",Bt);var P=class{static compareSingleValues(t,e,r){switch(r){case"identifier":case"string":return t===e;case"integer":{let i=parseInt(t,10),o=parseInt(e,10);if(!isNaN(i)&&!isNaN(o))return i===o;console.error(`Cannot convert ${t} and/or ${e} to int.`);break}case"float":{let i=parseFloat(t),o=parseFloat(e);if(!isNaN(i)&&!isNaN(o))return i===o;console.error(`couldn't convert ${t} and/or ${e} to float.`);break}case"pair":case"directedPair":{let i=t.split(" ").sort(),o=e.split(" ").sort();if(i.length===2&&o.length===2)return r==="pair"&&(i.sort(),o.sort()),i.join(" ")===o.join(" ");console.error(`compared two pair but one of the values does not have 2 values: 1: ${t} 2: ${e}`);break}}return!1}};var jt=class extends x{constructor(){super(...arguments);this.toleranceMode="exact"}getResult(){if(this.children.length===2){let e=this.getVariables(),r=e[0],i=e[1];return this.toleranceMode!=="exact"?(console.error("toleranceMode is not supported yet"),!1):r.cardinality!=="single"||i.cardinality!=="single"||Array.isArray(r.value)||Array.isArray(i.value)?(console.error("unexpected cardinality in qti equal"),!1):P.compareSingleValues(r.value,i.value,r.baseType)}return console.error("unexpected number of children in qti-equal"),null}};l([d({type:String})],jt.prototype,"toleranceMode",2);customElements.define("qti-equal",jt);var Tr=class extends x{getResult(){if(this.children.length===2){let t=this.getVariables(),e=t[0],r=t[1];if(e.baseType===r.baseType&&(e.baseType==="integer"||e.baseType==="float"))return+e.value>+r.value;console.error("unexpected baseType or cardinality in qti gt")}return console.error("unexpected number of children in qt"),null}};customElements.define("qti-gt",Tr);var Ar=class extends H{getResult(){if(this.children.length===2){let t=this.getVariables(),e=t[0],r=t[1];return e.baseType===r.baseType&&(e.baseType==="integer"||e.baseType==="float")?+e.value>=+r.value:(console.error("unexpected baseType or cardinality in qti gte"),null)}return console.log("unexpected number of children in qte"),null}};customElements.define("qti-gte",Ar);var _r=class extends x{getResult(){if(this.children.length===1){let t=this.getVariables();if(!t)return!0;let e=t[0].value;return e==null||e==null||e===""}return console.error("unexpected number of children in qti Null"),null}};customElements.define("qti-is-null",_r);var Sr=class extends x{getResult(){if(this.children.length===2){let t=this.getVariables(),e=t[0],r=t[1];if(e.baseType===r.baseType&&(e.baseType==="integer"||e.baseType==="float"))return+e.value<+r.value;console.error("unexpected baseType or cardinality in qti lt")}return console.error("unexpected number of children in lt"),null}};customElements.define("qti-lt",Sr);var Rr=class extends H{getResult(){if(this.children.length===2){let t=this.getVariables(),e=t[0],r=t[1];return e.baseType===r.baseType&&(e.baseType==="integer"||e.baseType==="float")?+e.value<=+r.value:(console.error("unexpected baseType or cardinality in qti lte"),null)}return console.log("unexpected number of children in lte"),null}};customElements.define("qti-lte",Rr);var Xt=class extends x{getResult(){let t=this.assessmentItem.getResponse(this.identifier);if(!t)return console.warn(`Response ${this.identifier} can not be found`),null;let e=t.mapping,r=Array.isArray(t.value)?t.value:[t.value],i=0;for(let o of r){let n=e.mapEntries.find(a=>P.compareSingleValues(a.mapKey,o,t.baseType));n==null||n.mappedValue==null?i+=e.defaultValue:i+=n.mappedValue}return e.lowerBound!=null&&(i=Math.max(e.lowerBound,i)),e.upperBound!=null&&(i=Math.min(e.upperBound,i)),i}};l([d({type:String})],Xt.prototype,"identifier",2);customElements.define("qti-map-response",Xt);var Me=class extends u{constructor(){super(...arguments);this.defaultValue=0}get mapEntries(){return Array.from(this.querySelectorAll("qti-map-entry")).map(e=>({mapKey:e.getAttribute("map-key"),mappedValue:+e.getAttribute("mapped-value")}))}};l([d({attribute:"default-value",type:Number})],Me.prototype,"defaultValue",2),l([d({attribute:"lower-bound",type:Number})],Me.prototype,"lowerBound",2),l([d({attribute:"upper-bound",type:Number})],Me.prototype,"upperBound",2);customElements.define("qti-mapping",Me);var Mr=class s extends x{getResult(){if(this.children.length===2){let t=this.getVariables(),e=t[0],r=t[1];return s.match(e,r)}return console.error("unexpected number of children in match"),null}static match(t,e){var r;switch(e.cardinality){case"single":return t.value===null?!1:Array.isArray(t.value)||Array.isArray(e.value)?(console.error("unexpected cardinality in qti match"),!1):P.compareSingleValues((r=t.value)==null?void 0:r.toString(),e.value.toString(),e.baseType);case"ordered":{if(!Array.isArray(t.value)||!Array.isArray(e.value))return console.error("unexpected cardinality in qti match"),!1;if(t.value.length!==e.value.length)return!1;for(let i=0;i<t.value.length;i++)if(!P.compareSingleValues(e.value[i],t.value[i],e.baseType))return!1;return!0}case"multiple":{if(!Array.isArray(t.value)||!Array.isArray(e.value))return console.error("unexpected cardinality in qti match"),!1;if(t.value.length!==e.value.length)return!1;let i=0;for(let o of e.value){let n=null,a=[...t.value];for(let c of a)if(P.compareSingleValues(o,c,e.baseType)){n=c;break}if(n!==null)a.splice(a.indexOf(n),1);else return!1;i++}return!0}default:return console.error("unexpected cardinality in qti match"),!1}}};customElements.define("qti-match",Mr);var Lr=class extends x{getResult(){let t=this.getVariables();this.children.length!==2&&console.warn("The member operator takes two sub-expressions");let[e,r]=t;if(e.baseType!==r.baseType&&console.warn("Which must both have the same base-type"),r.cardinality==="multiple"||r.cardinality==="ordered"||console.warn("and the second must be a multiple or ordered container"),(e.baseType==="float"||r.baseType==="float")&&console.warn("The member operator should not be used on sub-expressions with a base-type of float"),(e.baseType==="duration"||r.baseType==="duration")&&console.warn("It must not be used on sub-expressions with a base-type of duration"),e.value===null||r.value===null)return null;let i=e.value;return r.value.includes(i)}};customElements.define("qti-member",Lr);var $r=class extends x{getResult(){let t=this.getVariables();if(t.length===0)return console.error("unexpected number of children in qti multiple"),null;for(let e of t)if(e.cardinality!=="multiple"&&e.cardinality!=="single")return console.error("unexpected cardinality in qti multiple"),[];return t}};customElements.define("qti-multiple",$r);var Dr=class extends x{render(){return h`${super.render()}`}getResult(){return!this.firstElementChild.calculate()}};customElements.define("qti-not",Dr);var Hr=class extends H{getResult(){return Array.from(this.children).map(e=>{let r=e;if(!r.calculate)return console.error("Element doesn't implement QtiConditionExpression"),null;let i=r.calculate();if(typeof i=="string")if(i==="true")i=!0;else if(i==="false")i=!1;else return console.error("unexpected value in qti-or, expected boolean"),null;return i}).some(e=>typeof e=="boolean"&&e)}};customElements.define("qti-or",Hr);var Pr=class extends x{getResult(){let t=this.getVariables();if(t.length===0)return console.error("unexpected number of children in qti multiple"),null;for(let e of t)if(e.cardinality!=="ordered"&&e.cardinality!=="single")return console.error("unexpected cardinality in qti ordered"),[];return t}};customElements.define("qti-ordered",Pr);var at=class extends u{render(){var e,r;let t=(r=(e=this.itemContext)==null?void 0:e.variables.find(i=>i.identifier===this.identifier))==null?void 0:r.value;return h`${JSON.stringify(t,null,2)}`}calculate(){let t=this.closest("qti-assessment-item"),e=this.identifier;return t.getVariable(e).value}};l([d({type:String})],at.prototype,"identifier",2),l([J({context:I,subscribe:!0}),q()],at.prototype,"itemContext",2);customElements.define("qti-printed-variable",at);var Nr=class extends x{getResult(){return this.getVariables().reduce((r,i)=>{if(i.baseType=="float"||i.baseType=="integer")try{return r*parseInt(i.value.toString())}catch(o){console.warn("can not convert to number")}else console.warn(`has another baseType ${i.baseType}`);return r},1)}};customElements.define("qti-product",Nr);var Yt=class extends x{constructor(){super(...arguments);this.caseSensitive="true"}getResult(){if(this.children.length===2){let e=this.getVariables(),r=e[0],i=e[1];if(r.cardinality!=="single"||i.cardinality!=="single"||Array.isArray(r.value)||Array.isArray(i.value))return console.error("unexpected cardinality in qti string-match"),!1;let o=this.caseSensitive==="true"?r.value:r.value.toLowerCase(),n=this.caseSensitive==="true"?i.value:i.value.toLowerCase();return P.compareSingleValues(o,n,r.baseType)}return console.error("unexpected number of children in qti-string-match"),null}};l([d({type:String,attribute:"case-sensitive"})],Yt.prototype,"caseSensitive",2);customElements.define("qti-string-match",Yt);var Vr=class extends x{constructor(){super(),this._expression=new Ir(Array.from(this.children))}getResult(){return this._expression.calculate()}},Ir=class{constructor(t){this.expressions=t}calculate(){return this.expressions.map(e=>{if(!e.calculate)return console.error("Element doesn't implement QtiConditionExpression"),null;let r=e.calculate();return Number.isNaN(r)?(console.error("unexpected value in qti-sum, expected number"),null):Number(r)}).reduce((e,r)=>e+r,0)}};customElements.define("qti-sum",Vr);var Or=class extends x{getResult(){let t=this.getAttribute("identifier");return this.closest("qti-assessment-item").getVariable(t).value}};customElements.define("qti-variable",Or);var pe=class extends T{constructor(){super(...arguments);this._errorMessage=null;this.loadConfig=async(e,r)=>{e=this.removeDoubleSlashes(e);try{let i=await fetch(e);if(i.ok){let n=await i.json();for(let a in n.paths)r&&(n.paths[a]=this.getResolvablePath(n.paths[a],r));return n}}catch(i){}return null};this.getResolvablePathString=(e,r)=>(e=e.replace(/\.js$/,""),e!=null&&e.toLocaleLowerCase().startsWith("http")||!r?e:this.removeDoubleSlashes(`${r}/${e}`));this.getResolvablePath=(e,r)=>Array.isArray(e)?e.map(i=>this.getResolvablePathString(i,r)):this.getResolvablePathString(e,r)}convertQtiVariableJSON(e){for(let r in e)if(e.hasOwnProperty(r)){let i=e[r];if(i){for(let o in i)if(i.hasOwnProperty(o)){let n=i[o];if(Array.isArray(n))return n.map(String);if(n!=null)return String(n)}}}return null}startChecking(){this.intervalId=setInterval(()=>{let e=this.pci.getResponse(),r=this.pci.getResponse(),i=JSON.stringify(e);if(i!==this.rawResponse){this.rawResponse=i;let o=this.convertQtiVariableJSON(r);this.response=o,this.saveResponse(o)}},200)}stopChecking(){this.intervalId!==void 0&&clearInterval(this.intervalId)}validate(){return!0}set response(e){}getTAOConfig(e){let r=e.querySelectorAll("properties"),i={},o=a=>{let c={},p=a.getAttribute("key");if(p){let f=Array.from(a.children),g=f.map(v=>v.getAttribute("key"));g.length>0&&!g.find(v=>!Number.isInteger(+v))?c[p]=f.map(v=>n(v)):c[p]=a.textContent}return c},n=a=>{if(a){let c={};for(let p of a.children)c=C(C({},c),o(p));return c}};for(let a of r)return a.getAttribute("key")||(i=C(C({},i),n(a))),i;return console.log("Can not find qti-custom-interaction config"),null}register(e){this.pci=e;let r=this.parentElement.tagName==="QTI-CUSTOM-INTERACTION"?"TAO":"IMS",i=r=="IMS"?this.querySelector("qti-interaction-markup"):this.querySelector("markup");i.classList.add("qti-customInteraction"),r=="TAO"&&this.querySelector("properties")&&(this.querySelector("properties").style.display="none");let o=r=="IMS"?{properties:this.dataset,onready:()=>{console.log("onready")}}:this.getTAOConfig(this);r=="IMS"?e.getInstance(i,o,void 0):e.initialize(this.customInteractionTypeIdentifier,i.firstElementChild,o),r=="TAO"&&Array.from(this.querySelectorAll("link")).map(a=>a.getAttribute("href")).forEach(a=>{let c=document.createElement("link");c.rel="stylesheet",c.type="text/css",c.media="screen",c.href=a,i.appendChild(c)}),this.startChecking()}connectedCallback(){super.connectedCallback(),define("qtiCustomInteractionContext",()=>({register:i=>{this.register(i)},notifyReady:()=>{}}));let e=this.buildRequireConfig();requirejs.config(e)(["require"],i=>{i([this.module])})}disconnectedCallback(){super.disconnectedCallback(),requirejs.undef(this.customInteractionTypeIdentifier);let e=requirejs.s.contexts;delete e[this.customInteractionTypeIdentifier],this.stopChecking()}buildRequireConfig(){let e={context:this.customInteractionTypeIdentifier,catchError:!0,paths:window.requirePaths||{},shim:window.requireShim||{}};if(!globalThis.require)return this._errorMessage="RequireJS not found. Please load it via CDN: https://cdnjs.com/libraries/require.js",null;let r=this.getAttribute("data-base-url"),i=this.querySelector("qti-interaction-modules");if(i){let o=i.querySelectorAll("qti-interaction-module");for(let n of o){let a=n.getAttribute("id"),c=n.getAttribute("primary-path"),p=n.getAttribute("fallback-path");if(a&&c){let f=p?this.combineRequireResolvePaths(this.getResolvablePath(c,r),this.getResolvablePath(p,r)):this.getResolvablePath(c,r),g=e.paths[a]||[];e.paths[a]=this.combineRequireResolvePaths(g,f)}}}return e}combineRequireResolvePaths(e,r){let i=Array.isArray(e)?e:[e],o=Array.isArray(r)?r:[r];return i.concat(o)}removeDoubleSlashes(e){return e.replace(/([^:]\/)\/+/g,"$1").replace(/\/\//g,"/").replace("http:/","http://").replace("https:/","https://")}render(){return h`<slot></slot>${this._errorMessage&&h`<div style="color:red">
248
248
  <h1>Error</h1>
249
249
  ${this._errorMessage}
250
- </div>`}`}};l([d({type:String,attribute:"response-identifier"})],pe.prototype,"responseIdentifier",2),l([d({type:String,attribute:"module"})],pe.prototype,"module",2),l([d({type:String,attribute:"custom-interaction-type-identifier"})],pe.prototype,"customInteractionTypeIdentifier",2),l([q()],pe.prototype,"_errorMessage",2),pe=l([m("qti-portable-custom-interaction")],pe);var Wt=class s{constructor(){this.touchStartTime=0;this.touchStartPoint=null;this.lastClickTime=0;this.isDraggable=!1;this.dragSource=null;this.dragClone=null;this.touchEndTriggered=!1;this.isDragging=!1;this.initialTransform="";this.hasDispatchedDragStart=!1;this.rootNode=null;this.focusedElement=null;this.focusableDropZones=[];this.currentDropZoneIndex=-1;this.dataTransfer={data:{},setData(t,e){this.data[t]=e},getData(t){return this.data[t]},effectAllowed:"move"};this.cloneOffset={x:0,y:0};this.lastTarget=null;this.currentDropTarget=null;this.allowClick=!0;this.copyStylesForDragClone=!0;this.dragOnClickEnabled=!1;this.useDragClone=!1;this.MIN_DRAG_DISTANCE=5;this.DRAG_CLONE_OPACITY=1;if(s.instance)return s.instance;s.instance=this,document.addEventListener("touchmove",this.handleTouchMove.bind(this),{passive:!1}),document.addEventListener("mousemove",this.handleTouchMove.bind(this),{passive:!1}),document.addEventListener("touchend",this.handleTouchEnd.bind(this),{passive:!1}),document.addEventListener("mouseup",this.handleTouchEnd.bind(this),{passive:!1}),document.addEventListener("touchcancel",this.handleTouchCancel.bind(this),{passive:!1}),document.addEventListener("keydown",this.handleKeyDown.bind(this)),document.addEventListener("keyup",this.handleKeyUp.bind(this))}addDraggableElements(t){t.forEach(e=>{e.setAttribute("tabindex","0"),e.addEventListener("focus",()=>this.focusedElement=e),e.addEventListener("blur",()=>this.focusedElement=null),e.addEventListener("touchstart",this.handleTouchStart.bind(this),{passive:!1}),e.addEventListener("mousedown",this.handleTouchStart.bind(this),{passive:!1})})}handleTouchStart(t){this.touchStartTime=Date.now();let{x:e,y:r}=this.getEventCoordinates(t);if(this.touchStartPoint={x:e,y:r},this.dragSource=t.currentTarget,this.isDraggable=!0,this.rootNode=this.dragSource.getRootNode(),this.dragOnClickEnabled&&(this.isDragging=!0,this.createDragClone(t,{clientX:e,clientY:r})),!this.useDragClone){let i=window.getComputedStyle(this.dragSource);this.initialTransform=i.transform==="none"?"":i.transform,this.initialTransition=i.transition||"",this.dragSource.style.transition="none";let o=this.dragSource.getBoundingClientRect();this.cloneOffset.x=e-o.left,this.cloneOffset.y=r-o.top,this.dragSource.style.zIndex="9999",this.dragSource.focus()}t.preventDefault()}handleTouchMove(t){if(this.isDraggable&&this.dragSource){let{x:e,y:r}=this.getEventCoordinates(t),i={clientX:e,clientY:r};this.calculateDragDistance(i)>=this.MIN_DRAG_DISTANCE&&(this.dragSource.style.pointerEvents="none",this.isDragging=!0),this.createDragClone(t,i),t.preventDefault()}}createDragClone(t,e){if(!this.isDragging)return;if(this.useDragClone){if(!this.dragClone){if(this.dragSource.style.opacity=this.DRAG_CLONE_OPACITY.toString(),this.dragClone=this.dragSource.cloneNode(!0),this.copyStylesForDragClone){let i=window.getComputedStyle(this.dragSource);for(let o of i)this.dragClone.style[o]=i.getPropertyValue(o)}this.rootNode instanceof ShadowRoot?this.rootNode.host.appendChild(this.dragClone):this.rootNode instanceof Document&&document.body.appendChild(this.dragClone),this.calculateClonePosition(e),this.setDragCloneStyles(e),this.dispatchCustomEvent(this.dragSource,"dragstart")}this.updateDragClonePosition(e)}else if(this.touchStartPoint){let i=e.clientX-this.touchStartPoint.x,o=e.clientY-this.touchStartPoint.y;this.dragSource.style.transform=`${this.initialTransform} translate(${i}px, ${o}px)`,this.hasDispatchedDragStart||(this.dispatchCustomEvent(this.dragSource,"dragstart"),this.hasDispatchedDragStart=!0)}let r=this.findDropTarget(t);r!==this.lastTarget&&(this.dispatchCustomEvent(r,"dragenter"),this.dispatchCustomEvent(this.lastTarget,"dragleave"),this.lastTarget=r),this.currentDropTarget=r,this.currentDropTarget&&this.dispatchCustomEvent(r,"dragover")}handleTouchEnd(t){var r;this.touchEndTriggered=!0,this.isDraggable=!1;let e=!1;if(this.currentDropTarget)this.dispatchCustomEvent(this.currentDropTarget,"drop"),this.dispatchCustomEvent(this.dragSource,"dragend"),e=!0;else if(this.isDragging){let i=new CustomEvent("dragend",{bubbles:!0,cancelable:!0});i.dataTransfer={dropEffect:"none"},(r=this.dragSource)==null||r.dispatchEvent(i)}this.resetDragState(e)}handleTouchCancel(t){this.resetDragState()}findDropTarget(t){let{x:e,y:r}=this.getEventCoordinates(t);return this.getDropTargetAtPoint(document,e,r)}getDropTargetAtPoint(t,e,r,i=0){if(i>2)return null;let n=t.elementFromPoint(e,r);if(!n)return null;if(n.hasAttribute("dropzone"))return n;let a=n.parentElement;for(;a;){if(a.hasAttribute("dropzone"))return a;a=a.parentElement}if(n.shadowRoot&&i<2){let c=this.getDropTargetAtPoint(n.shadowRoot,e,r,i+1);if(c)return c}return null}handleKeyDown(t){this.focusedElement&&(t.key===" "&&!this.isDragging?(t.preventDefault(),this.isDraggable=!0,this.dragSource=this.focusedElement,this.isDragging=!0,this.collectDropZones(),this.dispatchCustomEvent(this.dragSource,"dragstart")):t.key==="Tab"&&this.isDragging&&(t.preventDefault(),this.moveToNextDropZone()))}handleKeyUp(t){t.key===" "&&this.isDragging&&this.currentDropTarget&&(t.preventDefault(),this.dispatchCustomEvent(this.currentDropTarget,"drop"),this.dispatchCustomEvent(this.dragSource,"dragend"),this.resetDragState(!0))}collectDropZones(){this.focusableDropZones=Array.from(document.querySelectorAll("[dropzone]")),this.currentDropZoneIndex=-1}moveToNextDropZone(){if(this.focusableDropZones.length===0)return;this.currentDropZoneIndex=(this.currentDropZoneIndex+1)%this.focusableDropZones.length;let t=this.focusableDropZones[this.currentDropZoneIndex];t.focus(),this.currentDropTarget=t,this.dispatchCustomEvent(t,"dragenter")}getEventCoordinates(t,e=!1){let r=t.touches?t.touches[0]:t;return{x:e?r.pageX:r.clientX,y:e?r.pageY:r.clientY}}calculateClonePosition(t){let e=this.dragSource.getBoundingClientRect();this.cloneOffset.x=t.clientX-e.left,this.cloneOffset.y=t.clientY-e.top}setDragCloneStyles(t){this.dragClone.style.position="fixed",this.dragClone.style.top=`${t.clientY-this.cloneOffset.y}px`,this.dragClone.style.left=`${t.clientX-this.cloneOffset.x}px`,this.dragClone.style.pointerEvents="none",this.dragClone.style.zIndex="999999"}updateDragClonePosition(t){requestAnimationFrame(()=>{if(this.touchEndTriggered||!this.dragClone)return;let e=t.clientX-this.cloneOffset.x,r=t.clientY-this.cloneOffset.y,{newLeft:i,newTop:o}=this.applyBoundaries(e,r,this.dragClone);this.dragClone.style.left=`${i}px`,this.dragClone.style.top=`${o}px`})}applyTransformBoundaries(t,e){let r;this.rootNode instanceof ShadowRoot?r=this.rootNode.host.getBoundingClientRect():this.rootNode instanceof Document?r=document.documentElement.getBoundingClientRect():r=new DOMRect(0,0,window.innerWidth,window.innerHeight);let i=this.dragSource.getBoundingClientRect(),o=i.width,n=i.height,a=i.left+t,c=i.top+e,p=Math.max(r.left,Math.min(a,r.right-o)),f=Math.max(r.top,Math.min(c,r.bottom-n)),g=p-i.left,y=f-i.top;return{boundedDeltaX:g,boundedDeltaY:y}}applyBoundaries(t,e,r){let i;this.rootNode instanceof ShadowRoot?i=this.rootNode.host.getBoundingClientRect():this.rootNode instanceof Document?i=document.documentElement.getBoundingClientRect():i=new DOMRect(0,0,window.innerWidth,window.innerHeight);let o=r.getBoundingClientRect(),n=o.width,a=o.height,c=Math.max(i.left,Math.min(t,i.right-n)),p=Math.max(i.top,Math.min(e,i.bottom-a));return{newLeft:c,newTop:p}}calculateDragDistance(t){let e=Math.abs(t.clientX-this.touchStartPoint.x),r=Math.abs(t.clientY-this.touchStartPoint.y);return e+r}dispatchCustomEvent(t,e,r=!0){if(!t)return;let i=new CustomEvent(e,{bubbles:r,cancelable:!0});i.dataTransfer=this.dataTransfer,t.dispatchEvent(i)}resetDragState(t=!1){var e;this.isDragging&&(this.useDragClone?(this.dragSource.style.opacity="1.0",(e=this.dragClone)==null||e.parentElement.removeChild(this.dragClone)):(t||(this.dragSource.style.transform="translate(0, 0)"),this.dragSource.style.zIndex="",this.dragSource.style.pointerEvents="",this.dragSource.style.transition=this.initialTransition,this.initialTransition="")),this.isDragging=!1,this.dragSource=null,this.dragClone=null,this.isDraggable=!1,this.touchStartTime=0,this.touchStartPoint=null,this.touchEndTriggered=!1,this.dataTransfer={data:{},setData(r,i){this.data[r]=i},getData(r){return this.data[r]},effectAllowed:"move"},this.cloneOffset={x:0,y:0},this.lastTarget=null,this.currentDropTarget=null,this.allowClick=!0,this.initialTransform="",this.hasDispatchedDragStart=!1,this.rootNode=null}};var Ni=(s,t,e)=>{class r extends s{constructor(){super(...arguments);this.disabled=!1}firstUpdated(n){if(this.isMatchTabular())return;super.firstUpdated(n);let a=this.getDroppableElements();this.initializeEventHandlers(),a.forEach(c=>{this.prepareDroppable(c),this.observeDroppableAttributes(c)})}isMatchTabular(){return this.classList.contains("qti-match-tabular")}getDroppableElements(){return Array.from(t?this.shadowRoot.querySelectorAll(e):this.querySelectorAll(e))}initializeEventHandlers(){this.dragoverHandler=this.dragoverHandler.bind(this),this.dragleaveHandler=this.dragleaveHandler.bind(this),this.dragenterHandler=this.dragenterHandler.bind(this),this.dropHandler=this.dropHandler.bind(this)}prepareDroppable(n){n.setAttribute("dropzone","move"),n.addEventListener("dragleave",this.dragleaveHandler),this.attachEventListeners(n)}observeDroppableAttributes(n){this.observer=new MutationObserver(a=>{a.forEach(({attributeName:c})=>{c==="disabled"&&this.toggleDroppableHandlers(n)})}),this.observer.observe(n,{attributes:!0})}toggleDroppableHandlers(n){n.hasAttribute("disabled")?this.removeEventListeners(n):this.attachEventListeners(n)}attachEventListeners(n){n.addEventListener("dragover",this.dragoverHandler),n.addEventListener("dragenter",this.dragenterHandler),n.addEventListener("drop",this.dropHandler)}removeEventListeners(n){n.removeEventListener("dragover",this.dragoverHandler),n.removeEventListener("dragenter",this.dragenterHandler),n.removeEventListener("drop",this.dropHandler)}disconnectedCallback(){var n;this.isMatchTabular()||(super.disconnectedCallback(),(n=this.observer)==null||n.disconnect())}dragenterHandler(n){n.preventDefault()}dragoverHandler(n){return n.preventDefault(),this.activateDroppable(n.currentTarget),n.dataTransfer.dropEffect="move",!1}activateDroppable(n){n.setAttribute("active","")}async dropHandler(n){n.preventDefault();let a=n.currentTarget,c=this.findDraggable(n.dataTransfer.getData("text"));return!c||!this.isValidDrop(a,c)?(c.style.transform="translate(0, 0)",!1):(await this.moveDraggableToDroppable(c,a),this.deactivateDroppable(a),!1)}findDraggable(n){return this.querySelector(`[identifier=${n}]`)||this.shadowRoot.querySelector(`[identifier=${n}]`)}isValidDrop(n,a){return a.parentElement.getAttribute("identifier")!==n.getAttribute("identifier")}async moveDraggableToDroppable(n,a){let c=()=>{n.style.transform="translate(0, 0)",a.appendChild(n),this.checkMaxAssociations()};if(!document.startViewTransition){c();return}await document.startViewTransition(c).finished}deactivateDroppable(n){n.removeAttribute("active")}dragleaveHandler(n){return n.preventDefault(),this.deactivateDroppable(n.currentTarget),n.dataTransfer.dropEffect="none",!1}}return l([d({type:Boolean,reflect:!0})],r.prototype,"disabled",2),r};var Vi=(s,t,e)=>{class r extends s{}return r};var Y=(s,t,e,r)=>{class i extends Vi(Ni(s,e,r),r,t){constructor(){super(...arguments);this.draggables=new Map;this.droppables=[];this.responseIdentifier="";this.configuration={copyStylesDragClone:!0,dragCanBePlacedBack:!0,dragOnClick:!1};this.disabled=!1;this.readonly=!1;this.minAssociations=1;this.maxAssociations=1;this.handleDragStart=a=>{let c=a.currentTarget;a.dataTransfer.setData("text",c.getAttribute("identifier")),c.setAttribute("dragging",""),this.activateDroppables()};this.handleDragEnd=a=>{a.preventDefault(),this.deactivateDroppables();let c=a.currentTarget;c.removeAttribute("dragging"),this.wasDropped(a)||this.configuration.dragCanBePlacedBack&&this.restoreInitialDraggablePosition(c),this.wasMoved(a)&&this.saveResponse()}}handleDraggablesChange(a,c){if(this.isMatchTabular())return;let p=this.filterExistingDraggables(a);p.length>0&&this.addNewDraggables(p)}firstUpdated(a){super.firstUpdated(a),this.initializeDroppables()}connectedCallback(){super.connectedCallback(),this.initializeDragDropApi()}initializeDragDropApi(){this.dragDropApi=new Wt,this.dispatchEvent(new CustomEvent("qti-register-interaction",{bubbles:!0,composed:!0,detail:this}))}isMatchTabular(){return this.classList.contains("qti-match-tabular")}filterExistingDraggables(a){return a.filter(c=>!this.draggables.has(c))}addNewDraggables(a){this.dragDropApi.addDraggableElements(a),a.forEach(c=>this.storeDraggable(c))}storeDraggable(a){let c=Array.from(a.parentNode.children).indexOf(a);this.draggables.set(a,{parent:a.parentElement,index:c}),a.style.viewTransitionName=`drag-${c}-${this.getAttribute("identifier")}`,a.setAttribute("qti-draggable","true"),a.addEventListener("dragstart",this.handleDragStart),a.addEventListener("dragend",this.handleDragEnd)}initializeDroppables(){this.droppables=Array.from(e?this.shadowRoot.querySelectorAll(r):this.querySelectorAll(r))}activateDroppables(){this.droppables.forEach(a=>a.setAttribute("enabled",""))}deactivateDroppables(){this.droppables.forEach(a=>a.removeAttribute("enabled"))}wasDropped(a){return a.dataTransfer.dropEffect!=="none"}wasMoved(a){return a.dataTransfer.dropEffect==="move"}async restoreInitialDraggablePosition(a){let{parent:c,index:p}=this.draggables.get(a),f=Math.min(p,c.children.length),g=(v,w,k)=>{let A=Math.min(k,w.children.length);w.insertBefore(v,w.children[A]),v.style.transform="translate(0, 0)",this.checkMaxAssociations(),this.saveResponse()};if(!document.startViewTransition){g(a,c,p);return}let y=document.startViewTransition(()=>{a.style.transform="",g(a,c,p)})}checkMaxAssociations(){this.droppables.forEach((a,c)=>{let p=+(a.getAttribute("match-max")||1);a.querySelectorAll('[qti-draggable="true"]').length>=p?this.disableDroppable(a):this.enableDroppable(a)})}disableDroppable(a){a.setAttribute("disabled",""),a.removeAttribute("dropzone")}enableDroppable(a){a.removeAttribute("disabled"),a.setAttribute("dropzone","move")}set response(a){this.isMatchTabular()||(this.resetDroppables(),a==null||a.forEach(c=>this.placeResponse(c)))}placeResponse(a){let[c,...p]=a.split(" ").reverse(),f=this.findDroppableById(c);p.forEach(g=>this.placeDraggableInDroppable(g,f))}findDroppableById(a){return this.droppables.find(c=>c.getAttribute("identifier")===a)}async placeDraggableInDroppable(a,c){let p=this.querySelector(`[identifier=${a}]`);if(!c||!p){console.error(`Cannot find draggable or droppable with the given identifier: ${a}`);return}let f=()=>{p.style.transform="translate(0, 0)",c.appendChild(p),this.checkMaxAssociations()};document.startViewTransition?await document.startViewTransition(f).finished:f()}validate(){let a=this.getValidAssociations();return this.minAssociations<=0||this.minAssociations<=a}getValidAssociations(){return this.droppables.filter(a=>a.childElementCount>0).length}saveResponse(){let a=this.collectResponseData();this.dispatchEvent(new CustomEvent("qti-interaction-response",{bubbles:!0,composed:!0,detail:{responseIdentifier:this.responseIdentifier,response:a}}))}collectResponseData(){return this.droppables.map(a=>{let c=a.querySelectorAll('[qti-draggable="true"]'),p=Array.from(c).map(g=>g.getAttribute("identifier")),f=a.getAttribute("identifier");return[...p,f].join(" ")})}reset(a=!0){this.resetDroppables(),a&&this.saveResponse()}async resetDroppables(){let a=(p,f,g)=>{p.style.transform="translate(0, 0)";let y=Math.min(g,f.children.length);f.insertBefore(p,f.children[y])};if(!document.startViewTransition){this.draggables.forEach(({parent:p,index:f},g)=>{a(g,p,f)});return}await document.startViewTransition(()=>{this.draggables.forEach(({parent:p,index:f},g)=>{a(g,p,f)})}).finished}}return l([d({type:String,attribute:"response-identifier"})],i.prototype,"responseIdentifier",2),l([d({attribute:!1,type:Object})],i.prototype,"configuration",2),l([d({type:Boolean,reflect:!0})],i.prototype,"disabled",2),l([d({type:Boolean,reflect:!0})],i.prototype,"readonly",2),l([d({type:Number,reflect:!0,attribute:"min-associations"})],i.prototype,"minAssociations",2),l([d({type:Number,reflect:!0,attribute:"max-associations"})],i.prototype,"maxAssociations",2),l([Mi(t)],i.prototype,"handleDraggablesChange",1),i};var Ii=b`
250
+ </div>`}`}};l([d({type:String,attribute:"response-identifier"})],pe.prototype,"responseIdentifier",2),l([d({type:String,attribute:"module"})],pe.prototype,"module",2),l([d({type:String,attribute:"custom-interaction-type-identifier"})],pe.prototype,"customInteractionTypeIdentifier",2),l([q()],pe.prototype,"_errorMessage",2),pe=l([m("qti-portable-custom-interaction")],pe);var Wt=class s{constructor(){this.touchStartTime=0;this.touchStartPoint=null;this.lastClickTime=0;this.isDraggable=!1;this.dragSource=null;this.dragClone=null;this.touchEndTriggered=!1;this.isDragging=!1;this.initialTransform="";this.hasDispatchedDragStart=!1;this.rootNode=null;this.focusedElement=null;this.focusableDropZones=[];this.currentDropZoneIndex=-1;this.dataTransfer={data:{},setData(t,e){this.data[t]=e},getData(t){return this.data[t]},effectAllowed:"move"};this.cloneOffset={x:0,y:0};this.lastTarget=null;this.currentDropTarget=null;this.allowClick=!0;this.copyStylesForDragClone=!0;this.dragOnClickEnabled=!1;this.useDragClone=!1;this.MIN_DRAG_DISTANCE=5;this.DRAG_CLONE_OPACITY=1;if(s.instance)return s.instance;s.instance=this,document.addEventListener("touchmove",this.handleTouchMove.bind(this),{passive:!1}),document.addEventListener("mousemove",this.handleTouchMove.bind(this),{passive:!1}),document.addEventListener("touchend",this.handleTouchEnd.bind(this),{passive:!1}),document.addEventListener("mouseup",this.handleTouchEnd.bind(this),{passive:!1}),document.addEventListener("touchcancel",this.handleTouchCancel.bind(this),{passive:!1}),document.addEventListener("keydown",this.handleKeyDown.bind(this)),document.addEventListener("keyup",this.handleKeyUp.bind(this))}addDraggableElements(t){t.forEach(e=>{e.setAttribute("tabindex","0"),e.addEventListener("focus",()=>this.focusedElement=e),e.addEventListener("blur",()=>this.focusedElement=null),e.addEventListener("touchstart",this.handleTouchStart.bind(this),{passive:!1}),e.addEventListener("mousedown",this.handleTouchStart.bind(this),{passive:!1})})}handleTouchStart(t){this.touchStartTime=Date.now();let{x:e,y:r}=this.getEventCoordinates(t);if(this.touchStartPoint={x:e,y:r},this.dragSource=t.currentTarget,this.isDraggable=!0,this.rootNode=this.dragSource.getRootNode(),this.dragOnClickEnabled&&(this.isDragging=!0,this.createDragClone(t,{clientX:e,clientY:r})),!this.useDragClone){let i=window.getComputedStyle(this.dragSource);this.initialTransform=i.transform==="none"?"":i.transform,this.initialTransition=i.transition||"",this.dragSource.style.transition="none";let o=this.dragSource.getBoundingClientRect();this.cloneOffset.x=e-o.left,this.cloneOffset.y=r-o.top,this.dragSource.style.zIndex="9999",this.dragSource.focus()}t.preventDefault()}handleTouchMove(t){if(this.isDraggable&&this.dragSource){let{x:e,y:r}=this.getEventCoordinates(t),i={clientX:e,clientY:r};this.calculateDragDistance(i)>=this.MIN_DRAG_DISTANCE&&(this.dragSource.style.pointerEvents="none",this.isDragging=!0),this.createDragClone(t,i),t.preventDefault()}}createDragClone(t,e){if(!this.isDragging)return;if(this.useDragClone){if(!this.dragClone){if(this.dragSource.style.opacity=this.DRAG_CLONE_OPACITY.toString(),this.dragClone=this.dragSource.cloneNode(!0),this.copyStylesForDragClone){let i=window.getComputedStyle(this.dragSource);for(let o of i)this.dragClone.style[o]=i.getPropertyValue(o)}this.rootNode instanceof ShadowRoot?this.rootNode.host.appendChild(this.dragClone):this.rootNode instanceof Document&&document.body.appendChild(this.dragClone),this.calculateClonePosition(e),this.setDragCloneStyles(e),this.dispatchCustomEvent(this.dragSource,"dragstart")}this.updateDragClonePosition(e)}else if(this.touchStartPoint){let i=e.clientX-this.touchStartPoint.x,o=e.clientY-this.touchStartPoint.y;this.dragSource.style.transform=`${this.initialTransform} translate(${i}px, ${o}px)`,this.hasDispatchedDragStart||(this.dispatchCustomEvent(this.dragSource,"dragstart"),this.hasDispatchedDragStart=!0)}let r=this.findDropTarget(t);r!==this.lastTarget&&(this.dispatchCustomEvent(r,"dragenter"),this.dispatchCustomEvent(this.lastTarget,"dragleave"),this.lastTarget=r),this.currentDropTarget=r,this.currentDropTarget&&this.dispatchCustomEvent(r,"dragover")}handleTouchEnd(t){var r;this.touchEndTriggered=!0,this.isDraggable=!1;let e=!1;if(this.currentDropTarget)this.dispatchCustomEvent(this.currentDropTarget,"drop"),this.dispatchCustomEvent(this.dragSource,"dragend"),e=!0;else if(this.isDragging){let i=new CustomEvent("dragend",{bubbles:!0,cancelable:!0});i.dataTransfer={dropEffect:"none"},(r=this.dragSource)==null||r.dispatchEvent(i)}this.resetDragState(e)}handleTouchCancel(t){this.resetDragState()}findDropTarget(t){let{x:e,y:r}=this.getEventCoordinates(t);return this.getDropTargetAtPoint(document,e,r)}getDropTargetAtPoint(t,e,r,i=0){if(i>2)return null;let n=t.elementFromPoint(e,r);if(!n)return null;if(n.hasAttribute("dropzone"))return n;let a=n.parentElement;for(;a;){if(a.hasAttribute("dropzone"))return a;a=a.parentElement}if(n.shadowRoot&&i<2){let c=this.getDropTargetAtPoint(n.shadowRoot,e,r,i+1);if(c)return c}return null}handleKeyDown(t){this.focusedElement&&(t.key===" "&&!this.isDragging?(t.preventDefault(),this.isDraggable=!0,this.dragSource=this.focusedElement,this.isDragging=!0,this.collectDropZones(),this.dispatchCustomEvent(this.dragSource,"dragstart")):t.key==="Tab"&&this.isDragging&&(t.preventDefault(),this.moveToNextDropZone()))}handleKeyUp(t){t.key===" "&&this.isDragging&&this.currentDropTarget&&(t.preventDefault(),this.dispatchCustomEvent(this.currentDropTarget,"drop"),this.dispatchCustomEvent(this.dragSource,"dragend"),this.resetDragState(!0))}collectDropZones(){this.focusableDropZones=Array.from(document.querySelectorAll("[dropzone]")),this.currentDropZoneIndex=-1}moveToNextDropZone(){if(this.focusableDropZones.length===0)return;this.currentDropZoneIndex=(this.currentDropZoneIndex+1)%this.focusableDropZones.length;let t=this.focusableDropZones[this.currentDropZoneIndex];t.focus(),this.currentDropTarget=t,this.dispatchCustomEvent(t,"dragenter")}getEventCoordinates(t,e=!1){let r=t.touches?t.touches[0]:t;return{x:e?r.pageX:r.clientX,y:e?r.pageY:r.clientY}}calculateClonePosition(t){let e=this.dragSource.getBoundingClientRect();this.cloneOffset.x=t.clientX-e.left,this.cloneOffset.y=t.clientY-e.top}setDragCloneStyles(t){this.dragClone.style.position="fixed",this.dragClone.style.top=`${t.clientY-this.cloneOffset.y}px`,this.dragClone.style.left=`${t.clientX-this.cloneOffset.x}px`,this.dragClone.style.pointerEvents="none",this.dragClone.style.zIndex="999999"}updateDragClonePosition(t){requestAnimationFrame(()=>{if(this.touchEndTriggered||!this.dragClone)return;let e=t.clientX-this.cloneOffset.x,r=t.clientY-this.cloneOffset.y,{newLeft:i,newTop:o}=this.applyBoundaries(e,r,this.dragClone);this.dragClone.style.left=`${i}px`,this.dragClone.style.top=`${o}px`})}applyTransformBoundaries(t,e){let r;this.rootNode instanceof ShadowRoot?r=this.rootNode.host.getBoundingClientRect():this.rootNode instanceof Document?r=document.documentElement.getBoundingClientRect():r=new DOMRect(0,0,window.innerWidth,window.innerHeight);let i=this.dragSource.getBoundingClientRect(),o=i.width,n=i.height,a=i.left+t,c=i.top+e,p=Math.max(r.left,Math.min(a,r.right-o)),f=Math.max(r.top,Math.min(c,r.bottom-n)),g=p-i.left,y=f-i.top;return{boundedDeltaX:g,boundedDeltaY:y}}applyBoundaries(t,e,r){let i;this.rootNode instanceof ShadowRoot?i=this.rootNode.host.getBoundingClientRect():this.rootNode instanceof Document?i=document.documentElement.getBoundingClientRect():i=new DOMRect(0,0,window.innerWidth,window.innerHeight);let o=r.getBoundingClientRect(),n=o.width,a=o.height,c=Math.max(i.left,Math.min(t,i.right-n)),p=Math.max(i.top,Math.min(e,i.bottom-a));return{newLeft:c,newTop:p}}calculateDragDistance(t){let e=Math.abs(t.clientX-this.touchStartPoint.x),r=Math.abs(t.clientY-this.touchStartPoint.y);return e+r}dispatchCustomEvent(t,e,r=!0){if(!t)return;let i=new CustomEvent(e,{bubbles:r,cancelable:!0});i.dataTransfer=this.dataTransfer,t.dispatchEvent(i)}resetDragState(t=!1){var e;this.isDragging&&(this.useDragClone?(this.dragSource.style.opacity="1.0",(e=this.dragClone)==null||e.parentElement.removeChild(this.dragClone)):(t||(this.dragSource.style.transform="translate(0, 0)"),this.dragSource.style.zIndex="",this.dragSource.style.pointerEvents="",this.dragSource.style.transition=this.initialTransition,this.initialTransition="")),this.isDragging=!1,this.dragSource=null,this.dragClone=null,this.isDraggable=!1,this.touchStartTime=0,this.touchStartPoint=null,this.touchEndTriggered=!1,this.dataTransfer={data:{},setData(r,i){this.data[r]=i},getData(r){return this.data[r]},effectAllowed:"move"},this.cloneOffset={x:0,y:0},this.lastTarget=null,this.currentDropTarget=null,this.allowClick=!0,this.initialTransform="",this.hasDispatchedDragStart=!1,this.rootNode=null}};var Ni=(s,t,e)=>{class r extends s{constructor(){super(...arguments);this.disabled=!1}firstUpdated(n){if(this.isMatchTabular())return;super.firstUpdated(n);let a=this.getDroppableElements();this.initializeEventHandlers(),a.forEach(c=>{this.prepareDroppable(c),this.observeDroppableAttributes(c)})}isMatchTabular(){return this.classList.contains("qti-match-tabular")}getDroppableElements(){return Array.from(t?this.shadowRoot.querySelectorAll(e):this.querySelectorAll(e))}initializeEventHandlers(){this.dragoverHandler=this.dragoverHandler.bind(this),this.dragleaveHandler=this.dragleaveHandler.bind(this),this.dragenterHandler=this.dragenterHandler.bind(this),this.dropHandler=this.dropHandler.bind(this)}prepareDroppable(n){n.setAttribute("dropzone","move"),n.addEventListener("dragleave",this.dragleaveHandler),this.attachEventListeners(n)}observeDroppableAttributes(n){this.observer=new MutationObserver(a=>{a.forEach(({attributeName:c})=>{c==="disabled"&&this.toggleDroppableHandlers(n)})}),this.observer.observe(n,{attributes:!0})}toggleDroppableHandlers(n){n.hasAttribute("disabled")?this.removeEventListeners(n):this.attachEventListeners(n)}attachEventListeners(n){n.addEventListener("dragover",this.dragoverHandler),n.addEventListener("dragenter",this.dragenterHandler),n.addEventListener("drop",this.dropHandler)}removeEventListeners(n){n.removeEventListener("dragover",this.dragoverHandler),n.removeEventListener("dragenter",this.dragenterHandler),n.removeEventListener("drop",this.dropHandler)}disconnectedCallback(){var n;this.isMatchTabular()||(super.disconnectedCallback(),(n=this.observer)==null||n.disconnect())}dragenterHandler(n){n.preventDefault()}dragoverHandler(n){return n.preventDefault(),this.activateDroppable(n.currentTarget),n.dataTransfer.dropEffect="move",!1}activateDroppable(n){n.setAttribute("active","")}async dropHandler(n){n.preventDefault();let a=n.currentTarget,c=this.findDraggable(n.dataTransfer.getData("text"));return!c||!this.isValidDrop(a,c)?(c.style.transform="translate(0, 0)",!1):(await this.moveDraggableToDroppable(c,a),this.deactivateDroppable(a),!1)}findDraggable(n){return this.querySelector(`[identifier=${n}]`)||this.shadowRoot.querySelector(`[identifier=${n}]`)}isValidDrop(n,a){return a.parentElement.getAttribute("identifier")!==n.getAttribute("identifier")}async moveDraggableToDroppable(n,a){let c=()=>{n.style.transform="translate(0, 0)",a.appendChild(n),this.checkMaxAssociations(),this.saveResponse()};if(!document.startViewTransition){c();return}await document.startViewTransition(c).finished}deactivateDroppable(n){n.removeAttribute("active")}dragleaveHandler(n){return n.preventDefault(),this.deactivateDroppable(n.currentTarget),n.dataTransfer.dropEffect="none",!1}}return l([d({type:Boolean,reflect:!0})],r.prototype,"disabled",2),r};var Vi=(s,t,e)=>{class r extends s{}return r};var Y=(s,t,e,r)=>{class i extends Vi(Ni(s,e,r),r,t){constructor(){super(...arguments);this.draggables=new Map;this.droppables=[];this.responseIdentifier="";this.configuration={copyStylesDragClone:!0,dragCanBePlacedBack:!0,dragOnClick:!1};this.disabled=!1;this.readonly=!1;this.minAssociations=1;this.maxAssociations=1;this.handleDragStart=a=>{let c=a.currentTarget;a.dataTransfer.setData("text",c.getAttribute("identifier")),c.setAttribute("dragging",""),this.activateDroppables()};this.handleDragEnd=a=>{a.preventDefault(),this.deactivateDroppables();let c=a.currentTarget;c.removeAttribute("dragging"),this.wasDropped(a)||this.configuration.dragCanBePlacedBack&&this.restoreInitialDraggablePosition(c)}}handleDraggablesChange(a,c){if(this.isMatchTabular())return;let p=this.filterExistingDraggables(a);p.length>0&&this.addNewDraggables(p)}firstUpdated(a){super.firstUpdated(a),this.initializeDroppables()}connectedCallback(){super.connectedCallback(),this.initializeDragDropApi()}initializeDragDropApi(){this.dragDropApi=new Wt,this.dispatchEvent(new CustomEvent("qti-register-interaction",{bubbles:!0,composed:!0,detail:this}))}isMatchTabular(){return this.classList.contains("qti-match-tabular")}filterExistingDraggables(a){return a.filter(c=>!this.draggables.has(c))}addNewDraggables(a){this.dragDropApi.addDraggableElements(a),a.forEach(c=>this.storeDraggable(c))}storeDraggable(a){let c=Array.from(a.parentNode.children).indexOf(a);this.draggables.set(a,{parent:a.parentElement,index:c}),a.style.viewTransitionName=`drag-${c}-${this.getAttribute("identifier")}`,a.setAttribute("qti-draggable","true"),a.addEventListener("dragstart",this.handleDragStart),a.addEventListener("dragend",this.handleDragEnd)}initializeDroppables(){this.droppables=Array.from(e?this.shadowRoot.querySelectorAll(r):this.querySelectorAll(r))}activateDroppables(){this.droppables.forEach(a=>a.setAttribute("enabled",""))}deactivateDroppables(){this.droppables.forEach(a=>a.removeAttribute("enabled"))}wasDropped(a){return a.dataTransfer.dropEffect!=="none"}wasMoved(a){return a.dataTransfer.dropEffect==="move"}async restoreInitialDraggablePosition(a){let{parent:c,index:p}=this.draggables.get(a),f=Math.min(p,c.children.length),g=(v,w,k)=>{let A=Math.min(k,w.children.length);w.insertBefore(v,w.children[A]),v.style.transform="translate(0, 0)",this.checkMaxAssociations(),this.saveResponse()};if(!document.startViewTransition){g(a,c,p);return}let y=document.startViewTransition(()=>{a.style.transform="",g(a,c,p)})}checkMaxAssociations(){this.droppables.forEach((a,c)=>{let p=+(a.getAttribute("match-max")||1);a.querySelectorAll('[qti-draggable="true"]').length>=p?this.disableDroppable(a):this.enableDroppable(a)})}disableDroppable(a){a.setAttribute("disabled",""),a.removeAttribute("dropzone")}enableDroppable(a){a.removeAttribute("disabled"),a.setAttribute("dropzone","move")}set response(a){this.isMatchTabular()||(this.resetDroppables(),a==null||a.forEach(c=>this.placeResponse(c)))}placeResponse(a){let[c,...p]=a.split(" ").reverse(),f=this.findDroppableById(c);p.forEach(g=>this.placeDraggableInDroppable(g,f))}findDroppableById(a){return this.droppables.find(c=>c.getAttribute("identifier")===a)}async placeDraggableInDroppable(a,c){let p=this.querySelector(`[identifier=${a}]`);if(!c||!p){console.error(`Cannot find draggable or droppable with the given identifier: ${a}`);return}let f=()=>{p.style.transform="translate(0, 0)",c.appendChild(p),this.checkMaxAssociations()};document.startViewTransition?await document.startViewTransition(f).finished:f()}validate(){let a=this.getValidAssociations();return this.minAssociations<=0||this.minAssociations<=a}getValidAssociations(){return this.droppables.filter(a=>a.childElementCount>0).length}saveResponse(){let a=this.collectResponseData();this.dispatchEvent(new CustomEvent("qti-interaction-response",{bubbles:!0,composed:!0,detail:{responseIdentifier:this.responseIdentifier,response:a}}))}collectResponseData(){return this.droppables.map(a=>{let c=a.querySelectorAll('[qti-draggable="true"]'),p=Array.from(c).map(g=>g.getAttribute("identifier")),f=a.getAttribute("identifier");return[...p,f].join(" ")})}reset(a=!0){this.resetDroppables(),a&&this.saveResponse()}async resetDroppables(){let a=(p,f,g)=>{p.style.transform="translate(0, 0)";let y=Math.min(g,f.children.length);f.insertBefore(p,f.children[y])};if(!document.startViewTransition){this.draggables.forEach(({parent:p,index:f},g)=>{a(g,p,f)});return}await document.startViewTransition(()=>{this.draggables.forEach(({parent:p,index:f},g)=>{a(g,p,f)})}).finished}}return l([d({type:String,attribute:"response-identifier"})],i.prototype,"responseIdentifier",2),l([d({attribute:!1,type:Object})],i.prototype,"configuration",2),l([d({type:Boolean,reflect:!0})],i.prototype,"disabled",2),l([d({type:Boolean,reflect:!0})],i.prototype,"readonly",2),l([d({type:Number,reflect:!0,attribute:"min-associations"})],i.prototype,"minAssociations",2),l([d({type:Number,reflect:!0,attribute:"max-associations"})],i.prototype,"maxAssociations",2),l([Mi(t)],i.prototype,"handleDraggablesChange",1),i};var Ii=b`
251
251
  :host {
252
252
  display: block; /* necessary to calculate scaling position */
253
253
  }