@astl/player 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.
@@ -48,6 +48,8 @@ export type AttemptChange =
48
48
  | { readonly type: 'result'; readonly response: CheckResponse | SubmitResponse }
49
49
  /** A check of one interaction (`checkElement`): its result only, the last whole result stays. */
50
50
  | { readonly type: 'element'; readonly id: string; readonly response: CheckResponse }
51
+ /** A check of a Check element's questions (`checkElements`): their result only, the last whole result stays. */
52
+ | { readonly type: 'elements'; readonly ids: readonly string[]; readonly response: CheckResponse }
51
53
  /** A check of one view page (`check(page)`): its result only, the last whole result stays. */
52
54
  | { readonly type: 'page-check'; readonly id: string; readonly response: CheckResponse }
53
55
  | { readonly type: 'reset' };
@@ -245,11 +247,20 @@ export class AttemptController {
245
247
  return this.#check(undefined, id);
246
248
  }
247
249
 
248
- #check(page: string | undefined, element?: string): Promise<CheckResponse> {
250
+ /**
251
+ * Practice with `checkScope: 'interaction'` only: grades several interactions at once (a Check element's questions,
252
+ * view element ids), as one check. The response comes as an `elements` change; `result` and `response` keep the
253
+ * last whole check.
254
+ */
255
+ checkElements(ids: readonly string[]): Promise<CheckResponse> {
256
+ return this.#check(undefined, undefined, [...ids]);
257
+ }
258
+
259
+ #check(page: string | undefined, element?: string, elements?: readonly string[]): Promise<CheckResponse> {
249
260
  if (this.#pendingCheck) return this.#pendingCheck;
250
- const refused = this.#checkRefusal(page, element);
261
+ const refused = this.#checkRefusal(page, element ?? elements);
251
262
  if (refused) return Promise.reject(refused);
252
- const run = this.#runCheck(page, element).finally(() => {
263
+ const run = this.#runCheck(page, element, elements).finally(() => {
253
264
  this.#pendingCheck = null;
254
265
  });
255
266
  this.#pendingCheck = run;
@@ -308,8 +319,12 @@ export class AttemptController {
308
319
  return Math.max(0, Date.parse(this.policy.deadline) - this.#now());
309
320
  }
310
321
 
311
- #checkRefusal(page: string | undefined, element: string | undefined): CheckerError | null {
322
+ #checkRefusal(
323
+ page: string | undefined,
324
+ element: string | readonly string[] | undefined,
325
+ ): CheckerError | null {
312
326
  if (this.policy.mode !== 'practice') return refusal(ProblemCode.checkNotAllowed, 403);
327
+ if (Array.isArray(element) && element.length === 0) return refusal(ProblemCode.notFound, 404);
313
328
  if (element !== undefined && helpPolicy(this.policy).checkScope !== 'interaction') {
314
329
  return refusal(ProblemCode.checkNotAllowed, 403);
315
330
  }
@@ -322,18 +337,29 @@ export class AttemptController {
322
337
  return null;
323
338
  }
324
339
 
325
- async #runCheck(page: string | undefined, element: string | undefined): Promise<CheckResponse> {
340
+ async #runCheck(
341
+ page: string | undefined,
342
+ element: string | undefined,
343
+ elements: readonly string[] | undefined,
344
+ ): Promise<CheckResponse> {
326
345
  this.start();
327
346
  this.#setState('checking');
328
347
  try {
329
348
  const answers = this.answers;
330
- const scope = page !== undefined ? { page } : element !== undefined ? { element } : {};
349
+ const scope =
350
+ page !== undefined
351
+ ? { page }
352
+ : element !== undefined
353
+ ? { element }
354
+ : elements !== undefined
355
+ ? { elements }
356
+ : {};
331
357
  const response = await this.checker.check({ answers, ...scope });
332
358
  this.#checks++;
333
359
  this.#checksLeft =
334
360
  response.checksLeft ??
335
361
  (this.policy.maxChecks === null ? null : Math.max(0, this.policy.maxChecks - this.#checks));
336
- if (element === undefined && page === undefined) {
362
+ if (element === undefined && elements === undefined && page === undefined) {
337
363
  this.#result = response.result;
338
364
  this.#response = response;
339
365
  }
@@ -341,9 +367,11 @@ export class AttemptController {
341
367
  this.#emit(
342
368
  element !== undefined
343
369
  ? { type: 'element', id: element, response }
344
- : page !== undefined
345
- ? { type: 'page-check', id: page, response }
346
- : { type: 'result', response },
370
+ : elements !== undefined
371
+ ? { type: 'elements', ids: elements, response }
372
+ : page !== undefined
373
+ ? { type: 'page-check', id: page, response }
374
+ : { type: 'result', response },
347
375
  );
348
376
  return response;
349
377
  } catch (error) {
@@ -10,6 +10,8 @@
10
10
  "help.check": "this question",
11
11
  "help.checkField": "field {n}",
12
12
  "help.checkPage": "Check this page",
13
+ "help.checkMany": "{count, plural, one {# question} other {# questions}}",
14
+ "help.checkSummary": "{correct} of {total} correct",
13
15
  "help.why": "Why?",
14
16
  "error.hints_not_allowed": "Hints are not available in this exercise.",
15
17
  "error.hints_exhausted": "There are no more hints."
@@ -10,6 +10,8 @@
10
10
  "help.check": "to pytanie",
11
11
  "help.checkField": "pole {n}",
12
12
  "help.checkPage": "Sprawdź tę stronę",
13
+ "help.checkMany": "{count, plural, one {# pytanie} few {# pytania} many {# pytań} other {# pytania}}",
14
+ "help.checkSummary": "{correct} z {total} poprawnie",
13
15
  "help.why": "Dlaczego?",
14
16
  "error.hints_not_allowed": "W tym zadaniu nie ma podpowiedzi.",
15
17
  "error.hints_exhausted": "Nie ma już więcej podpowiedzi."
@@ -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,
@@ -127,6 +130,16 @@ function codeOf(error: unknown, fallback: string): string {
127
130
  return typeof code === 'string' && code !== '' ? code : fallback;
128
131
  }
129
132
 
133
+ /**
134
+ * How narrow a player of `width` px is, in the root font size: 1 at 18rem and under, 2 at 12rem and under (about 200%
135
+ * text on a phone), else 0; null when it is not laid out (hidden), which keeps the step it had.
136
+ */
137
+ function narrowStep(width: number): 0 | 1 | 2 | null {
138
+ if (width === 0) return null;
139
+ const rem = Number.parseFloat(getComputedStyle(document.documentElement).fontSize) || 16;
140
+ return width <= 12 * rem ? 2 : width <= 18 * rem ? 1 : 0;
141
+ }
142
+
130
143
  function clock(ms: number): string {
131
144
  const seconds = Math.ceil(ms / 1000);
132
145
  const pad = (n: number) => String(n).padStart(2, '0');
@@ -200,6 +213,13 @@ export class AstlPlayer extends LitElement {
200
213
  /** Whether the book shows two pages side by side now: its module says the player is wide enough. */
201
214
  #spread = false;
202
215
  #resize: ResizeObserver | null = null;
216
+ /** How narrow the player is (`narrowStep`); its padding follows. */
217
+ #narrow: 0 | 1 | 2 = 0;
218
+ /** Watches the mark at the top of the shadow root: as wide as the player, 1rem tall, taking no room. */
219
+ #width: ResizeObserver | null = null;
220
+ /** The mark's width when last seen: 0 while hidden. */
221
+ #widthSeen = 0;
222
+ #widthFrame = 0;
203
223
  /** Page headings, null where a page has none (a single page without a label). */
204
224
  #headings: (HTMLElement | null)[] = [];
205
225
  #sourceChecker: Checker | null = null;
@@ -263,20 +283,45 @@ export class AstlPlayer extends LitElement {
263
283
 
264
284
  /**
265
285
  * 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.
286
+ * with `checkScope: 'interaction'`, a view element (that interaction only) or a Check element (its questions at once,
287
+ * one check): none of them is an `astl-result`. Failures are shown and emitted, never thrown.
268
288
  */
269
289
  async check(id?: string): Promise<CheckResponse | null> {
270
290
  const controller = this.#controller;
271
291
  if (controller === null) return null;
292
+ const check = id === undefined ? null : this.#checkElement(id);
293
+ if (check !== null) return this.#checkMany(checkFor(check.getAttribute(CHECK_FOR_ATTRIBUTE)));
294
+ return this.#run(() =>
295
+ id === undefined || controller.pages.some((p) => p.id === id)
296
+ ? controller.check(id)
297
+ : controller.checkElement(id),
298
+ );
299
+ }
300
+
301
+ /** A Check element of the mounted view by its view id, or null. */
302
+ #checkElement(id: string): Element | null {
303
+ const content = this.#query('.canvas');
304
+ return Array.from(content?.querySelectorAll(CHECK_TAG) ?? []).find((el) => el.id === id) ?? null;
305
+ }
306
+
307
+ /** Several interactions at once, as one check (a Check element's questions, or a group of fields). */
308
+ #checkMany(ids: readonly string[]): Promise<CheckResponse | null> {
309
+ return this.#run(() => {
310
+ const controller = this.#controller as AttemptController;
311
+ return controller.checkElements(ids);
312
+ });
313
+ }
314
+
315
+ /** Runs a check with the player's checker; a failure is shown and emitted, never thrown. */
316
+ async #run(check: () => Promise<CheckResponse>): Promise<CheckResponse | null> {
317
+ if (this.#controller === null) return null;
272
318
  this.#problem = null;
273
319
  if (this.#effectiveChecker() === null) {
274
320
  this.#showProblem('no_checker');
275
321
  return null;
276
322
  }
277
323
  try {
278
- if (id === undefined || controller.pages.some((p) => p.id === id)) return await controller.check(id);
279
- return await controller.checkElement(id);
324
+ return await check();
280
325
  } catch (error) {
281
326
  this.#showProblem(codeOf(error, 'internal_error'));
282
327
  return null;
@@ -360,6 +405,7 @@ export class AstlPlayer extends LitElement {
360
405
  super.connectedCallback();
361
406
  this.#syncClock();
362
407
  this.#resize?.observe(this);
408
+ this.#watchWidth();
363
409
  void this.#autoload();
364
410
  }
365
411
 
@@ -377,9 +423,12 @@ export class AstlPlayer extends LitElement {
377
423
  this.#flushSnapshot();
378
424
  this.#syncClock();
379
425
  this.#resize?.disconnect();
426
+ this.#width?.disconnect();
427
+ cancelAnimationFrame(this.#widthFrame);
380
428
  }
381
429
 
382
430
  protected override firstUpdated(): void {
431
+ this.#watchWidth();
383
432
  this.#query('.canvas')?.addEventListener(PlayerEvent.change, (event) => {
384
433
  const detail = (event as CustomEvent<ChangeDetail>).detail;
385
434
  if (detail?.answers) this.#controller?.setAnswers(detail.answers);
@@ -410,13 +459,14 @@ export class AstlPlayer extends LitElement {
410
459
  const locale = this.#uiLocale();
411
460
  const t = this.#i18n().translator(locale, PLAYER_NAMESPACE);
412
461
  const controller = this.#controller;
413
- return html`<div
462
+ return html`<div class="mark"></div><div
414
463
  class="root"
415
464
  part="player"
416
465
  lang=${locale}
417
466
  dir=${directionOf(locale)}
418
467
  data-style-template=${this.#documentTemplate ?? nothing}
419
468
  ?data-spread=${this.#spread}
469
+ data-narrow=${this.#narrow === 0 ? nothing : this.#narrow}
420
470
  aria-busy=${this.#state === 'loading' ? 'true' : 'false'}
421
471
  >
422
472
  ${this.#state === 'loading' ? html`<p class="status">${t('loading')}</p>` : nothing}
@@ -987,6 +1037,7 @@ export class AstlPlayer extends LitElement {
987
1037
  root: this.renderRoot,
988
1038
  checker: () => this.#effectiveChecker(),
989
1039
  check: (id) => this.check(id),
1040
+ checkMany: (ids) => this.#checkMany(ids),
990
1041
  overall: (response) => {
991
1042
  this.#overall = response;
992
1043
  this.requestUpdate();
@@ -1032,6 +1083,8 @@ export class AstlPlayer extends LitElement {
1032
1083
  this.#collect(child, found, notice);
1033
1084
  continue;
1034
1085
  }
1086
+ // A Check element is no component: the help module draws it.
1087
+ if (tag === CHECK_TAG) continue;
1035
1088
  const registration = runtime.elements.get(tag);
1036
1089
  const version = Number.parseInt(child.getAttribute('v') ?? '1', 10);
1037
1090
  if (
@@ -1077,6 +1130,11 @@ export class AstlPlayer extends LitElement {
1077
1130
  this.#applyResult(change.response);
1078
1131
  this.#scheduleSnapshot();
1079
1132
  break;
1133
+ case 'elements':
1134
+ // Only its questions: a server that does not know `elements` grades everything, and the rest is not asked.
1135
+ this.#applyResult(change.response, new Set(change.ids));
1136
+ this.#scheduleSnapshot();
1137
+ break;
1080
1138
  case 'reset':
1081
1139
  for (const { element } of this.#mounted) {
1082
1140
  element.setAnswers(Object.fromEntries(element.slotIds.map((id) => [id, ''])));
@@ -1096,7 +1154,7 @@ export class AstlPlayer extends LitElement {
1096
1154
  * announces the summary. With `checked`, the response of a check of one element or one page: the verdicts of the
1097
1155
  * elements it graded, no summary.
1098
1156
  */
1099
- #applyResult(checked?: CheckResponse): void {
1157
+ #applyResult(checked?: CheckResponse, only?: ReadonlySet<string>): void {
1100
1158
  const controller = this.#controller;
1101
1159
  if (controller === null) return;
1102
1160
  const response = checked ?? controller.response;
@@ -1104,6 +1162,7 @@ export class AstlPlayer extends LitElement {
1104
1162
  const solution = controller.solution;
1105
1163
  const groups = new Map(result?.groups.map((g) => [g.id, g.verdict]) ?? []);
1106
1164
  for (const { element } of this.#mounted) {
1165
+ if (only !== undefined && !only.has(element.id)) continue;
1107
1166
  // Its groups: those it names (graded in parts) or its own, as the scoring the key chose has them.
1108
1167
  if (checked !== undefined && ![element.id, ...(element.groupIds ?? [])].some((id) => groups.has(id)))
1109
1168
  continue;
@@ -1166,6 +1225,34 @@ export class AstlPlayer extends LitElement {
1166
1225
  return this.#spread ? this.#shown(page)[0] + 2 * direction : page + direction;
1167
1226
  }
1168
1227
 
1228
+ /**
1229
+ * Follows the player's width (the mark's) without size containment, so in any layout the player takes the width it
1230
+ * had: measured at once when rendered or connected, before it is painted, then on every resize. A resize applies a
1231
+ * frame later, outside the observer's delivery, which a change of size in a box sized by its content would loop;
1232
+ * only a player just shown (from hidden) applies at once, as the mark does not follow the padding.
1233
+ */
1234
+ #watchWidth(): void {
1235
+ const mark = this.#query('.mark');
1236
+ if (mark === null || typeof ResizeObserver === 'undefined') return;
1237
+ this.#widthSeen = mark.clientWidth;
1238
+ this.#setNarrow(narrowStep(this.#widthSeen));
1239
+ this.#width ??= new ResizeObserver(([entry]) => {
1240
+ const width = entry?.contentRect.width ?? 0;
1241
+ const shown = this.#widthSeen === 0;
1242
+ this.#widthSeen = width;
1243
+ cancelAnimationFrame(this.#widthFrame);
1244
+ if (shown) this.#setNarrow(narrowStep(width));
1245
+ else this.#widthFrame = requestAnimationFrame(() => this.#setNarrow(narrowStep(width)));
1246
+ });
1247
+ this.#width.observe(mark);
1248
+ }
1249
+
1250
+ #setNarrow(step: 0 | 1 | 2 | null): void {
1251
+ if (step === null || step === this.#narrow) return;
1252
+ this.#narrow = step;
1253
+ this.requestUpdate();
1254
+ }
1255
+
1169
1256
  /** The book's module says whether the player is wide enough for a spread: switching keeps the page, without focus. */
1170
1257
  #setSpread(spread: boolean): void {
1171
1258
  if (spread === this.#spread) return;
@@ -154,6 +154,34 @@ export const playerStyles: CSSResultGroup = [
154
154
  line-height: 1.25;
155
155
  }
156
156
  `,
157
+ // A narrow player (a small phone, larger text) keeps more of its width for the exercise: less space around the card
158
+ // and inside its sides, in two steps (`data-narrow`, from the player's own width; the second for about 200% text on
159
+ // a phone). A phone of 360 px or more at 100% text keeps the full padding. The mark is what the player measures: as
160
+ // wide as the player and 1rem tall, so a new root font size is a resize too, and it takes no room.
161
+ css`
162
+ .mark {
163
+ block-size: 1rem;
164
+ margin-block-end: -1rem;
165
+ }
166
+ .root[data-narrow] {
167
+ padding: var(--astl-space-2);
168
+ }
169
+ .root[data-narrow] > .canvas {
170
+ padding-inline: var(--astl-space-3);
171
+ }
172
+ .root[data-narrow='2'] {
173
+ padding-inline: 0;
174
+ }
175
+ .root[data-narrow='2'] > .canvas {
176
+ padding-inline: var(--astl-space-1);
177
+ }
178
+ `,
179
+ // A Check element shows only where the help module draws it (practice that checks one question at a time).
180
+ css`
181
+ .canvas astl-check:not([data-shown]) {
182
+ display: none;
183
+ }
184
+ `,
157
185
  // The card's padding is the space at its edges: no extra margin above a page's first block or below its last.
158
186
  css`
159
187
  .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
  }