Skip to content

Player

<astl-player> mounts a view, attaches the component elements, renders the chrome (pages, actions, results) and runs one attempt. It never holds answer logic: verdicts come from a checker.

Define it once with the elements you use (astrolabe.js and astrolabe-player.js do this for the built-ins):

import { definePlayer } from '@astl/player';
import { builtInElements } from '@astl/components/elements';
definePlayer({ elements: builtInElements }); // or only some, e.g. [gapElement]
definePlayer option Type and meaning
elements ElementEntry[]: component elements. A registration ({ manifest, element, messages }) is defined under its manifest tag right away; a LazyElement ({ tag, load }) is imported the first time a view contains its tag, and a load that fails shows load_failed (the next view tries again). The built-ins are lazy.
catalogs MessageCatalog[]: more or overriding messages, for example another UI locale
styleTemplates StyleTemplate[]: named looks that style-template picks on <astl-doc>, a component or the player: Looks
compileSource SourceCompiler: turns a light-DOM source into a view and a checker (HTML with answers); astrolabe.js registers one
urlPolicy UrlPolicy: which links, pictures and url attributes of a view stay; the engine's policy, or the player removes what it kept. Default isSafeUrl; one policy per page, the last call that passes one sets it. An address stays only when the policy answers true (URLs)
registry CustomElementRegistry: where the elements are defined. Default: the global customElements

Calling it again is safe: a tag already defined by the same class, or a lazy element with the same load, is skipped; a tag taken by another class, another loader or the other kind of entry throws.

The player loads the first of these that it finds:

  1. the view property (or load({ view }));
  2. an <astl-doc> in its light DOM: a compiled view plays directly; a source (with author ids and answers) goes through compileSource, and without one the player shows source_needs_compiler;
  3. the src attribute: fetched, checked against integrity, then played.
Attribute Values and meaning
locale A BCP 47 tag: the UI locale (buttons, messages, announcements). Matched against the available catalogs, with English as the fallback. Default: the player's lang, else the browser languages.
theme light, dark, hc or auto: the colour theme; auto (the default) follows prefers-color-scheme. Written to the player's data-theme.
src A URL: a view to fetch when no view is given.
integrity A lowercase hex SHA-256: the viewHash the fetched src must match; a mismatch (or an empty value) shows integrity_mismatch.
endpoint A URL: the grading endpoint of this attempt (protocol 1). Creates an httpChecker when no checker is set.
persist Boolean: keep snapshots in localStorage (key astl:snapshot:<viewHash>) and restore them on load. Off by default.
style-template A registered template name: the default look where neither the view's <astl-doc> nor a component names one (property styleTemplate): Looks.
hint-position row or top: where a question's hint goes (property hintPosition). row, the default: in its help row, after its Check. top: at the top of the question, a round "?" at the end of its line with the next hint's cost before it, the hints given under them, in a group of its own named "Hints for this question" ("Hints for field 2"; the row keeps "Help with this question"). A page's hint, and the hint of a question that floats or is placed, stays in its row. Another value is row. A change applies at once.
page-nav bar or contents: how a view of several pages shows them (property pageNav). bar, the default: a counter and a numbered button per page above the card. contents: a table of contents, beside the card on a wide player and in a drawer on a narrow one. Another value is bar. A change applies at once.
Property Type and meaning
view string: the view HTML to play. Setting it loads it. Default ''.
policy AttemptPolicy: which buttons and rules apply. Default PRACTICE_POLICY. Changing it reloads the view and keeps the answers.
checker Checker | null: grades checks and submits. Default null: an HTTP checker for endpoint, if set.
snapshot Snapshot | null: restored on load when its viewHash matches the view (or is null). Default null.
locale, theme, src, integrity, endpoint, persist The attributes above.
state (read only) AttemptState: loading, ready, active, checking, submitting, submitted, review or error.
viewHash (read only) string | null: SHA-256 of the mounted view; null before mounting or without WebCrypto.
page (read only) number: the 0-based index of the current page.
Method Meaning
load(options): Promise<void> Plays a view: options is { view, policy?, checker?, snapshot? }, and omitted fields keep the current properties. Resolves when it is mounted (astl-ready); rejects with the error code when it cannot.
check(id?): Promise<CheckResponse | null> Practice: grades and shows verdicts. With id, a view page (its questions at once, then its help) or, under checkScope: 'interaction', a view element (that interaction only, its verdict and help) or a Check element (its questions at once, one check): none of them is an astl-result, but each counts as a check. Failures are shown and emitted as astl-error, never thrown.
submit(): Promise<SubmitResponse | null> Hands the answers in (final) and moves the focus to the result. Failures are shown and emitted, never thrown.
goTo(index): boolean Goes to a page; false when not allowed (linear navigation, unknown page).
next(): boolean, previous(): boolean One page forward or back.
reset(): boolean Clears answers and results and goes to the first page; not after a hand-in.
getAnswers(): Answers The current answers, by slot id.
setAnswers(answers): void Sets answers without change events ('' clears). Only what the elements accept is kept.
getSnapshot(): Snapshot | null Everything needed to restore the attempt later.

All events bubble and are composed (they cross shadow roots). Names are in PlayerEvent of @astl/core.

Event Detail When
astl-ready ReadyDetail: { viewHash: string; pages: number; slots: number } the view is mounted and every element has rendered
astl-change ChangeDetail: { answers: Answers } (changed slots only, '' = cleared) a student changed an answer (sent by the element)
astl-page PageDetail: { index: number; count: number; id: string } the page changed
astl-state StateDetail: { state: AttemptState; previous: AttemptState } the attempt state changed
astl-result CheckResponse | SubmitResponse a check or a hand-in finished
astl-snapshot Snapshot there is progress worth saving (debounced, 300 ms)
astl-error ErrorDetail: { code: string; message: string } loading, checking or handing in failed; message is in the UI locale
import { PlayerEvent, type Snapshot } from '@astl/core';
const player = document.querySelector('astl-player')!;
player.addEventListener(PlayerEvent.snapshot, (event) => {
const snapshot = (event as CustomEvent<Snapshot>).detail;
void fetch('/api/drafts/123', { method: 'PUT', body: JSON.stringify(snapshot) });
});

astl-error and the player's own notices use these codes; each has a message error.<code> in the astl.player catalog.

Code Meaning
invalid_request, unauthorized, check_not_allowed, checks_exhausted, not_found, method_not_allowed, attempt_closed, payload_too_large, internal_error a problem from the checker: the grading protocol codes
no_checker there is nothing to grade with (no checker, no endpoint, no compiled source)
load_failed src could not be fetched, or a lazy element the view uses did not load
view_invalid the view is not one <astl-doc>
integrity_mismatch the fetched view does not match integrity
source_needs_compiler a source with answers is in the light DOM, but no compileSource is registered (use astrolabe.js)
source_invalid the source does not compile; its errors are listed under the notice for the author
Policy Buttons Notes
practice per question "Check" (its own verdict) and "Hint" (help fields), one "Check" for several questions where a Check element or a run of text has them; per page with check "Check this page"; "Start over" once every question has a result. Under checkScope: 'exercise': one "Check" at the foot for everything, and no check of one question "x checks left" once at the foot when maxChecks is set, one count for the attempt; a Check is aria-disabled when no check is possible
test "Hand in" asks "Hand in anyway?" when answers are empty; shows what reveal allows
review none read only

Practice checks one question at a time (checkScope: 'interaction', the default of PRACTICE_POLICY): every graded question gets a row under it with its own "Check" (after its paragraph, for a field in a line of text; at the same float and width, for a placed component), unless a Check for several questions has it, and there is no Check for everything at the foot. A question's check shows its verdict on it alone, read out with its feedback text, and never brings the help of its page.

A page with check ("Check this page" in the editor) has "Check this page" at its foot: one request for all its questions (check(pageId)), which gives each its verdict and then shows the page's feedback and explanation. A page with help of its own but without check (a source written for 0.1) gets the same button, as its help needs a check of the page.

Once every question has a result, from its own check or its page's, the foot shows the overall result, composed from those checks with no request of its own, and "Start over"; a changed answer makes its question's result stale, and the overall result goes until it is checked again. "x checks left" counts every check of the attempt, once at the foot. The overall result is not an astl-result: neither is a check of one question or of one page. Under checkScope: 'exercise' the foot has one "Check" for everything, as before 0.2, and that one is.

Where practice checks one question at a time, a Check element has a row where it is with one "Check" (its label, or "Check" in the UI language, named with how many questions it checks, "Check 3 questions"). Its questions have no Check of their own; their rows keep their hints, feedback and "Why?". A press is one request for all of them (CheckRequest.elements), one check against maxChecks: each question shows its verdict, the row says how they came out ("2 of 3 correct", which the button is described by), the live region reads it out, and the focus stays on the button. A changed answer takes that away until the next check. check(id) with the check's view id does the same.

The questions of a run of text that no Check element has share an automatic Check after the last of them, when there are two or more, worked out as the player plays (three sentences with a gap each: one Check after the third). A question alone keeps its own Check.

A check's row is .astl-help[data-check] (data-check="auto" for an automatic one), with the parts help check; its summary has the part check-summary. In a test, and in practice that checks everything at once, Check elements do not show and there are no automatic ones. The player takes from a response only the results of the check's questions: a grader that does not know elements (before 0.3) grades the whole exercise, and the rest is left unshown.

A view that offers help (hints, explanation or feedback on an element or a page, see the content format) loads the player's help module with it, and so does practice that checks one question at a time; other views never download it. The rows of the questions carry it, and a page's help sits at the page's foot:

  • "Check": that question's check (above).
  • "Hint 1 of 2": asks the checker for the next hint (Checker.hint); the hint shows in a list and is read out. A hint that costs says so beside its button before it is asked for, in points where the view says them ("Costs 0.5 points"; a view compiled before 0.2 says the share, "Costs 25% of the points"). Only in practice with hints.
  • The feedback box: the text for the verdict, in a box coloured by it, after a check (or a revealing hand-in). It opens with the verdict's icon and word; under a block, which says its verdict in words right above, the word is left to screen readers and the icon stays on the first line of the text.
  • "Why?": a disclosure with the explanation, once the checker sent it.

A row goes in that order, a Check element's row and a page's too: "Check" first, then the hint and its cost, then the feedback and "Why?" (a Check element's summary after its button); the DOM, and so the reading and tab order, is the order shown. Every control and text has a part of its own, the controls in a flex row inside the row's flex column, so a host orders, aligns, spaces or hides them in its own stylesheet (Looks); hint-position moves a question's hint to the top of the question.

What the checker sends is cleaned like view content, in the element's language. Changing an answer clears its feedback; "Start over" clears feedback and explanations (hints already given stay, as the checker counts them). Hints are not restored from a snapshot: a reload asks the checker again, which continues where it was (index, left).

With navigation: 'linear' there is no "Back" button and the page progress is not clickable. With a deadline, the header shows a countdown, the live region announces 5 and 1 minutes left, and the player hands in when it reaches zero (the server stays authoritative).

A page with a label shows it as its heading. A page without one, in a view of several pages, gets a generated heading, "Page 2" in the UI language, which is visually hidden: it is still an <h2> in the accessibility tree, and the focus goes to it when the page changes, but nothing is drawn, so a lesson of untitled pages is not a stack of "Page n" headings. A view of one page without a label has no generated heading; the canvas takes the focus.

A view whose <astl-doc> has kind="book" and more than one page plays as a book. While the player is at least 56rem wide (in the page's root font size), it shows two pages side by side, a spread (1-2, 3-4, ...; an odd last page alone), with a line between them, and its canvas grows to 1240px. "Next" and "Back" move a spread, both pages are current in the progress, the counter says "Pages 1-2 of 5", and the focus goes to the heading of the page it turned to (the spread's first for "Next" and "Back"). The new spread slides in (240 ms), not under prefers-reduced-motion: reduce or forced-colors: active. Narrower, or with one page, it plays one page at a time, as an exercise; a resize switches between the two and keeps the page. Policies, checks, scores, snapshots and events are the same for every kind.

With page-nav="contents", a view of several pages shows a table of contents in place of the counter and the numbered buttons, one row per page:

  • its number, and its title: the page's label, else "Page 2" in the UI language;
  • what the page holds, as an icon or two: practice where it has something to answer (an element with slots: a graded component, a long answer), theory where it has nothing to answer (text, pictures, media, flash cards), both where it has something to answer and a block of text of its own (an ungraded element that wraps rich text, such as a callout);
  • on a page with something to answer, a ring around the number that fills as it is answered: how much, never whether right.

The current page is marked (aria-current="step"; both pages of a spread), and so is it for a screen reader, which reads each row as its number, title, kind and how much is answered ("3 Practice 1, practice, partly answered"). A row goes to its page and moves the focus to the page's heading; under linear navigation the rows only show.

At 50rem wide and over (in the page's root font size), the list sits in a column of its own at the start of the card, 20rem wide, and stays in view while the page scrolls (it scrolls by itself when it is taller than the screen); a book's spread keeps the rest of the width for its two pages, or shows one page at a time when they do not fit. Narrower, the top of the player shows a button, "Contents" with the counter, which opens the list in a drawer from the start edge: a modal dialog over the dimmed page, 80% of the screen and at most 24rem wide, that slides in (not under prefers-reduced-motion: reduce). Picking a page closes it and moves the focus to the page's heading; Escape, a click beside it or its close button close it and give the focus back to the button. A view of one page shows neither.

Set the column's width with --astl-contents-size and the drawer's with --astl-contents-drawer-size (100% covers the screen) on the player; the rows, the button and the drawer have parts. The list loads as a module of its own, with the players that show it; without it (a chunk that fails to load), the pages show in the bar.

The player sizes its spacing from its own width, in the page's root font size, so it follows larger text, by zoom or by font size:

  • At 18rem and under, the space around its card is 0.5rem (1rem otherwise) and the card's sides 0.75rem (1.5rem otherwise); the card keeps 1.5rem above and below.
  • At 12rem and under, the card reaches the player's sides and keeps 0.25rem inside them.

A 390 px phone at 100% text, a player of about 20rem, keeps the full spacing; with 200% text the same phone takes the second step. The player measures its width rather than being a size container, so in any layout it takes the width it would have anyway: a block, a flex or grid item, an inline-block. In a box that sizes to its content, a player that narrow because its content is narrow takes the smaller spacing too. A resize applies a frame later.

player, header, canvas, result, footer, problem-details, help on each row of help, help check on the row of a check for several questions and check-summary on what it says after a check; in a row, help-actions (its controls), check-button, hint-offer (the next hint's button with its cost), hint-button, hint-cost, hints (the hints given), help-feedback, help-why and help-problem; help-top, a question's hint at its top with hint-position="top"; with page-nav="contents", contents (the list beside the card), contents-title, contents-item (each row), contents-button (the button that opens the drawer) and contents-drawer (the drawer). See Looks.

Component elements talk to the player only through PlayerElementApi (@astl/core): slotIds, getAnswers(), setAnswers(), feedback, solution, disabled, units() and attach(context); an element graded in parts also lists its groupIds and gets their verdicts in feedback.groups. The base classes AstlElement and SingleSlotElement in @astl/player implement most of it; see Write your own component and the API reference.