@qti-components/base 2.4.0 → 2.4.1
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.
|
@@ -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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OAOG;IACO,eAAe,CAAC,UAAkB;QAC1C,OAAO,CACL,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,IAAI,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,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,CAA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IAsBD;;;;;;;OAOG;IACO,eAAe,CAAC,UAAkB;QAC1C,OAAO,CACL,IAAI,CAAC,OAAO,EAAE,SAAS,CAAC,IAAI,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"]}
|
|
@@ -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;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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H,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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,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"]}
|