@astl/engine 0.2.3 → 0.3.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.
package/src/checker.ts CHANGED
@@ -22,7 +22,7 @@ import {
22
22
  type SubmitRequest,
23
23
  type SubmitResponse,
24
24
  } from '@astl/core';
25
- import { helpShown, hintCount, isGradedElement, nextHint, resultHelp } from './help.js';
25
+ import { areGradedElements, helpShown, hintCount, isGradedElement, nextHint, resultHelp } from './help.js';
26
26
  import { round6 } from './round.js';
27
27
 
28
28
  export interface LocalChecker extends Checker {
@@ -89,20 +89,33 @@ export function localChecker(
89
89
  return { ...used };
90
90
  },
91
91
  async check(request: CheckRequest): Promise<CheckResponse> {
92
- const { page, element } = request;
92
+ const { page, element, elements } = request;
93
93
  if (policy.mode !== 'practice') throw problem(ProblemCode.checkNotAllowed);
94
94
  if (submitted) throw problem(ProblemCode.attemptClosed);
95
- if (page !== undefined && element !== undefined) throw problem(ProblemCode.invalidRequest);
96
- if (element !== undefined && helpPolicy(policy).checkScope !== 'interaction') {
95
+ if ([page, element, elements].filter((scope) => scope !== undefined).length > 1) {
96
+ throw problem(ProblemCode.invalidRequest);
97
+ }
98
+ if (
99
+ (element !== undefined || elements !== undefined) &&
100
+ helpPolicy(policy).checkScope !== 'interaction'
101
+ ) {
97
102
  throw problem(ProblemCode.checkNotAllowed);
98
103
  }
99
104
  if (page !== undefined && !key.pages.includes(page)) throw problem(ProblemCode.notFound);
100
105
  if (element !== undefined && !isGradedElement(key, element)) throw problem(ProblemCode.notFound);
106
+ if (elements !== undefined && !areGradedElements(key, elements)) throw problem(ProblemCode.notFound);
101
107
  if (checksLeft() === 0) throw problem(ProblemCode.checksExhausted);
102
108
  checks++;
103
- const scope = page !== undefined ? { page } : element !== undefined ? { element } : {};
109
+ const scope =
110
+ page !== undefined
111
+ ? { page }
112
+ : element !== undefined
113
+ ? { element }
114
+ : elements !== undefined
115
+ ? { elements }
116
+ : {};
104
117
  const result = engine.grade(key, request.answers, { ...scope, hintsUsed: { ...used } });
105
- const help = resultHelp(key, result, helpShown(policy, 'check'), element);
118
+ const help = resultHelp(key, result, helpShown(policy, 'check'), element ?? elements);
106
119
  return { result, checksLeft: checksLeft(), ...help };
107
120
  },
108
121
  async hint(request: HintRequest): Promise<HintResponse> {
package/src/compile.ts CHANGED
@@ -4,6 +4,9 @@
4
4
  import {
5
5
  type AnswerKey,
6
6
  BLOCK_TAGS,
7
+ CHECK_FOR_ATTRIBUTE,
8
+ CHECK_LABEL_ATTRIBUTE,
9
+ CHECK_TAG,
7
10
  type Compilation,
8
11
  type CompileContext,
9
12
  type ComponentManifest,
@@ -83,6 +86,7 @@ export async function compileDocument(doc: DocRecord, setup: CompileSetup): Prom
83
86
  paths.push(elementPath(rec.sourceId));
84
87
  for (const local of localsOf(rec)) paths.push(elementPath(rec.sourceId, local));
85
88
  }
89
+ for (const check of doc.checks.values()) paths.push(elementPath(check.sourceId));
86
90
  const digestList = await Promise.all(paths.map((p) => setup.hmac(idMessage(setup.salt, p))));
87
91
  const digests = new Map<string, Uint8Array>();
88
92
  const ids = new Map<string, string>();
@@ -133,10 +137,28 @@ export async function compileDocument(doc: DocRecord, setup: CompileSetup): Prom
133
137
  if (costs.some((c) => c > 0)) costly.push({ attrs, id, costs });
134
138
  return attrs;
135
139
  };
140
+ /** A Check element: its opaque id, its questions' opaque ids in `for`; one with nothing to check is left out. */
141
+ const viewCheck = (node: ElementNode): Node[] => {
142
+ const check = doc.checks.get(node);
143
+ if (check === undefined || check.targets.length === 0) return [];
144
+ const attrs: Record<string, string> = {
145
+ id: idOf(elementPath(check.sourceId)),
146
+ [CHECK_FOR_ATTRIBUTE]: check.targets.map((target) => idOf(elementPath(target))).join(' '),
147
+ };
148
+ for (const name of [CHECK_LABEL_ATTRIBUTE, 'lang', 'dir']) {
149
+ const value = own(node.attrs, name);
150
+ if (value !== undefined) attrs[name] = value;
151
+ }
152
+ return [element(CHECK_TAG, attrs, [])];
153
+ };
154
+ const viewNodes = (nodes: readonly Node[]): Node[] =>
155
+ nodes.flatMap((node) =>
156
+ node.type === 'element' && node.tag === CHECK_TAG ? viewCheck(node) : [viewNode(node)],
157
+ );
136
158
  const viewNode = (node: Node): Node => {
137
159
  if (node.type === 'text') return node;
138
160
  const rec = doc.components.get(node);
139
- if (rec === undefined) return element(node.tag, node.attrs, node.children.map(viewNode));
161
+ if (rec === undefined) return element(node.tag, node.attrs, viewNodes(node.children));
140
162
  const ctx = contextOf(rec);
141
163
  const view = rec.definition.toView(rec.element, ctx);
142
164
  guardView(view, rec.element, rec.definition.manifest, { id: ctx.opaque(), urlPolicy: setup.urlPolicy });
@@ -149,13 +171,13 @@ export async function compileDocument(doc: DocRecord, setup: CompileSetup): Prom
149
171
  const value = own(page.attrs, name);
150
172
  if (name !== 'id' && value !== undefined) attrs[name] = value;
151
173
  }
152
- const children = page.children.map(viewNode);
174
+ const children = viewNodes(page.children);
153
175
  return element(PAGE_TAG, offer(id, doc.pages[index]?.help ?? null, attrs), children);
154
176
  };
155
177
  const children = doc.explicitPages
156
- ? doc.root.children.map((n) => {
178
+ ? doc.root.children.flatMap((n) => {
157
179
  const index = n.type === 'element' ? doc.pageNodes.get(n) : undefined;
158
- return index === undefined || n.type !== 'element' ? viewNode(n) : viewPage(n, index);
180
+ return index === undefined || n.type !== 'element' ? viewNodes([n]) : [viewPage(n, index)];
159
181
  })
160
182
  : [
161
183
  viewPage(
package/src/grade.ts CHANGED
@@ -77,10 +77,13 @@ function elementOf(key: AnswerKey, group: ScoringGroup): string | undefined {
77
77
 
78
78
  function groupsFor(key: AnswerKey, options: GradeOptions): readonly ScoringGroup[] {
79
79
  const { page, element } = options;
80
- return key.groups.filter(
81
- (g) =>
82
- (page === undefined || g.page === page) && (element === undefined || elementOf(key, g) === element),
83
- );
80
+ const elements = options.elements === undefined ? null : new Set(options.elements);
81
+ return key.groups.filter((g) => {
82
+ if (page !== undefined && g.page !== page) return false;
83
+ if (element === undefined && elements === null) return true;
84
+ const owner = elementOf(key, g);
85
+ return owner !== undefined && (owner === element || (elements?.has(owner) ?? false));
86
+ });
84
87
  }
85
88
 
86
89
  /**
@@ -167,10 +170,10 @@ export function gradeKey(
167
170
  assertKey(key);
168
171
  const input: object = typeof answers === 'object' && answers !== null ? answers : {};
169
172
  const groups = groupsFor(key, options);
170
- // A check of one element reports its page's score of that element only.
173
+ // A check of one element (or of a Check element's questions) reports its page's score of those only.
171
174
  const graded = new Set(groups.map((g) => g.page));
172
175
  const pageIds =
173
- options.element !== undefined
176
+ options.element !== undefined || options.elements !== undefined
174
177
  ? key.pages.filter((p) => graded.has(p))
175
178
  : options.page === undefined
176
179
  ? key.pages
package/src/help.ts CHANGED
@@ -64,6 +64,16 @@ export function isGradedElement(key: AnswerKey, id: string): boolean {
64
64
  return [...elementsOf(key).values()].includes(id);
65
65
  }
66
66
 
67
+ /**
68
+ * Whether `ids` name graded view elements of the key, each of them: what a check of a Check element's questions may
69
+ * name (at least one, and no more than the key has).
70
+ */
71
+ export function areGradedElements(key: AnswerKey, ids: unknown): ids is readonly string[] {
72
+ if (!Array.isArray(ids) || ids.length === 0) return false;
73
+ const graded = new Set(elementsOf(key).values());
74
+ return ids.length <= graded.size && ids.every((id) => typeof id === 'string' && graded.has(id));
75
+ }
76
+
67
77
  /**
68
78
  * One verdict for several groups (an element graded in parts, a page): nothing answered is `empty`, everything right
69
79
  * `correct`, something right `partial`, else `incorrect`.
@@ -83,14 +93,15 @@ function feedbackFor(help: KeyHelp, verdict: GroupVerdict): Feedback | null {
83
93
 
84
94
  /**
85
95
  * The help a result brings, for what it graded: each graded element's feedback for its verdict and its explanation,
86
- * and, unless one element was checked (`element`), each graded page's own, its feedback picked by the page's overall
87
- * verdict. `shown` says which of the two the policy gives now (`helpShown`). Empty parts are left out.
96
+ * and, unless one element or a Check element's questions were checked (`element`), each graded page's own, its
97
+ * feedback picked by the page's overall verdict. `shown` says which of the two the policy gives now (`helpShown`).
98
+ * Empty parts are left out.
88
99
  */
89
100
  export function resultHelp(
90
101
  key: AnswerKey,
91
102
  result: GradeResult,
92
103
  shown: { readonly feedback: boolean; readonly explanations: boolean },
93
- element?: string,
104
+ element?: string | readonly string[],
94
105
  ): ResultHelp {
95
106
  if (key.help === undefined || (!shown.feedback && !shown.explanations)) return {};
96
107
  const elements = elementsOf(key);
package/src/index.ts CHANGED
@@ -3,7 +3,7 @@ export { localChecker } from './checker.js';
3
3
  export type { Leak, RefResolver } from './conformance.js';
4
4
  export { leakProbe, refResolver } from './conformance.js';
5
5
  export { createEngine } from './engine.js';
6
- export { helpShown, hintCount, isGradedElement, nextHint, resultHelp } from './help.js';
6
+ export { areGradedElements, helpShown, hintCount, isGradedElement, nextHint, resultHelp } from './help.js';
7
7
  export { parseHtml, serializeHtml } from './html.js';
8
8
  export * as kit from './kit/index.js';
9
9
  export { engineMessages } from './messages.js';
@@ -45,5 +45,10 @@
45
45
  "HINT_COST_INVALID": "The cost of a hint is a fraction of the points from 0 to 1, such as 0.25, not “{value}”.",
46
46
  "FEEDBACK_WHEN_INVALID": "Feedback is for one verdict: when=\"correct\", \"incorrect\", \"partial\" or \"omitted\", not “{value}”.",
47
47
  "FEEDBACK_DUPLICATE": "There are two feedback texts for the verdict “{when}” here. Keep one.",
48
- "EXPLANATION_DUPLICATE": "There are two explanations here. Keep one."
48
+ "EXPLANATION_DUPLICATE": "There are two explanations here. Keep one.",
49
+ "CHECK_EMPTY": "The Check button {check} has no questions to check: pick them in its card, or put it right under the sentences with gaps. Until then it does not show.",
50
+ "CHECK_TARGET_UNKNOWN": "The Check button {check} names {id}, but nothing in the exercise has that id: it is left out.",
51
+ "CHECK_TARGET_NOT_GRADED": "The Check button {check} names {id}, which is not a question to check: it is left out.",
52
+ "CHECK_TARGET_OTHER_PAGE": "The Check button {check} names question {id} on another page: a Check button checks questions of its own page, so it is left out.",
53
+ "CHECK_TARGET_TWICE": "Question {id} has a Check button already: the Check button {check} leaves it out."
49
54
  }
@@ -45,5 +45,10 @@
45
45
  "HINT_COST_INVALID": "Koszt podpowiedzi to część punktów od 0 do 1, np. 0.25, a nie „{value}”.",
46
46
  "FEEDBACK_WHEN_INVALID": "Informacja zwrotna dotyczy jednego wyniku: when=\"correct\", \"incorrect\", \"partial\" albo \"omitted\", a nie „{value}”.",
47
47
  "FEEDBACK_DUPLICATE": "Są tu dwie informacje zwrotne dla wyniku „{when}”. Zostaw jedną.",
48
- "EXPLANATION_DUPLICATE": "Są tu dwa wyjaśnienia. Zostaw jedno."
48
+ "EXPLANATION_DUPLICATE": "Są tu dwa wyjaśnienia. Zostaw jedno.",
49
+ "CHECK_EMPTY": "Przycisk Sprawdź {check} nie ma pytań do sprawdzenia: wybierz je w jego karcie albo postaw go zaraz pod zdaniami z lukami. Do tego czasu się nie pokazuje.",
50
+ "CHECK_TARGET_UNKNOWN": "Przycisk Sprawdź {check} wskazuje {id}, ale nic w ćwiczeniu nie ma takiego identyfikatora: jest pominięty.",
51
+ "CHECK_TARGET_NOT_GRADED": "Przycisk Sprawdź {check} wskazuje {id}, a to nie jest pytanie do sprawdzenia: jest pominięty.",
52
+ "CHECK_TARGET_OTHER_PAGE": "Przycisk Sprawdź {check} wskazuje pytanie {id} z innej strony: przycisk Sprawdź sprawdza pytania ze swojej strony, więc je pomija.",
53
+ "CHECK_TARGET_TWICE": "Pytanie {id} ma już swój przycisk Sprawdź: przycisk Sprawdź {check} je pomija."
49
54
  }