@qti-components/base 2.3.0 → 2.4.1-next.0
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/abstract/interaction.d.ts +1 -1
- package/dist/abstract/interaction.js +96 -4
- package/dist/abstract/interaction.js.map +1 -1
- package/dist/abstract/qti-expression.d.ts +7 -0
- package/dist/abstract/qti-expression.js +15 -5
- package/dist/abstract/qti-expression.js.map +1 -1
- package/dist/abstract/qti-feedback.d.ts +1 -2
- package/dist/abstract/qti-feedback.js +39 -12
- package/dist/abstract/qti-feedback.js.map +1 -1
- package/dist/context/context-root.d.ts +12 -0
- package/dist/context/context-root.js +24 -0
- package/dist/context/context-root.js.map +1 -0
- package/dist/context/session.context.d.ts +2 -0
- package/dist/context/session.context.js +1 -1
- package/dist/context/session.context.js.map +1 -1
- package/dist/context/types/item.types.d.ts +10 -0
- package/dist/context/types/item.types.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/utils/scoring-helper.js +6 -0
- package/dist/utils/scoring-helper.js.map +1 -1
- package/package.json +1 -1
|
@@ -10,7 +10,7 @@ import type { ResponseVariable } from '../lib/variables';
|
|
|
10
10
|
*/
|
|
11
11
|
export declare abstract class Interaction extends LitElement implements ValidatableInteraction {
|
|
12
12
|
#private;
|
|
13
|
-
private _context;
|
|
13
|
+
private get _context();
|
|
14
14
|
/**
|
|
15
15
|
* Delivery configuration, from the nearest provider — `qti-test` or `qti-item`.
|
|
16
16
|
*
|
|
@@ -4,7 +4,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
|
|
4
4
|
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
5
|
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
6
|
};
|
|
7
|
-
import { consume, provide } from '@lit/context';
|
|
7
|
+
import { ContextConsumer, consume, provide } from '@lit/context';
|
|
8
8
|
import { LitElement } from 'lit';
|
|
9
9
|
import { property } from 'lit/decorators.js';
|
|
10
10
|
import { configContext } from '../context/config.context';
|
|
@@ -15,6 +15,86 @@ import { itemContext } from '../context/item.context';
|
|
|
15
15
|
* `@qti-components/corrections` package.
|
|
16
16
|
*/
|
|
17
17
|
export class Interaction extends LitElement {
|
|
18
|
+
/**
|
|
19
|
+
* The item's variables. The interaction takes its response from here as well as publishing it:
|
|
20
|
+
* when the item's value for this response changes to something other than what the interaction
|
|
21
|
+
* shows, it adopts it. That is how `item.variables = …` reaches it, with no list of interactions
|
|
22
|
+
* kept by the item. See {@link Interaction.#adoptResponse}.
|
|
23
|
+
*/
|
|
24
|
+
#itemContext;
|
|
25
|
+
get _context() {
|
|
26
|
+
return this.#itemContext.value;
|
|
27
|
+
}
|
|
28
|
+
#seenReadonly;
|
|
29
|
+
#seenDisabled;
|
|
30
|
+
/**
|
|
31
|
+
* Follows the item: its `readonly` and `disabled`, and the value it holds for this response.
|
|
32
|
+
* `readonly` and `disabled` are only taken when the item says something, so an interaction
|
|
33
|
+
* authored with either stays so inside an item that does not mention it.
|
|
34
|
+
*/
|
|
35
|
+
#followItem(context) {
|
|
36
|
+
if (context?.readonly !== undefined && context.readonly !== this.#seenReadonly) {
|
|
37
|
+
this.#seenReadonly = context.readonly;
|
|
38
|
+
this.readonly = context.readonly;
|
|
39
|
+
}
|
|
40
|
+
if (context?.disabled !== undefined && context.disabled !== this.#seenDisabled) {
|
|
41
|
+
this.#seenDisabled = context.disabled;
|
|
42
|
+
this.disabled = context.disabled;
|
|
43
|
+
}
|
|
44
|
+
this.#adoptResponse(context);
|
|
45
|
+
}
|
|
46
|
+
/** The item's last value for this response, serialised, to tell a change from an unrelated update. */
|
|
47
|
+
#seenResponse;
|
|
48
|
+
/**
|
|
49
|
+
* What this interaction last published or adopted, serialised. It is kept from the interaction's
|
|
50
|
+
* own `qti-interaction-response` events, which every emitter dispatches on the interaction itself,
|
|
51
|
+
* and not read back from `response`: that getter has no common shape (the drag-drop interactions
|
|
52
|
+
* return one comma-joined string where they publish an array), so it cannot be compared.
|
|
53
|
+
*/
|
|
54
|
+
#lastResponse;
|
|
55
|
+
#adoptScheduled;
|
|
56
|
+
/**
|
|
57
|
+
* Adopts the item's value for this response when it changed and the interaction does not already
|
|
58
|
+
* show it.
|
|
59
|
+
*
|
|
60
|
+
* Two things keep this from fighting the candidate. It reacts to the item's value for *this*
|
|
61
|
+
* response changing, not to any context update, so a score or a timer ticking never rewrites what
|
|
62
|
+
* is being typed. And when the item's value is what the interaction itself last published (which
|
|
63
|
+
* is what happens right after it publishes an answer) it does nothing, so there is no echo.
|
|
64
|
+
*
|
|
65
|
+
* The first value is only adopted when it says something: an unanswered item must not wipe a
|
|
66
|
+
* `response` attribute the author put on the interaction.
|
|
67
|
+
*
|
|
68
|
+
* Setting `response` on an interaction that has not rendered yet is what the item used to avoid
|
|
69
|
+
* by waiting, so until the first update this waits too, then looks at the latest value.
|
|
70
|
+
*/
|
|
71
|
+
#adoptResponse(context) {
|
|
72
|
+
const id = this.responseIdentifier ?? this.getAttribute('response-identifier');
|
|
73
|
+
const variable = context?.variables?.find(v => v.type === 'response' && v.identifier === id);
|
|
74
|
+
if (!variable)
|
|
75
|
+
return;
|
|
76
|
+
if (!this.hasUpdated) {
|
|
77
|
+
if (!this.#adoptScheduled) {
|
|
78
|
+
this.#adoptScheduled = true;
|
|
79
|
+
void this.updateComplete.then(() => {
|
|
80
|
+
this.#adoptScheduled = false;
|
|
81
|
+
this.#adoptResponse(this._context);
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const first = this.#seenResponse === undefined;
|
|
87
|
+
const serialised = JSON.stringify(variable.value ?? null);
|
|
88
|
+
if (serialised === this.#seenResponse)
|
|
89
|
+
return;
|
|
90
|
+
this.#seenResponse = serialised;
|
|
91
|
+
if (first && (variable.value === null || variable.value === undefined))
|
|
92
|
+
return;
|
|
93
|
+
if (serialised === this.#lastResponse)
|
|
94
|
+
return;
|
|
95
|
+
this.#lastResponse = serialised;
|
|
96
|
+
this.response = variable.value;
|
|
97
|
+
}
|
|
18
98
|
#didLogDisableAfterIfMaxChoicesReachedDeprecation;
|
|
19
99
|
static { this.formAssociated = true; }
|
|
20
100
|
get internals() {
|
|
@@ -157,6 +237,18 @@ export class Interaction extends LitElement {
|
|
|
157
237
|
}
|
|
158
238
|
constructor() {
|
|
159
239
|
super();
|
|
240
|
+
/**
|
|
241
|
+
* The item's variables. The interaction takes its response from here as well as publishing it:
|
|
242
|
+
* when the item's value for this response changes to something other than what the interaction
|
|
243
|
+
* shows, it adopts it. That is how `item.variables = …` reaches it, with no list of interactions
|
|
244
|
+
* kept by the item. See {@link Interaction.#adoptResponse}.
|
|
245
|
+
*/
|
|
246
|
+
this.#itemContext = new ContextConsumer(this, {
|
|
247
|
+
context: itemContext,
|
|
248
|
+
subscribe: true,
|
|
249
|
+
callback: context => this.#followItem(context)
|
|
250
|
+
});
|
|
251
|
+
this.#adoptScheduled = false;
|
|
160
252
|
this.#didLogDisableAfterIfMaxChoicesReachedDeprecation = false;
|
|
161
253
|
/*
|
|
162
254
|
* Published to the choice elements inside this interaction — their role, and how to tell
|
|
@@ -170,6 +262,9 @@ export class Interaction extends LitElement {
|
|
|
170
262
|
this.disabled = false;
|
|
171
263
|
this.readonly = false;
|
|
172
264
|
this._internals = this.attachInternals();
|
|
265
|
+
this.addEventListener('qti-interaction-response', (e) => {
|
|
266
|
+
this.#lastResponse = JSON.stringify(e.detail?.response ?? null);
|
|
267
|
+
});
|
|
173
268
|
}
|
|
174
269
|
/**
|
|
175
270
|
* Optional lifecycle bridge for interaction subclasses that do not need changed-property data.
|
|
@@ -185,9 +280,6 @@ export class Interaction extends LitElement {
|
|
|
185
280
|
*/
|
|
186
281
|
firstUpdated(_changedProperties) { }
|
|
187
282
|
}
|
|
188
|
-
__decorate([
|
|
189
|
-
consume({ context: itemContext, subscribe: true })
|
|
190
|
-
], Interaction.prototype, "_context", void 0);
|
|
191
283
|
__decorate([
|
|
192
284
|
consume({ context: configContext, subscribe: true })
|
|
193
285
|
], Interaction.prototype, "configContext", void 0);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interaction.js","sourceRoot":"","sources":["../../src/abstract/interaction.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,KAAK,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAE7C,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAStD;;;GAGG;AACH,MAAM,OAAgB,WAAY,SAAQ,UAAU;IA+BlD,iDAAiD,CAAS;aAanD,mBAAc,GAAG,IAAI,AAAP,CAAQ;IAG7B,IAAI,SAAS;QACX,OAAO,IAAI,CAAC,UAAU,CAAC;IACzB,CAAC;IAUD,qFAAqF;IACrF,IAAc,iBAAiB;QAC7B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,KAAK,CAAC;IACf,CAAC;IAED,IAAI,gBAAgB;QAClB,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,SAAS,EAAE,CAAC;YAC9B,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,MAAM,iBAAiB,GAAG,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,UAAU,CAAuB,CAAC;QAC3G,MAAM,kBAAkB,GAAG,IAAI,CAAC,YAAY,CAAC,qBAAqB,CAAC,CAAC;QACpE,OAAO,iBAAiB,CAAC,IAAI,C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,EAAE,OAAO,EAAE,kBAAkB,EAAE,CAAC;wDACoE;AAS/C;IAA7D,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,qBAAqB,EAAE,CAAC;uDAA4B;AAE7C;IAA3C,QAAQ,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;6CAAkB;AAEjB;IAA3C,QAAQ,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;6CAAkB;AAEjC;IAA3B,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;yCAAM","sourcesContent":["import { consume, provide } from '@lit/context';\nimport { LitElement } from 'lit';\nimport { property } from 'lit/decorators.js';\n\nimport { configContext } from '../context/config.context';\nimport { interactionContext } from '../context/interaction.context';\nimport { itemContext } from '../context/item.context';\n\nimport type { PropertyValues } from 'lit';\nimport type { InteractionContext } from '../context/interaction.context';\nimport type { ConfigContext, ValidationDisplayMode } from '../context/config.context';\nimport type { ItemContext } from '../context/types/item.types';\nimport type { ValidatableInteraction } from '../lib/interaction.interface';\nimport type { ResponseVariable } from '../lib/variables';\n\n/**\n * Shared QTI interaction base. Formative correction behavior is supplied by the\n * `@qti-components/corrections` package.\n */\nexport abstract class Interaction extends LitElement implements ValidatableInteraction {\n @consume({ context: itemContext, subscribe: true })\n private _context: ItemContext;\n\n /**\n * Delivery configuration, from the nearest provider — `qti-test` or `qti-item`.\n *\n * **Public so it can be assigned directly, which is the development-time route.** An interaction\n * has to work standalone, and in a story or a spec there is usually no provider above it — so\n * setting the field is all that is needed:\n *\n * orderInteraction.configContext = { allowReorder: false, validationDisplayMode: 'none' };\n *\n * With no provider, nothing ever overwrites it. That is the whole contract, and its limit: where a\n * provider DOES exist it re-emits on its next update and wins, because `@consume` writes this same\n * field. There is no merging — set the value on the provider in that case.\n *\n * In a lit-html template, bind it as a property rather than assigning after the fact:\n *\n * html`<qti-order-interaction .configContext=${{ allowReorder: false }}>…`\n *\n * The binding is committed on the detached template clone, before the fragment is inserted, so it\n * is in place by `connectedCallback` — which matters for anything that reads config on connect.\n *\n * It was `protected`, which fooled nobody: every caller reached it anyway through an\n * `as any` / `as { configContext?: … }` cast. Public says what was already true and removes the\n * casts, rather than pretending at an encapsulation the type system was the only thing enforcing.\n */\n @consume({ context: configContext, subscribe: true })\n public configContext: ConfigContext;\n\n #didLogDisableAfterIfMaxChoicesReachedDeprecation = false;\n\n /*\n * Published to the choice elements inside this interaction — their role, and how to tell\n * whether they are draggable. Provided here on the base rather than in a mixin so that\n * ChoicesMixin and the drag-drop mixins can each contribute without two providers of the same\n * context competing on one element.\n *\n * Reassign, never mutate: an in-place change does not notify consumers.\n */\n @provide({ context: interactionContext })\n protected _interactionContext: Readonly<InteractionContext> = { choiceRole: null, draggablesSelector: null };\n\n static formAssociated = true;\n protected _internals: ElementInternals;\n\n get internals(): ElementInternals {\n return this._internals;\n }\n\n @property({ type: String, attribute: 'response-identifier' }) responseIdentifier: string;\n\n @property({ reflect: true, type: Boolean }) disabled = false;\n\n @property({ reflect: true, type: Boolean }) readonly = false;\n\n @property({ type: String }) name;\n\n /** Extension point used by wrappers that should not register as candidate inputs. */\n protected get registersWithItem(): boolean {\n return true;\n }\n\n get isInline(): boolean {\n return false;\n }\n\n get responseVariable(): ResponseVariable | undefined {\n if (!this._context?.variables) {\n return undefined;\n }\n const responseVariables = this._context.variables.filter(v => v.type === 'response') as ResponseVariable[];\n const responseIdentifier = this.getAttribute('response-identifier');\n return responseVariables.find(v => v.identifier === responseIdentifier);\n }\n\n abstract validate(): boolean;\n\n get value(): string | null {\n return JSON.stringify(this.response);\n }\n\n set value(val: string | null) {\n this.response = val ? JSON.parse(val) : null;\n }\n\n abstract get response(): string | string[] | null;\n abstract set response(val: string | string[] | null);\n\n public reportValidity(): boolean {\n const isValid = this._internals.validity.valid;\n const mode = this.validationDisplayMode;\n\n if (mode === 'native' || mode === 'both') {\n this._internals.reportValidity();\n }\n\n if (mode === 'inline' || mode === 'both') {\n this.updateInlineValidationMessage();\n } else {\n this.clearInlineValidationMessage();\n }\n\n if (mode === 'none') {\n this.clearInlineValidationMessage();\n }\n\n return isValid;\n }\n\n protected get validationDisplayMode(): ValidationDisplayMode {\n return this.configContext?.validationDisplayMode ?? 'inline';\n }\n\n protected resolveAllowReorder(options?: { defaultWhenUnset?: boolean }): boolean {\n const defaultWhenUnset = options?.defaultWhenUnset ?? true;\n const config = this.configContext;\n if (!config) {\n return defaultWhenUnset;\n }\n if (config.allowReorder !== undefined) {\n return config.allowReorder;\n }\n return defaultWhenUnset;\n }\n\n protected resolveDisableAfterMaxReached(options?: { defaultWhenUnset?: boolean }): boolean {\n const defaultWhenUnset = options?.defaultWhenUnset ?? false;\n const config = this.configContext;\n\n if (!config) {\n return defaultWhenUnset;\n }\n\n if (config.disableAfterMaxReached !== undefined) {\n return config.disableAfterMaxReached;\n }\n\n if (config.disableAfterIfMaxChoicesReached !== undefined) {\n if (!this.#didLogDisableAfterIfMaxChoicesReachedDeprecation) {\n this.#didLogDisableAfterIfMaxChoicesReachedDeprecation = true;\n console.warn(\n '[QTI Config] `disableAfterIfMaxChoicesReached` is deprecated. Use `disableAfterMaxReached` instead.'\n );\n }\n return config.disableAfterIfMaxChoicesReached;\n }\n\n return defaultWhenUnset;\n }\n\n protected setInteractionValidity(\n isValid: boolean,\n validityMessage = '',\n anchor?: HTMLElement | null,\n options?: { suppressInline?: boolean }\n ): void {\n const validityAnchor = anchor ?? this;\n this._internals.setValidity(isValid ? {} : { customError: true }, validityMessage, validityAnchor);\n\n if (\n options?.suppressInline !== true &&\n (this.validationDisplayMode === 'inline' || this.validationDisplayMode === 'both')\n ) {\n this.updateInlineValidationMessage();\n }\n }\n\n protected updateInlineValidationMessage(): void {\n const validationMessageElement = this.getValidationMessageElement();\n if (!validationMessageElement) {\n return;\n }\n\n if (!this._internals.validity.valid) {\n validationMessageElement.textContent = this._internals.validationMessage;\n validationMessageElement.style.setProperty('display', 'block', 'important');\n return;\n }\n\n validationMessageElement.textContent = '';\n validationMessageElement.style.display = 'none';\n }\n\n protected clearInlineValidationMessage(): void {\n const validationMessageElement = this.getValidationMessageElement();\n if (!validationMessageElement) {\n return;\n }\n\n validationMessageElement.textContent = '';\n validationMessageElement.style.display = 'none';\n }\n\n protected getValidationMessageElement(): HTMLElement | null {\n return this.shadowRoot?.querySelector('#validation-message') as HTMLElement | null;\n }\n\n public reset(): void {\n this.response = null;\n }\n\n public formResetCallback(): void {\n this.reset();\n }\n\n public override connectedCallback(): void {\n super.connectedCallback();\n\n if (!this.registersWithItem) {\n return;\n }\n\n this.dispatchEvent(\n new CustomEvent('qti-register-interaction', {\n bubbles: true,\n composed: true,\n cancelable: false,\n detail: {\n interactionElement: this,\n responseIdentifier: this.responseIdentifier\n }\n })\n );\n }\n\n public saveResponse(value: string | string[], state?: string | null): void {\n this.dispatchEvent(\n new CustomEvent('qti-interaction-response', {\n bubbles: true,\n composed: true,\n cancelable: false,\n detail: {\n responseIdentifier: this.responseIdentifier,\n response: Array.isArray(value) ? [...value] : value,\n ...(state !== undefined ? { state } : {})\n }\n })\n );\n }\n\n constructor() {\n super();\n this._internals = this.attachInternals();\n }\n\n /**\n * Optional lifecycle bridge for interaction subclasses that do not need changed-property data.\n *\n * The parameter is `PropertyValues`, matching LitElement, and NOT `PropertyValues<this>`.\n * The polymorphic `this` narrowed the parameter per subclass, which made every interaction\n * class structurally incompatible with `LitElement` — so `Constructor<LitElement>`, the\n * standard constraint for a Lit mixin, rejected all of them and consumers could not wrap an\n * interaction in a mixin without casting. `this` buys nothing in a parameter position and\n * costs contravariant compatibility with the base class.\n *\n * Still optional, so subclasses that ignore the argument can override with `firstUpdated()`.\n */\n protected override firstUpdated(_changedProperties?: PropertyValues): void {}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"interaction.js","sourceRoot":"","sources":["../../src/abstract/interaction.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,eAAe,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AAE,CAAC;6CAAkB;AAEjC;IAA3B,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;yCAAM","sourcesContent":["import { ContextConsumer, consume, provide } from '@lit/context';\nimport { LitElement } from 'lit';\nimport { property } from 'lit/decorators.js';\n\nimport { configContext } from '../context/config.context';\nimport { interactionContext } from '../context/interaction.context';\nimport { itemContext } from '../context/item.context';\n\nimport type { PropertyValues } from 'lit';\nimport type { InteractionContext } from '../context/interaction.context';\nimport type { ConfigContext, ValidationDisplayMode } from '../context/config.context';\nimport type { ItemContext } from '../context/types/item.types';\nimport type { ValidatableInteraction } from '../lib/interaction.interface';\nimport type { ResponseVariable } from '../lib/variables';\n\n/**\n * Shared QTI interaction base. Formative correction behavior is supplied by the\n * `@qti-components/corrections` package.\n */\nexport abstract class Interaction extends LitElement implements ValidatableInteraction {\n /**\n * The item's variables. The interaction takes its response from here as well as publishing it:\n * when the item's value for this response changes to something other than what the interaction\n * shows, it adopts it. That is how `item.variables = …` reaches it, with no list of interactions\n * kept by the item. See {@link Interaction.#adoptResponse}.\n */\n #itemContext = new ContextConsumer(this, {\n context: itemContext,\n subscribe: true,\n callback: context => this.#followItem(context)\n });\n\n private get _context(): ItemContext | undefined {\n return this.#itemContext.value;\n }\n\n #seenReadonly?: boolean;\n #seenDisabled?: boolean;\n\n /**\n * Follows the item: its `readonly` and `disabled`, and the value it holds for this response.\n * `readonly` and `disabled` are only taken when the item says something, so an interaction\n * authored with either stays so inside an item that does not mention it.\n */\n #followItem(context: ItemContext | undefined) {\n if (context?.readonly !== undefined && context.readonly !== this.#seenReadonly) {\n this.#seenReadonly = context.readonly;\n this.readonly = context.readonly;\n }\n if (context?.disabled !== undefined && context.disabled !== this.#seenDisabled) {\n this.#seenDisabled = context.disabled;\n this.disabled = context.disabled;\n }\n this.#adoptResponse(context);\n }\n\n /** The item's last value for this response, serialised, to tell a change from an unrelated update. */\n #seenResponse?: string;\n /**\n * What this interaction last published or adopted, serialised. It is kept from the interaction's\n * own `qti-interaction-response` events, which every emitter dispatches on the interaction itself,\n * and not read back from `response`: that getter has no common shape (the drag-drop interactions\n * return one comma-joined string where they publish an array), so it cannot be compared.\n */\n #lastResponse?: string;\n #adoptScheduled = false;\n\n /**\n * Adopts the item's value for this response when it changed and the interaction does not already\n * show it.\n *\n * Two things keep this from fighting the candidate. It reacts to the item's value for *this*\n * response changing, not to any context update, so a score or a timer ticking never rewrites what\n * is being typed. And when the item's value is what the interaction itself last published (which\n * is what happens right after it publishes an answer) it does nothing, so there is no echo.\n *\n * The first value is only adopted when it says something: an unanswered item must not wipe a\n * `response` attribute the author put on the interaction.\n *\n * Setting `response` on an interaction that has not rendered yet is what the item used to avoid\n * by waiting, so until the first update this waits too, then looks at the latest value.\n */\n #adoptResponse(context: ItemContext | undefined) {\n const id = this.responseIdentifier ?? this.getAttribute('response-identifier');\n const variable = context?.variables?.find(v => v.type === 'response' && v.identifier === id);\n if (!variable) return;\n\n if (!this.hasUpdated) {\n if (!this.#adoptScheduled) {\n this.#adoptScheduled = true;\n void this.updateComplete.then(() => {\n this.#adoptScheduled = false;\n this.#adoptResponse(this._context);\n });\n }\n return;\n }\n\n const first = this.#seenResponse === undefined;\n const serialised = JSON.stringify(variable.value ?? null);\n if (serialised === this.#seenResponse) return;\n this.#seenResponse = serialised;\n if (first && (variable.value === null || variable.value === undefined)) return;\n if (serialised === this.#lastResponse) return;\n this.#lastResponse = serialised;\n this.response = variable.value as string | string[] | null;\n }\n\n /**\n * Delivery configuration, from the nearest provider — `qti-test` or `qti-item`.\n *\n * **Public so it can be assigned directly, which is the development-time route.** An interaction\n * has to work standalone, and in a story or a spec there is usually no provider above it — so\n * setting the field is all that is needed:\n *\n * orderInteraction.configContext = { allowReorder: false, validationDisplayMode: 'none' };\n *\n * With no provider, nothing ever overwrites it. That is the whole contract, and its limit: where a\n * provider DOES exist it re-emits on its next update and wins, because `@consume` writes this same\n * field. There is no merging — set the value on the provider in that case.\n *\n * In a lit-html template, bind it as a property rather than assigning after the fact:\n *\n * html`<qti-order-interaction .configContext=${{ allowReorder: false }}>…`\n *\n * The binding is committed on the detached template clone, before the fragment is inserted, so it\n * is in place by `connectedCallback` — which matters for anything that reads config on connect.\n *\n * It was `protected`, which fooled nobody: every caller reached it anyway through an\n * `as any` / `as { configContext?: … }` cast. Public says what was already true and removes the\n * casts, rather than pretending at an encapsulation the type system was the only thing enforcing.\n */\n @consume({ context: configContext, subscribe: true })\n public configContext: ConfigContext;\n\n #didLogDisableAfterIfMaxChoicesReachedDeprecation = false;\n\n /*\n * Published to the choice elements inside this interaction — their role, and how to tell\n * whether they are draggable. Provided here on the base rather than in a mixin so that\n * ChoicesMixin and the drag-drop mixins can each contribute without two providers of the same\n * context competing on one element.\n *\n * Reassign, never mutate: an in-place change does not notify consumers.\n */\n @provide({ context: interactionContext })\n protected _interactionContext: Readonly<InteractionContext> = { choiceRole: null, draggablesSelector: null };\n\n static formAssociated = true;\n protected _internals: ElementInternals;\n\n get internals(): ElementInternals {\n return this._internals;\n }\n\n @property({ type: String, attribute: 'response-identifier' }) responseIdentifier: string;\n\n @property({ reflect: true, type: Boolean }) disabled = false;\n\n @property({ reflect: true, type: Boolean }) readonly = false;\n\n @property({ type: String }) name;\n\n /** Extension point used by wrappers that should not register as candidate inputs. */\n protected get registersWithItem(): boolean {\n return true;\n }\n\n get isInline(): boolean {\n return false;\n }\n\n get responseVariable(): ResponseVariable | undefined {\n if (!this._context?.variables) {\n return undefined;\n }\n const responseVariables = this._context.variables.filter(v => v.type === 'response') as ResponseVariable[];\n const responseIdentifier = this.getAttribute('response-identifier');\n return responseVariables.find(v => v.identifier === responseIdentifier);\n }\n\n abstract validate(): boolean;\n\n get value(): string | null {\n return JSON.stringify(this.response);\n }\n\n set value(val: string | null) {\n this.response = val ? JSON.parse(val) : null;\n }\n\n abstract get response(): string | string[] | null;\n abstract set response(val: string | string[] | null);\n\n public reportValidity(): boolean {\n const isValid = this._internals.validity.valid;\n const mode = this.validationDisplayMode;\n\n if (mode === 'native' || mode === 'both') {\n this._internals.reportValidity();\n }\n\n if (mode === 'inline' || mode === 'both') {\n this.updateInlineValidationMessage();\n } else {\n this.clearInlineValidationMessage();\n }\n\n if (mode === 'none') {\n this.clearInlineValidationMessage();\n }\n\n return isValid;\n }\n\n protected get validationDisplayMode(): ValidationDisplayMode {\n return this.configContext?.validationDisplayMode ?? 'inline';\n }\n\n protected resolveAllowReorder(options?: { defaultWhenUnset?: boolean }): boolean {\n const defaultWhenUnset = options?.defaultWhenUnset ?? true;\n const config = this.configContext;\n if (!config) {\n return defaultWhenUnset;\n }\n if (config.allowReorder !== undefined) {\n return config.allowReorder;\n }\n return defaultWhenUnset;\n }\n\n protected resolveDisableAfterMaxReached(options?: { defaultWhenUnset?: boolean }): boolean {\n const defaultWhenUnset = options?.defaultWhenUnset ?? false;\n const config = this.configContext;\n\n if (!config) {\n return defaultWhenUnset;\n }\n\n if (config.disableAfterMaxReached !== undefined) {\n return config.disableAfterMaxReached;\n }\n\n if (config.disableAfterIfMaxChoicesReached !== undefined) {\n if (!this.#didLogDisableAfterIfMaxChoicesReachedDeprecation) {\n this.#didLogDisableAfterIfMaxChoicesReachedDeprecation = true;\n console.warn(\n '[QTI Config] `disableAfterIfMaxChoicesReached` is deprecated. Use `disableAfterMaxReached` instead.'\n );\n }\n return config.disableAfterIfMaxChoicesReached;\n }\n\n return defaultWhenUnset;\n }\n\n protected setInteractionValidity(\n isValid: boolean,\n validityMessage = '',\n anchor?: HTMLElement | null,\n options?: { suppressInline?: boolean }\n ): void {\n const validityAnchor = anchor ?? this;\n this._internals.setValidity(isValid ? {} : { customError: true }, validityMessage, validityAnchor);\n\n if (\n options?.suppressInline !== true &&\n (this.validationDisplayMode === 'inline' || this.validationDisplayMode === 'both')\n ) {\n this.updateInlineValidationMessage();\n }\n }\n\n protected updateInlineValidationMessage(): void {\n const validationMessageElement = this.getValidationMessageElement();\n if (!validationMessageElement) {\n return;\n }\n\n if (!this._internals.validity.valid) {\n validationMessageElement.textContent = this._internals.validationMessage;\n validationMessageElement.style.setProperty('display', 'block', 'important');\n return;\n }\n\n validationMessageElement.textContent = '';\n validationMessageElement.style.display = 'none';\n }\n\n protected clearInlineValidationMessage(): void {\n const validationMessageElement = this.getValidationMessageElement();\n if (!validationMessageElement) {\n return;\n }\n\n validationMessageElement.textContent = '';\n validationMessageElement.style.display = 'none';\n }\n\n protected getValidationMessageElement(): HTMLElement | null {\n return this.shadowRoot?.querySelector('#validation-message') as HTMLElement | null;\n }\n\n public reset(): void {\n this.response = null;\n }\n\n public formResetCallback(): void {\n this.reset();\n }\n\n public override connectedCallback(): void {\n super.connectedCallback();\n\n if (!this.registersWithItem) {\n return;\n }\n\n this.dispatchEvent(\n new CustomEvent('qti-register-interaction', {\n bubbles: true,\n composed: true,\n cancelable: false,\n detail: {\n interactionElement: this,\n responseIdentifier: this.responseIdentifier\n }\n })\n );\n }\n\n public saveResponse(value: string | string[], state?: string | null): void {\n this.dispatchEvent(\n new CustomEvent('qti-interaction-response', {\n bubbles: true,\n composed: true,\n cancelable: false,\n detail: {\n responseIdentifier: this.responseIdentifier,\n response: Array.isArray(value) ? [...value] : value,\n ...(state !== undefined ? { state } : {})\n }\n })\n );\n }\n\n constructor() {\n super();\n this._internals = this.attachInternals();\n this.addEventListener('qti-interaction-response', (e: Event) => {\n this.#lastResponse = JSON.stringify((e as CustomEvent).detail?.response ?? null);\n });\n }\n\n /**\n * Optional lifecycle bridge for interaction subclasses that do not need changed-property data.\n *\n * The parameter is `PropertyValues`, matching LitElement, and NOT `PropertyValues<this>`.\n * The polymorphic `this` narrowed the parameter per subclass, which made every interaction\n * class structurally incompatible with `LitElement` — so `Constructor<LitElement>`, the\n * standard constraint for a Lit mixin, rejected all of them and consumers could not wrap an\n * interaction in a mixin without casting. `this` buys nothing in a parameter position and\n * costs contravariant compatibility with the base class.\n *\n * Still optional, so subclasses that ignore the argument can override with `firstUpdated()`.\n */\n protected override firstUpdated(_changedProperties?: PropertyValues): void {}\n}\n"]}
|
|
@@ -48,6 +48,13 @@ export declare abstract class QtiExpression<T> extends LitElement implements Qti
|
|
|
48
48
|
* throwing, so callers degrade gracefully.
|
|
49
49
|
*/
|
|
50
50
|
protected resolveVariable(identifier: string): VariableDeclaration<string | string[] | null> | null;
|
|
51
|
+
/**
|
|
52
|
+
* `ITEMREF.VAR`: a variable of an individual item session, looked up by prefixing the variable
|
|
53
|
+
* with the identifier the item ref gave the item (QTI 3 `qti-variable`), e.g. `Q01.SCORE`. An
|
|
54
|
+
* item that was never presented has no variables, which resolves to NULL. Instances of a cloned
|
|
55
|
+
* item (`Q01.2.SCORE`) are not supported: the item itself is used.
|
|
56
|
+
*/
|
|
57
|
+
private resolveItemVariable;
|
|
51
58
|
getVariables: () => ExpressionVariable[];
|
|
52
59
|
}
|
|
53
60
|
export {};
|
|
@@ -69,10 +69,7 @@ const inferContainerBaseType = (expression, value) => {
|
|
|
69
69
|
if (!Array.isArray(value) || value.length > 0) {
|
|
70
70
|
return undefined;
|
|
71
71
|
}
|
|
72
|
-
return expression
|
|
73
|
-
.lastVariables
|
|
74
|
-
.find(variable => variable?.baseType && variable.baseType !== 'record' && variable.cardinality !== 'record')
|
|
75
|
-
?.baseType;
|
|
72
|
+
return expression.lastVariables.find(variable => variable?.baseType && variable.baseType !== 'record' && variable.cardinality !== 'record')?.baseType;
|
|
76
73
|
};
|
|
77
74
|
export class QtiExpression extends LitElement {
|
|
78
75
|
constructor() {
|
|
@@ -293,7 +290,20 @@ export class QtiExpression extends LitElement {
|
|
|
293
290
|
resolveVariable(identifier) {
|
|
294
291
|
return (this.context?.variables.find(v => v.identifier === identifier) ??
|
|
295
292
|
this._testContext?.testOutcomeVariables?.find(v => v.identifier === identifier) ??
|
|
296
|
-
|
|
293
|
+
this.resolveItemVariable(identifier));
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* `ITEMREF.VAR`: a variable of an individual item session, looked up by prefixing the variable
|
|
297
|
+
* with the identifier the item ref gave the item (QTI 3 `qti-variable`), e.g. `Q01.SCORE`. An
|
|
298
|
+
* item that was never presented has no variables, which resolves to NULL. Instances of a cloned
|
|
299
|
+
* item (`Q01.2.SCORE`) are not supported: the item itself is used.
|
|
300
|
+
*/
|
|
301
|
+
resolveItemVariable(identifier) {
|
|
302
|
+
if (!identifier?.includes('.'))
|
|
303
|
+
return null;
|
|
304
|
+
const parts = identifier.split('.');
|
|
305
|
+
const item = this._testContext?.items?.find(i => i.identifier === parts[0]);
|
|
306
|
+
return item?.variables?.find(v => v.identifier === parts[parts.length - 1]) ?? null;
|
|
297
307
|
}
|
|
298
308
|
}
|
|
299
309
|
__decorate([
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"qti-expression.js","sourceRoot":"","sources":["../../src/abstract/qti-expression.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,KAAK,CAAC;AAE5C,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAkBtD;;;;;;;;;;;;;GAaG;AACH,MAAM,iBAAiB,GAAG,CAAC,KAAc,EAAE,QAAmB,EAAoB,EAAE;IAClF;;;;;;OAMG;IACH,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QAC1C,OAAO;YACL,UAAU,EAAE,EAAE;YACd,QAAQ,EAAE,QAAQ;YAClB,KAAK,EAAE,IAAI;YACX,WAAW,EAAE,QAAQ;YACrB,IAAI,EAAE,UAAU;SACG,CAAC;IACxB,CAAC;IAED,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO;YACL,UAAU,EAAE,EAAE;YACd,QAAQ,EAAE,QAAQ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,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,KAAK,UAAU,CAAC;YAC9D,IAAI,CAAC,YAAY,EAAE,oBAAoB,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,KAAK,UAAU,CAAC;YAC/E,IAAI,CACL,CAAC;IACJ,CAAC;;AAtBS;IADT,OAAO,CAAC,EAAE,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;8CACnB;AAGtB;IADT,OAAO,CAAC,EAAE,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;iDAChB;AAGxB;IADT,OAAO,CAAC,EAAE,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;mDACd","sourcesContent":["import { consume } from '@lit/context';\nimport { css, html, LitElement } from 'lit';\n\nimport { itemContext } from '../context/item.context';\nimport { qtiContext } from '../context/qti.context';\nimport { testContext } from '../context/test.context';\n\nimport type { ItemContext } from '../context/types/item.types';\nimport type { QtiContext, QtiContextType } from '../context/qti.context';\nimport type { Calculate } from '../lib/expression-result';\nimport type { BaseType } from '../lib/expression-result';\nimport type { ResponseVariable, VariableDeclaration } from '../lib/variables';\nimport type { TestContext } from '../context/test.context';\n\ntype ExpressionVariable = ResponseVariable | VariableDeclaration<QtiContextType>;\n\nexport interface QtiExpressionBase<T> {\n // get assessmentItem(): QtiAssessmentItem;\n\n // getVariables(): VariableDeclaration<number | string | (number | string)[] | null>[];\n calculate(): Readonly<T>;\n}\n\n/**\n * Wrap whatever an expression handed back in a variable, reading the base type\n * off the value itself.\n *\n * An operator that knows its own result type says so through `resultBaseType`\n * and that wins, because the QTI vocabulary fixes it regardless of the operands\n * — `qti-divide` is a float even when it divides two integers exactly. Only\n * when nothing is declared, as for a custom operator returning whatever the\n * host computed, is the type read off the value.\n *\n * Everything used to be labelled `integer`, and since `compareSingleValues`\n * parses an integer with `parseInt`, that silently truncated:\n * `equal(divide(5, 2), 2.4)` compared 2 against 2 and answered true.\n */\nconst variableFromValue = (value: unknown, declared?: BaseType): ResponseVariable => {\n /*\n * A NULL result is still a value: the operand exists and is NULL. Returning\n * nothing would drop it from the list, which both hides the NULL from\n * `qti-is-null` and shifts every operand after it — a binary operator with a\n * NULL first argument would silently read its second as its first. The base\n * type is moot here, since every operator tests the value before it.\n */\n if (value === null || value === undefined) {\n return {\n identifier: '',\n baseType: 'string',\n value: null,\n cardinality: 'single',\n type: 'response'\n } as ResponseVariable;\n }\n\n if (Array.isArray(value)) {\n return {\n identifier: '',\n baseType: declared ?? inferBaseType(value[0]),\n value: value.map(entry => String(entry)),\n cardinality: 'multiple',\n type: 'response'\n } as ResponseVariable;\n }\n\n return {\n identifier: '',\n baseType: declared ?? inferBaseType(value),\n value: String(value),\n cardinality: 'single',\n type: 'response'\n } as ResponseVariable;\n};\n\n/** A JS value's QTI base type. A string stays text; it is not re-parsed. */\nconst inferBaseType = (value: unknown): BaseType => {\n if (typeof value === 'number') return Number.isInteger(value) ? 'integer' : 'float';\n if (typeof value === 'boolean') return 'boolean';\n return 'string';\n};\n\nconst inferContainerBaseType = (expression: QtiExpression<unknown>, value: unknown): BaseType | undefined => {\n if (!Array.isArray(value) || value.length > 0) {\n return undefined;\n }\n\n return expression\n .lastVariables\n .find(variable => variable?.baseType && variable.baseType !== 'record' && variable.cardinality !== 'record')\n ?.baseType as BaseType | undefined;\n};\n\nexport abstract class QtiExpression<T> extends LitElement implements QtiExpressionBase<T> {\n /*\n * Not `@state()`. Nothing renders it any more (see `render` below), so making\n * it reactive only scheduled an update per `calculate()` — and response\n * processing calls that on every expression of every rule it walks.\n */\n protected result: any;\n #lastVariables: ExpressionVariable[] = [];\n\n /**\n * What the last `calculate()` produced, or undefined if it has not run.\n *\n * This is the supported way to inspect a scoring run: process the responses,\n * then walk the rule tree reading this off each expression. A tool that wants\n * to visualise how a score came about gets the whole tree annotated with its\n * values, without the components having to re-render to show them.\n */\n public get lastResult(): Readonly<T> | undefined {\n return this.result;\n }\n\n public get lastVariables(): readonly ExpressionVariable[] {\n return this.#lastVariables;\n }\n\n /*\n * Written here rather than imported from a .css file, and that is a packaging constraint rather\n * than a style preference.\n *\n * The rule used to live in qti-expression.css, imported with Vite's inline-stylesheet query so\n * DevTools could show source-file provenance. That query is a VITE specifier, and tsc copies it\n * verbatim into dist — so the published package shipped an import only a Vite-based consumer\n * could resolve. Every other consumer broke on it: plain Node, tsx, any non-Vite bundler. It was\n * the single such specifier reachable from this package, and it took down QTI-Editor's schema\n * check, which loads the components under tsx to build the real ProseMirror schema\n * (ERR_UNKNOWN_FILE_EXTENSION on a file that has nothing to do with schemas).\n *\n * A `build:assets` step used to copy the .css into dist beside it. That went too — it existed\n * only to give the unresolvable import something to point at.\n *\n * Two lines of CSS are not worth a dist that only one bundler can consume. If this ever grows\n * into a real stylesheet, give it a `.styles.ts` exporting a `css` template — the house pattern\n * everywhere else in this repo — rather than reintroducing a bundler-specific import.\n *\n * The element renders a debug <pre> of its computed result plus a <slot>; hiding the slot is all\n * the styling it has ever had.\n */\n static override styles = css`\n slot {\n display: none;\n }\n `;\n\n /*\n * Just the slot. This used to render `JSON.stringify(this.result, null, 2)`\n * into a <pre> beside it — a development aid that nobody could see, because\n * expressions live inside `qti-response-processing`, which is `display: none`.\n * It cost a full serialisation of the result on every render.\n */\n override render() {\n return html`<slot></slot>`;\n }\n\n /*\n * Render once, then never again: the template above is constant, so every\n * later update is pure overhead.\n *\n * It is not the `@state()` decorators that drive those updates — `@consume`\n * subscribes through `ContextConsumer`, which calls `host.requestUpdate()`\n * itself on every context change, \"in case this value is used in a template\".\n * Here it is not. An item with 30 response-processing rules holds ~180\n * expression elements and the test context changes on every keystroke, so\n * that was ~180 renders per keystroke producing identical output.\n *\n * The subscriptions stay, because `calculate()` reads the current values when\n * a rule invokes it. Only the rendering stops.\n */\n protected override shouldUpdate(): boolean {\n return !this.hasUpdated;\n }\n\n public calculate(): Readonly<T> {\n this.result = this.getResult();\n return this.result;\n }\n\n protected getResult(): Readonly<T> {\n throw new Error('Not implemented');\n }\n\n /**\n * The base type this operator always produces, when the QTI vocabulary fixes\n * one regardless of its operands — `qti-divide` is a float even dividing two\n * integers exactly, and `qti-round` is an integer whatever it rounds.\n *\n * Left undefined by operators whose result type follows their operands (a\n * `qti-sum` of integers is an integer) and by those that return no number at\n * all; the type is then read off the value.\n */\n public get resultBaseType(): BaseType | undefined {\n return undefined;\n }\n\n /*\n * Subscribed but deliberately NOT `@state()`.\n *\n * An expression is pull-based: nothing reads these until a rule calls\n * `calculate()`, which reads whatever the consumer has by then. Marking them\n * reactive made every context change schedule a render of every expression\n * element in the document — an item with 30 response-processing rules holds\n * ~180 of them, and the test context changes on every keystroke. The\n * subscription still keeps the properties current; it just no longer asks\n * for a render nothing depends on.\n */\n @consume({ context: itemContext, subscribe: true })\n protected context?: ItemContext;\n\n @consume({ context: qtiContext, subscribe: true })\n protected qtiContext?: QtiContext;\n\n @consume({ context: testContext, subscribe: true })\n protected _testContext?: TestContext;\n\n /**\n * Resolve a declared variable from the closest available scope: item-level\n * first, then the test-level outcome variables. So an expression used in an\n * assessmentTest's outcome processing can reference a test-level outcome\n * (e.g. a total set earlier in the same run) — which the QTI variable\n * expression is specified to do. Returns null when unresolved rather than\n * throwing, so callers degrade gracefully.\n */\n protected resolveVariable(identifier: string): VariableDeclaration<string | string[] | null> | null {\n return (\n this.context?.variables.find(v => v.identifier === identifier) ??\n this._testContext?.testOutcomeVariables?.find(v => v.identifier === identifier) ??\n null\n );\n }\n\n getVariables = (): ExpressionVariable[] => {\n // FIXME: if this itself is multiple, this will never enter the qti-multiple switch\n // See this example here: https://github.com/1EdTech/qti-examples/blob/master/qtiv3-examples/packaging/items/Example05-feedbackBlock-adaptive.xml\n\n const variables = Array.from(this.children)\n .map((e: Element) => {\n switch (e.tagName.toLowerCase()) {\n case 'qti-base-value': {\n return {\n baseType: e.getAttribute('base-type'),\n value: e.textContent.trim(),\n cardinality: 'single'\n } as ResponseVariable;\n }\n case 'qti-variable': {\n const identifier = e.getAttribute('identifier') || '';\n\n // Special handling for QTI_CONTEXT\n if (identifier === 'QTI_CONTEXT') {\n if (!this.qtiContext?.QTI_CONTEXT) {\n console.warn('QTI_CONTEXT not available');\n return {\n identifier: 'QTI_CONTEXT',\n baseType: 'record',\n value: this.qtiContext.QTI_CONTEXT,\n cardinality: 'record',\n type: 'context'\n } as VariableDeclaration<QtiContextType>;\n }\n return {\n identifier: 'QTI_CONTEXT',\n baseType: 'record',\n value: this.qtiContext.QTI_CONTEXT,\n cardinality: 'record',\n type: 'context'\n } as VariableDeclaration<QtiContextType>;\n }\n\n return this.resolveVariable(identifier);\n }\n case 'qti-multiple': {\n const multiple = e as QtiExpression<ResponseVariable[]>;\n\n const values = multiple.getResult();\n if (values?.length > 0) {\n return {\n identifier: '',\n baseType: values[0].baseType,\n value: values.map(v => v.value),\n cardinality: 'multiple',\n type: 'response'\n } as ResponseVariable;\n }\n return null;\n }\n case 'qti-ordered': {\n const multiple = e as QtiExpression<ResponseVariable[]>;\n const values = multiple.getResult();\n if (values?.length > 0) {\n return {\n identifier: '',\n baseType: values[0].baseType,\n value: values.map(v => v.value),\n cardinality: 'ordered',\n type: 'response'\n } as ResponseVariable;\n }\n return null;\n }\n case 'qti-repeat': {\n const repeat = e as QtiExpression<ResponseVariable[]>;\n const values = repeat.getResult();\n if (values?.length > 0) {\n return values;\n }\n return null;\n }\n case 'qti-custom-operator': {\n // Not a QtiExpression — it has `calculate` but no `getResult`, so\n // the default branch below throws on it and the surrounding\n // expression is handed nothing.\n return variableFromValue((e as unknown as Calculate).calculate?.());\n }\n case 'qti-correct': {\n const identifier = e.getAttribute('identifier') || '';\n const responseVariable = this.context?.variables?.find(v => v.identifier === identifier) as\n | ResponseVariable\n | undefined;\n\n // A `qti-correct` naming a response that is not declared — a typo,\n // or an expression evaluated before the declaration registered —\n // used to dereference the null this deliberately produced and take\n // down the whole processing run. It is an unresolved variable, so\n // it is NULL.\n if (!responseVariable) {\n console.warn(`qti-correct: no response declaration for \"${identifier}\"`);\n return variableFromValue(null);\n }\n\n return {\n baseType: responseVariable.baseType,\n value: responseVariable.correctResponse,\n cardinality: responseVariable.cardinality\n } as ResponseVariable;\n }\n default: {\n // Every operator without a case of its own lands here.\n try {\n const expression = e as QtiExpression<unknown>;\n const result = expression.getResult();\n return variableFromValue(result, expression.resultBaseType ?? inferContainerBaseType(expression, result));\n } catch (error) {\n console.warn(`getVariables: could not read a value from <${e.tagName.toLowerCase()}>`, error);\n }\n return null;\n }\n }\n })\n .flatMap(v => (Array.isArray(v) ? v : [v]))\n .filter((v): v is ExpressionVariable => v !== null);\n\n this.#lastVariables = variables;\n return variables;\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"qti-expression.js","sourceRoot":"","sources":["../../src/abstract/qti-expression.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,KAAK,CAAC;AAE5C,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAkBtD;;;;;;;;;;;;;GAaG;AACH,MAAM,iBAAiB,GAAG,CAAC,KAAc,EAAE,QAAmB,EAAoB,EAAE;IAClF;;;;;;OAMG;IACH,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QAC1C,OAAO;YACL,UAAU,EAAE,EAAE;YACd,QAAQ,EAAE,QAAQ;YAClB,KAAK,EAAE,IAAI;YACX,WAAW,EAAE,QAAQ;YACrB,IAAI,EAAE,UAAU;SACG,CAAC;IACxB,CAAC;IAED,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO;YACL,UAAU,EAAE,EAAE;YACd,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AI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,KAAK,UAAU,CAAC;YAC9D,IAAI,CAAC,YAAY,EAAE,oBAAoB,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,KAAK,UAAU,CAAC;YAC/E,IAAI,CAAC,mBAAmB,CAAC,UAAU,CAAC,CACrC,CAAC;IACJ,CAAC;IAED;;;;;OAKG;IACK,mBAAmB,CAAC,UAAkB;QAC5C,IAAI,CAAC,UAAU,EAAE,QAAQ,CAAC,GAAG,CAAC;YAAE,OAAO,IAAI,CAAC;QAC5C,MAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACpC,MAAM,IAAI,GAAG,IAAI,CAAC,YAAY,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;QAC5E,OAAO,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,KAAK,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC;IACtF,CAAC;;AAnCS;IADT,OAAO,CAAC,EAAE,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;8CACnB;AAGtB;IADT,OAAO,CAAC,EAAE,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;iDAChB;AAGxB;IADT,OAAO,CAAC,EAAE,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;mDACd","sourcesContent":["import { consume } from '@lit/context';\nimport { css, html, LitElement } from 'lit';\n\nimport { itemContext } from '../context/item.context';\nimport { qtiContext } from '../context/qti.context';\nimport { testContext } from '../context/test.context';\n\nimport type { ItemContext } from '../context/types/item.types';\nimport type { QtiContext, QtiContextType } from '../context/qti.context';\nimport type { Calculate } from '../lib/expression-result';\nimport type { BaseType } from '../lib/expression-result';\nimport type { ResponseVariable, VariableDeclaration } from '../lib/variables';\nimport type { TestContext } from '../context/test.context';\n\ntype ExpressionVariable = ResponseVariable | VariableDeclaration<QtiContextType>;\n\nexport interface QtiExpressionBase<T> {\n // get assessmentItem(): QtiAssessmentItem;\n\n // getVariables(): VariableDeclaration<number | string | (number | string)[] | null>[];\n calculate(): Readonly<T>;\n}\n\n/**\n * Wrap whatever an expression handed back in a variable, reading the base type\n * off the value itself.\n *\n * An operator that knows its own result type says so through `resultBaseType`\n * and that wins, because the QTI vocabulary fixes it regardless of the operands\n * — `qti-divide` is a float even when it divides two integers exactly. Only\n * when nothing is declared, as for a custom operator returning whatever the\n * host computed, is the type read off the value.\n *\n * Everything used to be labelled `integer`, and since `compareSingleValues`\n * parses an integer with `parseInt`, that silently truncated:\n * `equal(divide(5, 2), 2.4)` compared 2 against 2 and answered true.\n */\nconst variableFromValue = (value: unknown, declared?: BaseType): ResponseVariable => {\n /*\n * A NULL result is still a value: the operand exists and is NULL. Returning\n * nothing would drop it from the list, which both hides the NULL from\n * `qti-is-null` and shifts every operand after it — a binary operator with a\n * NULL first argument would silently read its second as its first. The base\n * type is moot here, since every operator tests the value before it.\n */\n if (value === null || value === undefined) {\n return {\n identifier: '',\n baseType: 'string',\n value: null,\n cardinality: 'single',\n type: 'response'\n } as ResponseVariable;\n }\n\n if (Array.isArray(value)) {\n return {\n identifier: '',\n baseType: declared ?? inferBaseType(value[0]),\n value: value.map(entry => String(entry)),\n cardinality: 'multiple',\n type: 'response'\n } as ResponseVariable;\n }\n\n return {\n identifier: '',\n baseType: declared ?? inferBaseType(value),\n value: String(value),\n cardinality: 'single',\n type: 'response'\n } as ResponseVariable;\n};\n\n/** A JS value's QTI base type. A string stays text; it is not re-parsed. */\nconst inferBaseType = (value: unknown): BaseType => {\n if (typeof value === 'number') return Number.isInteger(value) ? 'integer' : 'float';\n if (typeof value === 'boolean') return 'boolean';\n return 'string';\n};\n\nconst inferContainerBaseType = (expression: QtiExpression<unknown>, value: unknown): BaseType | undefined => {\n if (!Array.isArray(value) || value.length > 0) {\n return undefined;\n }\n\n return expression.lastVariables.find(\n variable => variable?.baseType && variable.baseType !== 'record' && variable.cardinality !== 'record'\n )?.baseType as BaseType | undefined;\n};\n\nexport abstract class QtiExpression<T> extends LitElement implements QtiExpressionBase<T> {\n /*\n * Not `@state()`. Nothing renders it any more (see `render` below), so making\n * it reactive only scheduled an update per `calculate()` — and response\n * processing calls that on every expression of every rule it walks.\n */\n protected result: any;\n #lastVariables: ExpressionVariable[] = [];\n\n /**\n * What the last `calculate()` produced, or undefined if it has not run.\n *\n * This is the supported way to inspect a scoring run: process the responses,\n * then walk the rule tree reading this off each expression. A tool that wants\n * to visualise how a score came about gets the whole tree annotated with its\n * values, without the components having to re-render to show them.\n */\n public get lastResult(): Readonly<T> | undefined {\n return this.result;\n }\n\n public get lastVariables(): readonly ExpressionVariable[] {\n return this.#lastVariables;\n }\n\n /*\n * Written here rather than imported from a .css file, and that is a packaging constraint rather\n * than a style preference.\n *\n * The rule used to live in qti-expression.css, imported with Vite's inline-stylesheet query so\n * DevTools could show source-file provenance. That query is a VITE specifier, and tsc copies it\n * verbatim into dist — so the published package shipped an import only a Vite-based consumer\n * could resolve. Every other consumer broke on it: plain Node, tsx, any non-Vite bundler. It was\n * the single such specifier reachable from this package, and it took down QTI-Editor's schema\n * check, which loads the components under tsx to build the real ProseMirror schema\n * (ERR_UNKNOWN_FILE_EXTENSION on a file that has nothing to do with schemas).\n *\n * A `build:assets` step used to copy the .css into dist beside it. That went too — it existed\n * only to give the unresolvable import something to point at.\n *\n * Two lines of CSS are not worth a dist that only one bundler can consume. If this ever grows\n * into a real stylesheet, give it a `.styles.ts` exporting a `css` template — the house pattern\n * everywhere else in this repo — rather than reintroducing a bundler-specific import.\n *\n * The element renders a debug <pre> of its computed result plus a <slot>; hiding the slot is all\n * the styling it has ever had.\n */\n static override styles = css`\n slot {\n display: none;\n }\n `;\n\n /*\n * Just the slot. This used to render `JSON.stringify(this.result, null, 2)`\n * into a <pre> beside it — a development aid that nobody could see, because\n * expressions live inside `qti-response-processing`, which is `display: none`.\n * It cost a full serialisation of the result on every render.\n */\n override render() {\n return html`<slot></slot>`;\n }\n\n /*\n * Render once, then never again: the template above is constant, so every\n * later update is pure overhead.\n *\n * It is not the `@state()` decorators that drive those updates — `@consume`\n * subscribes through `ContextConsumer`, which calls `host.requestUpdate()`\n * itself on every context change, \"in case this value is used in a template\".\n * Here it is not. An item with 30 response-processing rules holds ~180\n * expression elements and the test context changes on every keystroke, so\n * that was ~180 renders per keystroke producing identical output.\n *\n * The subscriptions stay, because `calculate()` reads the current values when\n * a rule invokes it. Only the rendering stops.\n */\n protected override shouldUpdate(): boolean {\n return !this.hasUpdated;\n }\n\n public calculate(): Readonly<T> {\n this.result = this.getResult();\n return this.result;\n }\n\n protected getResult(): Readonly<T> {\n throw new Error('Not implemented');\n }\n\n /**\n * The base type this operator always produces, when the QTI vocabulary fixes\n * one regardless of its operands — `qti-divide` is a float even dividing two\n * integers exactly, and `qti-round` is an integer whatever it rounds.\n *\n * Left undefined by operators whose result type follows their operands (a\n * `qti-sum` of integers is an integer) and by those that return no number at\n * all; the type is then read off the value.\n */\n public get resultBaseType(): BaseType | undefined {\n return undefined;\n }\n\n /*\n * Subscribed but deliberately NOT `@state()`.\n *\n * An expression is pull-based: nothing reads these until a rule calls\n * `calculate()`, which reads whatever the consumer has by then. Marking them\n * reactive made every context change schedule a render of every expression\n * element in the document — an item with 30 response-processing rules holds\n * ~180 of them, and the test context changes on every keystroke. The\n * subscription still keeps the properties current; it just no longer asks\n * for a render nothing depends on.\n */\n @consume({ context: itemContext, subscribe: true })\n protected context?: ItemContext;\n\n @consume({ context: qtiContext, subscribe: true })\n protected qtiContext?: QtiContext;\n\n @consume({ context: testContext, subscribe: true })\n protected _testContext?: TestContext;\n\n /**\n * Resolve a declared variable from the closest available scope: item-level\n * first, then the test-level outcome variables. So an expression used in an\n * assessmentTest's outcome processing can reference a test-level outcome\n * (e.g. a total set earlier in the same run) — which the QTI variable\n * expression is specified to do. Returns null when unresolved rather than\n * throwing, so callers degrade gracefully.\n */\n protected resolveVariable(identifier: string): VariableDeclaration<string | string[] | null> | null {\n return (\n this.context?.variables.find(v => v.identifier === identifier) ??\n this._testContext?.testOutcomeVariables?.find(v => v.identifier === identifier) ??\n this.resolveItemVariable(identifier)\n );\n }\n\n /**\n * `ITEMREF.VAR`: a variable of an individual item session, looked up by prefixing the variable\n * with the identifier the item ref gave the item (QTI 3 `qti-variable`), e.g. `Q01.SCORE`. An\n * item that was never presented has no variables, which resolves to NULL. Instances of a cloned\n * item (`Q01.2.SCORE`) are not supported: the item itself is used.\n */\n private resolveItemVariable(identifier: string): VariableDeclaration<string | string[] | null> | null {\n if (!identifier?.includes('.')) return null;\n const parts = identifier.split('.');\n const item = this._testContext?.items?.find(i => i.identifier === parts[0]);\n return item?.variables?.find(v => v.identifier === parts[parts.length - 1]) ?? null;\n }\n\n getVariables = (): ExpressionVariable[] => {\n // FIXME: if this itself is multiple, this will never enter the qti-multiple switch\n // See this example here: https://github.com/1EdTech/qti-examples/blob/master/qtiv3-examples/packaging/items/Example05-feedbackBlock-adaptive.xml\n\n const variables = Array.from(this.children)\n .map((e: Element) => {\n switch (e.tagName.toLowerCase()) {\n case 'qti-base-value': {\n return {\n baseType: e.getAttribute('base-type'),\n value: e.textContent.trim(),\n cardinality: 'single'\n } as ResponseVariable;\n }\n case 'qti-variable': {\n const identifier = e.getAttribute('identifier') || '';\n\n // Special handling for QTI_CONTEXT\n if (identifier === 'QTI_CONTEXT') {\n if (!this.qtiContext?.QTI_CONTEXT) {\n console.warn('QTI_CONTEXT not available');\n return {\n identifier: 'QTI_CONTEXT',\n baseType: 'record',\n value: this.qtiContext.QTI_CONTEXT,\n cardinality: 'record',\n type: 'context'\n } as VariableDeclaration<QtiContextType>;\n }\n return {\n identifier: 'QTI_CONTEXT',\n baseType: 'record',\n value: this.qtiContext.QTI_CONTEXT,\n cardinality: 'record',\n type: 'context'\n } as VariableDeclaration<QtiContextType>;\n }\n\n return this.resolveVariable(identifier);\n }\n case 'qti-multiple': {\n const multiple = e as QtiExpression<ResponseVariable[]>;\n\n const values = multiple.getResult();\n if (values?.length > 0) {\n return {\n identifier: '',\n baseType: values[0].baseType,\n value: values.map(v => v.value),\n cardinality: 'multiple',\n type: 'response'\n } as ResponseVariable;\n }\n return null;\n }\n case 'qti-ordered': {\n const multiple = e as QtiExpression<ResponseVariable[]>;\n const values = multiple.getResult();\n if (values?.length > 0) {\n return {\n identifier: '',\n baseType: values[0].baseType,\n value: values.map(v => v.value),\n cardinality: 'ordered',\n type: 'response'\n } as ResponseVariable;\n }\n return null;\n }\n case 'qti-repeat': {\n const repeat = e as QtiExpression<ResponseVariable[]>;\n const values = repeat.getResult();\n if (values?.length > 0) {\n return values;\n }\n return null;\n }\n case 'qti-custom-operator': {\n // Not a QtiExpression — it has `calculate` but no `getResult`, so\n // the default branch below throws on it and the surrounding\n // expression is handed nothing.\n return variableFromValue((e as unknown as Calculate).calculate?.());\n }\n case 'qti-correct': {\n const identifier = e.getAttribute('identifier') || '';\n const responseVariable = this.context?.variables?.find(v => v.identifier === identifier) as\n | ResponseVariable\n | undefined;\n\n // A `qti-correct` naming a response that is not declared — a typo,\n // or an expression evaluated before the declaration registered —\n // used to dereference the null this deliberately produced and take\n // down the whole processing run. It is an unresolved variable, so\n // it is NULL.\n if (!responseVariable) {\n console.warn(`qti-correct: no response declaration for \"${identifier}\"`);\n return variableFromValue(null);\n }\n\n return {\n baseType: responseVariable.baseType,\n value: responseVariable.correctResponse,\n cardinality: responseVariable.cardinality\n } as ResponseVariable;\n }\n default: {\n // Every operator without a case of its own lands here.\n try {\n const expression = e as QtiExpression<unknown>;\n const result = expression.getResult();\n return variableFromValue(result, expression.resultBaseType ?? inferContainerBaseType(expression, result));\n } catch (error) {\n console.warn(`getVariables: could not read a value from <${e.tagName.toLowerCase()}>`, error);\n }\n return null;\n }\n }\n })\n .flatMap(v => (Array.isArray(v) ? v : [v]))\n .filter((v): v is ExpressionVariable => v !== null);\n\n this.#lastVariables = variables;\n return variables;\n };\n}\n"]}
|
|
@@ -5,8 +5,7 @@ export declare abstract class QtiFeedback extends LitElement {
|
|
|
5
5
|
outcomeIdentifier: string;
|
|
6
6
|
protected identifier: string;
|
|
7
7
|
showStatus: string;
|
|
8
|
-
private _context
|
|
8
|
+
private get _context();
|
|
9
9
|
private _computedContext?;
|
|
10
|
-
connectedCallback(): void;
|
|
11
10
|
checkShowFeedback(outcomeIdentifier: string): void;
|
|
12
11
|
}
|
|
@@ -4,7 +4,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
|
|
|
4
4
|
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
5
|
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
6
|
};
|
|
7
|
-
import { consume } from '@lit/context';
|
|
7
|
+
import { ContextConsumer, consume } from '@lit/context';
|
|
8
8
|
import { LitElement } from 'lit';
|
|
9
9
|
import { property, state } from 'lit/decorators.js';
|
|
10
10
|
import { computedContext } from '../context/computed.context';
|
|
@@ -14,14 +14,45 @@ export class QtiFeedback extends LitElement {
|
|
|
14
14
|
constructor() {
|
|
15
15
|
super(...arguments);
|
|
16
16
|
this.showHide = 'show';
|
|
17
|
+
/**
|
|
18
|
+
* The item's variables. Feedback follows them itself: every time the item publishes a new context
|
|
19
|
+
* this decides, synchronously, whether its own outcome now calls for showing it, so the item has
|
|
20
|
+
* no list of feedback elements to push to. Synchronous matters. A host that sets an outcome
|
|
21
|
+
* reads `showStatus` straight after, with no await in between.
|
|
22
|
+
*/
|
|
23
|
+
this.#itemContext = new ContextConsumer(this, {
|
|
24
|
+
context: itemContext,
|
|
25
|
+
subscribe: true,
|
|
26
|
+
callback: context => this.#followItem(context)
|
|
27
|
+
});
|
|
17
28
|
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
29
|
+
/**
|
|
30
|
+
* The item's variables. Feedback follows them itself: every time the item publishes a new context
|
|
31
|
+
* this decides, synchronously, whether its own outcome now calls for showing it, so the item has
|
|
32
|
+
* no list of feedback elements to push to. Synchronous matters. A host that sets an outcome
|
|
33
|
+
* reads `showStatus` straight after, with no await in between.
|
|
34
|
+
*/
|
|
35
|
+
#itemContext;
|
|
36
|
+
get _context() {
|
|
37
|
+
return this.#itemContext.value;
|
|
38
|
+
}
|
|
39
|
+
/** What the last context carried that decides this feedback, to tell a relevant update from noise. */
|
|
40
|
+
#seen;
|
|
41
|
+
/**
|
|
42
|
+
* Re-decide when this feedback's outcome changed, or once an attempt has been made. Before the
|
|
43
|
+
* first attempt an unchanged outcome says nothing yet: a `hide` feedback would otherwise switch
|
|
44
|
+
* on for an item nobody has answered.
|
|
45
|
+
*/
|
|
46
|
+
#followItem(context) {
|
|
47
|
+
const variables = context?.variables;
|
|
48
|
+
if (!variables || !this.outcomeIdentifier)
|
|
49
|
+
return;
|
|
50
|
+
const outcome = JSON.stringify(variables.find(v => v.identifier === this.outcomeIdentifier)?.value ?? null);
|
|
51
|
+
const numAttempts = Number(variables.find(v => v.identifier === 'numAttempts')?.value) || 0;
|
|
52
|
+
const relevant = this.#seen === undefined ? numAttempts > 0 : this.#seen !== outcome || numAttempts > 0;
|
|
53
|
+
this.#seen = outcome;
|
|
54
|
+
if (relevant)
|
|
55
|
+
this.checkShowFeedback(this.outcomeIdentifier);
|
|
25
56
|
}
|
|
26
57
|
checkShowFeedback(outcomeIdentifier) {
|
|
27
58
|
const outcomeVariable = this._context.variables.find(v => v.identifier === outcomeIdentifier) || null;
|
|
@@ -95,10 +126,6 @@ __decorate([
|
|
|
95
126
|
__decorate([
|
|
96
127
|
property({ type: String, attribute: false })
|
|
97
128
|
], QtiFeedback.prototype, "showStatus", void 0);
|
|
98
|
-
__decorate([
|
|
99
|
-
consume({ context: itemContext, subscribe: true }),
|
|
100
|
-
state()
|
|
101
|
-
], QtiFeedback.prototype, "_context", void 0);
|
|
102
129
|
__decorate([
|
|
103
130
|
consume({ context: computedContext, subscribe: true }),
|
|
104
131
|
state()
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"qti-feedback.js","sourceRoot":"","sources":["../../src/abstract/qti-feedback.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"qti-feedback.js","sourceRoot":"","sources":["../../src/abstract/qti-feedback.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EAAE,UAAU,EAAE,MAAM,KAAK,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAEpD,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AACtD,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAKnD,MAAM,OAAgB,WAAY,SAAQ,UAAU;IAApD;;QAEY,aAAQ,GAAoB,MAAM,CAAC;QAW7C;;;;;WAKG;QACH,iBAAY,GAAG,IAAI,eAAe,CAAC,IAAI,EAAE;YACvC,OAAO,EAAE,WAAW;YACpB,SAAS,EAAE,IAAI;YACf,QAAQ,EAAE,OAAO,CAAC,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC;SAC/C,CAAC,CAAC;IAuFL,CAAC;IAjGC;;;;;OAKG;IACH,YAAY,CAIT;IAEH,IAAY,QAAQ;QAClB,OAAO,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC;IACjC,CAAC;IAED,sGAAsG;IACtG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,OAAO,UAAU,CAAC,gBAAgB,KAAK,WAAW,CAAC;QAE5E,uEAAuE;QACvE,MAAM,WAAW,GAAG,UAAU,CAAC,WAAW,IAAI,CAAC,CAAC;QAChD,IAAI,WAAW,IAAI,CAAC;YAAE,OAAO,IAAI,CAAC;QAElC,MAAM,WAAW,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,KAAK,aAAa,CAAC,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;QAC5G,OAAO,WAAW,GAAG,WAAW,CAAC;IACnC,CAAC;CACF;AA5GW;IADT,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,WAAW,EAAE,CAAC;6CACN;AAGtC;IADN,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,oBAAoB,EAAE,CAAC;sDAC3B;AAGvB;IADT,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;+CACE;AAGtB;IADN,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC;+CACnB;AAuBlB;IAFP,OAAO,CAAC,EAAE,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC;IACtD,KAAK,EAAE;qDACmC","sourcesContent":["import { ContextConsumer, consume } from '@lit/context';\nimport { LitElement } from 'lit';\nimport { property, state } from 'lit/decorators.js';\n\nimport { computedContext } from '../context/computed.context';\nimport { itemContext } from '../context/item.context';\nimport { IsNullOrUndefined } from '../utils/utils';\n\nimport type { ComputedContext } from '../context/types/computed.types';\nimport type { ItemContext } from '../context/types/item.types';\n\nexport abstract class QtiFeedback extends LitElement {\n @property({ type: String, attribute: 'show-hide' })\n protected showHide: 'show' | 'hide' = 'show';\n\n @property({ type: String, attribute: 'outcome-identifier' })\n public outcomeIdentifier: string;\n\n @property({ type: String })\n protected identifier: string;\n\n @property({ type: String, attribute: false })\n public showStatus: string;\n\n /**\n * The item's variables. Feedback follows them itself: every time the item publishes a new context\n * this decides, synchronously, whether its own outcome now calls for showing it, so the item has\n * no list of feedback elements to push to. Synchronous matters. A host that sets an outcome\n * reads `showStatus` straight after, with no await in between.\n */\n #itemContext = new ContextConsumer(this, {\n context: itemContext,\n subscribe: true,\n callback: context => this.#followItem(context)\n });\n\n private get _context(): ItemContext | undefined {\n return this.#itemContext.value;\n }\n\n /** What the last context carried that decides this feedback, to tell a relevant update from noise. */\n #seen?: string;\n\n @consume({ context: computedContext, subscribe: true })\n @state()\n private _computedContext?: ComputedContext;\n\n /**\n * Re-decide when this feedback's outcome changed, or once an attempt has been made. Before the\n * first attempt an unchanged outcome says nothing yet: a `hide` feedback would otherwise switch\n * on for an item nobody has answered.\n */\n #followItem(context: ItemContext | undefined) {\n const variables = context?.variables;\n if (!variables || !this.outcomeIdentifier) return;\n const outcome = JSON.stringify(variables.find(v => v.identifier === this.outcomeIdentifier)?.value ?? null);\n const numAttempts = Number(variables.find(v => v.identifier === 'numAttempts')?.value) || 0;\n const relevant = this.#seen === undefined ? numAttempts > 0 : this.#seen !== outcome || numAttempts > 0;\n this.#seen = outcome;\n if (relevant) this.checkShowFeedback(this.outcomeIdentifier);\n }\n\n public checkShowFeedback(outcomeIdentifier: string) {\n const outcomeVariable = this._context.variables.find(v => v.identifier === outcomeIdentifier) || null;\n if (this.outcomeIdentifier !== outcomeIdentifier || !outcomeVariable) return;\n let isFound = false;\n if (Array.isArray(outcomeVariable.value)) {\n isFound = outcomeVariable.value.includes(this.identifier);\n } else {\n isFound =\n (!IsNullOrUndefined(this.identifier) &&\n !IsNullOrUndefined(outcomeVariable?.value) &&\n this.identifier === outcomeVariable.value) ||\n false;\n }\n\n this.#showFeedback(isFound);\n }\n\n #showFeedback(value: boolean) {\n if (!this.#sessionControlAllowsFeedback()) {\n this.showStatus = 'off';\n return;\n }\n this.showStatus = (value && this.showHide === 'show') || (!value && this.showHide === 'hide') ? 'on' : 'off';\n }\n\n /**\n * The QTI `show-feedback` constraint governs exactly one state: after the end of\n * the last attempt. Up to that point the spec requires any applicable feedback to\n * be shown — \"a value of max-attempts greater than 1, by definition, indicates\n * that any applicable feedback must be shown\" — and only \"once the maximum number\n * of allowed attempts have been used (or for adaptive items, completionStatus has\n * been set to completed)\" does `show-feedback` decide.\n *\n * This only ever forces feedback off, so `show-feedback` being true settles it:\n * there is no state in which the constraint hides feedback. It defaults to\n * false, and an absent value suppresses once the attempts are gone.\n *\n * That leaves one question — is the item out of attempts? — and the two item\n * kinds answer it from different variables, so each reads only its own.\n */\n #sessionControlAllowsFeedback(): boolean {\n if (!this._computedContext) return true;\n const activeItem = this._computedContext.testParts\n ?.find(tp => tp.active)\n ?.sections.flatMap(s => s.items)\n .find(i => i.active);\n if (!activeItem || activeItem.showFeedback) return true;\n\n // Adaptive items ignore max-attempts: \"the number of attempts is limited by\n // the value of the completionStatus built-in outcome variable\".\n if (activeItem.adaptive) return activeItem.completionStatus !== 'completed';\n\n // `max-attempts=\"0\"` is \"no limit\", so the last attempt never arrives.\n const maxAttempts = activeItem.maxAttempts ?? 1;\n if (maxAttempts <= 0) return true;\n\n const numAttempts = Number(this._context?.variables?.find(v => v.identifier === 'numAttempts')?.value) || 0;\n return numAttempts < maxAttempts;\n }\n}\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Catches context requests nobody answered and asks again when a provider connects, so a component
|
|
3
|
+
* that upgrades before the element providing its context still gets the value.
|
|
4
|
+
*
|
|
5
|
+
* It has to live on the document and not on one of our elements: the case it exists for is the
|
|
6
|
+
* providing element not having upgraded yet, so there is nothing of ours to attach it to. It holds
|
|
7
|
+
* only requests that subscribe, which every `@consume` in this library does, and it holds them
|
|
8
|
+
* weakly, so nothing is kept alive that would not be anyway.
|
|
9
|
+
*
|
|
10
|
+
* Once per page, however many copies of the package the page ends up with.
|
|
11
|
+
*/
|
|
12
|
+
export declare const installContextRoot: () => void;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { ContextRoot } from '@lit/context';
|
|
2
|
+
const INSTALLED = Symbol.for('qti-components.context-root');
|
|
3
|
+
/**
|
|
4
|
+
* Catches context requests nobody answered and asks again when a provider connects, so a component
|
|
5
|
+
* that upgrades before the element providing its context still gets the value.
|
|
6
|
+
*
|
|
7
|
+
* It has to live on the document and not on one of our elements: the case it exists for is the
|
|
8
|
+
* providing element not having upgraded yet, so there is nothing of ours to attach it to. It holds
|
|
9
|
+
* only requests that subscribe, which every `@consume` in this library does, and it holds them
|
|
10
|
+
* weakly, so nothing is kept alive that would not be anyway.
|
|
11
|
+
*
|
|
12
|
+
* Once per page, however many copies of the package the page ends up with.
|
|
13
|
+
*/
|
|
14
|
+
export const installContextRoot = () => {
|
|
15
|
+
if (typeof document === 'undefined')
|
|
16
|
+
return;
|
|
17
|
+
const page = globalThis;
|
|
18
|
+
if (page[INSTALLED])
|
|
19
|
+
return;
|
|
20
|
+
page[INSTALLED] = new ContextRoot();
|
|
21
|
+
page[INSTALLED].attach(document.documentElement);
|
|
22
|
+
};
|
|
23
|
+
installContextRoot();
|
|
24
|
+
//# sourceMappingURL=context-root.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-root.js","sourceRoot":"","sources":["../../src/context/context-root.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC;AAE5D;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,GAAS,EAAE;IAC3C,IAAI,OAAO,QAAQ,KAAK,WAAW;QAAE,OAAO;IAC5C,MAAM,IAAI,GAAG,UAAgE,CAAC;IAC9E,IAAI,IAAI,CAAC,SAAS,CAAC;QAAE,OAAO;IAC5B,IAAI,CAAC,SAAS,CAAC,GAAG,IAAI,WAAW,EAAE,CAAC;IACpC,IAAI,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,eAAe,CAAC,CAAC;AACnD,CAAC,CAAC;AAEF,kBAAkB,EAAE,CAAC","sourcesContent":["import { ContextRoot } from '@lit/context';\n\nconst INSTALLED = Symbol.for('qti-components.context-root');\n\n/**\n * Catches context requests nobody answered and asks again when a provider connects, so a component\n * that upgrades before the element providing its context still gets the value.\n *\n * It has to live on the document and not on one of our elements: the case it exists for is the\n * providing element not having upgraded yet, so there is nothing of ours to attach it to. It holds\n * only requests that subscribe, which every `@consume` in this library does, and it holds them\n * weakly, so nothing is kept alive that would not be anyway.\n *\n * Once per page, however many copies of the package the page ends up with.\n */\nexport const installContextRoot = (): void => {\n if (typeof document === 'undefined') return;\n const page = globalThis as unknown as Record<symbol, ContextRoot | undefined>;\n if (page[INSTALLED]) return;\n page[INSTALLED] = new ContextRoot();\n page[INSTALLED].attach(document.documentElement);\n};\n\ninstallContextRoot();\n"]}
|
|
@@ -3,7 +3,9 @@ export interface SessionContext {
|
|
|
3
3
|
navPartId?: string | null;
|
|
4
4
|
navSectionId?: string | null;
|
|
5
5
|
navItemRefId?: string | null;
|
|
6
|
+
/** @deprecated Never set by the library. Removed in the next major. */
|
|
6
7
|
navItemLoading?: boolean;
|
|
8
|
+
/** @deprecated Never set by the library. Removed in the next major. */
|
|
7
9
|
navTestLoading?: boolean;
|
|
8
10
|
view?: View;
|
|
9
11
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { createContext } from '@lit/context';
|
|
2
2
|
export const INITIAL_SESSION_CONTEXT = { view: 'candidate' };
|
|
3
|
-
export const sessionContext = createContext(Symbol('
|
|
3
|
+
export const sessionContext = createContext(Symbol('sessionContext'));
|
|
4
4
|
//# sourceMappingURL=session.context.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.context.js","sourceRoot":"","sources":["../../src/context/session.context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"session.context.js","sourceRoot":"","sources":["../../src/context/session.context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAe7C,MAAM,CAAC,MAAM,uBAAuB,GAA6B,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC;AAEvF,MAAM,CAAC,MAAM,cAAc,GAAG,aAAa,CAA2B,MAAM,CAAC,gBAAgB,CAAC,CAAC,CAAC","sourcesContent":["import { createContext } from '@lit/context';\n\nexport type View = 'author' | 'candidate' | 'proctor' | 'scorer' | 'testConstructor' | 'tutor' | '';\n\nexport interface SessionContext {\n navPartId?: string | null;\n navSectionId?: string | null;\n navItemRefId?: string | null;\n /** @deprecated Never set by the library. Removed in the next major. */\n navItemLoading?: boolean;\n /** @deprecated Never set by the library. Removed in the next major. */\n navTestLoading?: boolean;\n view?: View;\n}\n\nexport const INITIAL_SESSION_CONTEXT: Readonly<SessionContext> = { view: 'candidate' };\n\nexport const sessionContext = createContext<Readonly<SessionContext>>(Symbol('sessionContext'));\n"]}
|
|
@@ -8,5 +8,15 @@ export interface ItemContext {
|
|
|
8
8
|
* Used for interactions that support state save/restore (e.g. PCI).
|
|
9
9
|
*/
|
|
10
10
|
state?: Record<string, string | null>;
|
|
11
|
+
/** The item is shown for reading only. Interactions follow it; see `qti-assessment-item`'s `readonly`. */
|
|
12
|
+
readonly?: boolean;
|
|
13
|
+
/** The item is locked, for example after it was submitted. Interactions follow it; see `qti-assessment-item`'s `disabled`. */
|
|
14
|
+
disabled?: boolean;
|
|
15
|
+
/**
|
|
16
|
+
* Whether the interactions in the item are valid right now (a required answer is given, a limit is
|
|
17
|
+
* respected). Published by the item whenever it checks, so a reader never has to ask the item.
|
|
18
|
+
* Unset until the item has checked once.
|
|
19
|
+
*/
|
|
20
|
+
valid?: boolean;
|
|
11
21
|
}
|
|
12
22
|
export declare const itemContextVariables: VariableDeclaration<string | string[]>[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"item.types.js","sourceRoot":"","sources":["../../../src/context/types/item.types.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"item.types.js","sourceRoot":"","sources":["../../../src/context/types/item.types.ts"],"names":[],"mappings":"AAuBA,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC;QACE,UAAU,EAAE,kBAAkB;QAC9B,WAAW,EAAE,QAAQ;QACrB,QAAQ,EAAE,QAAQ;QAClB,KAAK,EAAE,SAAS;QAChB,IAAI,EAAE,SAAS;KAChB;IACD;QACE,UAAU,EAAE,aAAa;QACzB,WAAW,EAAE,QAAQ;QACrB,QAAQ,EAAE,SAAS;QACnB,KAAK,EAAE,GAAG;QACV,IAAI,EAAE,UAAU;KACjB;CAC0C,CAAC","sourcesContent":["import type { VariableDeclaration } from '../../lib/variables';\n\nexport interface ItemContext {\n identifier?: string;\n href?: string;\n variables?: ReadonlyArray<VariableDeclaration<string | string[] | null>>;\n /**\n * Optional per-interaction opaque state, keyed by responseIdentifier.\n * Used for interactions that support state save/restore (e.g. PCI).\n */\n state?: Record<string, string | null>;\n /** The item is shown for reading only. Interactions follow it; see `qti-assessment-item`'s `readonly`. */\n readonly?: boolean;\n /** The item is locked, for example after it was submitted. Interactions follow it; see `qti-assessment-item`'s `disabled`. */\n disabled?: boolean;\n /**\n * Whether the interactions in the item are valid right now (a required answer is given, a limit is\n * respected). Published by the item whenever it checks, so a reader never has to ask the item.\n * Unset until the item has checked once.\n */\n valid?: boolean;\n}\n\nexport const itemContextVariables = [\n {\n identifier: 'completionStatus',\n cardinality: 'single',\n baseType: 'string',\n value: 'unknown',\n type: 'outcome'\n },\n {\n identifier: 'numAttempts',\n cardinality: 'single',\n baseType: 'integer',\n value: '0',\n type: 'response'\n }\n] as VariableDeclaration<string | string[]>[];\n"]}
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,YAAY,CAAC;AAEpB,cAAc,iCAAiC,CAAC;AAChD,cAAc,qCAAqC,CAAC;AACpD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,0BAA0B,CAAC;AACzC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,wBAAwB,CAAC;AACvC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,uBAAuB,CAAC;AACtC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,wBAAwB,CAAC;AAEvC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,oCAAoC,CAAC;AAEnD,cAAc,wBAAwB,CAAC;AACvC,cAAc,qCAAqC,CAAC;AACpD,cAAc,qCAAqC,CAAC;AACpD,cAAc,yBAAyB,CAAC;AACxC,cAAc,2BAA2B,CAAC;AAE1C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,yBAAyB,CAAC;AACxC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,iBAAiB,CAAC;AAChC,cAAc,qBAAqB,CAAC;AACpC,cAAc,wBAAwB,CAAC;AAEvC,cAAc,0BAA0B,CAAC;AACzC,cAAc,wBAAwB,CAAC;AACvC,cAAc,eAAe,CAAC","sourcesContent":["import './register';\n\nexport * from './context/computed-item.context';\nexport * from './context/types/computed-item.types';\nexport * from './context/computed.context';\nexport * from './context/types/computed.types';\nexport * from './context/config.context';\nexport * from './context/interaction.context';\nexport * from './context/item.context';\nexport * from './context/types/item.types';\nexport * from './context/qti.context';\nexport * from './context/session.context';\nexport * from './context/test.context';\n\nexport * from './styles/box-sizing.styles';\nexport * from './styles/drop-region.styles';\nexport * from './styles/validation-message.styles';\n\nexport * from './abstract/interaction';\nexport * from './abstract/qti-variable-declaration';\nexport * from './abstract/qti-condition-expression';\nexport * from './abstract/qti-feedback';\nexport * from './abstract/qti-expression';\n\nexport * from './lib/response';\nexport * from './lib/expression-result';\nexport * from './lib/interaction.interface';\nexport * from './lib/variables';\nexport * from './lib/qti-rule-base';\nexport * from './lib/custom-operators';\n\nexport * from './utils/custom-state-set';\nexport * from './utils/scoring-helper';\nexport * from './utils/utils';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,wBAAwB,CAAC;AAChC,OAAO,YAAY,CAAC;AAEpB,cAAc,iCAAiC,CAAC;AAChD,cAAc,qCAAqC,CAAC;AACpD,cAAc,4BAA4B,CAAC;AAC3C,cAAc,gCAAgC,CAAC;AAC/C,cAAc,0BAA0B,CAAC;AACzC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,wBAAwB,CAAC;AACvC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,uBAAuB,CAAC;AACtC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,wBAAwB,CAAC;AAEvC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,6BAA6B,CAAC;AAC5C,cAAc,oCAAoC,CAAC;AAEnD,cAAc,wBAAwB,CAAC;AACvC,cAAc,qCAAqC,CAAC;AACpD,cAAc,qCAAqC,CAAC;AACpD,cAAc,yBAAyB,CAAC;AACxC,cAAc,2BAA2B,CAAC;AAE1C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,yBAAyB,CAAC;AACxC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,iBAAiB,CAAC;AAChC,cAAc,qBAAqB,CAAC;AACpC,cAAc,wBAAwB,CAAC;AAEvC,cAAc,0BAA0B,CAAC;AACzC,cAAc,wBAAwB,CAAC;AACvC,cAAc,eAAe,CAAC","sourcesContent":["import './context/context-root';\nimport './register';\n\nexport * from './context/computed-item.context';\nexport * from './context/types/computed-item.types';\nexport * from './context/computed.context';\nexport * from './context/types/computed.types';\nexport * from './context/config.context';\nexport * from './context/interaction.context';\nexport * from './context/item.context';\nexport * from './context/types/item.types';\nexport * from './context/qti.context';\nexport * from './context/session.context';\nexport * from './context/test.context';\n\nexport * from './styles/box-sizing.styles';\nexport * from './styles/drop-region.styles';\nexport * from './styles/validation-message.styles';\n\nexport * from './abstract/interaction';\nexport * from './abstract/qti-variable-declaration';\nexport * from './abstract/qti-condition-expression';\nexport * from './abstract/qti-feedback';\nexport * from './abstract/qti-expression';\n\nexport * from './lib/response';\nexport * from './lib/expression-result';\nexport * from './lib/interaction.interface';\nexport * from './lib/variables';\nexport * from './lib/qti-rule-base';\nexport * from './lib/custom-operators';\n\nexport * from './utils/custom-state-set';\nexport * from './utils/scoring-helper';\nexport * from './utils/utils';\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
const SCORING_BOOLEANS = { true: true, '1': true, false: false, '0': false };
|
|
1
2
|
export class ScoringHelper {
|
|
2
3
|
/**
|
|
3
4
|
* Checks if a given point is within a specified area.
|
|
@@ -91,6 +92,11 @@ export class ScoringHelper {
|
|
|
91
92
|
case 'identifier':
|
|
92
93
|
case 'string':
|
|
93
94
|
return value1 === value2;
|
|
95
|
+
case 'boolean': {
|
|
96
|
+
// XML Schema booleans: "true" / "1" and "false" / "0"
|
|
97
|
+
const bool1 = SCORING_BOOLEANS[value1.trim().toLowerCase()];
|
|
98
|
+
return bool1 !== undefined && bool1 === SCORING_BOOLEANS[value2.trim().toLowerCase()];
|
|
99
|
+
}
|
|
94
100
|
case 'integer': {
|
|
95
101
|
const int1 = parseInt(value1, 10);
|
|
96
102
|
const int2 = parseInt(value2, 10);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scoring-helper.js","sourceRoot":"","sources":["../../src/utils/scoring-helper.ts"],"names":[],"mappings":"AAEA,MAAM,OAAO,aAAa;IACxB;;;;;;OAMG;IACI,MAAM,CAAC,aAAa,CAAC,KAAa,EAAE,OAAe,EAAE,QAAgB;QAC1E,IAAI,QAAQ,KAAK,OAAO,EAAE,CAAC;Y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AAC,KAAK,CAAC,oBAAoB,MAAM,WAAW,MAAM,YAAY,CAAC,CAAC;gBACzE,CAAC;gBACD,MAAM;YACR,CAAC;YACD,KAAK,MAAM,CAAC;YACZ,KAAK,cAAc,CAAC,CAAC,CAAC;gBACpB;;;;;;;;mBAQG;gBACH,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;gBAChC,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;gBAChC,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;oBAC7C,IAAI,QAAQ,KAAK,MAAM,EAAE,CAAC;wBACxB,KAAK,CAAC,IAAI,EAAE,CAAC;wBACb,KAAK,CAAC,IAAI,EAAE,CAAC;oBACf,CAAC;oBACD,OAAO,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;gBAC7C,CAAC;qBAAM,CAAC;oBACN,OAAO,CAAC,KAAK,CAAC,sEAAsE,MAAM,OAAO,MAAM,EAAE,CAAC,CAAC;gBAC7G,CAAC;gBACD,MAAM;YACR,CAAC;QACH,CAAC;QAED,OAAO,KAAK,CAAC;IACf,CAAC;CACF","sourcesContent":["import type { BaseType } from '../lib/expression-result';\n\nexport class ScoringHelper {\n /**\n * Checks if a given point is within a specified area.\n * @param point The point to test, represented as a string \"x y\" (e.g., \"102 113\").\n * @param areaKey The area definition, including shape and coordinates (e.g., \"circle,102,113,16\").\n * @param baseType The base type of the response, must be \"point\" for this method to proceed.\n * @returns True if the point is within the area; false otherwise.\n */\n public static isPointInArea(point: string, areaKey: string, baseType: string): boolean {\n if (baseType !== 'point') {\n console.warn(`Base type ${baseType} is not supported for point area mapping.`);\n return false;\n }\n\n // Parse the point as x and y coordinates\n const [px, py] = point.split(' ').map(Number);\n\n // Parse the area definition\n const [shape, ...coords] = areaKey.split(',');\n const coordinates = coords.map(Number);\n\n switch (shape.toLowerCase()) {\n // \"The default shape refers to the entire area of the associated image\" (QTI 3.0 §8.29), so\n // every point is inside it and the coords are not read — §7.9 says none should be given, and\n // the XSD still requires the attribute, so whatever is there is filler.\n //\n // This used to share the `circle` branch below, which demands exactly three coords and so\n // rejected any real default entry as an \"Invalid circle definition\" (Citolab/qti-components#83).\n case 'default':\n return true;\n\n case 'circle': {\n const [cx, cy, radius] = coordinates;\n if (coordinates.length !== 3) {\n console.warn(`Invalid circle definition: ${areaKey}`);\n return false;\n }\n const distance = Math.sqrt((px - cx) ** 2 + (py - cy) ** 2);\n return distance <= radius;\n }\n\n case 'rect': {\n const [x1, y1, x2, y2] = coordinates;\n if (coordinates.length !== 4) {\n console.warn(`Invalid rectangle definition: ${areaKey}`);\n return false;\n }\n return px >= x1 && px <= x2 && py >= y1 && py <= y2;\n }\n\n case 'ellipse': {\n const [cx, cy, rx, ry] = coordinates;\n if (coordinates.length !== 4) {\n console.warn(`Invalid ellipse definition: ${areaKey}`);\n return false;\n }\n // Ellipse equation: ((px - cx)² / rx²) + ((py - cy)² / ry²) <= 1\n const normalizedX = (px - cx) ** 2 / rx ** 2;\n const normalizedY = (py - cy) ** 2 / ry ** 2;\n return normalizedX + normalizedY <= 1;\n }\n\n case 'poly': {\n if (coordinates.length < 6 || coordinates.length % 2 !== 0) {\n console.warn(`Invalid polygon definition: ${areaKey}`);\n return false;\n }\n const vertices = [];\n for (let i = 0; i < coordinates.length; i += 2) {\n vertices.push({ x: coordinates[i], y: coordinates[i + 1] });\n }\n return this.isPointInPolygon({ x: px, y: py }, vertices);\n }\n\n default:\n console.warn(`Unsupported shape type: ${shape}`);\n return false;\n }\n }\n\n /**\n * Checks if a point is inside a polygon using the ray-casting algorithm.\n * @param point The point to test.\n * @param vertices The vertices of the polygon in order (array of {x, y} objects).\n * @returns True if the point is inside the polygon; false otherwise.\n */\n static isPointInPolygon(point: { x: number; y: number }, vertices: { x: number; y: number }[]): boolean {\n let inside = false;\n for (let i = 0, j = vertices.length - 1; i < vertices.length; j = i++) {\n const xi = vertices[i].x,\n yi = vertices[i].y;\n const xj = vertices[j].x,\n yj = vertices[j].y;\n\n const intersect = yi > point.y !== yj > point.y && point.x < ((xj - xi) * (point.y - yi)) / (yj - yi) + xi;\n\n if (intersect) inside = !inside;\n }\n return inside;\n }\n\n public static compareSingleValues(value1: Readonly<string>, value2: Readonly<string>, baseType: BaseType): boolean {\n switch (baseType) {\n case 'identifier':\n case 'string':\n return value1 === value2;\n case 'integer': {\n const int1 = parseInt(value1, 10);\n const int2 = parseInt(value2, 10);\n if (!isNaN(int1) && !isNaN(int2)) {\n /*\n * `parseInt` truncates, so on its own it reads \"2\" and \"2.5\" as the\n * same number. That matters because the base type is taken from one\n * operand: an expression whose result happens to be whole is an\n * integer, and it was then compared against a fractional value with\n * the fraction thrown away — `equal(divide(4, 2), 2.5)` was true.\n *\n * When either side has a fractional part the two are, by definition,\n * not the same number. Comparing them in full says so, while the\n * integer path keeps `parseInt`'s tolerance of a value like \"12 euro\"\n * for everything that really is whole.\n */\n const float1 = parseFloat(value1);\n const float2 = parseFloat(value2);\n if (!Number.isInteger(float1) || !Number.isInteger(float2)) {\n return float1 === float2;\n }\n return int1 === int2;\n } else {\n console.error(`Cannot convert ${value1} and/or ${value2} to int.`);\n }\n break;\n }\n case 'float': {\n const float1 = parseFloat(value1);\n const float2 = parseFloat(value2);\n if (!isNaN(float1) && !isNaN(float2)) {\n return float1 === float2;\n } else {\n console.error(`couldn't convert ${value1} and/or ${value2} to float.`);\n }\n break;\n }\n case 'pair':\n case 'directedPair': {\n /*\n * Only a `pair` is unordered. A `directedPair` is directed — \"A B\" and\n * \"B A\" are different values — so it must be compared as written.\n *\n * Both operands used to be sorted the moment they were split, which\n * made the `baseType === 'pair'` sort below it dead code and every\n * directedPair comparison order-insensitive: a candidate who matched\n * the right two identifiers the wrong way round scored as correct.\n */\n const pair1 = value1.split(' ');\n const pair2 = value2.split(' ');\n if (pair1.length === 2 && pair2.length === 2) {\n if (baseType === 'pair') {\n pair1.sort();\n pair2.sort();\n }\n return pair1.join(' ') === pair2.join(' ');\n } else {\n console.error(`compared two pair but one of the values does not have 2 values: 1: ${value1} 2: ${value2}`);\n }\n break;\n }\n }\n\n return false;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"scoring-helper.js","sourceRoot":"","sources":["../../src/utils/scoring-helper.ts"],"names":[],"mappings":"AAEA,MAAM,gBAAgB,GAAwC,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC;AAElH,MAAM,OAAO,aAAa;IACxB;;;;;;OAMG;IACI,MAAM,CAAC,aAAa,CAAC,KAAa,EAAE,OAAe,EAAE,QAAgB;QAC1E,IAAI,QAAQ,KAAK,OAAO,EAAE,CAAC;YACzB,OAAO,CAAC,IAAI,CAAC,aAAa,QAAQ,2CAA2C,CAAC,CAAC;YAC/E,OAAO,KAAK,CAAC;QACf,CAAC;QAED,yCAAyC;QACzC,MAAM,CAAC,EAAE,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAE9C,4BAA4B;QAC5B,MAAM,CAAC,KAAK,EAAE,GAAG,MAAM,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAC9C,MAAM,WAAW,GAAG,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAEvC,QAAQ,KAAK,CAAC,WAAW,EAAE,EAAE,CAAC;YAC5B,4FAA4F;YAC5F,6FAA6F;YAC7F,wEAAwE;YACxE,EAAE;YACF,0FAA0F;YAC1F,iGAAiG;YACjG,KAAK,SAAS;gBACZ,OAAO,IAAI,CAAC;YAEd,KAAK,QAAQ,CAAC,CAAC,CAAC;gBACd,MAAM,CAAC,EAAE,EAAE,EAAE,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AAE,CAAC;oBAC7C,IAAI,QAAQ,KAAK,MAAM,EAAE,CAAC;wBACxB,KAAK,CAAC,IAAI,EAAE,CAAC;wBACb,KAAK,CAAC,IAAI,EAAE,CAAC;oBACf,CAAC;oBACD,OAAO,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;gBAC7C,CAAC;qBAAM,CAAC;oBACN,OAAO,CAAC,KAAK,CAAC,sEAAsE,MAAM,OAAO,MAAM,EAAE,CAAC,CAAC;gBAC7G,CAAC;gBACD,MAAM;YACR,CAAC;QACH,CAAC;QAED,OAAO,KAAK,CAAC;IACf,CAAC;CACF","sourcesContent":["import type { BaseType } from '../lib/expression-result';\n\nconst SCORING_BOOLEANS: Record<string, boolean | undefined> = { true: true, '1': true, false: false, '0': false };\n\nexport class ScoringHelper {\n /**\n * Checks if a given point is within a specified area.\n * @param point The point to test, represented as a string \"x y\" (e.g., \"102 113\").\n * @param areaKey The area definition, including shape and coordinates (e.g., \"circle,102,113,16\").\n * @param baseType The base type of the response, must be \"point\" for this method to proceed.\n * @returns True if the point is within the area; false otherwise.\n */\n public static isPointInArea(point: string, areaKey: string, baseType: string): boolean {\n if (baseType !== 'point') {\n console.warn(`Base type ${baseType} is not supported for point area mapping.`);\n return false;\n }\n\n // Parse the point as x and y coordinates\n const [px, py] = point.split(' ').map(Number);\n\n // Parse the area definition\n const [shape, ...coords] = areaKey.split(',');\n const coordinates = coords.map(Number);\n\n switch (shape.toLowerCase()) {\n // \"The default shape refers to the entire area of the associated image\" (QTI 3.0 §8.29), so\n // every point is inside it and the coords are not read — §7.9 says none should be given, and\n // the XSD still requires the attribute, so whatever is there is filler.\n //\n // This used to share the `circle` branch below, which demands exactly three coords and so\n // rejected any real default entry as an \"Invalid circle definition\" (Citolab/qti-components#83).\n case 'default':\n return true;\n\n case 'circle': {\n const [cx, cy, radius] = coordinates;\n if (coordinates.length !== 3) {\n console.warn(`Invalid circle definition: ${areaKey}`);\n return false;\n }\n const distance = Math.sqrt((px - cx) ** 2 + (py - cy) ** 2);\n return distance <= radius;\n }\n\n case 'rect': {\n const [x1, y1, x2, y2] = coordinates;\n if (coordinates.length !== 4) {\n console.warn(`Invalid rectangle definition: ${areaKey}`);\n return false;\n }\n return px >= x1 && px <= x2 && py >= y1 && py <= y2;\n }\n\n case 'ellipse': {\n const [cx, cy, rx, ry] = coordinates;\n if (coordinates.length !== 4) {\n console.warn(`Invalid ellipse definition: ${areaKey}`);\n return false;\n }\n // Ellipse equation: ((px - cx)² / rx²) + ((py - cy)² / ry²) <= 1\n const normalizedX = (px - cx) ** 2 / rx ** 2;\n const normalizedY = (py - cy) ** 2 / ry ** 2;\n return normalizedX + normalizedY <= 1;\n }\n\n case 'poly': {\n if (coordinates.length < 6 || coordinates.length % 2 !== 0) {\n console.warn(`Invalid polygon definition: ${areaKey}`);\n return false;\n }\n const vertices = [];\n for (let i = 0; i < coordinates.length; i += 2) {\n vertices.push({ x: coordinates[i], y: coordinates[i + 1] });\n }\n return this.isPointInPolygon({ x: px, y: py }, vertices);\n }\n\n default:\n console.warn(`Unsupported shape type: ${shape}`);\n return false;\n }\n }\n\n /**\n * Checks if a point is inside a polygon using the ray-casting algorithm.\n * @param point The point to test.\n * @param vertices The vertices of the polygon in order (array of {x, y} objects).\n * @returns True if the point is inside the polygon; false otherwise.\n */\n static isPointInPolygon(point: { x: number; y: number }, vertices: { x: number; y: number }[]): boolean {\n let inside = false;\n for (let i = 0, j = vertices.length - 1; i < vertices.length; j = i++) {\n const xi = vertices[i].x,\n yi = vertices[i].y;\n const xj = vertices[j].x,\n yj = vertices[j].y;\n\n const intersect = yi > point.y !== yj > point.y && point.x < ((xj - xi) * (point.y - yi)) / (yj - yi) + xi;\n\n if (intersect) inside = !inside;\n }\n return inside;\n }\n\n public static compareSingleValues(value1: Readonly<string>, value2: Readonly<string>, baseType: BaseType): boolean {\n switch (baseType) {\n case 'identifier':\n case 'string':\n return value1 === value2;\n case 'boolean': {\n // XML Schema booleans: \"true\" / \"1\" and \"false\" / \"0\"\n const bool1 = SCORING_BOOLEANS[value1.trim().toLowerCase()];\n return bool1 !== undefined && bool1 === SCORING_BOOLEANS[value2.trim().toLowerCase()];\n }\n case 'integer': {\n const int1 = parseInt(value1, 10);\n const int2 = parseInt(value2, 10);\n if (!isNaN(int1) && !isNaN(int2)) {\n /*\n * `parseInt` truncates, so on its own it reads \"2\" and \"2.5\" as the\n * same number. That matters because the base type is taken from one\n * operand: an expression whose result happens to be whole is an\n * integer, and it was then compared against a fractional value with\n * the fraction thrown away — `equal(divide(4, 2), 2.5)` was true.\n *\n * When either side has a fractional part the two are, by definition,\n * not the same number. Comparing them in full says so, while the\n * integer path keeps `parseInt`'s tolerance of a value like \"12 euro\"\n * for everything that really is whole.\n */\n const float1 = parseFloat(value1);\n const float2 = parseFloat(value2);\n if (!Number.isInteger(float1) || !Number.isInteger(float2)) {\n return float1 === float2;\n }\n return int1 === int2;\n } else {\n console.error(`Cannot convert ${value1} and/or ${value2} to int.`);\n }\n break;\n }\n case 'float': {\n const float1 = parseFloat(value1);\n const float2 = parseFloat(value2);\n if (!isNaN(float1) && !isNaN(float2)) {\n return float1 === float2;\n } else {\n console.error(`couldn't convert ${value1} and/or ${value2} to float.`);\n }\n break;\n }\n case 'pair':\n case 'directedPair': {\n /*\n * Only a `pair` is unordered. A `directedPair` is directed — \"A B\" and\n * \"B A\" are different values — so it must be compared as written.\n *\n * Both operands used to be sorted the moment they were split, which\n * made the `baseType === 'pair'` sort below it dead code and every\n * directedPair comparison order-insensitive: a candidate who matched\n * the right two identifiers the wrong way round scored as correct.\n */\n const pair1 = value1.split(' ');\n const pair2 = value2.split(' ');\n if (pair1.length === 2 && pair2.length === 2) {\n if (baseType === 'pair') {\n pair1.sort();\n pair2.sort();\n }\n return pair1.join(' ') === pair2.join(' ');\n } else {\n console.error(`compared two pair but one of the values does not have 2 values: 1: ${value1} 2: ${value2}`);\n }\n break;\n }\n }\n\n return false;\n }\n}\n"]}
|