@astl/player 0.2.3 → 0.3.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.
@@ -9,6 +9,9 @@
9
9
  * paragraph holds other fields, their rows under each other after it; the end of the name is hidden otherwise);
10
10
  * - the feedback text of the last verdict, in a box of the verdict's colour and edge;
11
11
  * - "Dlaczego?", a disclosure with the explanation.
12
+ * A Check element (`astl-check`) checks its questions at once, as one check, from a row where it is, and they have no
13
+ * Check of their own; so does an automatic one, after the last of the questions of a run of text (paragraphs, lists,
14
+ * headings ending it) that no Check element has, when there are two or more ("Sprawdź", then "2 z 3 poprawnie").
12
15
  * At the foot of each page with help of its own, or with `check`, a row like it whose "Sprawdź tę stronę" checks the
13
16
  * page's questions at once (practice checking one question at a time); the page's feedback and explanation come only
14
17
  * with a check of the page or of everything, never with one question's. Once every question has a result, from its own
@@ -20,10 +23,16 @@
20
23
  */
21
24
  import {
22
25
  type AttemptPolicy,
26
+ CHECK_FOR_ATTRIBUTE,
27
+ CHECK_LABEL_ATTRIBUTE,
28
+ CHECK_TAG,
23
29
  type Checker,
24
30
  CheckerError,
25
31
  type CheckResponse,
32
+ type CheckTree,
26
33
  type ComponentManifest,
34
+ checkFor,
35
+ checkParts,
27
36
  createI18n,
28
37
  type ElementHelp,
29
38
  FEEDBACK_VARIANTS,
@@ -36,6 +45,7 @@ import {
36
45
  type MessageCatalog,
37
46
  PAGE_CHECK_ATTRIBUTE,
38
47
  type PlayerElementApi,
48
+ planChecks,
39
49
  type SubmitResponse,
40
50
  type Translate,
41
51
  type UrlPolicy,
@@ -74,6 +84,8 @@ export interface HelpHost {
74
84
  checker(): Checker | null;
75
85
  /** Checks one interaction or one page through the player, which shows a failure; resolves either way. */
76
86
  check(id: string): Promise<unknown>;
87
+ /** Checks several interactions at once, as one check (a Check element's questions); resolves either way. */
88
+ checkMany(ids: readonly string[]): Promise<unknown>;
77
89
  /**
78
90
  * The overall result composed from the latest checks once every question has one, null while one has none; returns
79
91
  * what to say of it, which the module says with the check that completed it.
@@ -192,6 +204,18 @@ interface Row {
192
204
  explanation: HTMLElement | null;
193
205
  }
194
206
 
207
+ /** A Check element's row, or an automatic one's: one Check for its questions, then how they came out. */
208
+ interface CheckRow {
209
+ /** Its questions, view element ids, in the order it names them. */
210
+ readonly targets: readonly string[];
211
+ readonly box: HTMLElement;
212
+ /** Its button's text: the check's `label`, else "Check". */
213
+ readonly label: string;
214
+ /** The language of an author's label (the content's), else null (UI text). */
215
+ readonly lang: string | null;
216
+ readonly summaryId: string;
217
+ }
218
+
195
219
  /** Where an element's row goes: after the block of the page (or column) that holds it. */
196
220
  function anchorOf(element: Element): Element {
197
221
  let anchor = element;
@@ -275,6 +299,40 @@ export function mountHelp(host: HelpHost): Help {
275
299
  const each = practice && help.checkScope === 'interaction';
276
300
  const isGraded = ({ element, manifest }: HelpHost['mounted'][number]) =>
277
301
  manifest.graded && element.slotIds.length > 0;
302
+ // There a Check element checks its questions at once, as one check, and they have no Check of their own; its row
303
+ // sits in it. Elsewhere it does not show.
304
+ const questionIds = new Set(host.mounted.filter(isGraded).map(({ element }) => element.id));
305
+ const explicit = each
306
+ ? host.pages.flatMap((page) =>
307
+ Array.from(page.querySelectorAll<HTMLElement>(CHECK_TAG), (element) => ({
308
+ element,
309
+ targets: checkFor(element.getAttribute(CHECK_FOR_ATTRIBUTE)).filter((id) => questionIds.has(id)),
310
+ })).filter((check) => check.targets.length > 0),
311
+ )
312
+ : [];
313
+ // The questions of a run of text that no Check element has, two or more, share an automatic one after the last of
314
+ // them: the rule of the engine and the editor (`planChecks`), over the view in the DOM. A view's checks name their
315
+ // questions (`for`), as the engine resolved them.
316
+ const byElement = new Map<Element, HelpHost['mounted'][number]>(host.mounted.map((m) => [m.element, m]));
317
+ const tree: CheckTree<Element> = {
318
+ tag: (node) => node.localName,
319
+ children: (node) => Array.from(node.children),
320
+ component: (node) => {
321
+ const mounted = byElement.get(node);
322
+ if (mounted === undefined) return null;
323
+ return { id: node.id || null, graded: isGraded(mounted), block: mounted.manifest.display === 'block' };
324
+ },
325
+ checkFor: (node) =>
326
+ node.hasAttribute(CHECK_FOR_ATTRIBUTE)
327
+ ? checkFor(node.getAttribute(CHECK_FOR_ATTRIBUTE)).filter((id) => questionIds.has(id))
328
+ : null,
329
+ };
330
+ const automatic = each
331
+ ? host.pages.flatMap((page) =>
332
+ planChecks(checkParts(Array.from(page.children), tree)).uncovered.filter((run) => run.length > 1),
333
+ )
334
+ : [];
335
+ const covered = new Set([...explicit.flatMap((check) => check.targets), ...automatic.flat()]);
278
336
  // The graded fields in a line of text per block: their rows sit under each other after it.
279
337
  const fields = new Map<Element, number>();
280
338
  for (const mounted of host.mounted) {
@@ -294,7 +352,12 @@ export function mountHelp(host: HelpHost): Help {
294
352
  const anchor = anchorOf(element);
295
353
  const entry = row(element, offer, {
296
354
  label: inline ? t('help.labelField', { n }) : t('help.label'),
297
- check: each && graded ? (inline ? t('help.checkField', { n }) : t('help.check')) : null,
355
+ check:
356
+ each && graded && !covered.has(element.id)
357
+ ? inline
358
+ ? t('help.checkField', { n })
359
+ : t('help.check')
360
+ : null,
298
361
  named: inline && (fields.get(anchor) ?? 0) > 1,
299
362
  ownVerdict: !inline,
300
363
  groups: [element.id, ...(element.groupIds ?? [])],
@@ -322,6 +385,50 @@ export function mountHelp(host: HelpHost): Help {
322
385
  page.append(entry.box);
323
386
  });
324
387
 
388
+ const checkRows: CheckRow[] = [];
389
+ const checkRow = (
390
+ box: HTMLElement,
391
+ targets: readonly string[],
392
+ label: string | null,
393
+ lang: string | null,
394
+ auto = false,
395
+ ) => {
396
+ box.className = 'astl-help';
397
+ box.setAttribute('part', 'help check');
398
+ box.dataset.check = auto ? 'auto' : '';
399
+ box.lang = locale;
400
+ const own = label?.trim() ?? '';
401
+ checkRows.push({
402
+ targets,
403
+ box,
404
+ label: own === '' ? t('action.check') : own,
405
+ lang: own === '' ? null : lang,
406
+ summaryId: `astl-check-summary-${checkRows.length}`,
407
+ });
408
+ };
409
+ for (const { element, targets } of explicit) {
410
+ const box = document.createElement('div');
411
+ element.dataset.shown = '';
412
+ element.append(box);
413
+ checkRow(
414
+ box,
415
+ targets,
416
+ element.getAttribute(CHECK_LABEL_ATTRIBUTE),
417
+ element.closest('[lang]')?.getAttribute('lang') ?? null,
418
+ );
419
+ }
420
+ const elementOf = new Map(host.mounted.map(({ element }) => [element.id, element]));
421
+ for (const run of automatic) {
422
+ const last = elementOf.get(run.at(-1) ?? '');
423
+ if (last === undefined) continue;
424
+ const box = document.createElement('div');
425
+ const anchor = anchorOf(last);
426
+ (after.get(anchor) ?? anchor).after(box);
427
+ after.set(anchor, box);
428
+ place(box, anchor);
429
+ checkRow(box, run, null, null, true);
430
+ }
431
+
325
432
  const content = (value: unknown, entry: Row): HTMLElement | null => {
326
433
  if (typeof value !== 'string') return null;
327
434
  const shown = readContent(value, host.urlPolicy);
@@ -330,12 +437,12 @@ export function mountHelp(host: HelpHost): Help {
330
437
  return shown;
331
438
  };
332
439
 
333
- /** Takes in what a response says of the rows it graded (`only`: a check of one interaction). */
334
- const apply = (response: CheckResponse | SubmitResponse, only: string | null): void => {
440
+ /** Takes in what a response says of the rows it graded (`only`: a check of one interaction, or of a few). */
441
+ const apply = (response: CheckResponse | SubmitResponse, only: ReadonlySet<string> | null): void => {
335
442
  const result: GradeResult | null = response.result;
336
443
  if (result === null) return;
337
444
  for (const entry of rows) {
338
- if (only !== null && entry.id !== only) continue;
445
+ if (only !== null && !only.has(entry.id)) continue;
339
446
  const verdicts = result.groups.filter((g) => entry.groups.includes(g.id)).map((g) => g.verdict);
340
447
  const graded = entry.groups.length === 0 ? Object.hasOwn(result.pages, entry.id) : verdicts.length > 0;
341
448
  if (!graded) continue;
@@ -352,6 +459,42 @@ export function mountHelp(host: HelpHost): Help {
352
459
 
353
460
  const update = (): void => {
354
461
  for (const entry of rows) render(view(entry), entry.box);
462
+ for (const check of checkRows) render(checkView(check), check.box);
463
+ };
464
+
465
+ /** How a check's questions came out ("2 of 3 correct"), once each has a result; null while one has none. */
466
+ const summaryOf = (check: CheckRow): string | null => {
467
+ const results = check.targets.map((id) => {
468
+ const entry = rows.find((r) => r.id === id);
469
+ return entry === undefined ? undefined : latest.get(entry);
470
+ });
471
+ if (results.some((groups) => groups === undefined)) return null;
472
+ const correct = results.filter(
473
+ (groups) => overall((groups ?? []).map((g) => g.verdict)) === 'correct',
474
+ ).length;
475
+ return t('help.checkSummary', { correct, total: check.targets.length });
476
+ };
477
+
478
+ const checkView = (check: CheckRow): TemplateResult | typeof nothing => {
479
+ check.box.hidden = controller.readOnly;
480
+ if (controller.readOnly) return nothing;
481
+ const summary = summaryOf(check);
482
+ return html`<div class="help-actions">
483
+ <button
484
+ type="button"
485
+ class="button"
486
+ aria-describedby=${summary === null ? nothing : check.summaryId}
487
+ aria-disabled=${controller.canCheck() ? nothing : 'true'}
488
+ @click=${() => {
489
+ if (controller.canCheck()) void host.checkMany(check.targets);
490
+ }}
491
+ >
492
+ <span lang=${check.lang ?? nothing}>${check.label}</span><span class="astl-vh">
493
+ ${t('help.checkMany', { count: check.targets.length })}</span
494
+ >
495
+ </button>
496
+ ${summary === null ? nothing : html`<span class="help-summary" part="check-summary" id=${check.summaryId}>${summary}</span>`}
497
+ </div>`;
355
498
  };
356
499
 
357
500
  const ask = async (entry: Row): Promise<void> => {
@@ -502,8 +645,9 @@ export function mountHelp(host: HelpHost): Help {
502
645
  const latest = new Map<Row, readonly GroupResult[]>();
503
646
  const questions = each ? rows.filter((r) => r.groups.length > 0) : [];
504
647
  let composed = false;
505
- const take = (response: CheckResponse | SubmitResponse): void => {
648
+ const take = (response: CheckResponse | SubmitResponse, only: ReadonlySet<string> | null = null): void => {
506
649
  for (const entry of questions) {
650
+ if (only !== null && !only.has(entry.id)) continue;
507
651
  const own = response.result?.groups.filter((g) => entry.groups.includes(g.id)) ?? [];
508
652
  if (own.length > 0) latest.set(entry, own);
509
653
  }
@@ -552,9 +696,18 @@ export function mountHelp(host: HelpHost): Help {
552
696
  // The player says a whole result itself.
553
697
  compose();
554
698
  } else if (change.type === 'element') {
555
- apply(change.response, change.id);
699
+ apply(change.response, new Set([change.id]));
556
700
  take(change.response);
557
701
  say(told(rows.find((r) => r.id === change.id)), compose());
702
+ } else if (change.type === 'elements') {
703
+ // Only its questions: a server that does not know `elements` grades everything, and the rest is not asked.
704
+ const ids = new Set(change.ids);
705
+ apply(change.response, ids);
706
+ take(change.response, ids);
707
+ const check = checkRows.find(
708
+ (c) => c.targets.length === ids.size && c.targets.every((id) => ids.has(id)),
709
+ );
710
+ say(check === undefined ? null : summaryOf(check), compose());
558
711
  } else if (change.type === 'page-check') {
559
712
  apply(change.response, null);
560
713
  take(change.response);
@@ -593,6 +746,10 @@ export function mountHelp(host: HelpHost): Help {
593
746
  destroy() {
594
747
  unsubscribe();
595
748
  for (const entry of rows) entry.box.remove();
749
+ for (const check of checkRows) {
750
+ check.box.parentElement?.removeAttribute('data-shown');
751
+ check.box.remove();
752
+ }
596
753
  },
597
754
  };
598
755
  }
@@ -614,6 +771,12 @@ const helpSheet = css`
614
771
  .canvas .astl-help[hidden] {
615
772
  display: none;
616
773
  }
774
+ .canvas astl-check[data-shown] {
775
+ display: block;
776
+ }
777
+ .help-summary {
778
+ font-weight: 600;
779
+ }
617
780
  .canvas .astl-help[data-page] {
618
781
  clear: both;
619
782
  padding-block-start: var(--astl-space-3);
@@ -6,6 +6,8 @@ import {
6
6
  type Answers,
7
7
  type AttemptPolicy,
8
8
  type AttemptState,
9
+ CHECK_FOR_ATTRIBUTE,
10
+ CHECK_TAG,
9
11
  type ChangeDetail,
10
12
  type Checker,
11
13
  CheckerError,
@@ -13,6 +15,7 @@ import {
13
15
  COLUMN_TAG,
14
16
  COLUMNS_TAG,
15
17
  type ComponentManifest,
18
+ checkFor,
16
19
  createI18n,
17
20
  directionOf,
18
21
  type ErrorDetail,
@@ -263,20 +266,45 @@ export class AstlPlayer extends LitElement {
263
266
 
264
267
  /**
265
268
  * Practice: grades the answers and shows verdicts; with `id`, a view page (its questions at once) or, under a policy
266
- * with `checkScope: 'interaction'`, a view element (that interaction only): neither is an `astl-result`. Failures are
267
- * shown and emitted, never thrown.
269
+ * with `checkScope: 'interaction'`, a view element (that interaction only) or a Check element (its questions at once,
270
+ * one check): none of them is an `astl-result`. Failures are shown and emitted, never thrown.
268
271
  */
269
272
  async check(id?: string): Promise<CheckResponse | null> {
270
273
  const controller = this.#controller;
271
274
  if (controller === null) return null;
275
+ const check = id === undefined ? null : this.#checkElement(id);
276
+ if (check !== null) return this.#checkMany(checkFor(check.getAttribute(CHECK_FOR_ATTRIBUTE)));
277
+ return this.#run(() =>
278
+ id === undefined || controller.pages.some((p) => p.id === id)
279
+ ? controller.check(id)
280
+ : controller.checkElement(id),
281
+ );
282
+ }
283
+
284
+ /** A Check element of the mounted view by its view id, or null. */
285
+ #checkElement(id: string): Element | null {
286
+ const content = this.#query('.canvas');
287
+ return Array.from(content?.querySelectorAll(CHECK_TAG) ?? []).find((el) => el.id === id) ?? null;
288
+ }
289
+
290
+ /** Several interactions at once, as one check (a Check element's questions, or a group of fields). */
291
+ #checkMany(ids: readonly string[]): Promise<CheckResponse | null> {
292
+ return this.#run(() => {
293
+ const controller = this.#controller as AttemptController;
294
+ return controller.checkElements(ids);
295
+ });
296
+ }
297
+
298
+ /** Runs a check with the player's checker; a failure is shown and emitted, never thrown. */
299
+ async #run(check: () => Promise<CheckResponse>): Promise<CheckResponse | null> {
300
+ if (this.#controller === null) return null;
272
301
  this.#problem = null;
273
302
  if (this.#effectiveChecker() === null) {
274
303
  this.#showProblem('no_checker');
275
304
  return null;
276
305
  }
277
306
  try {
278
- if (id === undefined || controller.pages.some((p) => p.id === id)) return await controller.check(id);
279
- return await controller.checkElement(id);
307
+ return await check();
280
308
  } catch (error) {
281
309
  this.#showProblem(codeOf(error, 'internal_error'));
282
310
  return null;
@@ -987,6 +1015,7 @@ export class AstlPlayer extends LitElement {
987
1015
  root: this.renderRoot,
988
1016
  checker: () => this.#effectiveChecker(),
989
1017
  check: (id) => this.check(id),
1018
+ checkMany: (ids) => this.#checkMany(ids),
990
1019
  overall: (response) => {
991
1020
  this.#overall = response;
992
1021
  this.requestUpdate();
@@ -1032,6 +1061,8 @@ export class AstlPlayer extends LitElement {
1032
1061
  this.#collect(child, found, notice);
1033
1062
  continue;
1034
1063
  }
1064
+ // A Check element is no component: the help module draws it.
1065
+ if (tag === CHECK_TAG) continue;
1035
1066
  const registration = runtime.elements.get(tag);
1036
1067
  const version = Number.parseInt(child.getAttribute('v') ?? '1', 10);
1037
1068
  if (
@@ -1077,6 +1108,11 @@ export class AstlPlayer extends LitElement {
1077
1108
  this.#applyResult(change.response);
1078
1109
  this.#scheduleSnapshot();
1079
1110
  break;
1111
+ case 'elements':
1112
+ // Only its questions: a server that does not know `elements` grades everything, and the rest is not asked.
1113
+ this.#applyResult(change.response, new Set(change.ids));
1114
+ this.#scheduleSnapshot();
1115
+ break;
1080
1116
  case 'reset':
1081
1117
  for (const { element } of this.#mounted) {
1082
1118
  element.setAnswers(Object.fromEntries(element.slotIds.map((id) => [id, ''])));
@@ -1096,7 +1132,7 @@ export class AstlPlayer extends LitElement {
1096
1132
  * announces the summary. With `checked`, the response of a check of one element or one page: the verdicts of the
1097
1133
  * elements it graded, no summary.
1098
1134
  */
1099
- #applyResult(checked?: CheckResponse): void {
1135
+ #applyResult(checked?: CheckResponse, only?: ReadonlySet<string>): void {
1100
1136
  const controller = this.#controller;
1101
1137
  if (controller === null) return;
1102
1138
  const response = checked ?? controller.response;
@@ -1104,6 +1140,7 @@ export class AstlPlayer extends LitElement {
1104
1140
  const solution = controller.solution;
1105
1141
  const groups = new Map(result?.groups.map((g) => [g.id, g.verdict]) ?? []);
1106
1142
  for (const { element } of this.#mounted) {
1143
+ if (only !== undefined && !only.has(element.id)) continue;
1107
1144
  // Its groups: those it names (graded in parts) or its own, as the scoring the key chose has them.
1108
1145
  if (checked !== undefined && ![element.id, ...(element.groupIds ?? [])].some((id) => groups.has(id)))
1109
1146
  continue;
@@ -154,6 +154,12 @@ export const playerStyles: CSSResultGroup = [
154
154
  line-height: 1.25;
155
155
  }
156
156
  `,
157
+ // A Check element shows only where the help module draws it (practice that checks one question at a time).
158
+ css`
159
+ .canvas astl-check:not([data-shown]) {
160
+ display: none;
161
+ }
162
+ `,
157
163
  // The card's padding is the space at its edges: no extra margin above a page's first block or below its last.
158
164
  css`
159
165
  .canvas astl-page > :first-child {
@@ -3,6 +3,8 @@ import {
3
3
  allAttributes,
4
4
  BLOCK_TAGS,
5
5
  CAPTION_TAG,
6
+ CHECK_ATTRIBUTES,
7
+ CHECK_TAG,
6
8
  type ChildSpec,
7
9
  COLUMN_TAG,
8
10
  COLUMNS_TAG,
@@ -154,6 +156,10 @@ export function cleanContent(
154
156
  } else if ((tag === COLUMNS_TAG || tag === COLUMN_TAG) && components && !inline) {
155
157
  keepAttributes(el, CONTENT_ATTRIBUTES);
156
158
  cleanContent(el, cleaning, false);
159
+ } else if (tag === CHECK_TAG && components && !inline) {
160
+ // A Check element: its attributes only; the help module draws it where practice checks a question at a time.
161
+ keepAttributes(el, [...CHECK_ATTRIBUTES, 'lang', 'dir']);
162
+ el.replaceChildren();
157
163
  } else if (tag === 'img') {
158
164
  cleanPicture(el, urlPolicy);
159
165
  } else if (tag === FIGURE_TAG && !inline) {
@@ -248,7 +254,7 @@ export function readView(view: string): DocumentFragment {
248
254
  export function viewTags(fragment: DocumentFragment): Set<string> {
249
255
  return new Set(
250
256
  Array.from(fragment.querySelectorAll('*'), (el) => el.localName).filter(
251
- (tag) => tag.includes('-') && tag !== COLUMNS_TAG && tag !== COLUMN_TAG,
257
+ (tag) => tag.includes('-') && tag !== COLUMNS_TAG && tag !== COLUMN_TAG && tag !== CHECK_TAG,
252
258
  ),
253
259
  );
254
260
  }